language stringclasses 1
value | repo stringclasses 60
values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timeline-pluginstorage/src/main/java/org/apache/hadoop/yarn/server/timeline/LogInfo.java | {
"start": 8983,
"end": 10672
} | class ____ extends LogInfo {
private static final Logger LOG = LoggerFactory.getLogger(
EntityGroupFSTimelineStore.class);
public DomainLogInfo(String attemptDirName, String file,
String owner) {
super(attemptDirName, file, owner);
}
protected long doParse(TimelineDataManager tdm, JsonParser parser,
ObjectMapper objMapper, UserGroupInformation ugi, boolean appCompleted)
throws IOException {
long count = 0;
long curPos;
boolean putError = false;
try {
MappingIterator<TimelineDomain> iter = objMapper.readValues(parser,
TimelineDomain.class);
while (iter.hasNext()) {
TimelineDomain domain = iter.next();
domain.setOwner(ugi.getShortUserName());
LOG.trace("Read domain {}", domain.getId());
++count;
curPos = ((FSDataInputStream) parser.getInputSource()).getPos();
LOG.debug("Parser now at offset {}", curPos);
try {
tdm.putDomain(domain, ugi);
setOffset(curPos);
} catch (YarnException e) {
putError = true;
throw new IOException("Error posting domain", e);
} catch (IOException e) {
putError = true;
throw new IOException("Error posting domain", e);
}
}
} catch (IOException e) {
// if app hasn't completed then there may be errors due to the
// incomplete file which are treated as EOF until app completes
if (appCompleted || putError) {
throw e;
}
} catch (RuntimeException e) {
if (appCompleted || !(e.getCause() instanceof JsonParseException)) {
throw e;
}
}
return count;
}
}
| DomainLogInfo |
java | apache__camel | components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/InlineQueryResultCachedGif.java | {
"start": 1256,
"end": 1814
} | class ____ extends InlineQueryResult {
private static final String TYPE = "gif";
@JsonProperty("gif_file_id")
private String gifFileId;
private String title;
private String caption;
@JsonProperty("parse_mode")
private String parseMode;
@JsonProperty("input_message_content")
private InputMessageContent inputMessageContext;
public InlineQueryResultCachedGif() {
super(TYPE);
}
public static Builder builder() {
return new Builder();
}
public static final | InlineQueryResultCachedGif |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/ClientOptions.java | {
"start": 1709,
"end": 8111
} | class ____ implements Serializable {
public static final boolean DEFAULT_AUTO_RECONNECT = true;
public static final MaintNotificationsConfig DEFAULT_MAINT_NOTIFICATIONS_CONFIG = MaintNotificationsConfig.enabled();
public static final Predicate<RedisCommand<?, ?, ?>> DEFAULT_REPLAY_FILTER = (cmd) -> false;
public static final int DEFAULT_BUFFER_USAGE_RATIO = 3;
public static final DisconnectedBehavior DEFAULT_DISCONNECTED_BEHAVIOR = DisconnectedBehavior.DEFAULT;
public static final ReauthenticateBehavior DEFAULT_REAUTHENTICATE_BEHAVIOUR = ReauthenticateBehavior.DEFAULT;
public static final boolean DEFAULT_PUBLISH_ON_SCHEDULER = false;
public static final boolean DEFAULT_PING_BEFORE_ACTIVATE_CONNECTION = true;
public static final ProtocolVersion DEFAULT_PROTOCOL_VERSION = ProtocolVersion.newestSupported();
public static final ReadOnlyCommands.ReadOnlyPredicate DEFAULT_READ_ONLY_COMMANDS = ReadOnlyCommands.asPredicate();
public static final int DEFAULT_REQUEST_QUEUE_SIZE = Integer.MAX_VALUE;
public static final Charset DEFAULT_SCRIPT_CHARSET = StandardCharsets.UTF_8;
public static final SocketOptions DEFAULT_SOCKET_OPTIONS = SocketOptions.create();
public static final Supplier<JsonParser> DEFAULT_JSON_PARSER = () -> {
try {
Iterator<JsonParser> services = ServiceLoader.load(JsonParser.class).iterator();
return services.hasNext() ? services.next() : null;
} catch (ServiceConfigurationError e) {
throw new RedisJsonException("Could not load JsonParser, please consult the guide"
+ "at https://redis.github.io/lettuce/user-guide/redis-json/", e);
}
};
public static final SslOptions DEFAULT_SSL_OPTIONS = SslOptions.create();
public static final boolean DEFAULT_SUSPEND_RECONNECT_PROTO_FAIL = false;
public static final TimeoutOptions DEFAULT_TIMEOUT_OPTIONS = TimeoutOptions.enabled();
public static final boolean DEFAULT_USE_HASH_INDEX_QUEUE = true;
private final boolean autoReconnect;
private final MaintNotificationsConfig maintNotificationsConfig;
private final Predicate<RedisCommand<?, ?, ?>> replayFilter;
private final DecodeBufferPolicy decodeBufferPolicy;
private final DisconnectedBehavior disconnectedBehavior;
private final ReauthenticateBehavior reauthenticateBehavior;
private final boolean publishOnScheduler;
private final boolean pingBeforeActivateConnection;
private final ProtocolVersion protocolVersion;
private final ReadOnlyCommands.ReadOnlyPredicate readOnlyCommands;
private final int requestQueueSize;
private final Charset scriptCharset;
private final Supplier<JsonParser> jsonParser;
private final SocketOptions socketOptions;
private final SslOptions sslOptions;
private final boolean suspendReconnectOnProtocolFailure;
private final TimeoutOptions timeoutOptions;
private final boolean useHashIndexedQueue;
protected ClientOptions(Builder builder) {
this.autoReconnect = builder.autoReconnect;
this.maintNotificationsConfig = builder.maintNotificationsConfig;
this.replayFilter = builder.replayFilter;
this.decodeBufferPolicy = builder.decodeBufferPolicy;
this.disconnectedBehavior = builder.disconnectedBehavior;
this.reauthenticateBehavior = builder.reauthenticateBehavior;
this.publishOnScheduler = builder.publishOnScheduler;
this.pingBeforeActivateConnection = builder.pingBeforeActivateConnection;
this.protocolVersion = builder.protocolVersion;
this.readOnlyCommands = builder.readOnlyCommands;
this.requestQueueSize = builder.requestQueueSize;
this.scriptCharset = builder.scriptCharset;
this.jsonParser = builder.jsonParser;
this.socketOptions = builder.socketOptions;
this.sslOptions = builder.sslOptions;
this.suspendReconnectOnProtocolFailure = builder.suspendReconnectOnProtocolFailure;
this.timeoutOptions = builder.timeoutOptions;
this.useHashIndexedQueue = builder.useHashIndexedQueue;
}
protected ClientOptions(ClientOptions original) {
this.autoReconnect = original.isAutoReconnect();
this.maintNotificationsConfig = original.getMaintNotificationsConfig();
this.replayFilter = original.getReplayFilter();
this.decodeBufferPolicy = original.getDecodeBufferPolicy();
this.disconnectedBehavior = original.getDisconnectedBehavior();
this.reauthenticateBehavior = original.getReauthenticateBehaviour();
this.publishOnScheduler = original.isPublishOnScheduler();
this.pingBeforeActivateConnection = original.isPingBeforeActivateConnection();
this.protocolVersion = original.getConfiguredProtocolVersion();
this.readOnlyCommands = original.getReadOnlyCommands();
this.requestQueueSize = original.getRequestQueueSize();
this.scriptCharset = original.getScriptCharset();
this.jsonParser = original.getJsonParser();
this.socketOptions = original.getSocketOptions();
this.sslOptions = original.getSslOptions();
this.suspendReconnectOnProtocolFailure = original.isSuspendReconnectOnProtocolFailure();
this.timeoutOptions = original.getTimeoutOptions();
this.useHashIndexedQueue = original.isUseHashIndexedQueue();
}
/**
* Create a copy of {@literal options}
*
* @param options the original
* @return A new instance of {@link ClientOptions} containing the values of {@literal options}
*/
public static ClientOptions copyOf(ClientOptions options) {
return new ClientOptions(options);
}
/**
* Returns a new {@link ClientOptions.Builder} to construct {@link ClientOptions}.
*
* @return a new {@link ClientOptions.Builder} to construct {@link ClientOptions}.
*/
public static ClientOptions.Builder builder() {
return new ClientOptions.Builder();
}
/**
* Create a new instance of {@link ClientOptions} with default settings.
*
* @return a new instance of {@link ClientOptions} with default settings
*/
public static ClientOptions create() {
return builder().build();
}
/**
* Builder for {@link ClientOptions}.
*/
public static | ClientOptions |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/indices/diskusage/TransportAnalyzeIndexDiskUsageAction.java | {
"start": 4208,
"end": 11026
} | class ____ extends AsyncBroadcastAction {
private final Queue<ShardRequest> queue = new LinkedList<>();
private final Map<DiscoveryNode, AtomicInteger> sendingCounters = ConcurrentCollections.newConcurrentMap();
private final int maxConcurrentRequestsPerNode;
LimitingRequestPerNodeBroadcastAction(
Task task,
AnalyzeIndexDiskUsageRequest request,
ActionListener<AnalyzeIndexDiskUsageResponse> listener,
int maxConcurrentRequestsPerNode
) {
super(task, request, listener);
this.maxConcurrentRequestsPerNode = maxConcurrentRequestsPerNode;
}
private void trySendRequests() {
assert Thread.holdsLock(this) == false;
final List<ShardRequest> readyRequests = new ArrayList<>();
synchronized (this) {
final Iterator<ShardRequest> it = queue.iterator();
while (it.hasNext()) {
final ShardRequest r = it.next();
final AtomicInteger sending = sendingCounters.computeIfAbsent(r.node, k -> new AtomicInteger());
assert 0 <= sending.get() && sending.get() <= maxConcurrentRequestsPerNode : sending;
if (sending.get() < maxConcurrentRequestsPerNode) {
sending.incrementAndGet();
readyRequests.add(r);
it.remove();
}
}
}
if (readyRequests.isEmpty()) {
return;
}
final Thread sendingThread = Thread.currentThread();
for (ShardRequest r : readyRequests) {
super.sendShardRequest(
r.node,
r.shardRequest,
ActionListener.runAfter(r.handler, () -> onRequestResponded(sendingThread, r.node))
);
}
}
private void onRequestResponded(Thread sendingThread, DiscoveryNode node) {
final AtomicInteger sending = sendingCounters.get(node);
assert sending != null && 1 <= sending.get() && sending.get() <= maxConcurrentRequestsPerNode : sending;
sending.decrementAndGet();
// fork to avoid StackOverflow
if (sendingThread == Thread.currentThread()) {
threadPool.generic().execute(this::trySendRequests);
} else {
trySendRequests();
}
}
@Override
protected synchronized void sendShardRequest(
DiscoveryNode node,
AnalyzeDiskUsageShardRequest shardRequest,
ActionListener<AnalyzeDiskUsageShardResponse> listener
) {
queue.add(new ShardRequest(node, shardRequest, listener));
}
@Override
public void start() {
super.start();
trySendRequests();
}
}
@Override
protected AnalyzeDiskUsageShardRequest newShardRequest(int numShards, ShardRouting shard, AnalyzeIndexDiskUsageRequest request) {
return new AnalyzeDiskUsageShardRequest(shard.shardId(), request);
}
@Override
protected AnalyzeDiskUsageShardResponse readShardResponse(StreamInput in) throws IOException {
return new AnalyzeDiskUsageShardResponse(in);
}
@Override
protected AnalyzeDiskUsageShardResponse shardOperation(AnalyzeDiskUsageShardRequest request, Task task) throws IOException {
final ShardId shardId = request.shardId();
assert task instanceof CancellableTask : "AnalyzeDiskUsageShardRequest must create a cancellable task";
final CancellableTask cancellableTask = (CancellableTask) task;
final Runnable checkForCancellation = cancellableTask::ensureNotCancelled;
final IndexShard shard = indicesService.indexServiceSafe(shardId.getIndex()).getShard(shardId.id());
try (Engine.IndexCommitRef commitRef = shard.acquireLastIndexCommit(request.flush)) {
final IndexDiskUsageStats stats = IndexDiskUsageAnalyzer.analyze(shardId, commitRef.getIndexCommit(), checkForCancellation);
return new AnalyzeDiskUsageShardResponse(shardId, stats);
}
}
@Override
protected AnalyzeIndexDiskUsageResponse newResponse(
AnalyzeIndexDiskUsageRequest request,
AtomicReferenceArray<?> shardsResponses,
ClusterState clusterState
) {
int successfulShards = 0;
final List<DefaultShardOperationFailedException> shardFailures = new ArrayList<>();
final Map<String, IndexDiskUsageStats> combined = new HashMap<>();
for (int i = 0; i < shardsResponses.length(); i++) {
final Object r = shardsResponses.get(i);
if (r instanceof AnalyzeDiskUsageShardResponse resp) {
++successfulShards;
combined.compute(resp.getIndex(), (k, v) -> v == null ? resp.stats : v.add(resp.stats));
} else if (r instanceof DefaultShardOperationFailedException e) {
shardFailures.add(e);
} else if (r instanceof Exception e) {
shardFailures.add(new DefaultShardOperationFailedException(ExceptionsHelper.convertToElastic(e)));
} else {
assert false : "unknown response [" + r + "]";
throw new IllegalStateException("unknown response [" + r + "]");
}
}
return new AnalyzeIndexDiskUsageResponse(shardsResponses.length(), successfulShards, shardFailures.size(), shardFailures, combined);
}
@Override
protected List<? extends ShardIterator> shards(
ClusterState clusterState,
AnalyzeIndexDiskUsageRequest request,
String[] concreteIndices
) {
ProjectState project = projectResolver.getProjectState(clusterState);
final List<SearchShardRouting> groups = clusterService.operationRouting().searchShards(project, concreteIndices, null, null);
for (ShardIterator group : groups) {
// fails fast if any non-active groups
if (group.size() == 0) {
throw new NoShardAvailableActionException(group.shardId());
}
}
return groups;
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, AnalyzeIndexDiskUsageRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, AnalyzeIndexDiskUsageRequest request, String[] concreteIndices) {
return state.blocks().indicesBlockedException(projectResolver.getProjectId(), ClusterBlockLevel.METADATA_READ, concreteIndices);
}
}
| LimitingRequestPerNodeBroadcastAction |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java | {
"start": 4202,
"end": 5018
} | class ____ extends BaseNodesRequest {
private final String requestName;
public CancellableNodesRequest(String requestName, String... nodesIds) {
super(nodesIds);
this.requestName = requestName;
}
@Override
public String getDescription() {
return "CancellableNodesRequest[" + requestName + "]";
}
@Override
public Task createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) {
return new CancellableTask(id, type, action, getDescription(), parentTaskId, headers);
}
}
/**
* Simulates a cancellable node-based task that can be used to block node tasks so they are guaranteed to be registered by task manager
*/
| CancellableNodesRequest |
java | elastic__elasticsearch | libs/x-content/src/test/java/org/elasticsearch/xcontent/ParseFieldTests.java | {
"start": 4255,
"end": 8133
} | class ____ implements DeprecationHandler {
public boolean compatibleWarningsUsed = false;
@Override
public void logRenamedField(String parserName, Supplier<XContentLocation> location, String oldName, String currentName) {}
@Override
public void logReplacedField(String parserName, Supplier<XContentLocation> location, String oldName, String replacedName) {}
@Override
public void logRemovedField(String parserName, Supplier<XContentLocation> location, String removedName) {}
@Override
public void logRenamedField(
String parserName,
Supplier<XContentLocation> location,
String oldName,
String currentName,
boolean isCompatibleDeprecation
) {
this.compatibleWarningsUsed = isCompatibleDeprecation;
}
@Override
public void logReplacedField(
String parserName,
Supplier<XContentLocation> location,
String oldName,
String replacedName,
boolean isCompatibleDeprecation
) {
this.compatibleWarningsUsed = isCompatibleDeprecation;
}
@Override
public void logRemovedField(
String parserName,
Supplier<XContentLocation> location,
String removedName,
boolean isCompatibleDeprecation
) {
this.compatibleWarningsUsed = isCompatibleDeprecation;
}
}
public void testCompatibleLoggerIsUsed() {
{
// a field deprecated in previous version and now available under old name only in compatible api
// emitting compatible logs
ParseField field = new ParseField("new_name", "old_name").forRestApiVersion(
RestApiVersion.equalTo(RestApiVersion.minimumSupported())
);
TestDeprecationHandler testDeprecationHandler = new TestDeprecationHandler();
assertTrue(field.match("old_name", testDeprecationHandler));
assertThat(testDeprecationHandler.compatibleWarningsUsed, is(true));
}
{
// a regular newly deprecated field. Emitting deprecation logs instead of compatible logs
ParseField field = new ParseField("new_name", "old_name");
TestDeprecationHandler testDeprecationHandler = new TestDeprecationHandler();
assertTrue(field.match("old_name", testDeprecationHandler));
assertThat(testDeprecationHandler.compatibleWarningsUsed, is(false));
}
}
public void testCompatibleWarnings() {
ParseField field = new ParseField("new_name", "old_name").forRestApiVersion(
RestApiVersion.equalTo(RestApiVersion.minimumSupported())
);
assertTrue(field.match("new_name", LoggingDeprecationHandler.INSTANCE));
ensureNoWarnings();
assertTrue(field.match("old_name", LoggingDeprecationHandler.INSTANCE));
assertCriticalWarnings("Deprecated field [old_name] used, expected [new_name] instead");
ParseField allDepField = new ParseField("dep", "old_name").withAllDeprecated()
.forRestApiVersion(RestApiVersion.equalTo(RestApiVersion.minimumSupported()));
assertTrue(allDepField.match("dep", LoggingDeprecationHandler.INSTANCE));
assertCriticalWarnings("Deprecated field [dep] used, this field is unused and will be removed entirely");
assertTrue(allDepField.match("old_name", LoggingDeprecationHandler.INSTANCE));
assertCriticalWarnings("Deprecated field [old_name] used, this field is unused and will be removed entirely");
ParseField regularField = new ParseField("new_name");
assertTrue(regularField.match("new_name", LoggingDeprecationHandler.INSTANCE));
ensureNoWarnings();
}
}
| TestDeprecationHandler |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/manytomany/ForeignKeyNameTest.java | {
"start": 1059,
"end": 1906
} | class ____ {
@Test
@JiraKey(value = "HHH-10247")
public void testJoinedSubclassForeignKeyNameIsNotAutoGeneratedWhenProvided(
DomainModelScope modelScope,
@TempDir File tmpDir) throws Exception {
final var scriptFile = new File( tmpDir, "script.sql" );
final var metadata = modelScope.getDomainModel();
metadata.orderColumns( false );
metadata.validate();
new SchemaExport()
.setOutputFile( scriptFile.getAbsolutePath() )
.setDelimiter( ";" )
.setFormat( true )
.create( EnumSet.of( TargetType.SCRIPT ), metadata );
String fileContent = new String( Files.readAllBytes( scriptFile.toPath() ) );
MatcherAssert.assertThat( fileContent.toLowerCase().contains( "fk_user_group" ), is( true ) );
MatcherAssert.assertThat( fileContent.toLowerCase().contains( "fk_group_user" ), is( true ) );
}
}
| ForeignKeyNameTest |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/annotation/InterfaceStability.java | {
"start": 1760,
"end": 1930
} | interface ____ { }
/**
* Compatibility may be broken at minor release (i.e. m.x).
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @ | Stable |
java | hibernate__hibernate-orm | hibernate-testing/src/main/java/org/hibernate/testing/cleaner/DB2DatabaseCleaner.java | {
"start": 454,
"end": 12529
} | class ____ implements DatabaseCleaner {
private static final Logger LOG = Logger.getLogger( DB2DatabaseCleaner.class.getName() );
private static final String SYSTEM_SCHEMAS = "'SYSCAT',"
+ "'SYSIBM',"
+ "'SYSIBMADM',"
+ "'SYSPUBLIC',"
+ "'SYSSTAT',"
+ "'DB2GSE',"
+ "'SYSTOOLS'";
private final List<String> ignoredTables = new ArrayList<>();
private final Map<String, Map<String, List<String>>> cachedForeignKeysPerSchema = new HashMap<>();
@Override
public boolean isApplicable(Connection connection) {
try {
return connection.getMetaData().getDatabaseProductName().startsWith( "DB2" );
}
catch (SQLException e) {
throw new RuntimeException( "Could not resolve the database metadata!", e );
}
}
@Override
public void addIgnoredTable(String tableName) {
ignoredTables.add( tableName );
}
@Override
public void clearAllSchemas(Connection c) {
cachedForeignKeysPerSchema.clear();
try (Statement s = c.createStatement()) {
ResultSet rs;
List<String> sqls = new ArrayList<>();
// Collect schema objects
LOG.log( Level.FINEST, "Collect schema objects: START" );
rs = s.executeQuery(
"SELECT 'DROP INDEX \"' || TRIM(INDSCHEMA) || '\".\"' || TRIM(INDNAME) || '\"' " +
"FROM SYSCAT.INDEXES " +
"WHERE UNIQUERULE = 'D' " +
"AND INDSCHEMA NOT IN (" + SYSTEM_SCHEMAS + ")"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'ALTER TABLE \"' || TRIM(TABSCHEMA) || '\".\"' || TRIM(TABNAME) || '\" DROP FOREIGN KEY \"' || TRIM(CONSTNAME) || '\"' " +
"FROM SYSCAT.TABCONST " +
"WHERE TYPE = 'F' " +
"AND TABSCHEMA NOT IN (" + SYSTEM_SCHEMAS + ")"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'ALTER TABLE \"' || TRIM(TABSCHEMA) || '\".\"' || TRIM(TABNAME) || '\" DROP UNIQUE \"' || TRIM(INDNAME) || '\"' " +
"FROM SYSCAT.INDEXES " +
"WHERE UNIQUERULE = 'U' " +
"AND INDSCHEMA NOT IN (" + SYSTEM_SCHEMAS + ")"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'ALTER TABLE \"' || TRIM(TABSCHEMA) || '\".\"' || TRIM(TABNAME) || '\" DROP PRIMARY KEY' " +
"FROM SYSCAT.INDEXES " +
"WHERE UNIQUERULE = 'P' " +
"AND INDSCHEMA NOT IN (" + SYSTEM_SCHEMAS + ")"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'DROP VIEW \"' || TRIM(TABSCHEMA) || '\".\"' || TRIM(TABNAME) || '\"' " +
"FROM SYSCAT.TABLES " +
"WHERE TYPE = 'V' " +
"AND TABSCHEMA NOT IN (" + SYSTEM_SCHEMAS + ")"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'DROP TABLE \"' || TRIM(TABSCHEMA) || '\".\"' || TRIM(TABNAME) || '\"' " +
"FROM SYSCAT.TABLES " +
"WHERE TYPE = 'T' " +
"AND TABSCHEMA NOT IN (" + SYSTEM_SCHEMAS + ")"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'DROP SEQUENCE \"' || TRIM(SEQSCHEMA) || '\".\"' || TRIM(SEQNAME) || '\"' " +
"FROM SYSCAT.SEQUENCES " +
"WHERE SEQSCHEMA NOT IN (" + SYSTEM_SCHEMAS + ")"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
LOG.log( Level.FINEST, "Collect schema objects: END" );
LOG.log( Level.FINEST, "Dropping schema objects: START" );
for ( String sql : sqls ) {
try {
s.execute( sql );
}
catch (SQLException e) {
if ( -204 == e.getErrorCode() ) {
// Apparently we deleted this along with a dependent object since it doesn't exist anymore
}
else {
throw e;
}
}
}
LOG.log( Level.FINEST, "Dropping schema objects: END" );
LOG.log( Level.FINEST, "Committing: START" );
c.commit();
LOG.log( Level.FINEST, "Committing: END" );
}
catch (SQLException e) {
try {
c.rollback();
}
catch (SQLException e1) {
e.addSuppressed( e1 );
}
throw new RuntimeException( e );
}
}
@Override
public void clearSchema(Connection c, String schemaName) {
cachedForeignKeysPerSchema.remove( schemaName );
schemaName = schemaName.toUpperCase();
try (Statement s = c.createStatement()) {
ResultSet rs;
List<String> sqls = new ArrayList<>();
// Collect schema objects
LOG.log( Level.FINEST, "Collect schema objects: START" );
rs = s.executeQuery(
"SELECT 'DROP INDEX \"' || TRIM(INDSCHEMA) || '\".\"' || TRIM(INDNAME) || '\"' " +
"FROM SYSCAT.INDEXES " +
"WHERE UNIQUERULE = 'D' " +
"AND INDSCHEMA = '" + schemaName + "'"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'ALTER TABLE \"' || TRIM(TABSCHEMA) || '\".\"' || TRIM(TABNAME) || '\" DROP FOREIGN KEY \"' || TRIM(CONSTNAME) || '\"' " +
"FROM SYSCAT.TABCONST " +
"WHERE TYPE = 'F' " +
"AND TABSCHEMA = '" + schemaName + "'"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'ALTER TABLE \"' || TRIM(TABSCHEMA) || '\".\"' || TRIM(TABNAME) || '\" DROP UNIQUE \"' || TRIM(INDNAME) || '\"' " +
"FROM SYSCAT.INDEXES " +
"WHERE UNIQUERULE = 'U' " +
"AND INDSCHEMA = '" + schemaName + "'"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'ALTER TABLE \"' || TRIM(TABSCHEMA) || '\".\"' || TRIM(TABNAME) || '\" DROP PRIMARY KEY' " +
"FROM SYSCAT.INDEXES " +
"WHERE UNIQUERULE = 'P' " +
"AND INDSCHEMA = '" + schemaName + "'"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'DROP VIEW \"' || TRIM(TABSCHEMA) || '\".\"' || TRIM(TABNAME) || '\"' " +
"FROM SYSCAT.TABLES " +
"WHERE TYPE = 'V' " +
"AND TABSCHEMA = '" + schemaName + "'"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'DROP TABLE \"' || TRIM(TABSCHEMA) || '\".\"' || TRIM(TABNAME) || '\"' " +
"FROM SYSCAT.TABLES " +
"WHERE TYPE = 'T' " +
"AND TABSCHEMA = '" + schemaName + "'"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
rs = s.executeQuery(
"SELECT 'DROP SEQUENCE \"' || TRIM(SEQSCHEMA) || '\".\"' || TRIM(SEQNAME) || '\"' " +
"FROM SYSCAT.SEQUENCES " +
"WHERE SEQSCHEMA = '" + schemaName + "'"
);
while ( rs.next() ) {
sqls.add( rs.getString( 1 ) );
}
LOG.log( Level.FINEST, "Collect schema objects: END" );
LOG.log( Level.FINEST, "Dropping schema objects: START" );
for ( String sql : sqls ) {
try {
s.execute( sql );
}
catch (SQLException e) {
if ( -204 == e.getErrorCode() ) {
// Apparently we deleted this along with a dependent object since it doesn't exist anymore
}
else {
throw e;
}
}
}
LOG.log( Level.FINEST, "Dropping schema objects: END" );
LOG.log( Level.FINEST, "Committing: START" );
c.commit();
LOG.log( Level.FINEST, "Committing: END" );
}
catch (SQLException e) {
try {
c.rollback();
}
catch (SQLException e1) {
e.addSuppressed( e1 );
}
throw new RuntimeException( e );
}
}
@Override
public void clearAllData(Connection connection) {
Map<String, List<String>> cachedForeignKeys = cachedForeignKeysPerSchema.get( null );
if ( cachedForeignKeys == null ) {
cachedForeignKeys = collectAllForeignKeys( connection );
cachedForeignKeysPerSchema.put( null, cachedForeignKeys );
}
deleteAllData( connection, cachedForeignKeys );
}
@Override
public void clearData(Connection connection, String schemaName) {
Map<String, List<String>> cachedForeignKeys = cachedForeignKeysPerSchema.get( schemaName );
if ( cachedForeignKeys == null ) {
cachedForeignKeys = collectForeignKeys( connection, schemaName.toUpperCase() );
cachedForeignKeysPerSchema.put( schemaName, cachedForeignKeys );
}
deleteAllData( connection, cachedForeignKeys );
}
private Map<String, List<String>> collectAllForeignKeys(Connection c) {
try (Statement s = c.createStatement()) {
// Collect table names for schemas
LOG.log( Level.FINEST, "Collect table names: START" );
ResultSet rs = s.executeQuery(
"SELECT TABLE_SCHEMA || '.' || TABLE_NAME FROM SYSIBM.TABLES WHERE TABLE_SCHEMA NOT IN (" + SYSTEM_SCHEMAS + ")"
);
Map<String, List<String>> foreignKeys = new HashMap<>();
while ( rs.next() ) {
foreignKeys.put( rs.getString( 1 ), new ArrayList<String>() );
}
LOG.log( Level.FINEST, "Collect table names: END" );
// Collect foreign keys for tables
LOG.log( Level.FINEST, "Collect foreign keys: START" );
ResultSet rs2 = s.executeQuery(
"SELECT FKTABLE_SCHEM || '.' || FKTABLE_NAME, FK_NAME FROM SYSIBM.SQLFOREIGNKEYS WHERE FKTABLE_SCHEM NOT IN (" + SYSTEM_SCHEMAS + ")"
);
while ( rs2.next() ) {
foreignKeys.get( rs2.getString( 1 ) ).add( rs2.getString( 2 ) );
}
LOG.log( Level.FINEST, "Collect foreign keys: END" );
return foreignKeys;
}
catch (SQLException e) {
try {
c.rollback();
}
catch (SQLException e1) {
e.addSuppressed( e1 );
}
throw new RuntimeException( e );
}
}
private Map<String, List<String>> collectForeignKeys(Connection c, String schemaName) {
try (Statement s = c.createStatement()) {
// Collect table names for schemas
LOG.log( Level.FINEST, "Collect table names: START" );
ResultSet rs = s.executeQuery(
"SELECT TRIM(TABLE_SCHEMA) || '.' || TABLE_NAME FROM SYSIBM.TABLES WHERE TABLE_SCHEMA = '" + schemaName + "'"
);
Map<String, List<String>> foreignKeys = new HashMap<>();
while ( rs.next() ) {
foreignKeys.put( rs.getString( 1 ), new ArrayList<String>() );
}
LOG.log( Level.FINEST, "Collect table names: END" );
// Collect foreign keys for tables
LOG.log( Level.FINEST, "Collect foreign keys: START" );
ResultSet rs2 = s.executeQuery(
"SELECT FKTABLE_SCHEM || '.' || FKTABLE_NAME, FK_NAME FROM SYSIBM.SQLFOREIGNKEYS WHERE FKTABLE_SCHEM = '" + schemaName + "'"
);
while ( rs2.next() ) {
foreignKeys.get( rs2.getString( 1 ) ).add( rs2.getString( 2 ) );
}
LOG.log( Level.FINEST, "Collect foreign keys: END" );
return foreignKeys;
}
catch (SQLException e) {
try {
c.rollback();
}
catch (SQLException e1) {
e.addSuppressed( e1 );
}
throw new RuntimeException( e );
}
}
private void deleteAllData(Connection c, Map<String, List<String>> foreignKeys) {
try (Statement s = c.createStatement()) {
// Disable foreign keys
LOG.log( Level.FINEST, "Disable foreign keys: START" );
for ( Map.Entry<String, List<String>> entry : foreignKeys.entrySet() ) {
for ( String fk : entry.getValue() ) {
s.execute( "ALTER TABLE " + entry.getKey() + " ALTER FOREIGN KEY " + fk + " NOT ENFORCED" );
}
}
c.commit();
LOG.log( Level.FINEST, "Disable foreign keys: END" );
// Delete data
LOG.log( Level.FINEST, "Deleting data: START" );
for ( String table : foreignKeys.keySet() ) {
if ( !ignoredTables.contains( table ) ) {
s.execute( "TRUNCATE TABLE " + table + " IMMEDIATE" );
// DB2 needs a commit after every truncate statement
c.commit();
}
}
LOG.log( Level.FINEST, "Deleting data: END" );
// Enable foreign keys
LOG.log( Level.FINEST, "Enabling foreign keys: START" );
for ( Map.Entry<String, List<String>> entry : foreignKeys.entrySet() ) {
for ( String fk : entry.getValue() ) {
s.execute( "ALTER TABLE " + entry.getKey() + " ALTER FOREIGN KEY " + fk + " ENFORCED" );
}
}
LOG.log( Level.FINEST, "Enabling foreign keys: END" );
LOG.log( Level.FINEST, "Committing: START" );
c.commit();
LOG.log( Level.FINEST, "Committing: END" );
}
catch (SQLException e) {
try {
c.rollback();
}
catch (SQLException e1) {
e.addSuppressed( e1 );
}
throw new RuntimeException( e );
}
}
}
| DB2DatabaseCleaner |
java | junit-team__junit5 | junit-platform-launcher/src/main/java/org/junit/platform/launcher/listeners/discovery/LauncherDiscoveryListeners.java | {
"start": 1058,
"end": 3203
} | class ____ {
private LauncherDiscoveryListeners() {
}
/**
* Create a {@link LauncherDiscoveryListener} that aborts test discovery on
* failures.
*
* <p>The following events are considered failures:
*
* <ul>
* <li>
* any recoverable {@link Throwable} thrown by
* {@link TestEngine#discover}.
* </li>
* </ul>
*/
public static LauncherDiscoveryListener abortOnFailure() {
return new AbortOnFailureLauncherDiscoveryListener();
}
/**
* Create a {@link LauncherDiscoveryListener} that logs test discovery
* events based on their severity.
*
* <p>For example, failures during test discovery are logged as errors.
*/
public static LauncherDiscoveryListener logging() {
return new LoggingLauncherDiscoveryListener();
}
@API(status = INTERNAL, since = "1.6")
public static LauncherDiscoveryListener composite(List<LauncherDiscoveryListener> listeners) {
Preconditions.notNull(listeners, "listeners must not be null");
Preconditions.containsNoNullElements(listeners, "listeners must not contain any null elements");
if (listeners.isEmpty()) {
return LauncherDiscoveryListener.NOOP;
}
if (listeners.size() == 1) {
return listeners.get(0);
}
return new CompositeLauncherDiscoveryListener(listeners);
}
@API(status = INTERNAL, since = "1.6")
public static LauncherDiscoveryListener fromConfigurationParameter(String key, String value) {
return Arrays.stream(LauncherDiscoveryListenerType.values()) //
.filter(type -> type.parameterValue.equalsIgnoreCase(value)) //
.findFirst() //
.map(type -> type.creator.get()) //
.orElseThrow(() -> newInvalidConfigurationParameterException(key, value));
}
private static JUnitException newInvalidConfigurationParameterException(String key, String value) {
String allowedValues = Arrays.stream(LauncherDiscoveryListenerType.values()) //
.map(type -> type.parameterValue) //
.collect(joining("', '", "'", "'"));
return new JUnitException("Invalid value of configuration parameter '" + key + "': " //
+ value + " (allowed are " + allowedValues + ")");
}
private | LauncherDiscoveryListeners |
java | apache__camel | components/camel-quartz/src/test/java/org/apache/camel/component/quartz/QuartzCronRouteWithSmallCacheTest.java | {
"start": 1373,
"end": 2463
} | class ____ extends BaseQuartzTest {
private final CountDownLatch latch = new CountDownLatch(3);
@Test
public void testQuartzCronRouteWithSmallCache() throws Exception {
boolean wait = latch.await(10, TimeUnit.SECONDS);
assertTrue(wait);
assertTrue(latch.getCount() <= 0, "Quartz should trigger at least 3 times");
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
context.getGlobalOptions().put(Exchange.MAXIMUM_ENDPOINT_CACHE_SIZE, "1");
return context;
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:foo").to("log:foo");
from("quartz://myGroup/myTimerName?cron=0/2+*+*+*+*+?").process(exchange -> {
latch.countDown();
template.sendBody("direct:foo", "Quartz triggered");
});
}
};
}
}
| QuartzCronRouteWithSmallCacheTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/rawcoder/ByteArrayDecodingState.java | {
"start": 1022,
"end": 1138
} | class ____ maintains decoding state during a decode call using
* byte array inputs.
*/
@InterfaceAudience.Private
| that |
java | quarkusio__quarkus | integration-tests/spring-data-jpa/src/test/java/io/quarkus/it/spring/data/jpa/complex/ParentTest.java | {
"start": 503,
"end": 1367
} | class ____ {
@Test
@Order(1)
void noEntities() {
when().get("/complex/parents/p1/1")
.then()
.statusCode(204);
when().get("/complex/parents/p2/1")
.then()
.statusCode(204);
}
@Test
@Order(2)
void createParent() {
given().accept(ContentType.JSON).when().post("/complex/parents/1")
.then()
.statusCode(200)
.body("id", is(1));
}
@Test
@Order(3)
void existingEntities() {
when().get("/complex/parents/p1/1?name=Test")
.then()
.statusCode(200)
.body("age", is(50));
when().get("/complex/parents/p2/1?name=Test")
.then()
.statusCode(200)
.body("age", is(50));
}
}
| ParentTest |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/PassThroughConfigUpdate.java | {
"start": 1050,
"end": 4730
} | class ____ extends NlpConfigUpdate implements NamedXContentObject {
public static final String NAME = PassThroughConfig.NAME;
public static PassThroughConfigUpdate fromMap(Map<String, Object> map) {
Map<String, Object> options = new HashMap<>(map);
String resultsField = (String) options.remove(RESULTS_FIELD.getPreferredName());
TokenizationUpdate tokenizationUpdate = NlpConfigUpdate.tokenizationFromMap(options);
if (options.isEmpty() == false) {
throw ExceptionsHelper.badRequestException("Unrecognized fields {}.", options.keySet());
}
return new PassThroughConfigUpdate(resultsField, tokenizationUpdate);
}
private static final ObjectParser<PassThroughConfigUpdate.Builder, Void> STRICT_PARSER = createParser(false);
private static ObjectParser<PassThroughConfigUpdate.Builder, Void> createParser(boolean lenient) {
ObjectParser<PassThroughConfigUpdate.Builder, Void> parser = new ObjectParser<>(
NAME,
lenient,
PassThroughConfigUpdate.Builder::new
);
parser.declareString(PassThroughConfigUpdate.Builder::setResultsField, RESULTS_FIELD);
parser.declareNamedObject(
PassThroughConfigUpdate.Builder::setTokenizationUpdate,
(p, c, n) -> p.namedObject(TokenizationUpdate.class, n, lenient),
TOKENIZATION
);
return parser;
}
public static PassThroughConfigUpdate fromXContentStrict(XContentParser parser) {
return STRICT_PARSER.apply(parser, null).build();
}
private final String resultsField;
public PassThroughConfigUpdate(String resultsField, TokenizationUpdate tokenizationUpdate) {
super(tokenizationUpdate);
this.resultsField = resultsField;
}
public PassThroughConfigUpdate(StreamInput in) throws IOException {
super(in);
this.resultsField = in.readOptionalString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalString(resultsField);
}
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
if (resultsField != null) {
builder.field(RESULTS_FIELD.getPreferredName(), resultsField);
}
return builder;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public String getName() {
return NAME;
}
@Override
public boolean isSupported(InferenceConfig config) {
return config instanceof PassThroughConfig;
}
@Override
public String getResultsField() {
return resultsField;
}
@Override
public InferenceConfigUpdate.Builder<? extends InferenceConfigUpdate.Builder<?, ?>, ? extends InferenceConfigUpdate> newBuilder() {
return new PassThroughConfigUpdate.Builder().setResultsField(resultsField).setTokenizationUpdate(tokenizationUpdate);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PassThroughConfigUpdate that = (PassThroughConfigUpdate) o;
return Objects.equals(resultsField, that.resultsField) && Objects.equals(tokenizationUpdate, that.tokenizationUpdate);
}
@Override
public int hashCode() {
return Objects.hash(resultsField, tokenizationUpdate);
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersion.minimumCompatible();
}
public static | PassThroughConfigUpdate |
java | google__auto | factory/src/test/resources/expected/SimpleClassVarargsFactory.java | {
"start": 841,
"end": 1541
} | class ____ implements SimpleClassVarargs.InterfaceWithVarargs {
@Inject
SimpleClassVarargsFactory() {}
SimpleClassVarargs create(String... args) {
return new SimpleClassVarargs(checkNotNull(args, 1, 1));
}
@Override
public SimpleClassVarargs build(String... args) {
return create(args);
}
private static <T> T checkNotNull(T reference, int argumentNumber, int argumentCount) {
if (reference == null) {
throw new NullPointerException(
"@AutoFactory method argument is null but is not marked @Nullable. Argument "
+ argumentNumber
+ " of "
+ argumentCount);
}
return reference;
}
}
| SimpleClassVarargsFactory |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/annotations/SQLUpdates.java | {
"start": 446,
"end": 493
} | interface ____ {
SQLUpdate[] value();
}
| SQLUpdates |
java | quarkusio__quarkus | extensions/panache/hibernate-orm-rest-data-panache/deployment/src/test/java/io/quarkus/hibernate/orm/rest/data/panache/deployment/repository/PanacheRepositoryResourcePostMethodTest.java | {
"start": 260,
"end": 845
} | class ____ extends AbstractPostMethodTest {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(Collection.class, CollectionsResource.class, CollectionsRepository.class,
AbstractEntity.class, AbstractItem.class, Item.class, ItemsResource.class,
ItemsRepository.class)
.addAsResource("application.properties")
.addAsResource("import.sql"));
}
| PanacheRepositoryResourcePostMethodTest |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/StreamTaskStateInitializerImplTest.java | {
"start": 4348,
"end": 17764
} | class ____ {
@Test
void testNoRestore() throws Exception {
HashMapStateBackend stateBackend = spy(new HashMapStateBackend());
// No job manager provided state to restore
StreamTaskStateInitializer streamTaskStateManager =
streamTaskStateManager(
stateBackend,
null,
new SubTaskInitializationMetricsBuilder(
SystemClock.getInstance().absoluteTimeMillis()),
true);
OperatorID operatorID = new OperatorID(47L, 11L);
AbstractStreamOperator<?> streamOperator = mock(AbstractStreamOperator.class);
when(streamOperator.getOperatorID()).thenReturn(operatorID);
TypeSerializer<?> typeSerializer = new IntSerializer();
CloseableRegistry closeableRegistry = new CloseableRegistry();
StreamOperatorStateContext stateContext =
streamTaskStateManager.streamOperatorStateContext(
streamOperator.getOperatorID(),
streamOperator.getClass().getSimpleName(),
new TestProcessingTimeService(),
streamOperator,
typeSerializer,
closeableRegistry,
new UnregisteredMetricsGroup(),
1.0,
false,
false);
OperatorStateBackend operatorStateBackend = stateContext.operatorStateBackend();
CheckpointableKeyedStateBackend<?> keyedStateBackend = stateContext.keyedStateBackend();
InternalTimeServiceManager<?> timeServiceManager =
stateContext.internalTimerServiceManager();
CloseableIterable<KeyGroupStatePartitionStreamProvider> keyedStateInputs =
stateContext.rawKeyedStateInputs();
CloseableIterable<StatePartitionStreamProvider> operatorStateInputs =
stateContext.rawOperatorStateInputs();
assertThat(stateContext.isRestored())
.as("Expected the context to NOT be restored")
.isFalse();
assertThat(operatorStateBackend).isNotNull();
assertThat(keyedStateBackend).isNotNull();
assertThat(timeServiceManager).isNotNull();
assertThat(keyedStateInputs).isNotNull();
assertThat(operatorStateInputs).isNotNull();
checkCloseablesRegistered(
closeableRegistry,
operatorStateBackend,
keyedStateBackend,
keyedStateInputs,
operatorStateInputs);
assertThat(keyedStateInputs.iterator()).isExhausted();
assertThat(operatorStateInputs.iterator()).isExhausted();
}
@SuppressWarnings("unchecked")
@Test
void testWithRestore() throws Exception {
StateBackend mockingBackend =
spy(
new StateBackend() {
@Override
public <K> AbstractKeyedStateBackend<K> createKeyedStateBackend(
KeyedStateBackendParameters<K> parameters) throws Exception {
return mock(AbstractKeyedStateBackend.class);
}
@Override
public OperatorStateBackend createOperatorStateBackend(
OperatorStateBackendParameters parameters) throws Exception {
return mock(OperatorStateBackend.class);
}
});
OperatorID operatorID = new OperatorID(47L, 11L);
TaskStateSnapshot taskStateSnapshot = new TaskStateSnapshot();
Random random = new Random(0x42);
OperatorSubtaskState operatorSubtaskState =
OperatorSubtaskState.builder()
.setManagedOperatorState(
new OperatorStreamStateHandle(
Collections.singletonMap(
"a",
new OperatorStateHandle.StateMetaInfo(
new long[] {0, 10}, SPLIT_DISTRIBUTE)),
CheckpointTestUtils.createDummyStreamStateHandle(
random, null)))
.setRawOperatorState(
new OperatorStreamStateHandle(
Collections.singletonMap(
"_default_",
new OperatorStateHandle.StateMetaInfo(
new long[] {0, 20, 30}, SPLIT_DISTRIBUTE)),
CheckpointTestUtils.createDummyStreamStateHandle(
random, null)))
.setManagedKeyedState(
CheckpointTestUtils.createDummyKeyGroupStateHandle(random, null))
.setRawKeyedState(
CheckpointTestUtils.createDummyKeyGroupStateHandle(random, null))
.setInputChannelState(
singleton(createNewInputChannelStateHandle(10, random)))
.setResultSubpartitionState(
singleton(createNewResultSubpartitionStateHandle(10, random)))
.build();
taskStateSnapshot.putSubtaskStateByOperatorID(operatorID, operatorSubtaskState);
JobManagerTaskRestore jobManagerTaskRestore =
new JobManagerTaskRestore(42L, taskStateSnapshot);
SubTaskInitializationMetricsBuilder metricsBuilder =
new SubTaskInitializationMetricsBuilder(
SystemClock.getInstance().absoluteTimeMillis());
StreamTaskStateInitializer streamTaskStateManager =
streamTaskStateManager(
mockingBackend, jobManagerTaskRestore, metricsBuilder, false);
AbstractStreamOperator<?> streamOperator = mock(AbstractStreamOperator.class);
when(streamOperator.getOperatorID()).thenReturn(operatorID);
TypeSerializer<?> typeSerializer = new IntSerializer();
CloseableRegistry closeableRegistry = new CloseableRegistry();
StreamOperatorStateContext stateContext =
streamTaskStateManager.streamOperatorStateContext(
streamOperator.getOperatorID(),
streamOperator.getClass().getSimpleName(),
new TestProcessingTimeService(),
streamOperator,
typeSerializer,
closeableRegistry,
new UnregisteredMetricsGroup(),
1.0,
false,
false);
OperatorStateBackend operatorStateBackend = stateContext.operatorStateBackend();
CheckpointableKeyedStateBackend<?> keyedStateBackend = stateContext.keyedStateBackend();
InternalTimeServiceManager<?> timeServiceManager =
stateContext.internalTimerServiceManager();
CloseableIterable<KeyGroupStatePartitionStreamProvider> keyedStateInputs =
stateContext.rawKeyedStateInputs();
CloseableIterable<StatePartitionStreamProvider> operatorStateInputs =
stateContext.rawOperatorStateInputs();
assertThat(stateContext.isRestored()).as("Expected the context to be restored").isTrue();
assertThat(stateContext.getRestoredCheckpointId()).hasValue(42L);
assertThat(operatorStateBackend).isNotNull();
assertThat(keyedStateBackend).isNotNull();
// this is deactivated on purpose so that it does not attempt to consume the raw keyed
// state.
assertThat(timeServiceManager).isNull();
assertThat(keyedStateInputs).isNotNull();
assertThat(operatorStateInputs).isNotNull();
int count = 0;
for (KeyGroupStatePartitionStreamProvider keyedStateInput : keyedStateInputs) {
++count;
}
assertThat(count).isOne();
count = 0;
for (StatePartitionStreamProvider operatorStateInput : operatorStateInputs) {
++count;
}
assertThat(count).isEqualTo(3);
long expectedSumLocalMemory =
Stream.of(
operatorSubtaskState.getManagedOperatorState().stream(),
operatorSubtaskState.getManagedKeyedState().stream(),
operatorSubtaskState.getRawKeyedState().stream(),
operatorSubtaskState.getRawOperatorState().stream())
.flatMap(i -> i)
.mapToLong(StateObject::getStateSize)
.sum();
long expectedSumUnknown =
Stream.concat(
operatorSubtaskState.getInputChannelState().stream(),
operatorSubtaskState.getResultSubpartitionState().stream())
.mapToLong(StateObject::getStateSize)
.sum();
SubTaskInitializationMetrics metrics = metricsBuilder.build();
assertThat(metrics.getDurationMetrics())
.hasSize(2)
.containsEntry(
MetricNames.RESTORED_STATE_SIZE
+ "."
+ StateObject.StateObjectLocation.LOCAL_MEMORY.name(),
expectedSumLocalMemory)
.containsEntry(
MetricNames.RESTORED_STATE_SIZE
+ "."
+ StateObject.StateObjectLocation.UNKNOWN.name(),
expectedSumUnknown);
checkCloseablesRegistered(
closeableRegistry,
operatorStateBackend,
keyedStateBackend,
keyedStateInputs,
operatorStateInputs);
}
private static void checkCloseablesRegistered(
CloseableRegistry closeableRegistry, Closeable... closeables) {
for (Closeable closeable : closeables) {
assertThat(closeableRegistry.unregisterCloseable(closeable)).isTrue();
}
}
private StreamTaskStateInitializer streamTaskStateManager(
StateBackend stateBackend,
JobManagerTaskRestore jobManagerTaskRestore,
SubTaskInitializationMetricsBuilder metricsBuilder,
boolean createTimerServiceManager) {
JobID jobID = new JobID(42L, 43L);
ExecutionAttemptID executionAttemptID = createExecutionAttemptId();
TestCheckpointResponder checkpointResponderMock = new TestCheckpointResponder();
TaskLocalStateStore taskLocalStateStore = new TestTaskLocalStateStore();
InMemoryStateChangelogStorage changelogStorage = new InMemoryStateChangelogStorage();
TaskStateManager taskStateManager =
new TaskStateManagerImpl(
jobID,
executionAttemptID,
taskLocalStateStore,
null,
changelogStorage,
new TaskExecutorStateChangelogStoragesManager(),
jobManagerTaskRestore,
checkpointResponderMock);
DummyEnvironment dummyEnvironment =
new DummyEnvironment(
"test-task",
1,
executionAttemptID.getExecutionVertexId().getSubtaskIndex());
dummyEnvironment.setTaskStateManager(taskStateManager);
if (createTimerServiceManager) {
return new StreamTaskStateInitializerImpl(dummyEnvironment, stateBackend);
} else {
return new StreamTaskStateInitializerImpl(
dummyEnvironment,
stateBackend,
metricsBuilder,
TtlTimeProvider.DEFAULT,
new InternalTimeServiceManager.Provider() {
@Override
public <K> InternalTimeServiceManager<K> create(
TaskIOMetricGroup taskIOMetricGroup,
PriorityQueueSetFactory factory,
KeyGroupRange keyGroupRange,
ClassLoader userClassloader,
KeyContext keyContext,
ProcessingTimeService processingTimeService,
Iterable<KeyGroupStatePartitionStreamProvider> rawKeyedStates,
StreamTaskCancellationContext cancellationContext)
throws Exception {
return null;
}
},
StreamTaskCancellationContext.alwaysRunning());
}
}
}
| StreamTaskStateInitializerImplTest |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/connector/sink/abilities/SupportsBucketing.java | {
"start": 3509,
"end": 4287
} | interface ____ {
/**
* Returns the set of supported bucketing algorithms.
*
* <p>The set must be non-empty. Otherwise, the planner will throw an error during validation.
*
* <p>If specifying an algorithm is optional, this set must include {@link
* TableDistribution.Kind#UNKNOWN}.
*/
Set<TableDistribution.Kind> listAlgorithms();
/**
* Returns whether the {@link DynamicTableSink} requires a bucket count.
*
* <p>If this method returns {@code true}, the {@link DynamicTableSink} will require a bucket
* count.
*
* <p>If this method return {@code false}, the {@link DynamicTableSink} may or may not consider
* the provided bucket count.
*/
boolean requiresBucketCount();
}
| SupportsBucketing |
java | quarkusio__quarkus | extensions/security/deployment/src/test/java/io/quarkus/security/test/permissionsallowed/MethodLevelComputedPermissionsAllowedTest.java | {
"start": 8548,
"end": 12561
} | class ____ {
@PermissionsAllowed(value = IGNORED, permission = AllStrAutodetectedPermission.class)
public String autodetect(String hello, String world, String exclamationMark) {
return SUCCESS;
}
@PermissionsAllowed(value = IGNORED, permission = AllIntAutodetectedPermission.class)
public String autodetect(int one, String world, int two, int three, Object obj1, Object obj2) {
return SUCCESS;
}
@PermissionsAllowed(value = "permissionName:action1234", permission = InheritanceWithActionsPermission.class)
public String autodetect(Parent obj) {
return SUCCESS;
}
@PermissionsAllowed(value = { "permissionName:action1234",
"permission1:action1" }, permission = InheritanceWithActionsPermission.class)
public String autodetectMultiplePermissions(Parent obj) {
return SUCCESS;
}
@PermissionsAllowed(value = "permissionName:action1234", permission = InheritanceWithActionsPermission.class)
public Uni<String> autodetectNonBlocking(Parent obj) {
return Uni.createFrom().item(SUCCESS);
}
@PermissionsAllowed(value = { "permissionName:action1234",
"permission1:action1" }, permission = InheritanceWithActionsPermission.class)
public Uni<String> autodetectMultiplePermissionsNonBlocking(Parent obj) {
return Uni.createFrom().item(SUCCESS);
}
@PermissionsAllowed(value = IGNORED, permission = AllStrAutodetectedPermission.class)
public Uni<String> autodetectNonBlocking(String hello, String world, String exclamationMark) {
return Uni.createFrom().item(SUCCESS);
}
@PermissionsAllowed(value = IGNORED, permission = AllIntAutodetectedPermission.class)
public Uni<String> autodetectNonBlocking(int one, String world, int two, int three, Object obj1, Object obj2) {
return Uni.createFrom().item(SUCCESS);
}
@PermissionsAllowed(value = IGNORED, permission = AllStrMatchingParamsPermission.class, params = {
"hello", "world", "exclamationMark" })
public String explicitlyDeclaredParams(String something, String hello, String whatever, String world,
String exclamationMark, int i) {
return SUCCESS;
}
@PermissionsAllowed(value = IGNORED, permission = AllStrMatchingParamsPermission.class, params = {
"hello", "world", "exclamationMark" })
public Uni<String> explicitlyDeclaredParamsNonBlocking(String something, String hello, String whatever, String world,
String exclamationMark, int i) {
return Uni.createFrom().item(SUCCESS);
}
@PermissionsAllowed(value = IGNORED, permission = InheritancePermission.class, params = "obj")
public String explicitlyDeclaredParamsInheritance(String something, String hello, String whatever, String world,
String exclamationMark, int i, Child obj) {
return SUCCESS;
}
@PermissionsAllowed(value = IGNORED, permission = InheritancePermission.class, params = "obj")
public Uni<String> explicitlyDeclaredParamsInheritanceNonBlocking(String something, String hello, String whatever,
String world, String exclamationMark, int i, Child obj) {
return Uni.createFrom().item(SUCCESS);
}
@PermissionsAllowed("read")
@PermissionsAllowed(value = "permissionName:action1234", permission = InheritanceWithActionsPermission.class)
public Uni<String> combinationNonBlocking(Parent obj) {
return Uni.createFrom().item(SUCCESS);
}
@PermissionsAllowed("read")
@PermissionsAllowed(value = "permissionName:action1234", permission = InheritanceWithActionsPermission.class)
public String combination(Parent obj) {
return SUCCESS;
}
}
public | SecuredBean |
java | FasterXML__jackson-core | src/main/java/tools/jackson/core/base/BinaryTSFactory.java | {
"start": 248,
"end": 363
} | class ____ as the base for
* binary (non-textual) data formats.
*/
@SuppressWarnings("resource")
public abstract | used |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/vectors/AbstractIVFKnnVectorQueryTestCase.java | {
"start": 45044,
"end": 45763
} | class ____ extends FilterDirectoryReader {
private NoLiveDocsDirectoryReader(DirectoryReader in) throws IOException {
super(in, new SubReaderWrapper() {
@Override
public LeafReader wrap(LeafReader reader) {
return new NoLiveDocsLeafReader(reader);
}
});
}
@Override
protected DirectoryReader doWrapDirectoryReader(DirectoryReader in) throws IOException {
return new NoLiveDocsDirectoryReader(in);
}
@Override
public CacheHelper getReaderCacheHelper() {
return in.getReaderCacheHelper();
}
}
private static | NoLiveDocsDirectoryReader |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/ManagedDomainType.java | {
"start": 1276,
"end": 3042
} | class ____ the entity type.
*/
@Override
default Class<J> getJavaType() {
return getExpressibleJavaType().getJavaTypeClass();
}
/**
* The descriptor of the supertype of this type.
*/
@Nullable ManagedDomainType<? super J> getSuperType();
/**
* The descriptors of all known managed subtypes of this type.
*/
Collection<? extends ManagedDomainType<? extends J>> getSubTypes();
@Internal
void addSubType(ManagedDomainType<? extends J> subType);
void visitAttributes(Consumer<? super PersistentAttribute<? super J, ?>> action);
void visitDeclaredAttributes(Consumer<? super PersistentAttribute<J, ?>> action);
@Override
PersistentAttribute<? super J,?> getAttribute(String name);
@Override
PersistentAttribute<J,?> getDeclaredAttribute(String name);
@Nullable PersistentAttribute<? super J,?> findAttribute(String name);
@Nullable PersistentAttribute<?, ?> findSubTypesAttribute(String name);
/**
* @deprecated Use {@link #findAttribute(String)}
*/
@Deprecated(since = "7.0", forRemoval = true)
default @Nullable PersistentAttribute<? super J, ?> findAttributeInSuperTypes(String name) {
return findAttribute( name );
}
@Nullable SingularPersistentAttribute<? super J,?> findSingularAttribute(String name);
@Nullable PluralPersistentAttribute<? super J, ?,?> findPluralAttribute(String name);
@Nullable PersistentAttribute<? super J, ?> findConcreteGenericAttribute(String name);
@Nullable PersistentAttribute<J,?> findDeclaredAttribute(String name);
@Nullable SingularPersistentAttribute<J, ?> findDeclaredSingularAttribute(String name);
@Nullable PluralPersistentAttribute<J, ?, ?> findDeclaredPluralAttribute(String name);
@Nullable PersistentAttribute<J, ?> findDeclaredConcreteGenericAttribute(String name);
}
| of |
java | apache__camel | components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/HttpProxyManualIT.java | {
"start": 2201,
"end": 8188
} | class ____ extends AbstractSalesforceTestBase {
private static final Logger LOG = LoggerFactory.getLogger(HttpProxyManualIT.class);
private static final String HTTP_PROXY_HOST = "localhost";
private static final String HTTP_PROXY_USER_NAME = "camel-user";
private static final String HTTP_PROXY_PASSWORD = "camel-user-password";
private static final String HTTP_PROXY_REALM = "proxy-realm";
private static Server server;
private static int httpProxyPort;
private static final AtomicBoolean WENT_THROUGH_PROXY = new AtomicBoolean();
@Parameter
private Consumer<SalesforceComponent> configurationMethod;
@Parameters
public static Iterable<Consumer<SalesforceComponent>> methods() {
return Arrays.asList(HttpProxyManualIT::configureProxyViaComponentProperties,
HttpProxyManualIT::configureProxyViaClientPropertiesMap);
}
@Test
public void testGetVersions() throws Exception {
doTestGetVersions("");
doTestGetVersions("Xml");
assertTrue(WENT_THROUGH_PROXY.get(), "Should have gone through the test proxy");
}
@SuppressWarnings("unchecked")
private void doTestGetVersions(String suffix) throws Exception {
// test getVersions doesn't need a body
// assert expected result
Object o = template().requestBody("direct:getVersions" + suffix, (Object) null);
List<Version> versions = null;
if (o instanceof Versions) {
versions = ((Versions) o).getVersions();
} else {
versions = (List<Version>) o;
}
assertNotNull(versions);
LOG.debug("Versions: {}", versions);
}
@BeforeAll
public static void setupServer() throws Exception {
// start a local HTTP proxy using Jetty server
server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setHost(HTTP_PROXY_HOST);
server.addConnector(connector);
final String authenticationString
= "Basic " + Base64.getEncoder().encodeToString(
(HTTP_PROXY_USER_NAME + ":" + HTTP_PROXY_PASSWORD).getBytes(StandardCharsets.ISO_8859_1));
ConnectHandler connectHandler = new ConnectHandler() {
@Override
protected boolean handleAuthentication(Request request, Response response, String address) {
// validate proxy-authentication header
final String header = request.getHeaders().get(PROXY_AUTHORIZATION.toString());
if (!authenticationString.equals(header)) {
LOG.warn("Missing header {}", PROXY_AUTHORIZATION);
// ask for authentication header
response.getHeaders().add(PROXY_AUTHENTICATE.toString(),
String.format("Basic realm=\"%s\"", HTTP_PROXY_REALM));
return false;
}
LOG.info("Request contains required header {}", PROXY_AUTHORIZATION);
WENT_THROUGH_PROXY.set(true);
return true;
}
};
server.setHandler(connectHandler);
LOG.info("Starting proxy server...");
server.start();
httpProxyPort = connector.getLocalPort();
LOG.info("Started proxy server on port {}", httpProxyPort);
}
@Override
protected void createComponent() throws Exception {
super.createComponent();
final SalesforceComponent salesforce = (SalesforceComponent) context().getComponent("salesforce");
// set HTTP client properties
final HashMap<String, Object> properties = new HashMap<>();
properties.put("timeout", "60000");
properties.put("removeIdleDestinations", "true");
salesforce.setHttpClientProperties(properties);
configurationMethod.accept(salesforce);
}
@AfterAll
public static void cleanup() throws Exception {
// stop the proxy server after component
LOG.info("Stopping proxy server...");
server.stop();
LOG.info("Stopped proxy server");
}
@Override
protected RouteBuilder doCreateRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// testGetVersion
from("direct:getVersions").to("salesforce:getVersions");
// allow overriding format per endpoint
from("direct:getVersionsXml").to("salesforce:getVersions?format=XML");
}
};
}
private static void configureProxyViaComponentProperties(final SalesforceComponent salesforce) {
salesforce.setHttpProxyHost(HTTP_PROXY_HOST);
salesforce.setHttpProxyPort(httpProxyPort);
salesforce.setHttpProxySecure(false);
salesforce.setHttpProxyUsername(HTTP_PROXY_USER_NAME);
salesforce.setHttpProxyPassword(HTTP_PROXY_PASSWORD);
salesforce.setHttpProxyAuthUri(String.format("http://%s:%s", HTTP_PROXY_HOST, httpProxyPort));
salesforce.setHttpProxyRealm(HTTP_PROXY_REALM);
}
private static void configureProxyViaClientPropertiesMap(final SalesforceComponent salesforce) {
final Map<String, Object> properties = salesforce.getHttpClientProperties();
properties.put(SalesforceComponent.HTTP_PROXY_HOST, HTTP_PROXY_HOST);
properties.put(SalesforceComponent.HTTP_PROXY_PORT, httpProxyPort);
properties.put(SalesforceComponent.HTTP_PROXY_IS_SECURE, false);
properties.put(SalesforceComponent.HTTP_PROXY_USERNAME, HTTP_PROXY_USER_NAME);
properties.put(SalesforceComponent.HTTP_PROXY_PASSWORD, HTTP_PROXY_PASSWORD);
properties.put(SalesforceComponent.HTTP_PROXY_AUTH_URI, String.format("http://%s:%s", HTTP_PROXY_HOST, httpProxyPort));
properties.put(SalesforceComponent.HTTP_PROXY_REALM, HTTP_PROXY_REALM);
}
}
| HttpProxyManualIT |
java | mockito__mockito | mockito-extensions/mockito-junit-jupiter/src/test/java/org/mockitousage/GenericTypeMockTest.java | {
"start": 9463,
"end": 10111
} | class ____ extends ArrayList<String> {}
@Mock ConcreteStringList concreteStringList;
@InjectMocks
UnderTestWithTypeParameter<Integer> underTestWithTypeParameters =
new UnderTestWithTypeParameter<Integer>();
@Test
void testWithTypeParameters() {
assertNotNull(concreteStringList);
// verify that when no concrete type candidate matches, none is injected
assertNull(underTestWithTypeParameters.tList);
}
}
/**
* Verify regression https://github.com/mockito/mockito/issues/2958 is fixed.
*/
@Nested
public | ConcreteStringList |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/WatsonTextToSpeechEndpointBuilderFactory.java | {
"start": 14693,
"end": 15070
} | class ____ extends AbstractEndpointBuilder implements WatsonTextToSpeechEndpointBuilder, AdvancedWatsonTextToSpeechEndpointBuilder {
public WatsonTextToSpeechEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new WatsonTextToSpeechEndpointBuilderImpl(path);
}
} | WatsonTextToSpeechEndpointBuilderImpl |
java | apache__camel | components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlConsumerOutputTypeSelectOneTest.java | {
"start": 1517,
"end": 5765
} | class ____ {
private EmbeddedDatabase db;
private DefaultCamelContext camel1;
@BeforeEach
public void setUp() {
db = new EmbeddedDatabaseBuilder()
.setName(getClass().getSimpleName())
.setType(EmbeddedDatabaseType.H2)
.addScript("sql/createAndPopulateDatabase.sql").build();
camel1 = new DefaultCamelContext();
camel1.getCamelContextExtension().setName("camel-1");
camel1.getComponent("sql", SqlComponent.class).setDataSource(db);
}
@AfterEach
public void tearDown() {
camel1.stop();
if (db != null) {
db.shutdown();
}
}
@Test
public void testSelectOneWithClass() throws Exception {
camel1.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("sql:select * from projects where id=3?outputType=SelectOne&outputClass=org.apache.camel.component.sql.ProjectModel&initialDelay=0&delay=50")
.to("mock:result");
}
});
camel1.start();
MockEndpoint mock = (MockEndpoint) camel1.getEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.assertIsSatisfied(2000);
List<Exchange> exchanges = mock.getReceivedExchanges();
assertThat(exchanges.size(), CoreMatchers.is(1));
ProjectModel result = exchanges.get(0).getIn().getBody(ProjectModel.class);
assertThat(result.getId(), CoreMatchers.is(3));
assertThat(result.getProject(), CoreMatchers.is("Linux"));
assertThat(result.getLicense(), CoreMatchers.is("XXX"));
}
@Test
public void testSelectOneWithoutClass() throws Exception {
camel1.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("sql:select * from projects where id=3?outputType=SelectOne&initialDelay=0&delay=50")
.to("mock:result");
}
});
camel1.start();
MockEndpoint mock = (MockEndpoint) camel1.getEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.assertIsSatisfied(2000);
List<Exchange> exchanges = mock.getReceivedExchanges();
assertThat(exchanges.size(), CoreMatchers.is(1));
Map<String, Object> result = exchanges.get(0).getIn().getBody(Map.class);
assertThat((Integer) result.get("ID"), CoreMatchers.is(3));
assertThat((String) result.get("PROJECT"), CoreMatchers.is("Linux"));
assertThat((String) result.get("LICENSE"), CoreMatchers.is("XXX"));
}
@Test
public void testSelectOneSingleColumn() throws Exception {
camel1.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("sql:select project from projects where id=3?outputType=SelectOne&initialDelay=0&delay=50")
.to("mock:result");
}
});
camel1.start();
MockEndpoint mock = (MockEndpoint) camel1.getEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.assertIsSatisfied(2000);
List<Exchange> exchanges = mock.getReceivedExchanges();
assertThat(exchanges.size(), CoreMatchers.is(1));
String result = exchanges.get(0).getIn().getBody(String.class);
assertThat(result, CoreMatchers.is("Linux"));
}
@Test
public void testSelectOneSingleColumnCount() throws Exception {
camel1.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("sql:select count(*) from projects?outputType=SelectOne&initialDelay=0&delay=50")
.to("mock:result");
}
});
camel1.start();
MockEndpoint mock = (MockEndpoint) camel1.getEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.assertIsSatisfied(2000);
List<Exchange> exchanges = mock.getReceivedExchanges();
assertThat(exchanges.size(), CoreMatchers.is(1));
Long result = exchanges.get(0).getIn().getBody(Long.class);
assertThat(result, CoreMatchers.is(3L));
}
}
| SqlConsumerOutputTypeSelectOneTest |
java | apache__camel | tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/PackageLanguageMojo.java | {
"start": 12116,
"end": 17657
} | class ____ find functionClass and add each field as a function in the model
Class<?> classElement = loadClass(javaType.getName());
final Language lan = classElement.getAnnotation(Language.class);
if (lan.functionsClass() != void.class) {
classElement = loadClass(lan.functionsClass().getName());
if (classElement != null) {
for (Field field : classElement.getFields()) {
final boolean isEnum = classElement.isEnum();
if ((isEnum || isStatic(field.getModifiers()) && field.getType() == String.class)
&& field.isAnnotationPresent(Metadata.class)) {
try {
addFunction(model, field);
} catch (Exception e) {
getLog().warn(e);
}
}
}
}
}
return model;
}
private void addFunction(LanguageModel model, Field field) throws Exception {
final Class<?> declaringClass = field.getDeclaringClass();
final Metadata cm = declaringClass.getAnnotation(Metadata.class);
String prefix = null;
String suffix = null;
if (cm != null && cm.annotations() != null) {
for (String s : cm.annotations()) {
prefix = Strings.after(s, "prefix=", prefix);
suffix = Strings.after(s, "suffix=", suffix);
}
}
final Metadata metadata = field.getAnnotation(Metadata.class);
LanguageModel.LanguageFunctionModel fun = new LanguageModel.LanguageFunctionModel();
fun.setConstantName(String.format("%s#%s", declaringClass.getName(), field.getName()));
fun.setName((String) field.get(null));
fun.setPrefix(prefix);
fun.setSuffix(suffix);
fun.setDescription(metadata.description().trim());
fun.setKind("function");
String displayName = metadata.displayName();
// compute a display name if we don't have anything
if (Strings.isNullOrEmpty(displayName)) {
displayName = fun.getName();
int pos = displayName.indexOf('(');
if (pos == -1) {
pos = displayName.indexOf(':');
}
if (pos == -1) {
pos = displayName.indexOf('.');
}
if (pos != -1) {
displayName = displayName.substring(0, pos);
}
displayName = displayName.replace('-', ' ');
displayName = Strings.asTitle(displayName);
}
fun.setDisplayName(displayName);
fun.setJavaType(metadata.javaType());
fun.setRequired(metadata.required());
fun.setDefaultValue(metadata.defaultValue());
fun.setDeprecated(field.isAnnotationPresent(Deprecated.class));
fun.setDeprecationNote(metadata.deprecationNote());
fun.setSecret(metadata.secret());
String label = metadata.label();
boolean ognl = false;
if (label.contains(",ognl")) {
ognl = true;
label = label.replace(",ognl", "");
}
String group = EndpointHelper.labelAsGroupName(label, false, false);
fun.setGroup(group);
fun.setLabel(label);
fun.setOgnl(ognl);
model.addFunction(fun);
}
private static String readClassFromCamelResource(File file, StringBuilder buffer, BuildContext buildContext)
throws MojoExecutionException {
// skip directories as there may be a sub .resolver directory such as in
// camel-script
if (file.isDirectory()) {
return null;
}
String name = file.getName();
if (name.charAt(0) != '.') {
if (!buffer.isEmpty()) {
buffer.append(" ");
}
buffer.append(name);
}
if (!buildContext.hasDelta(file)) {
// if this file has not changed,
// then no need to store the javatype
// for the json file to be generated again
// (but we do need the name above!)
return null;
}
// find out the javaType for each data format
try {
String text = PackageHelper.loadText(file);
Map<String, String> map = PackageHelper.parseAsMap(text);
return map.get("class");
} catch (IOException e) {
throw new MojoExecutionException("Failed to read file " + file + ". Reason: " + e, e);
}
}
private static String asModelName(String name) {
// special for some languages
if ("bean".equals(name)) {
return "method";
} else if ("file".equals(name)) {
return "simple";
}
return name;
}
private static String asTitle(String name, String title) {
// special for some languages
if ("file".equals(name)) {
return "File";
}
return title;
}
private static String asDescription(String name, String description) {
// special for some languages
if ("file".equals(name)) {
return "File related capabilities for the Simple language";
}
return description;
}
private static String schemaSubDirectory(String javaType) {
int idx = javaType.lastIndexOf('.');
String pckName = javaType.substring(0, idx);
return "META-INF/" + pckName.replace('.', '/');
}
}
| and |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/rest/action/RestQueryWatchesAction.java | {
"start": 782,
"end": 1713
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(GET, "/_watcher/_query/watches"), new Route(POST, "/_watcher/_query/watches"));
}
@Override
public String getName() {
return "watcher_query_watches";
}
@Override
protected RestChannelConsumer prepareRequest(final RestRequest request, NodeClient client) throws IOException {
final QueryWatchesAction.Request queryWatchesRequest;
if (request.hasContentOrSourceParam()) {
queryWatchesRequest = QueryWatchesAction.Request.fromXContent(request.contentOrSourceParamParser());
} else {
queryWatchesRequest = new QueryWatchesAction.Request(null, null, null, null, null);
}
return channel -> client.execute(QueryWatchesAction.INSTANCE, queryWatchesRequest, new RestToXContentListener<>(channel));
}
}
| RestQueryWatchesAction |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/arm-java/org/apache/hadoop/ipc/protobuf/TestRpcServiceProtosLegacy.java | {
"start": 115347,
"end": 117433
} | class ____ extends org.apache.hadoop.ipc.protobuf.TestRpcServiceProtosLegacy.NewProtobufRpcProto implements Interface {
private Stub(com.google.protobuf.RpcChannel channel) {
this.channel = channel;
}
private final com.google.protobuf.RpcChannel channel;
public com.google.protobuf.RpcChannel getChannel() {
return channel;
}
public void ping(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyRequestProto request,
com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto> done) {
channel.callMethod(
getDescriptor().getMethods().get(0),
controller,
request,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.getDefaultInstance(),
com.google.protobuf.RpcUtil.generalizeCallback(
done,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.class,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.EmptyResponseProto.getDefaultInstance()));
}
public void echo(
com.google.protobuf.RpcController controller,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptRequestProto request,
com.google.protobuf.RpcCallback<org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptResponseProto> done) {
channel.callMethod(
getDescriptor().getMethods().get(1),
controller,
request,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptResponseProto.getDefaultInstance(),
com.google.protobuf.RpcUtil.generalizeCallback(
done,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptResponseProto.class,
org.apache.hadoop.ipc.protobuf.TestProtosLegacy.OptResponseProto.getDefaultInstance()));
}
}
public static BlockingInterface newBlockingStub(
com.google.protobuf.BlockingRpcChannel channel) {
return new BlockingStub(channel);
}
public | Stub |
java | google__truth | extensions/proto/src/main/java/com/google/common/truth/extensions/proto/FieldDescriptorValidator.java | {
"start": 937,
"end": 2793
} | enum ____ {
ALLOW_ALL() {
@Override
void validate(FieldDescriptor fieldDescriptor) {}
},
IS_FIELD_WITH_ABSENCE() {
@Override
void validate(FieldDescriptor fieldDescriptor) {
checkArgument(
!fieldDescriptor.isRepeated(),
"%s is a repeated field; repeated fields cannot be absent, only empty",
fieldDescriptor);
checkArgument(
fieldDescriptor.hasPresence(),
"%s is a field without presence; it cannot be absent",
fieldDescriptor);
}
},
IS_FIELD_WITH_ORDER() {
@Override
void validate(FieldDescriptor fieldDescriptor) {
checkArgument(
!fieldDescriptor.isMapField(), "%s is a map field; it has no order", fieldDescriptor);
checkArgument(
fieldDescriptor.isRepeated(),
"%s is not a repeated field; it has no order",
fieldDescriptor);
}
},
IS_FIELD_WITH_EXTRA_ELEMENTS() {
@Override
void validate(FieldDescriptor fieldDescriptor) {
checkArgument(
fieldDescriptor.isRepeated(),
"%s is not a repeated field or a map field; it cannot contain extra elements",
fieldDescriptor);
}
},
IS_DOUBLE_FIELD() {
@Override
void validate(FieldDescriptor fieldDescriptor) {
checkArgument(
fieldDescriptor.getJavaType() == JavaType.DOUBLE,
"%s is not a double field",
fieldDescriptor);
}
},
IS_FLOAT_FIELD() {
@Override
void validate(FieldDescriptor fieldDescriptor) {
checkArgument(
fieldDescriptor.getJavaType() == JavaType.FLOAT,
"%s is not a float field",
fieldDescriptor);
}
};
/** Validates the given {@link FieldDescriptor} according to this instance's rules. */
abstract void validate(FieldDescriptor fieldDescriptor);
}
| FieldDescriptorValidator |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/clause/PartitionExtensionClause.java | {
"start": 915,
"end": 2181
} | class ____ extends OracleSQLObjectImpl {
private boolean subPartition;
private SQLName partition;
private final List<SQLName> target = new ArrayList<SQLName>();
public boolean isSubPartition() {
return subPartition;
}
public void setSubPartition(boolean subPartition) {
this.subPartition = subPartition;
}
public SQLName getPartition() {
return partition;
}
public void setPartition(SQLName partition) {
this.partition = partition;
}
public List<SQLName> getFor() {
return target;
}
@Override
public void accept0(OracleASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, partition);
acceptChild(visitor, target);
}
visitor.endVisit(this);
}
public PartitionExtensionClause clone() {
PartitionExtensionClause x = new PartitionExtensionClause();
x.subPartition = subPartition;
if (partition != null) {
x.setPartition(partition.clone());
}
for (SQLName item : target) {
SQLName item1 = item.clone();
item1.setParent(x);
x.target.add(item1);
}
return x;
}
}
| PartitionExtensionClause |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/impl/DefaultInjectorTest.java | {
"start": 2160,
"end": 2431
} | class ____ {
private static final MyOtherBean me = new MyOtherBean();
public static MyOtherBean getInstance() {
return me;
}
public Object doSomething(String body) {
return body + body;
}
}
}
| MyOtherBean |
java | apache__camel | tooling/maven/camel-eip-documentation-enricher-maven-plugin/src/main/java/org/apache/camel/maven/DomFinder.java | {
"start": 1085,
"end": 2334
} | class ____ {
private final Document document;
private final XPath xPath;
public DomFinder(Document document, XPath xPath) {
this.document = document;
this.xPath = xPath;
}
public NodeList findElementsAndTypes() throws XPathExpressionException {
return (NodeList) xPath.compile("/xs:schema/xs:element")
.evaluate(document, XPathConstants.NODESET);
}
public NodeList findAttributesElements(String name) throws XPathExpressionException {
return (NodeList) xPath.compile(
"/xs:schema/xs:complexType[@name='" + name + "']//xs:attribute")
.evaluate(document, XPathConstants.NODESET);
}
public NodeList findElementsElements(String name) throws XPathExpressionException {
return (NodeList) xPath.compile(
"/xs:schema/xs:complexType[@name='" + name + "']//xs:element")
.evaluate(document, XPathConstants.NODESET);
}
public String findBaseType(String name) throws XPathExpressionException {
return (String) xPath.compile(
"/xs:schema/xs:complexType[@name='" + name + "']//xs:extension/@base")
.evaluate(document, XPathConstants.STRING);
}
}
| DomFinder |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/aggregate/AvgOverTime.java | {
"start": 1652,
"end": 4403
} | class ____ extends TimeSeriesAggregateFunction implements OptionalArgument, SurrogateExpression {
public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(
Expression.class,
"AvgOverTime",
AvgOverTime::new
);
@FunctionInfo(
returnType = "double",
description = "Calculates the average over time of a numeric field.",
type = FunctionType.TIME_SERIES_AGGREGATE,
appliesTo = { @FunctionAppliesTo(lifeCycle = FunctionAppliesToLifecycle.PREVIEW, version = "9.2.0") },
preview = true,
examples = { @Example(file = "k8s-timeseries", tag = "avg_over_time") }
)
public AvgOverTime(
Source source,
@Param(
name = "number",
type = { "aggregate_metric_double", "double", "integer", "long" },
description = "Expression that outputs values to average."
) Expression field,
@Param(
name = "window",
type = { "time_duration" },
description = "the time window over which to compute the average",
optional = true
) Expression window
) {
this(source, field, Literal.TRUE, Objects.requireNonNullElse(window, NO_WINDOW));
}
public AvgOverTime(Source source, Expression field, Expression filter, Expression window) {
super(source, field, filter, window, emptyList());
}
private AvgOverTime(StreamInput in) throws IOException {
super(in);
}
@Override
protected TypeResolution resolveType() {
return perTimeSeriesAggregation().resolveType();
}
@Override
public String getWriteableName() {
return ENTRY.name;
}
@Override
public DataType dataType() {
return perTimeSeriesAggregation().dataType();
}
@Override
protected NodeInfo<AvgOverTime> info() {
return NodeInfo.create(this, AvgOverTime::new, field(), filter(), window());
}
@Override
public AvgOverTime replaceChildren(List<Expression> newChildren) {
return new AvgOverTime(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2));
}
@Override
public AvgOverTime withFilter(Expression filter) {
return new AvgOverTime(source(), field(), filter, window());
}
@Override
public Expression surrogate() {
Source s = source();
Expression f = field();
return new Div(s, new SumOverTime(s, f, filter(), window()), new CountOverTime(s, f, filter(), window()), dataType());
}
@Override
public AggregateFunction perTimeSeriesAggregation() {
return new Avg(source(), field(), filter(), window(), SummationMode.LOSSY_LITERAL);
}
}
| AvgOverTime |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/kstream/TimeWindowedCogroupedKStream.java | {
"start": 1365,
"end": 17136
} | interface ____<K, V> {
/**
* Aggregate the values of records in this stream by the grouped key and defined windows.
* Records with {@code null} key or value are ignored.
* The result is written into a local {@link WindowStore} (which is basically an ever-updating materialized view).
* Furthermore, updates to the store are sent downstream into a {@link KTable} changelog stream.
* <p>
* The specified {@link Initializer} is applied directly before the first input record (per key) in each window is
* processed to provide an initial intermediate aggregation result that is used to process the first record for
* the window (per key).
* The specified {@link Aggregator} (as specified in {@link KGroupedStream#cogroup(Aggregator)} or
* {@link CogroupedKStream#cogroup(KGroupedStream, Aggregator)}) is applied for each input record and computes a new
* aggregate using the current aggregate (or for the very first record using the intermediate aggregation result
* provided via the {@link Initializer}) and the record's value.
* Thus, {@code aggregate()} can be used to compute aggregate functions like count or sum etc.
* <p>
* The default key and value serde from the config will be used for serializing the result.
* If a different serde is required then you should use {@link #aggregate(Initializer, Materialized)}.
* Not all updates might get sent downstream, as an internal cache is used to deduplicate consecutive updates to
* the same window and key.
* The rate of propagated updates depends on your input data rate, the number of distinct keys, the number of
* parallel running Kafka Streams instances, and the {@link StreamsConfig configuration} parameters for
* {@link StreamsConfig#STATESTORE_CACHE_MAX_BYTES_CONFIG cache size}, and
* {@link StreamsConfig#COMMIT_INTERVAL_MS_CONFIG commit interval}.
* <p>
* For failure and recovery the store (which always will be of type {@link TimestampedWindowStore}) will be backed by
* an internal changelog topic that will be created in Kafka.
* The changelog topic will be named "${applicationId}-${internalStoreName}-changelog", where "applicationId" is
* user-specified in {@link StreamsConfig} via parameter
* {@link StreamsConfig#APPLICATION_ID_CONFIG APPLICATION_ID_CONFIG}, "internalStoreName" is an internal name
* and "-changelog" is a fixed suffix.
* Note that the internal store name may not be queryable through Interactive Queries.
* <p>
* You can retrieve all generated internal topic names via {@link Topology#describe()}.
*
* @param initializer an {@link Initializer} that computes an initial intermediate aggregation result. Cannot be {@code null}.
* @return a windowed {@link KTable} that contains "update" records with unmodified keys, and values that represent
* the latest (rolling) aggregate for each key within a window
*/
KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer);
/**
* Aggregate the values of records in this stream by the grouped key and defined windows.
* Records with {@code null} key or value are ignored.
* The result is written into a local {@link WindowStore} (which is basically an ever-updating materialized view).
* Furthermore, updates to the store are sent downstream into a {@link KTable} changelog stream.
* <p>
* The specified {@link Initializer} is applied directly before the first input record (per key) in each window is
* processed to provide an initial intermediate aggregation result that is used to process the first record for
* the window (per key).
* The specified {@link Aggregator} (as specified in {@link KGroupedStream#cogroup(Aggregator)} or
* {@link CogroupedKStream#cogroup(KGroupedStream, Aggregator)}) is applied for each input record and computes a new
* aggregate using the current aggregate (or for the very first record using the intermediate aggregation result
* provided via the {@link Initializer}) and the record's value.
* Thus, {@code aggregate()} can be used to compute aggregate functions like count or sum etc.
* <p>
* The default key and value serde from the config will be used for serializing the result.
* If a different serde is required then you should use {@link #aggregate(Initializer, Named, Materialized)}.
* Not all updates might get sent downstream, as an internal cache is used to deduplicate consecutive updates to
* the same window and key.
* The rate of propagated updates depends on your input data rate, the number of distinct
* keys, the number of parallel running Kafka Streams instances, and the {@link StreamsConfig configuration}
* parameters for {@link StreamsConfig#STATESTORE_CACHE_MAX_BYTES_CONFIG cache size}, and
* {@link StreamsConfig#COMMIT_INTERVAL_MS_CONFIG commit interval}.
* <p>
* For failure and recovery the store (which always will be of type {@link TimestampedWindowStore}) will be backed by
* an internal changelog topic that will be created in Kafka.
* The changelog topic will be named "${applicationId}-${internalStoreName}-changelog", where "applicationId" is
* user-specified in {@link StreamsConfig} via parameter
* {@link StreamsConfig#APPLICATION_ID_CONFIG APPLICATION_ID_CONFIG}, "internalStoreName" is an internal name
* and "-changelog" is a fixed suffix.
* Note that the internal store name may not be queryable through Interactive Queries.
* <p>
* You can retrieve all generated internal topic names via {@link Topology#describe()}.
*
* @param initializer an {@link Initializer} that computes an initial intermediate aggregation result. Cannot be {@code null}.
* @param named a {@link Named} config used to name the processor in the topology. Cannot be {@code null}.
* @return a windowed {@link KTable} that contains "update" records with unmodified keys, and values that represent
* the latest (rolling) aggregate for each key within a window
*/
KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer,
final Named named);
/**
* Aggregate the values of records in this stream by the grouped key and defined windows.
* Records with {@code null} key or value are ignored.
* The result is written into a local {@link WindowStore} (which is basically an ever-updating materialized view)
* that can be queried using the store name as provided with {@link Materialized}.
* Furthermore, updates to the store are sent downstream into a {@link KTable} changelog stream.
* <p>
* The specified {@link Initializer} is applied directly before the first input record (per key) in each window is
* processed to provide an initial intermediate aggregation result that is used to process the first record for
* the window (per key).
* The specified {@link Aggregator} (as specified in {@link KGroupedStream#cogroup(Aggregator)} or
* {@link CogroupedKStream#cogroup(KGroupedStream, Aggregator)}) is applied for each input record and computes a new
* aggregate using the current aggregate (or for the very first record using the intermediate aggregation result
* provided via the {@link Initializer}) and the record's value.
* Thus, {@code aggregate()} can be used to compute aggregate functions like count or sum etc.
* <p>
* Not all updates might get sent downstream, as an internal cache is used to deduplicate consecutive updates to
* the same window and key if caching is enabled on the {@link Materialized} instance.
* When caching is enabled the rate of propagated updates depends on your input data rate, the number of distinct
* keys, the number of parallel running Kafka Streams instances, and the {@link StreamsConfig configuration}
* parameters for {@link StreamsConfig#STATESTORE_CACHE_MAX_BYTES_CONFIG cache size}, and
* {@link StreamsConfig#COMMIT_INTERVAL_MS_CONFIG commit interval}.
* <p>
* To query the local {@link ReadOnlyWindowStore} it must be obtained via
* {@link KafkaStreams#store(StoreQueryParameters) KafkaStreams#store(...)}:
* <pre>{@code
* KafkaStreams streams = ... // counting words
* Store queryableStoreName = ... // the queryableStoreName should be the name of the store as defined by the Materialized instance
* StoreQueryParameters<ReadOnlyKeyValueStore<K, ValueAndTimestamp<VR>>> storeQueryParams = StoreQueryParameters.fromNameAndType(queryableStoreName, QueryableStoreTypes.timestampedWindowStore());
* ReadOnlyWindowStore<K, ValueAndTimestamp<VR>> localWindowStore = streams.store(storeQueryParams);
* K key = "some-word";
* long fromTime = ...;
* long toTime = ...;
* WindowStoreIterator<ValueAndTimestamp<V>> aggregateStore = localWindowStore.fetch(key, timeFrom, timeTo); // key must be local (application state is shared over all running Kafka Streams instances)
* }</pre>
* For non-local keys, a custom RPC mechanism must be implemented using {@link KafkaStreams#metadataForAllStreamsClients()} to
* query the value of the key on a parallel running instance of your Kafka Streams application.
* <p>
* For failure and recovery the store (which always will be of type {@link TimestampedWindowStore} -- regardless of what
* is specified in the parameter {@code materialized}) will be backed by an internal changelog topic that will be created in Kafka.
* Therefore, the store name defined by the {@link Materialized} instance must be a valid Kafka topic name and
* cannot contain characters other than ASCII alphanumerics, '.', '_' and '-'.
* The changelog topic will be named "${applicationId}-${storeName}-changelog", where "applicationId" is
* user-specified in {@link StreamsConfig} via parameter
* {@link StreamsConfig#APPLICATION_ID_CONFIG APPLICATION_ID_CONFIG}, "storeName" is the
* name of the store defined in {@link Materialized}, and "-changelog" is a fixed suffix.
* <p>
* You can retrieve all generated internal topic names via {@link Topology#describe()}.
*
* @param initializer an {@link Initializer} that computes an initial intermediate aggregation result. Cannot be {@code null}.
* @param materialized a {@link Materialized} config used to materialize a state store. Cannot be {@code null}.
* @return a windowed {@link KTable} that contains "update" records with unmodified keys, and values that represent
* the latest (rolling) aggregate for each key within a window
*/
KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer,
final Materialized<K, V, WindowStore<Bytes, byte[]>> materialized);
/**
* Aggregate the values of records in this stream by the grouped key and defined windows.
* Records with {@code null} key or value are ignored.
* The result is written into a local {@link WindowStore} (which is basically an ever-updating materialized view)
* that can be queried using the store name as provided with {@link Materialized}.
* Furthermore, updates to the store are sent downstream into a {@link KTable} changelog stream.
* <p>
* The specified {@link Initializer} is applied directly before the first input record (per key) in each window is
* processed to provide an initial intermediate aggregation result that is used to process the first record for
* the window (per key).
* The specified {@link Aggregator} (as specified in {@link KGroupedStream#cogroup(Aggregator)} or
* {@link CogroupedKStream#cogroup(KGroupedStream, Aggregator)}) is applied for each input record and computes a new
* aggregate using the current aggregate (or for the very first record using the intermediate aggregation result
* provided via the {@link Initializer}) and the record's value.
* Thus, {@code aggregate()} can be used to compute aggregate functions like count or sum etc.
* <p>
* Not all updates might get sent downstream, as an internal cache will be used to deduplicate consecutive updates
* to the same window and key if caching is enabled on the {@link Materialized} instance.
* When caching is enabled the rate of propagated updates depends on your input data rate, the number of distinct
* keys, the number of parallel running Kafka Streams instances, and the {@link StreamsConfig configuration}
* parameters for {@link StreamsConfig#STATESTORE_CACHE_MAX_BYTES_CONFIG cache size}, and
* {@link StreamsConfig#COMMIT_INTERVAL_MS_CONFIG commit interval}.
* <p>
* To query the local {@link ReadOnlyWindowStore} it must be obtained via
* {@link KafkaStreams#store(StoreQueryParameters) KafkaStreams#store(...)}:
* <pre>{@code
* KafkaStreams streams = ... // counting words
* Store queryableStoreName = ... // the queryableStoreName should be the name of the store as defined by the Materialized instance
* StoreQueryParameters<ReadOnlyKeyValueStore<K, ValueAndTimestamp<VR>>> storeQueryParams = StoreQueryParameters.fromNameAndType(queryableStoreName, QueryableStoreTypes.timestampedWindowStore());
* ReadOnlyWindowStore<K, ValueAndTimestamp<VR>> localWindowStore = streams.store(storeQueryParams);
*
* K key = "some-word";
* long fromTime = ...;
* long toTime = ...;
* WindowStoreIterator<ValueAndTimestamp<V>> aggregateStore = localWindowStore.fetch(key, timeFrom, timeTo); // key must be local (application state is shared over all running Kafka Streams instances)
* }</pre>
* For non-local keys, a custom RPC mechanism must be implemented using {@link KafkaStreams#metadataForAllStreamsClients()} to
* query the value of the key on a parallel running instance of your Kafka Streams application.
* <p>
* For failure and recovery the store (which always will be of type {@link TimestampedWindowStore} -- regardless of what
* is specified in the parameter {@code materialized}) will be backed by an internal changelog topic that will be created in Kafka.
* Therefore, the store name defined by the {@link Materialized} instance must be a valid Kafka topic name and
* cannot contain characters other than ASCII alphanumerics, '.', '_' and '-'.
* The changelog topic will be named "${applicationId}-${storeName}-changelog", where "applicationId" is
* user-specified in {@link StreamsConfig} via parameter
* {@link StreamsConfig#APPLICATION_ID_CONFIG APPLICATION_ID_CONFIG}, "storeName" is the
* name of the store defined in {@link Materialized}, and "-changelog" is a fixed suffix.
* <p>
* You can retrieve all generated internal topic names via {@link Topology#describe()}.
*
* @param initializer an {@link Initializer} that computes an initial intermediate aggregation result. Cannot be {@code null}.
* @param named a {@link Named} config used to name the processor in the topology. Cannot be {@code null}.
* @param materialized a {@link Materialized} config used to materialize a state store. Cannot be {@code null}.
* @return a windowed {@link KTable} that contains "update" records with unmodified keys, and values that represent
* the latest (rolling) aggregate for each key within a window
*/
KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer,
final Named named,
final Materialized<K, V, WindowStore<Bytes, byte[]>> materialized);
}
| TimeWindowedCogroupedKStream |
java | elastic__elasticsearch | x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/async/AsyncTaskManagementService.java | {
"start": 2574,
"end": 3355
} | interface ____<
Request extends TaskAwareRequest,
Response extends ActionResponse,
T extends CancellableTask & AsyncTask> {
T createTask(
Request request,
long id,
String type,
String action,
TaskId parentTaskId,
Map<String, String> headers,
Map<String, String> originHeaders,
AsyncExecutionId asyncExecutionId
);
void execute(Request request, T task, ActionListener<Response> listener);
Response initialResponse(T task);
Response readResponse(StreamInput inputStream) throws IOException;
}
/**
* Wrapper for EsqlQueryRequest that creates an async version of EsqlQueryTask
*/
private | AsyncOperation |
java | quarkusio__quarkus | extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/GeneratedStaticResourceBuildItemDuplicatedTest.java | {
"start": 684,
"end": 2288
} | class ____ {
@RegisterExtension
final static QuarkusUnitTest test = new QuarkusUnitTest().withApplicationRoot(
(jar) -> jar.add(new StringAsset(""), "application.properties"))
.addBuildChainCustomizer(new Consumer<BuildChainBuilder>() {
@Override
public void accept(BuildChainBuilder buildChainBuilder) {
buildChainBuilder.addBuildStep(new BuildStep() {
@Override
public void execute(BuildContext context) {
context.produce(new GeneratedStaticResourceBuildItem(
"/index.html", "Hello from Quarkus".getBytes(StandardCharsets.UTF_8)));
context.produce(new GeneratedStaticResourceBuildItem("/index.html",
"GeneratedStaticResourceBuildItem says: Hello from me!".getBytes(StandardCharsets.UTF_8)));
}
}).produces(GeneratedStaticResourceBuildItem.class).produces(GeneratedResourceBuildItem.class).build();
}
})
.assertException(throwable -> {
String message = throwable.getCause().getMessage();
assertThat(message)
.contains("Duplicate endpoints detected, the endpoint for static resources must be unique:");
assertThat(message).contains("/index.html");
});
@Test
void assertTrue() {
Assertions.assertTrue(true);
}
}
| GeneratedStaticResourceBuildItemDuplicatedTest |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamTask.java | {
"start": 9006,
"end": 9683
} | class ____ all streaming tasks. A task is the unit of local processing that is deployed and
* executed by the TaskManagers. Each task runs one or more {@link StreamOperator}s which form the
* Task's operator chain. Operators that are chained together execute synchronously in the same
* thread and hence on the same stream partition. A common case for these chains are successive
* map/flatmap/filter tasks.
*
* <p>The task chain contains one "head" operator and multiple chained operators. The StreamTask is
* specialized for the type of the head operator: one-input and two-input tasks, as well as for
* sources, iteration heads and iteration tails.
*
* <p>The Task | for |
java | apache__kafka | trogdor/src/main/java/org/apache/kafka/trogdor/workload/ShareConsumeBenchWorker.java | {
"start": 17741,
"end": 19457
} | class ____ {
private final KafkaShareConsumer<byte[], byte[]> consumer;
private final String clientId;
private final ReentrantLock consumerLock;
private boolean closed = false;
ThreadSafeShareConsumer(KafkaShareConsumer<byte[], byte[]> consumer, String clientId) {
this.consumer = consumer;
this.clientId = clientId;
this.consumerLock = new ReentrantLock();
}
ConsumerRecords<byte[], byte[]> poll() {
this.consumerLock.lock();
try {
return consumer.poll(Duration.ofMillis(50));
} finally {
this.consumerLock.unlock();
}
}
void close() {
if (closed)
return;
this.consumerLock.lock();
try {
consumer.unsubscribe();
Utils.closeQuietly(consumer, "consumer");
closed = true;
} finally {
this.consumerLock.unlock();
}
}
void subscribe(Set<String> topics) {
this.consumerLock.lock();
try {
consumer.subscribe(topics);
} finally {
this.consumerLock.unlock();
}
}
Set<String> subscription() {
this.consumerLock.lock();
try {
return consumer.subscription();
} finally {
this.consumerLock.unlock();
}
}
String clientId() {
return clientId;
}
KafkaShareConsumer<byte[], byte[]> consumer() {
return consumer;
}
}
}
| ThreadSafeShareConsumer |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/taobao/MTopTest.java | {
"start": 2584,
"end": 2642
} | interface ____ {
String schema();
}
}
| UrlIdentify |
java | apache__camel | core/camel-management/src/test/java/org/apache/camel/management/ManagedEnricherTest.java | {
"start": 1568,
"end": 4075
} | class ____ extends ManagementTestSupport {
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
context.getManagementStrategy().getManagementAgent().setStatisticsLevel(ManagementStatisticsLevel.Extended);
return context;
}
@Test
public void testManageEnricher() throws Exception {
MockEndpoint foo = getMockEndpoint("mock:foo");
foo.expectedMessageCount(2);
MockEndpoint bar = getMockEndpoint("mock:bar");
bar.expectedMessageCount(1);
template.sendBodyAndHeader("direct:start", "Hello World", "whereto", "foo");
template.sendBodyAndHeader("direct:start", "Bye World", "whereto", "foo");
template.sendBodyAndHeader("direct:start", "Hi World", "whereto", "bar");
assertMockEndpointsSatisfied();
// get the stats for the route
MBeanServer mbeanServer = getMBeanServer();
// get the object name for the delayer
ObjectName on = getCamelObjectName(TYPE_PROCESSOR, "mysend");
// should be on route1
String routeId = (String) mbeanServer.getAttribute(on, "RouteId");
assertEquals("route1", routeId);
String camelId = (String) mbeanServer.getAttribute(on, "CamelId");
assertEquals(context.getManagementName(), camelId);
String state = (String) mbeanServer.getAttribute(on, "State");
assertEquals(ServiceStatus.Started.name(), state);
String lan = (String) mbeanServer.getAttribute(on, "ExpressionLanguage");
assertEquals("simple", lan);
String uri = (String) mbeanServer.getAttribute(on, "Expression");
assertEquals("direct:${header.whereto}", uri);
String destination = (String) mbeanServer.getAttribute(on, "Destination");
assertEquals("direct:${header.whereto}", destination);
TabularData data = (TabularData) mbeanServer.invoke(on, "extendedInformation", null, null);
assertNotNull(data);
assertEquals(2, data.size());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.enrich().simple("direct:${header.whereto}").id("mysend");
from("direct:foo").to("mock:foo");
from("direct:bar").to("mock:bar");
}
};
}
}
| ManagedEnricherTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/jobhistory/JobHistoryParser.java | {
"start": 2207,
"end": 16363
} | class ____ implements HistoryEventHandler {
private static final Logger LOG =
LoggerFactory.getLogger(JobHistoryParser.class);
private final FSDataInputStream in;
private JobInfo info = null;
private IOException parseException = null;
/**
* Create a job history parser for the given history file using the
* given file system
* @param fs
* @param file
* @throws IOException
*/
public JobHistoryParser(FileSystem fs, String file) throws IOException {
this(fs, new Path(file));
}
/**
* Create the job history parser for the given history file using the
* given file system
* @param fs
* @param historyFile
* @throws IOException
*/
public JobHistoryParser(FileSystem fs, Path historyFile)
throws IOException {
this(fs.open(historyFile));
}
/**
* Create the history parser based on the input stream
* @param in
*/
public JobHistoryParser(FSDataInputStream in) {
this.in = in;
}
public synchronized void parse(HistoryEventHandler handler)
throws IOException {
parse(new EventReader(in), handler);
}
/**
* Only used for unit tests.
*/
@Private
public synchronized void parse(EventReader reader, HistoryEventHandler handler)
throws IOException {
int eventCtr = 0;
HistoryEvent event;
try {
while ((event = reader.getNextEvent()) != null) {
handler.handleEvent(event);
++eventCtr;
}
} catch (IOException ioe) {
LOG.info("Caught exception parsing history file after " + eventCtr +
" events", ioe);
parseException = ioe;
} finally {
in.close();
}
}
/**
* Parse the entire history file and populate the JobInfo object
* The first invocation will populate the object, subsequent calls
* will return the already parsed object.
* The input stream is closed on return
*
* This api ignores partial records and stops parsing on encountering one.
* {@link #getParseException()} can be used to fetch the exception, if any.
*
* @return The populated jobInfo object
* @throws IOException
* @see #getParseException()
*/
public synchronized JobInfo parse() throws IOException {
return parse(new EventReader(in));
}
/**
* Only used for unit tests.
*/
@Private
public synchronized JobInfo parse(EventReader reader) throws IOException {
if (info != null) {
return info;
}
info = new JobInfo();
parse(reader, this);
return info;
}
/**
* Get the parse exception, if any.
*
* @return the parse exception, if any
* @see #parse()
*/
public synchronized IOException getParseException() {
return parseException;
}
@Override
public void handleEvent(HistoryEvent event) {
EventType type = event.getEventType();
switch (type) {
case JOB_SUBMITTED:
handleJobSubmittedEvent((JobSubmittedEvent)event);
break;
case JOB_STATUS_CHANGED:
break;
case JOB_INFO_CHANGED:
handleJobInfoChangeEvent((JobInfoChangeEvent) event);
break;
case JOB_INITED:
handleJobInitedEvent((JobInitedEvent) event);
break;
case JOB_PRIORITY_CHANGED:
handleJobPriorityChangeEvent((JobPriorityChangeEvent) event);
break;
case JOB_QUEUE_CHANGED:
handleJobQueueChangeEvent((JobQueueChangeEvent) event);
break;
case JOB_FAILED:
case JOB_KILLED:
case JOB_ERROR:
handleJobFailedEvent((JobUnsuccessfulCompletionEvent) event);
break;
case JOB_FINISHED:
handleJobFinishedEvent((JobFinishedEvent)event);
break;
case TASK_STARTED:
handleTaskStartedEvent((TaskStartedEvent) event);
break;
case TASK_FAILED:
handleTaskFailedEvent((TaskFailedEvent) event);
break;
case TASK_UPDATED:
handleTaskUpdatedEvent((TaskUpdatedEvent) event);
break;
case TASK_FINISHED:
handleTaskFinishedEvent((TaskFinishedEvent) event);
break;
case MAP_ATTEMPT_STARTED:
case CLEANUP_ATTEMPT_STARTED:
case REDUCE_ATTEMPT_STARTED:
case SETUP_ATTEMPT_STARTED:
handleTaskAttemptStartedEvent((TaskAttemptStartedEvent) event);
break;
case MAP_ATTEMPT_FAILED:
case CLEANUP_ATTEMPT_FAILED:
case REDUCE_ATTEMPT_FAILED:
case SETUP_ATTEMPT_FAILED:
case MAP_ATTEMPT_KILLED:
case CLEANUP_ATTEMPT_KILLED:
case REDUCE_ATTEMPT_KILLED:
case SETUP_ATTEMPT_KILLED:
handleTaskAttemptFailedEvent(
(TaskAttemptUnsuccessfulCompletionEvent) event);
break;
case MAP_ATTEMPT_FINISHED:
handleMapAttemptFinishedEvent((MapAttemptFinishedEvent) event);
break;
case REDUCE_ATTEMPT_FINISHED:
handleReduceAttemptFinishedEvent((ReduceAttemptFinishedEvent) event);
break;
case SETUP_ATTEMPT_FINISHED:
case CLEANUP_ATTEMPT_FINISHED:
handleTaskAttemptFinishedEvent((TaskAttemptFinishedEvent) event);
break;
case AM_STARTED:
handleAMStartedEvent((AMStartedEvent) event);
break;
default:
break;
}
}
private void handleTaskAttemptFinishedEvent(TaskAttemptFinishedEvent event) {
TaskInfo taskInfo = info.tasksMap.get(event.getTaskId());
TaskAttemptInfo attemptInfo =
taskInfo.attemptsMap.get(event.getAttemptId());
attemptInfo.finishTime = event.getFinishTime();
attemptInfo.status = StringInterner.weakIntern(event.getTaskStatus());
attemptInfo.state = StringInterner.weakIntern(event.getState());
attemptInfo.counters = event.getCounters();
attemptInfo.hostname = StringInterner.weakIntern(event.getHostname());
info.completedTaskAttemptsMap.put(event.getAttemptId(), attemptInfo);
}
private void handleReduceAttemptFinishedEvent
(ReduceAttemptFinishedEvent event) {
TaskInfo taskInfo = info.tasksMap.get(event.getTaskId());
TaskAttemptInfo attemptInfo =
taskInfo.attemptsMap.get(event.getAttemptId());
attemptInfo.finishTime = event.getFinishTime();
attemptInfo.status = StringInterner.weakIntern(event.getTaskStatus());
attemptInfo.state = StringInterner.weakIntern(event.getState());
attemptInfo.shuffleFinishTime = event.getShuffleFinishTime();
attemptInfo.sortFinishTime = event.getSortFinishTime();
attemptInfo.counters = event.getCounters();
attemptInfo.hostname = StringInterner.weakIntern(event.getHostname());
attemptInfo.port = event.getPort();
attemptInfo.rackname = StringInterner.weakIntern(event.getRackName());
info.completedTaskAttemptsMap.put(event.getAttemptId(), attemptInfo);
}
private void handleMapAttemptFinishedEvent(MapAttemptFinishedEvent event) {
TaskInfo taskInfo = info.tasksMap.get(event.getTaskId());
TaskAttemptInfo attemptInfo =
taskInfo.attemptsMap.get(event.getAttemptId());
attemptInfo.finishTime = event.getFinishTime();
attemptInfo.status = StringInterner.weakIntern(event.getTaskStatus());
attemptInfo.state = StringInterner.weakIntern(event.getState());
attemptInfo.mapFinishTime = event.getMapFinishTime();
attemptInfo.counters = event.getCounters();
attemptInfo.hostname = StringInterner.weakIntern(event.getHostname());
attemptInfo.port = event.getPort();
attemptInfo.rackname = StringInterner.weakIntern(event.getRackName());
info.completedTaskAttemptsMap.put(event.getAttemptId(), attemptInfo);
}
private void handleTaskAttemptFailedEvent(
TaskAttemptUnsuccessfulCompletionEvent event) {
TaskInfo taskInfo = info.tasksMap.get(event.getTaskId());
if(taskInfo == null) {
LOG.warn("TaskInfo is null for TaskAttemptUnsuccessfulCompletionEvent"
+ " taskId: " + event.getTaskId().toString());
return;
}
TaskAttemptInfo attemptInfo =
taskInfo.attemptsMap.get(event.getTaskAttemptId());
if(attemptInfo == null) {
LOG.warn("AttemptInfo is null for TaskAttemptUnsuccessfulCompletionEvent"
+ " taskAttemptId: " + event.getTaskAttemptId().toString());
return;
}
attemptInfo.finishTime = event.getFinishTime();
attemptInfo.error = StringInterner.weakIntern(event.getError());
attemptInfo.status = StringInterner.weakIntern(event.getTaskStatus());
attemptInfo.hostname = StringInterner.weakIntern(event.getHostname());
attemptInfo.port = event.getPort();
attemptInfo.rackname = StringInterner.weakIntern(event.getRackName());
attemptInfo.shuffleFinishTime = event.getFinishTime();
attemptInfo.sortFinishTime = event.getFinishTime();
attemptInfo.mapFinishTime = event.getFinishTime();
attemptInfo.counters = event.getCounters();
if(TaskStatus.State.SUCCEEDED.toString().equals(taskInfo.status))
{
//this is a successful task
if(attemptInfo.getAttemptId().equals(taskInfo.getSuccessfulAttemptId()))
{
// the failed attempt is the one that made this task successful
// so its no longer successful. Reset fields set in
// handleTaskFinishedEvent()
taskInfo.counters = null;
taskInfo.finishTime = -1;
taskInfo.status = null;
taskInfo.successfulAttemptId = null;
}
}
info.completedTaskAttemptsMap.put(event.getTaskAttemptId(), attemptInfo);
}
private void handleTaskAttemptStartedEvent(TaskAttemptStartedEvent event) {
TaskAttemptID attemptId = event.getTaskAttemptId();
TaskInfo taskInfo = info.tasksMap.get(event.getTaskId());
TaskAttemptInfo attemptInfo = new TaskAttemptInfo();
attemptInfo.startTime = event.getStartTime();
attemptInfo.attemptId = event.getTaskAttemptId();
attemptInfo.httpPort = event.getHttpPort();
attemptInfo.trackerName = StringInterner.weakIntern(event.getTrackerName());
attemptInfo.taskType = event.getTaskType();
attemptInfo.shufflePort = event.getShufflePort();
attemptInfo.containerId = event.getContainerId();
taskInfo.attemptsMap.put(attemptId, attemptInfo);
}
private void handleTaskFinishedEvent(TaskFinishedEvent event) {
TaskInfo taskInfo = info.tasksMap.get(event.getTaskId());
taskInfo.counters = event.getCounters();
taskInfo.finishTime = event.getFinishTime();
taskInfo.status = TaskStatus.State.SUCCEEDED.toString();
taskInfo.successfulAttemptId = event.getSuccessfulTaskAttemptId();
}
private void handleTaskUpdatedEvent(TaskUpdatedEvent event) {
TaskInfo taskInfo = info.tasksMap.get(event.getTaskId());
taskInfo.finishTime = event.getFinishTime();
}
private void handleTaskFailedEvent(TaskFailedEvent event) {
TaskInfo taskInfo = info.tasksMap.get(event.getTaskId());
taskInfo.status = TaskStatus.State.FAILED.toString();
taskInfo.finishTime = event.getFinishTime();
taskInfo.error = StringInterner.weakIntern(event.getError());
taskInfo.failedDueToAttemptId = event.getFailedAttemptID();
taskInfo.counters = event.getCounters();
}
private void handleTaskStartedEvent(TaskStartedEvent event) {
TaskInfo taskInfo = new TaskInfo();
taskInfo.taskId = event.getTaskId();
taskInfo.startTime = event.getStartTime();
taskInfo.taskType = event.getTaskType();
taskInfo.splitLocations = event.getSplitLocations();
info.tasksMap.put(event.getTaskId(), taskInfo);
}
private void handleJobFailedEvent(JobUnsuccessfulCompletionEvent event) {
info.finishTime = event.getFinishTime();
info.succeededMaps = event.getSucceededMaps();
info.succeededReduces = event.getSucceededReduces();
info.failedMaps = event.getFailedMaps();
info.failedReduces = event.getFailedReduces();
info.killedMaps = event.getKilledMaps();
info.killedReduces = event.getKilledReduces();
info.jobStatus = StringInterner.weakIntern(event.getStatus());
info.errorInfo = StringInterner.weakIntern(event.getDiagnostics());
}
private void handleJobFinishedEvent(JobFinishedEvent event) {
info.finishTime = event.getFinishTime();
info.succeededMaps = event.getSucceededMaps();
info.succeededReduces = event.getSucceededReduces();
info.failedMaps = event.getFailedMaps();
info.failedReduces = event.getFailedReduces();
info.killedMaps = event.getKilledMaps();
info.killedReduces = event.getKilledReduces();
info.totalCounters = event.getTotalCounters();
info.mapCounters = event.getMapCounters();
info.reduceCounters = event.getReduceCounters();
info.jobStatus = JobStatus.getJobRunState(JobStatus.SUCCEEDED);
}
private void handleJobPriorityChangeEvent(JobPriorityChangeEvent event) {
info.priority = event.getPriority();
}
private void handleJobQueueChangeEvent(JobQueueChangeEvent event) {
info.jobQueueName = event.getJobQueueName();
}
private void handleJobInitedEvent(JobInitedEvent event) {
info.launchTime = event.getLaunchTime();
info.totalMaps = event.getTotalMaps();
info.totalReduces = event.getTotalReduces();
info.uberized = event.getUberized();
}
private void handleAMStartedEvent(AMStartedEvent event) {
AMInfo amInfo = new AMInfo();
amInfo.appAttemptId = event.getAppAttemptId();
amInfo.startTime = event.getStartTime();
amInfo.containerId = event.getContainerId();
amInfo.nodeManagerHost = StringInterner.weakIntern(event.getNodeManagerHost());
amInfo.nodeManagerPort = event.getNodeManagerPort();
amInfo.nodeManagerHttpPort = event.getNodeManagerHttpPort();
if (info.amInfos == null) {
info.amInfos = new LinkedList<AMInfo>();
}
info.amInfos.add(amInfo);
info.latestAmInfo = amInfo;
}
private void handleJobInfoChangeEvent(JobInfoChangeEvent event) {
info.submitTime = event.getSubmitTime();
info.launchTime = event.getLaunchTime();
}
private void handleJobSubmittedEvent(JobSubmittedEvent event) {
info.jobid = event.getJobId();
info.jobname = event.getJobName();
info.username = StringInterner.weakIntern(event.getUserName());
info.submitTime = event.getSubmitTime();
info.jobConfPath = event.getJobConfPath();
info.jobACLs = event.getJobAcls();
info.jobQueueName = StringInterner.weakIntern(event.getJobQueueName());
}
/**
* The | JobHistoryParser |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/ClientOptionsUnitTests.java | {
"start": 694,
"end": 2381
} | class ____ {
@Test
void testNew() {
checkAssertions(ClientOptions.create());
}
@Test
void testDefault() {
ClientOptions options = ClientOptions.builder().build();
assertThat(options.getReadOnlyCommands().isReadOnly(new Command<>(CommandType.SET, null))).isFalse();
assertThat(options.getReadOnlyCommands().isReadOnly(new Command<>(CommandType.PUBLISH, null))).isFalse();
assertThat(options.getReadOnlyCommands().isReadOnly(new Command<>(CommandType.GET, null))).isTrue();
assertThat(options.getJsonParser().get()).isInstanceOf(DefaultJsonParser.class);
}
@Test
void testBuilder() {
ClientOptions options = ClientOptions.builder().scriptCharset(StandardCharsets.US_ASCII).build();
checkAssertions(options);
assertThat(options.getScriptCharset()).isEqualTo(StandardCharsets.US_ASCII);
}
@Test
void testCopy() {
ClientOptions original = ClientOptions.builder().scriptCharset(StandardCharsets.US_ASCII).build();
ClientOptions copy = ClientOptions.copyOf(original);
checkAssertions(copy);
assertThat(copy.getScriptCharset()).isEqualTo(StandardCharsets.US_ASCII);
assertThat(copy.mutate().build().getScriptCharset()).isEqualTo(StandardCharsets.US_ASCII);
assertThat(original.mutate()).isNotSameAs(copy.mutate());
}
@Test
void jsonParser() {
JsonParser parser = new CustomJsonParser();
ClientOptions options = ClientOptions.builder().jsonParser(() -> parser).build();
assertThat(options.getJsonParser().get()).isInstanceOf(CustomJsonParser.class);
}
static | ClientOptionsUnitTests |
java | apache__flink | flink-core/src/test/java/org/apache/flink/core/fs/local/LocalFileSystemRecoverableWriterTest.java | {
"start": 1149,
"end": 1549
} | class ____ extends AbstractRecoverableWriterTest {
@TempDir private static java.nio.file.Path tempFolder;
@Override
public Path getBasePath() throws Exception {
return new Path(TempDirUtils.newFolder(tempFolder).toURI());
}
@Override
public FileSystem initializeFileSystem() {
return FileSystem.getLocalFileSystem();
}
}
| LocalFileSystemRecoverableWriterTest |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/BaseTestTemplate.java | {
"start": 2426,
"end": 5028
} | class ____<S extends AbstractAssert<S, A>, A> {
protected S assertions;
protected Objects objects;
protected Conditions conditions;
protected AssertionErrorCreator assertionErrorCreator;
@BeforeEach
public final void setUp() {
assertions = create_assertions();
inject_internal_objects();
setRemoveAssertJRelatedElementsFromStackTrace(false);
}
/**
* Builds an instance of the {@link Assert} implementation under test.
* <p>
* This object will be accessible through the {@link #assertions} field.
*/
protected abstract S create_assertions();
/**
* Injects any additional internal objects (typically mocks) into {@link #assertions}.
* <p>
* Subclasses that override this method must call the superclass implementation.
*/
protected void inject_internal_objects() {
objects = mock(Objects.class);
assertions.objects = objects;
conditions = mock(Conditions.class);
assertions.conditions = conditions;
assertionErrorCreator = spy(assertions.assertionErrorCreator);
assertions.assertionErrorCreator = assertionErrorCreator;
}
@Test
public void should_have_internal_effects() {
invoke_api_method();
verify_internal_effects();
}
/**
* For the few API methods that don't return {@code this}, override this method to do nothing (see
* {@link AbstractAssert_isNull_Test#should_return_this()} for an example).
*/
@Test
public void should_return_this() {
S returned = invoke_api_method();
assertThat(returned).isSameAs(assertions);
}
protected AssertionInfo getInfo(S someAssertions) {
return someAssertions.info;
}
protected AssertionInfo info() {
return getInfo(assertions);
}
protected A getActual(S someAssertions) {
return someAssertions.actual;
}
protected Objects getObjects(S someAssertions) {
return someAssertions.objects;
}
/**
* Invokes the API method under test.
*
* @return the assertion object that is returned by the method. If the method is {@code void}, return {@code null} and override
* {@link #should_return_this()}.
*/
protected abstract S invoke_api_method();
/**
* Verifies that invoking the API method had the expected effects (usually, setting some internal state or invoking an internal
* object).
*/
protected abstract void verify_internal_effects();
protected Comparator<?> getComparisonStrategyComparatorOf(Object object) {
ComparisonStrategy comparisonStrategy = readField(object, "comparisonStrategy");
return readField(comparisonStrategy, "comparator");
}
}
| BaseTestTemplate |
java | apache__flink | flink-state-backends/flink-statebackend-changelog/src/main/java/org/apache/flink/state/changelog/restore/AggregatingStateChangeApplier.java | {
"start": 1162,
"end": 2242
} | class ____<K, N, IN, SV, OUT> extends KvStateChangeApplier<K, N> {
private final InternalAggregatingState<K, N, IN, SV, OUT> state;
protected AggregatingStateChangeApplier(
InternalKeyContext<K> keyContext, InternalAggregatingState<K, N, IN, SV, OUT> state) {
super(keyContext);
this.state = state;
}
@Override
protected InternalKvState<K, N, ?> getState() {
return state;
}
protected void applyInternal(StateChangeOperation operation, DataInputView in)
throws Exception {
switch (operation) {
case SET:
case SET_INTERNAL:
state.updateInternal(state.getValueSerializer().deserialize(in));
break;
case MERGE_NS:
applyMergeNamespaces(state, in);
break;
case CLEAR:
state.clear();
break;
default:
throw new IllegalArgumentException("Unknown state change operation: " + operation);
}
}
}
| AggregatingStateChangeApplier |
java | square__javapoet | src/main/java/com/squareup/javapoet/TypeSpec.java | {
"start": 24448,
"end": 24499
} | class ____ {
*
* }
* | NestedTypeA |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/ThreadsMaxQueueSizeTest.java | {
"start": 973,
"end": 2183
} | class ____ extends ContextTestSupport {
@Test
public void testThreadsMaxQueueSize() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Test
public void testThreadsMaxQueueSizeBuilder() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(1);
template.sendBody("direct:foo", "Hello World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
// will use a custom thread pool with 5 in core and 10 as max
// and a max task queue with 2000
.threads(5, 10).maxQueueSize(2000).to("mock:result");
from("direct:foo")
// using the builder style
.threads().poolSize(5).maxPoolSize(10).maxQueueSize(2000).threadName("myPool").to("mock:result");
}
};
}
}
| ThreadsMaxQueueSizeTest |
java | spring-projects__spring-boot | core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTestBeanTests.java | {
"start": 2177,
"end": 2376
} | class ____ {
private final String property;
ImmutableProperties(String property) {
this.property = property;
}
String getProperty() {
return this.property;
}
}
}
| ImmutableProperties |
java | quarkusio__quarkus | integration-tests/vertx-web/src/test/java/io/quarkus/it/vertx/StaticResourcesTest.java | {
"start": 177,
"end": 423
} | class ____ {
@Test
public void testExisting() {
when().get("/test.txt").then().statusCode(200);
}
@Test
public void testNonExisting() {
when().get("/test2.txt").then().statusCode(404);
}
}
| StaticResourcesTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/xml/complete/LineItem.java | {
"start": 347,
"end": 1073
} | class ____ extends LineItemSuper {
@Id
private Integer id;
@ManyToOne
@JoinColumn(name = "order_fk")
private Order order;
@ManyToOne
@JoinColumn(name = "product_fk")
private Product product;
public LineItem() {
}
public LineItem(Integer id, Order order, Product product, int quantity) {
super( quantity );
this.id = id;
this.order = order;
this.product = product;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
| LineItem |
java | junit-team__junit5 | junit-platform-console/src/main/java/org/junit/platform/console/options/SelectorConverter.java | {
"start": 4563,
"end": 4772
} | class ____ implements ITypeConverter<DiscoverySelectorIdentifier> {
@Override
public DiscoverySelectorIdentifier convert(String value) {
return DiscoverySelectorIdentifier.parse(value);
}
}
}
| Identifier |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/nullness/EqualsBrokenForNullTest.java | {
"start": 12053,
"end": 12499
} | class ____ {
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (other instanceof Test) {
Test otherTest = (Test) other;
Optional.empty().map(x -> otherTest.toString());
}
return other.equals(this);
}
}
""")
.doTest();
}
}
| Test |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/IntegerAssertBaseTest.java | {
"start": 837,
"end": 1325
} | class ____ extends BaseTestTemplate<IntegerAssert, Integer> {
protected Integers integers;
@Override
protected IntegerAssert create_assertions() {
return new IntegerAssert(0);
}
@Override
protected void inject_internal_objects() {
super.inject_internal_objects();
integers = mock(Integers.class);
assertions.integers = integers;
}
protected Integers getIntegers(IntegerAssert someAssertions) {
return someAssertions.integers;
}
}
| IntegerAssertBaseTest |
java | spring-projects__spring-boot | module/spring-boot-validation/src/test/java/org/springframework/boot/validation/autoconfigure/ValidationAutoConfigurationTests.java | {
"start": 17113,
"end": 17237
} | class ____ {
@Bean
SomeService someService() {
return new SomeService();
}
}
static | SomeServiceConfiguration |
java | grpc__grpc-java | core/src/main/java/io/grpc/internal/Rescheduler.java | {
"start": 949,
"end": 2285
} | class ____ {
// deps
private final ScheduledExecutorService scheduler;
private final Executor serializingExecutor;
private final Runnable runnable;
// state
private final Stopwatch stopwatch;
private long runAtNanos;
private boolean enabled;
private ScheduledFuture<?> wakeUp;
Rescheduler(
Runnable r,
Executor serializingExecutor,
ScheduledExecutorService scheduler,
Stopwatch stopwatch) {
this.runnable = r;
this.serializingExecutor = serializingExecutor;
this.scheduler = scheduler;
this.stopwatch = stopwatch;
stopwatch.start();
}
/* must be called from the {@link #serializingExecutor} originally passed in. */
void reschedule(long delay, TimeUnit timeUnit) {
long delayNanos = timeUnit.toNanos(delay);
long newRunAtNanos = nanoTime() + delayNanos;
enabled = true;
if (newRunAtNanos - runAtNanos < 0 || wakeUp == null) {
if (wakeUp != null) {
wakeUp.cancel(false);
}
wakeUp = scheduler.schedule(new FutureRunnable(), delayNanos, TimeUnit.NANOSECONDS);
}
runAtNanos = newRunAtNanos;
}
// must be called from channel executor
void cancel(boolean permanent) {
enabled = false;
if (permanent && wakeUp != null) {
wakeUp.cancel(false);
wakeUp = null;
}
}
private final | Rescheduler |
java | apache__kafka | generator/src/main/java/org/apache/kafka/message/CoordinatorRecordTypeGenerator.java | {
"start": 3218,
"end": 10005
} | enum ____ {%n");
buffer.incrementIndent();
generateEnumValues();
buffer.printf("%n");
generateInstanceVariables();
buffer.printf("%n");
generateEnumConstructor();
buffer.printf("%n");
generateFromApiKey();
buffer.printf("%n");
generateNewRecordKey();
buffer.printf("%n");
generateNewRecordValue();
buffer.printf("%n");
generateAccessor("id", "short");
buffer.printf("%n");
generateAccessor("lowestSupportedVersion", "short");
buffer.printf("%n");
generateAccessor("highestSupportedVersion", "short");
buffer.printf("%n");
generateToString();
buffer.decrementIndent();
buffer.printf("}%n");
headerGenerator.generate();
}
private String cleanName(String name) {
return name
.replace("Key", "")
.replace("Value", "");
}
private void generateEnumValues() {
int numProcessed = 0;
for (Map.Entry<Short, CoordinatorRecord> entry : records.entrySet()) {
MessageSpec key = entry.getValue().key;
if (key == null) {
throw new RuntimeException("Coordinator record " + entry.getKey() + " has no key.");
}
MessageSpec value = entry.getValue().value;
if (value == null) {
throw new RuntimeException("Coordinator record " + entry.getKey() + " has no value.");
}
String name = cleanName(key.name());
numProcessed++;
buffer.printf("%s(\"%s\", (short) %d, (short) %d, (short) %d)%s%n",
MessageGenerator.toSnakeCase(name).toUpperCase(Locale.ROOT),
MessageGenerator.capitalizeFirst(name),
entry.getKey(),
value.validVersions().lowest(),
value.validVersions().highest(),
(numProcessed == records.size()) ? ";" : ",");
}
}
private void generateInstanceVariables() {
buffer.printf("private final String name;%n");
buffer.printf("private final short id;%n");
buffer.printf("private final short lowestSupportedVersion;%n");
buffer.printf("private final short highestSupportedVersion;%n");
}
private void generateEnumConstructor() {
buffer.printf("CoordinatorRecordType(String name, short id, short lowestSupportedVersion, short highestSupportedVersion) {%n");
buffer.incrementIndent();
buffer.printf("this.name = name;%n");
buffer.printf("this.id = id;%n");
buffer.printf("this.lowestSupportedVersion = lowestSupportedVersion;%n");
buffer.printf("this.highestSupportedVersion = highestSupportedVersion;%n");
buffer.decrementIndent();
buffer.printf("}%n");
}
private void generateFromApiKey() {
buffer.printf("public static CoordinatorRecordType fromId(short id) {%n");
buffer.incrementIndent();
buffer.printf("switch (id) {%n");
buffer.incrementIndent();
for (Map.Entry<Short, CoordinatorRecord> entry : records.entrySet()) {
buffer.printf("case %d:%n", entry.getKey());
buffer.incrementIndent();
buffer.printf("return %s;%n", MessageGenerator.
toSnakeCase(cleanName(entry.getValue().key.name())).toUpperCase(Locale.ROOT));
buffer.decrementIndent();
}
buffer.printf("default:%n");
buffer.incrementIndent();
headerGenerator.addImport(MessageGenerator.UNSUPPORTED_VERSION_EXCEPTION_CLASS);
buffer.printf("throw new UnsupportedVersionException(\"Unknown record id \"" +
" + id);%n");
buffer.decrementIndent();
buffer.decrementIndent();
buffer.printf("}%n");
buffer.decrementIndent();
buffer.printf("}%n");
}
private void generateNewRecordKey() {
headerGenerator.addImport(MessageGenerator.API_MESSAGE_CLASS);
buffer.printf("public ApiMessage newRecordKey() {%n");
buffer.incrementIndent();
buffer.printf("switch (id) {%n");
buffer.incrementIndent();
for (Map.Entry<Short, CoordinatorRecord> entry : records.entrySet()) {
buffer.printf("case %d:%n", entry.getKey());
buffer.incrementIndent();
buffer.printf("return new %s();%n",
MessageGenerator.capitalizeFirst(entry.getValue().key.name()));
buffer.decrementIndent();
}
buffer.printf("default:%n");
buffer.incrementIndent();
headerGenerator.addImport(MessageGenerator.UNSUPPORTED_VERSION_EXCEPTION_CLASS);
buffer.printf("throw new UnsupportedVersionException(\"Unknown record id \"" +
" + id);%n");
buffer.decrementIndent();
buffer.decrementIndent();
buffer.printf("}%n");
buffer.decrementIndent();
buffer.printf("}%n");
}
private void generateNewRecordValue() {
headerGenerator.addImport(MessageGenerator.API_MESSAGE_CLASS);
buffer.printf("public ApiMessage newRecordValue() {%n");
buffer.incrementIndent();
buffer.printf("switch (id) {%n");
buffer.incrementIndent();
for (Map.Entry<Short, CoordinatorRecord> entry : records.entrySet()) {
buffer.printf("case %d:%n", entry.getKey());
buffer.incrementIndent();
buffer.printf("return new %s();%n",
MessageGenerator.capitalizeFirst(entry.getValue().value.name()));
buffer.decrementIndent();
}
buffer.printf("default:%n");
buffer.incrementIndent();
headerGenerator.addImport(MessageGenerator.UNSUPPORTED_VERSION_EXCEPTION_CLASS);
buffer.printf("throw new UnsupportedVersionException(\"Unknown record id \"" +
" + id);%n");
buffer.decrementIndent();
buffer.decrementIndent();
buffer.printf("}%n");
buffer.decrementIndent();
buffer.printf("}%n");
}
private void generateAccessor(String name, String type) {
buffer.printf("public %s %s() {%n", type, name);
buffer.incrementIndent();
buffer.printf("return this.%s;%n", name);
buffer.decrementIndent();
buffer.printf("}%n");
}
private void generateToString() {
buffer.printf("@Override%n");
buffer.printf("public String toString() {%n");
buffer.incrementIndent();
buffer.printf("return this.name();%n");
buffer.decrementIndent();
buffer.printf("}%n");
}
private void write(BufferedWriter writer) throws IOException {
headerGenerator.buffer().write(writer);
buffer.write(writer);
}
}
| CoordinatorRecordType |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/jpa/internal/util/PessimisticNumberParser.java | {
"start": 635,
"end": 898
} | class ____ convert String to Integer when it's unlikely to be successful: if you expect it to be a normal number,
* for example when a non successful parsing would be an error, using this utility is just an overhead.
*
* @author Sanne Grinovero
*/
public final | to |
java | apache__camel | components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathSplitTest.java | {
"start": 1262,
"end": 4516
} | class ____ extends CamelTestSupport {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.split().jsonpath("$.store.book[*]")
.to("mock:authors")
.convertBodyTo(String.class);
from("direct:start-1")
.split(jsonpath("text.div", String.class), "false")
.to("mock:result-1");
from("direct:start-2")
.split(jsonpath("text.div", String.class))
.to("mock:result-2");
from("direct:start-3")
.split(jsonpath("text.div", String.class), "#")
.to("mock:result-3");
}
};
}
@Test
public void testSplit() throws Exception {
getMockEndpoint("mock:authors").expectedMessageCount(3);
String out = template.requestBody("direct:start", new File("src/test/resources/books.json"), String.class);
assertNotNull(out);
MockEndpoint.assertIsSatisfied(context);
Map row = getMockEndpoint("mock:authors").getReceivedExchanges().get(0).getIn().getBody(Map.class);
assertEquals("Nigel Rees", row.get("author"));
assertEquals(Double.valueOf("8.95"), row.get("price"));
row = getMockEndpoint("mock:authors").getReceivedExchanges().get(1).getIn().getBody(Map.class);
assertEquals("Evelyn Waugh", row.get("author"));
assertEquals(Double.valueOf("12.99"), row.get("price"));
// should preserve quotes etc
assertTrue(out.contains("\"author\": \"Nigel Rees\""));
assertTrue(out.contains("\"price\": 8.95"));
assertTrue(out.contains("\"title\": \"Sword's of Honour\""));
assertTrue(out.contains("\"price\": 12.99,"));
}
@Test
public void testJsonPathSplitDelimiterDisable() throws Exception {
// CAMEL-15769
String json = "{ \"text\": { \"div\": \"some , text\" } }";
MockEndpoint m = getMockEndpoint("mock:result-1");
m.expectedPropertyReceived("CamelSplitSize", 1);
m.expectedBodiesReceived("some , text");
template.sendBody("direct:start-1", json);
m.assertIsSatisfied();
}
@Test
public void testJsonPathSplitDelimiterDefault() throws Exception {
// CAMEL-15769
String json = "{ \"text\": { \"div\": \"some , text\" } }";
MockEndpoint m = getMockEndpoint("mock:result-2");
m.expectedPropertyReceived("CamelSplitSize", 2);
m.expectedBodiesReceived("some ", " text");
template.sendBody("direct:start-2", json);
m.assertIsSatisfied();
}
@Test
public void testJsonPathSplitDelimiter() throws Exception {
// CAMEL-15769
String json = "{ \"text\": { \"div\": \"some ,# text\" } }";
MockEndpoint m = getMockEndpoint("mock:result-3");
m.expectedPropertyReceived("CamelSplitSize", 2);
m.expectedBodiesReceived("some ,", " text");
template.sendBody("direct:start-3", json);
m.assertIsSatisfied();
}
}
| JsonPathSplitTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/type/EnumSetTest.java | {
"start": 7679,
"end": 8204
} | class ____ {
@Id
private Long id;
@Enumerated(EnumType.ORDINAL)
@Column( name = "the_set" )
private Set<MyEnum> theSet;
public TableWithEnumSet() {
}
public TableWithEnumSet(Long id, Set<MyEnum> theSet) {
this.id = id;
this.theSet = theSet;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<MyEnum> getTheSet() {
return theSet;
}
public void setTheSet(Set<MyEnum> theSet) {
this.theSet = theSet;
}
}
public | TableWithEnumSet |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java | {
"start": 7856,
"end": 8481
} | class ____ extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("testBean", new TestBeanDefinitionParser());
registerBeanDefinitionParser("person", new PersonDefinitionParser());
registerBeanDefinitionDecorator("set", new PropertyModifyingBeanDefinitionDecorator());
registerBeanDefinitionDecorator("debug", new DebugBeanDefinitionDecorator());
registerBeanDefinitionDecorator("nop", new NopInterceptorBeanDefinitionDecorator());
registerBeanDefinitionDecoratorForAttribute("object-name", new ObjectNameBeanDefinitionDecorator());
}
private static | TestNamespaceHandler |
java | apache__flink | flink-core/src/main/java/org/apache/flink/core/fs/FileSystemKind.java | {
"start": 1002,
"end": 1314
} | enum ____ {
/** An actual file system, with files and directories. */
FILE_SYSTEM,
/**
* An Object store. Files correspond to objects. There are not really directories, but a
* directory-like structure may be mimicked by hierarchical naming of files.
*/
OBJECT_STORE
}
| FileSystemKind |
java | qos-ch__slf4j | slf4j-simple/src/test/java/org/slf4j/simple/DetectLoggerNameMismatchTest.java | {
"start": 4906,
"end": 4991
} | class ____ {
public Logger logger = LoggerFactory.getLogger(getClass());
}
| ShapeBase |
java | apache__maven | impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultDependencyResolver.java | {
"start": 2994,
"end": 13158
} | class ____ implements DependencyResolver {
/**
* Cache of information about the modules contained in a path element.
* Keys are the Java versions targeted by the project.
*
* <p><b>TODO:</b> This field should not be in this class, because the cache should be global to the session.
* This field exists here only temporarily, until clarified where to store session-wide caches.</p>
*/
private final Map<Runtime.Version, PathModularizationCache> moduleCaches;
/**
* Creates an initially empty resolver.
*/
public DefaultDependencyResolver() {
// TODO: the cache should not be instantiated here, but should rather be session-wide.
moduleCaches = new ConcurrentHashMap<>();
}
/**
* {@return the cache for the given request}.
*
* @param request the request for which to get the target version
* @throws IllegalArgumentException if the version string cannot be interpreted as a valid version
*/
private PathModularizationCache moduleCache(DependencyResolverRequest request) {
return moduleCaches.computeIfAbsent(getTargetVersion(request), PathModularizationCache::new);
}
/**
* Returns the target version of the given request as a Java version object.
*
* @param request the request for which to get the target version
* @return the target version as a Java object
* @throws IllegalArgumentException if the version string cannot be interpreted as a valid version
*/
static Runtime.Version getTargetVersion(DependencyResolverRequest request) {
Version target = request.getTargetVersion();
return (target != null) ? Runtime.Version.parse(target.toString()) : Runtime.version();
}
@Nonnull
@Override
public DependencyResolverResult collect(@Nonnull DependencyResolverRequest request)
throws DependencyResolverException, IllegalArgumentException {
requireNonNull(request, "request");
InternalSession session = InternalSession.from(request.getSession());
RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(session, request);
try {
Artifact rootArtifact;
DependencyCoordinates root;
Collection<DependencyCoordinates> dependencies;
Collection<DependencyCoordinates> managedDependencies;
List<RemoteRepository> remoteRepositories;
if (request.getProject().isPresent()) {
Project project = request.getProject().get();
rootArtifact = project.getPomArtifact();
root = null;
dependencies = project.getDependencies();
managedDependencies = project.getManagedDependencies();
remoteRepositories = request.getRepositories() != null
? request.getRepositories()
: session.getService(ProjectManager.class).getRemoteProjectRepositories(project);
} else {
rootArtifact = request.getRootArtifact().orElse(null);
root = request.getRoot().orElse(null);
dependencies = request.getDependencies();
managedDependencies = request.getManagedDependencies();
remoteRepositories =
request.getRepositories() != null ? request.getRepositories() : session.getRemoteRepositories();
}
ResolutionScope resolutionScope = null;
if (request.getPathScope() != null) {
resolutionScope = session.getSession()
.getScopeManager()
.getResolutionScope(request.getPathScope().id())
.orElseThrow();
}
CollectRequest collectRequest = new CollectRequest()
.setRootArtifact(rootArtifact != null ? session.toArtifact(rootArtifact) : null)
.setRoot(root != null ? session.toDependency(root, false) : null)
.setDependencies(session.toDependencies(dependencies, false))
.setManagedDependencies(session.toDependencies(managedDependencies, true))
.setRepositories(session.toResolvingRepositories(remoteRepositories))
.setRequestContext(trace.context())
.setTrace(trace.trace());
collectRequest.setResolutionScope(resolutionScope);
RepositorySystemSession systemSession = session.getSession();
if (request.getVerbose()) {
systemSession = new DefaultRepositorySystemSession(systemSession)
.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true)
.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true);
}
try {
final CollectResult result =
session.getRepositorySystem().collectDependencies(systemSession, collectRequest);
return new DefaultDependencyResolverResult(
null,
moduleCache(request),
result.getExceptions(),
session.getNode(result.getRoot(), request.getVerbose()),
0);
} catch (DependencyCollectionException e) {
throw new DependencyResolverException("Unable to collect dependencies", e);
}
} finally {
RequestTraceHelper.exit(trace);
}
}
@Nonnull
@Override
public List<Node> flatten(@Nonnull Session s, @Nonnull Node node, @Nullable PathScope scope)
throws DependencyResolverException {
InternalSession session = InternalSession.from(s);
DependencyNode root = cast(AbstractNode.class, node, "node").getDependencyNode();
List<DependencyNode> dependencies = session.getRepositorySystem()
.flattenDependencyNodes(session.getSession(), root, getScopeDependencyFilter(scope));
dependencies.remove(root);
return map(dependencies, session::getNode);
}
private static DependencyFilter getScopeDependencyFilter(PathScope scope) {
if (scope == null) {
return null;
}
Set<String> scopes =
scope.dependencyScopes().stream().map(DependencyScope::id).collect(Collectors.toSet());
return (n, p) -> {
org.eclipse.aether.graph.Dependency d = n.getDependency();
return d == null || scopes.contains(d.getScope());
};
}
/**
* Collects, flattens and resolves the dependencies.
*
* @param request the request to resolve
* @return the result of the resolution
*/
@Override
public DependencyResolverResult resolve(DependencyResolverRequest request)
throws DependencyResolverException, ArtifactResolverException {
InternalSession session =
InternalSession.from(requireNonNull(request, "request").getSession());
RequestTraceHelper.ResolverTrace trace = RequestTraceHelper.enter(session, request);
DependencyResolverResult result;
try {
DependencyResolverResult collectorResult = collect(request);
List<RemoteRepository> repositories = request.getRepositories() != null
? request.getRepositories()
: request.getProject().isPresent()
? session.getService(ProjectManager.class)
.getRemoteProjectRepositories(
request.getProject().get())
: session.getRemoteRepositories();
if (request.getRequestType() == DependencyResolverRequest.RequestType.COLLECT) {
result = collectorResult;
} else {
List<Node> nodes = flatten(session, collectorResult.getRoot(), request.getPathScope());
List<ArtifactCoordinates> coordinates = nodes.stream()
.map(Node::getDependency)
.filter(Objects::nonNull)
.map(Artifact::toCoordinates)
.collect(Collectors.toList());
Predicate<PathType> filter = request.getPathTypeFilter();
DefaultDependencyResolverResult resolverResult = new DefaultDependencyResolverResult(
null,
moduleCache(request),
collectorResult.getExceptions(),
collectorResult.getRoot(),
nodes.size());
if (request.getRequestType() == DependencyResolverRequest.RequestType.FLATTEN) {
for (Node node : nodes) {
resolverResult.addNode(node);
}
} else {
ArtifactResolverResult artifactResolverResult =
session.getService(ArtifactResolver.class).resolve(session, coordinates, repositories);
for (Node node : nodes) {
Path path = (node.getArtifact() != null)
? artifactResolverResult
.getResult(node.getArtifact().toCoordinates())
.getPath()
: null;
try {
resolverResult.addDependency(node, node.getDependency(), filter, path);
} catch (IOException e) {
throw cannotReadModuleInfo(path, e);
}
}
}
result = resolverResult;
}
} finally {
RequestTraceHelper.exit(trace);
}
return result;
}
private static DependencyResolverException cannotReadModuleInfo(final Path path, final IOException cause) {
return new DependencyResolverException("Cannot read module information of " + path, cause);
}
}
| DefaultDependencyResolver |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/format/datetime/standard/DurationFormatterUtils.java | {
"start": 1224,
"end": 1463
} | class ____ overloads that take a {@link DurationFormat.Unit} to
* be used as a fall-back instead of the ultimate MILLIS default.
*
* @author Phillip Webb
* @author Valentine Wu
* @author Simon Baslé
* @since 6.2
*/
public abstract | offer |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/oauth2/RestGetTokenActionTests.java | {
"start": 1931,
"end": 9277
} | class ____ extends ESTestCase {
public void testListenerHandlesExceptionProperly() {
FakeRestRequest restRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).build();
final SetOnce<RestResponse> responseSetOnce = new SetOnce<>();
RestChannel restChannel = new AbstractRestChannel(restRequest, randomBoolean()) {
@Override
public void sendResponse(RestResponse restResponse) {
responseSetOnce.set(restResponse);
}
};
CreateTokenResponseActionListener listener = new CreateTokenResponseActionListener(restChannel, restRequest, NoOpLogger.INSTANCE);
ActionRequestValidationException ve = new CreateTokenRequest(null, null, null, null, null, null).validate();
listener.onFailure(ve);
RestResponse response = responseSetOnce.get();
assertNotNull(response);
Map<String, Object> map = XContentHelper.convertToMap(response.content(), false, XContentType.fromMediaType(response.contentType()))
.v2();
assertThat(map, hasEntry("error", "unsupported_grant_type"));
assertThat(map, hasEntry("error_description", ve.getMessage()));
assertEquals(2, map.size());
assertEquals(RestStatus.BAD_REQUEST, response.status());
}
public void testSendResponse() {
FakeRestRequest restRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).build();
final SetOnce<RestResponse> responseSetOnce = new SetOnce<>();
RestChannel restChannel = new AbstractRestChannel(restRequest, randomBoolean()) {
@Override
public void sendResponse(RestResponse restResponse) {
responseSetOnce.set(restResponse);
}
};
CreateTokenResponseActionListener listener = new CreateTokenResponseActionListener(restChannel, restRequest, NoOpLogger.INSTANCE);
CreateTokenResponse createTokenResponse = new CreateTokenResponse(
randomAlphaOfLengthBetween(1, 256),
TimeValue.timeValueHours(1L),
null,
randomAlphaOfLength(4),
randomAlphaOfLength(5),
AuthenticationTestHelper.builder()
.user(new User("bar", "not_superuser"))
.realmRef(new Authentication.RealmRef("test", "test", "node"))
.runAs()
.user(new User("joe", "custom_superuser"))
.realmRef(new Authentication.RealmRef("test", "test", "node"))
.build()
);
listener.onResponse(createTokenResponse);
RestResponse response = responseSetOnce.get();
assertNotNull(response);
Map<String, Object> map = XContentHelper.convertToMap(response.content(), false, XContentType.fromMediaType(response.contentType()))
.v2();
assertEquals(RestStatus.OK, response.status());
assertThat(map, hasEntry("type", "Bearer"));
assertThat(map, hasEntry("access_token", createTokenResponse.getTokenString()));
assertThat(map, hasEntry("expires_in", Math.toIntExact(createTokenResponse.getExpiresIn().seconds())));
assertThat(map, hasEntry("refresh_token", createTokenResponse.getRefreshToken()));
assertThat(map, hasEntry("kerberos_authentication_response_token", createTokenResponse.getKerberosAuthenticationResponseToken()));
assertThat(map, hasKey("authentication"));
@SuppressWarnings("unchecked")
final Map<String, Object> authentication = (Map<String, Object>) (map.get("authentication"));
assertThat(
authentication,
hasEntry("username", createTokenResponse.getAuthentication().getEffectiveSubject().getUser().principal())
);
assertEquals(6, map.size());
}
public void testSendResponseKerberosError() {
FakeRestRequest restRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).build();
final SetOnce<RestResponse> responseSetOnce = new SetOnce<>();
RestChannel restChannel = new AbstractRestChannel(restRequest, randomBoolean()) {
@Override
public void sendResponse(RestResponse restResponse) {
responseSetOnce.set(restResponse);
}
};
CreateTokenResponseActionListener listener = new CreateTokenResponseActionListener(restChannel, restRequest, NoOpLogger.INSTANCE);
String errorMessage = "failed to authenticate user, gss context negotiation not complete";
ElasticsearchSecurityException ese = new ElasticsearchSecurityException(errorMessage, RestStatus.UNAUTHORIZED);
boolean addBase64EncodedToken = randomBoolean();
ese.addBodyHeader(KerberosAuthenticationToken.WWW_AUTHENTICATE, "Negotiate" + ((addBase64EncodedToken) ? " FAIL" : ""));
listener.onFailure(ese);
RestResponse response = responseSetOnce.get();
assertNotNull(response);
Map<String, Object> map = XContentHelper.convertToMap(response.content(), false, XContentType.fromMediaType(response.contentType()))
.v2();
assertThat(map, hasEntry("error", RestGetTokenAction.TokenRequestError._UNAUTHORIZED.name().toLowerCase(Locale.ROOT)));
if (addBase64EncodedToken) {
assertThat(map, hasEntry("error_description", "FAIL"));
} else {
assertThat(map, hasEntry("error_description", null));
}
assertEquals(2, map.size());
assertEquals(RestStatus.BAD_REQUEST, response.status());
}
public void testParser() throws Exception {
final String request = Strings.format("""
{
"grant_type": "password",
"username": "user1",
"password": "%s",
"scope": "FULL"
}""", SecuritySettingsSourceField.TEST_PASSWORD);
try (XContentParser parser = XContentType.JSON.xContent().createParser(XContentParserConfiguration.EMPTY, request)) {
CreateTokenRequest createTokenRequest = RestGetTokenAction.PARSER.parse(parser, null);
assertEquals("password", createTokenRequest.getGrantType());
assertEquals("user1", createTokenRequest.getUsername());
assertEquals("FULL", createTokenRequest.getScope());
assertTrue(SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING.equals(createTokenRequest.getPassword()));
}
}
public void testParserRefreshRequest() throws Exception {
final String token = randomAlphaOfLengthBetween(4, 32);
final String request = Strings.format("""
{
"grant_type": "refresh_token",
"refresh_token": "%s",
"scope": "FULL"
}""", token);
try (XContentParser parser = XContentType.JSON.xContent().createParser(XContentParserConfiguration.EMPTY, request)) {
CreateTokenRequest createTokenRequest = RestGetTokenAction.PARSER.parse(parser, null);
assertEquals("refresh_token", createTokenRequest.getGrantType());
assertEquals(token, createTokenRequest.getRefreshToken());
assertEquals("FULL", createTokenRequest.getScope());
assertNull(createTokenRequest.getUsername());
assertNull(createTokenRequest.getPassword());
}
}
}
| RestGetTokenActionTests |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/builder/BuilderTest_error.java | {
"start": 842,
"end": 1204
} | class ____ {
private VO vo = new VO();
public VO build() {
throw new IllegalStateException();
}
public VOBuilder withId(int id) {
vo.id = id;
return this;
}
public VOBuilder withName(String name) {
vo.name = name;
return this;
}
}
}
| VOBuilder |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/TestUtil.java | {
"start": 896,
"end": 3155
} | class ____ {
public static long getYoungGC() {
try {
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName;
if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=ParNew"))) {
objectName = new ObjectName("java.lang:type=GarbageCollector,name=ParNew");
} else if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=Copy"))) {
objectName = new ObjectName("java.lang:type=GarbageCollector,name=Copy");
} else {
objectName = new ObjectName("java.lang:type=GarbageCollector,name=PS Scavenge");
}
return (Long) mbeanServer.getAttribute(objectName, "CollectionCount");
} catch (Exception e) {
throw new RuntimeException("error");
}
}
public static long getFullGC() {
try {
MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName;
if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"))) {
objectName = new ObjectName("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep");
} else if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact"))) {
objectName = new ObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact");
} else {
objectName = new ObjectName("java.lang:type=GarbageCollector,name=PS MarkSweep");
}
return (Long) mbeanServer.getAttribute(objectName, "CollectionCount");
} catch (Exception e) {
throw new RuntimeException("error");
}
}
public static String getResource(String path) {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try (Reader reader = new InputStreamReader(
contextClassLoader
.getResourceAsStream(path), "UTF-8")
) {
return Utils.read(reader);
} catch (IOException ignored) {
return null;
}
}
}
| TestUtil |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationReactiveSupportTests.java | {
"start": 1902,
"end": 7944
} | class ____ {
@Test
void ensureReactor() {
assertThat(ScheduledAnnotationReactiveSupport.REACTOR_PRESENT).isTrue();
}
@ParameterizedTest
// Note: monoWithParams can't be found by this test.
@ValueSource(strings = { "mono", "flux", "monoString", "fluxString", "publisherMono",
"publisherString", "monoThrows", "flowable", "completable" })
void checkIsReactive(String method) {
Method m = ReflectionUtils.findMethod(ReactiveMethods.class, method);
assertThat(isReactive(m)).as(m.getName()).isTrue();
}
@Test
void checkNotReactive() {
Method string = ReflectionUtils.findMethod(ReactiveMethods.class, "oops");
assertThat(isReactive(string)).as("String-returning").isFalse();
}
@Test
void rejectReactiveAdaptableButNotDeferred() {
Method future = ReflectionUtils.findMethod(ReactiveMethods.class, "future");
assertThatIllegalArgumentException().isThrownBy(() -> isReactive(future))
.withMessage("Reactive methods may only be annotated with @Scheduled if the return type supports deferred execution");
}
@Test
void isReactiveRejectsWithParams() {
Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "monoWithParam", String.class);
// isReactive rejects with context
assertThatIllegalArgumentException().isThrownBy(() -> isReactive(m))
.withMessage("Reactive methods may only be annotated with @Scheduled if declared without arguments")
.withNoCause();
}
@Test
void rejectCantProducePublisher() {
ReactiveMethods target = new ReactiveMethods();
Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "monoThrows");
// static helper method
assertThatIllegalArgumentException().isThrownBy(() -> getPublisherFor(m, target))
.withMessage("Cannot obtain a Publisher-convertible value from the @Scheduled reactive method")
.withCause(new IllegalStateException("expected"));
}
@Test
void rejectCantAccessMethod() {
ReactiveMethods target = new ReactiveMethods();
Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "monoThrowsIllegalAccess");
// static helper method
assertThatIllegalArgumentException().isThrownBy(() -> getPublisherFor(m, target))
.withMessage("Cannot obtain a Publisher-convertible value from the @Scheduled reactive method")
.withCause(new IllegalAccessException("expected"));
}
@Test
void fixedDelayIsBlocking() {
ReactiveMethods target = new ReactiveMethods();
Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "mono");
Scheduled fixedDelayString = AnnotationUtils.synthesizeAnnotation(Map.of("fixedDelayString", "123"), Scheduled.class, null);
Scheduled fixedDelayLong = AnnotationUtils.synthesizeAnnotation(Map.of("fixedDelay", 123L), Scheduled.class, null);
List<Runnable> tracker = new ArrayList<>();
assertThat(createSubscriptionRunnable(m, target, fixedDelayString, () -> ObservationRegistry.NOOP, tracker))
.isInstanceOfSatisfying(ScheduledAnnotationReactiveSupport.SubscribingRunnable.class, sr ->
assertThat(sr.shouldBlock).as("fixedDelayString.shouldBlock").isTrue()
);
assertThat(createSubscriptionRunnable(m, target, fixedDelayLong, () -> ObservationRegistry.NOOP, tracker))
.isInstanceOfSatisfying(ScheduledAnnotationReactiveSupport.SubscribingRunnable.class, sr ->
assertThat(sr.shouldBlock).as("fixedDelayLong.shouldBlock").isTrue()
);
}
@Test
void fixedRateIsNotBlocking() {
ReactiveMethods target = new ReactiveMethods();
Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "mono");
Scheduled fixedRateString = AnnotationUtils.synthesizeAnnotation(Map.of("fixedRateString", "123"), Scheduled.class, null);
Scheduled fixedRateLong = AnnotationUtils.synthesizeAnnotation(Map.of("fixedRate", 123L), Scheduled.class, null);
List<Runnable> tracker = new ArrayList<>();
assertThat(createSubscriptionRunnable(m, target, fixedRateString, () -> ObservationRegistry.NOOP, tracker))
.isInstanceOfSatisfying(ScheduledAnnotationReactiveSupport.SubscribingRunnable.class, sr ->
assertThat(sr.shouldBlock).as("fixedRateString.shouldBlock").isFalse()
);
assertThat(createSubscriptionRunnable(m, target, fixedRateLong, () -> ObservationRegistry.NOOP, tracker))
.isInstanceOfSatisfying(ScheduledAnnotationReactiveSupport.SubscribingRunnable.class, sr ->
assertThat(sr.shouldBlock).as("fixedRateLong.shouldBlock").isFalse()
);
}
@Test
void cronIsNotBlocking() {
ReactiveMethods target = new ReactiveMethods();
Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "mono");
Scheduled cron = AnnotationUtils.synthesizeAnnotation(Map.of("cron", "-"), Scheduled.class, null);
List<Runnable> tracker = new ArrayList<>();
assertThat(createSubscriptionRunnable(m, target, cron, () -> ObservationRegistry.NOOP, tracker))
.isInstanceOfSatisfying(ScheduledAnnotationReactiveSupport.SubscribingRunnable.class, sr ->
assertThat(sr.shouldBlock).as("cron.shouldBlock").isFalse()
);
}
@Test
void hasCheckpointToString() {
ReactiveMethods target = new ReactiveMethods();
Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "mono");
Publisher<?> p = getPublisherFor(m, target);
assertThat(p.getClass().getName())
.as("checkpoint class")
.isEqualTo("reactor.core.publisher.FluxOnAssembly");
assertThat(p).hasToString("checkpoint(\"@Scheduled 'mono()' in 'org.springframework.scheduling.annotation.ScheduledAnnotationReactiveSupportTests$ReactiveMethods'\")");
}
@Test
void shouldProvideToString() {
ReactiveMethods target = new ReactiveMethods();
Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "mono");
Scheduled cron = AnnotationUtils.synthesizeAnnotation(Map.of("cron", "-"), Scheduled.class, null);
List<Runnable> tracker = new ArrayList<>();
assertThat(createSubscriptionRunnable(m, target, cron, () -> ObservationRegistry.NOOP, tracker))
.hasToString("org.springframework.scheduling.annotation.ScheduledAnnotationReactiveSupportTests$ReactiveMethods.mono");
}
static | ScheduledAnnotationReactiveSupportTests |
java | elastic__elasticsearch | test/fixtures/gcs-fixture/src/test/java/fixture/gcs/GoogleCloudStorageHttpHandlerTests.java | {
"start": 36217,
"end": 39203
} | class ____ extends HttpExchange {
private static final Headers EMPTY_HEADERS = new Headers();
private final String method;
private final URI uri;
private final BytesReference requestBody;
private final Headers requestHeaders;
private final Headers responseHeaders = new Headers();
private final BytesStreamOutput responseBody = new BytesStreamOutput();
private int responseCode;
TestHttpExchange(String method, String uri, BytesReference requestBody, Headers requestHeaders) {
this.method = method;
this.uri = URI.create(uri);
this.requestBody = requestBody;
this.requestHeaders = new Headers(requestHeaders);
this.requestHeaders.add("Host", HOST);
}
@Override
public Headers getRequestHeaders() {
return requestHeaders;
}
@Override
public Headers getResponseHeaders() {
return responseHeaders;
}
@Override
public URI getRequestURI() {
return uri;
}
@Override
public String getRequestMethod() {
return method;
}
@Override
public HttpContext getHttpContext() {
return null;
}
@Override
public void close() {}
@Override
public InputStream getRequestBody() {
try {
return requestBody.streamInput();
} catch (IOException e) {
throw new AssertionError(e);
}
}
@Override
public OutputStream getResponseBody() {
return responseBody;
}
@Override
public void sendResponseHeaders(int rCode, long responseLength) {
this.responseCode = rCode;
}
@Override
public InetSocketAddress getRemoteAddress() {
return null;
}
@Override
public int getResponseCode() {
return responseCode;
}
public BytesReference getResponseBodyContents() {
return responseBody.bytes();
}
@Override
public InetSocketAddress getLocalAddress() {
return null;
}
@Override
public String getProtocol() {
return "HTTP/1.1";
}
@Override
public Object getAttribute(String name) {
return null;
}
@Override
public void setAttribute(String name, Object value) {
fail("setAttribute not implemented");
}
@Override
public void setStreams(InputStream i, OutputStream o) {
fail("setStreams not implemented");
}
@Override
public HttpPrincipal getPrincipal() {
fail("getPrincipal not implemented");
throw new UnsupportedOperationException("getPrincipal not implemented");
}
}
}
| TestHttpExchange |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/resolver/TestInitializeMountTableResolver.java | {
"start": 1513,
"end": 2924
} | class ____ {
@Test
public void testDefaultNameserviceIsMissing() {
Configuration conf = new Configuration();
MountTableResolver mountTable = new MountTableResolver(conf);
assertEquals("", mountTable.getDefaultNamespace());
}
@Test
public void testDefaultNameserviceWithEmptyString() {
Configuration conf = new Configuration();
conf.set(DFS_ROUTER_DEFAULT_NAMESERVICE, "");
MountTableResolver mountTable = new MountTableResolver(conf);
assertEquals("", mountTable.getDefaultNamespace());
assertFalse(mountTable.isDefaultNSEnable(),
"Default NS should be disabled if default NS is set empty");
}
@Test
public void testRouterDefaultNameservice() {
Configuration conf = new Configuration();
conf.set(DFS_ROUTER_DEFAULT_NAMESERVICE, "router_ns");
MountTableResolver mountTable = new MountTableResolver(conf);
assertEquals("router_ns", mountTable.getDefaultNamespace());
}
// Default NS should be empty if configured false.
@Test
public void testRouterDefaultNameserviceDisabled() {
Configuration conf = new Configuration();
conf.setBoolean(DFS_ROUTER_DEFAULT_NAMESERVICE_ENABLE, false);
conf.set(DFS_NAMESERVICE_ID, "ns_id");
conf.set(DFS_NAMESERVICES, "nss");
MountTableResolver mountTable = new MountTableResolver(conf);
assertEquals("", mountTable.getDefaultNamespace());
}
} | TestInitializeMountTableResolver |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/async/AsyncJmsProducerTest.java | {
"start": 1569,
"end": 4165
} | class ____ extends AbstractJMSTest {
@Order(2)
@RegisterExtension
public static CamelContextExtension camelContextExtension = new TransientCamelContextExtension();
private static String beforeThreadName;
private static String afterThreadName;
protected CamelContext context;
protected ProducerTemplate template;
protected ConsumerTemplate consumer;
private MockEndpoint mockBefore;
private MockEndpoint mockAfter;
private MockEndpoint mockResult;
@BeforeEach
void setupMocks() {
mockBefore = getMockEndpoint("mock:before");
mockAfter = getMockEndpoint("mock:after");
mockResult = getMockEndpoint("mock:result");
mockBefore.expectedBodiesReceived("Hello Camel");
mockAfter.expectedBodiesReceived("Bye Camel");
mockResult.expectedBodiesReceived("Bye Camel");
}
@RepeatedTest(5)
public void testAsyncEndpoint() throws Exception {
String reply = template.requestBody("direct:start", "Hello Camel", String.class);
assertEquals("Bye Camel", reply);
mockBefore.assertIsSatisfied();
mockAfter.assertIsSatisfied();
mockResult.assertIsSatisfied();
assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should use different threads");
}
@Override
protected String getComponentName() {
return "activemq";
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.to("mock:before")
.to("log:before")
.process(exchange -> beforeThreadName = Thread.currentThread().getName())
.to("activemq:queue:AsyncJmsProducerTest")
.process(exchange -> afterThreadName = Thread.currentThread().getName())
.to("log:after")
.to("mock:after")
.to("mock:result");
from("activemq:queue:AsyncJmsProducerTest")
.transform(constant("Bye Camel"));
}
};
}
@Override
public CamelContextExtension getCamelContextExtension() {
return camelContextExtension;
}
@BeforeEach
void setUpRequirements() {
context = camelContextExtension.getContext();
template = camelContextExtension.getProducerTemplate();
consumer = camelContextExtension.getConsumerTemplate();
}
}
| AsyncJmsProducerTest |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/CatalogFactory.java | {
"start": 1251,
"end": 1467
} | interface ____ the {@link TableFactory} stack for compatibility purposes.
* This is deprecated, however, and new implementations should implement the {@link Factory} stack
* instead.
*/
@PublicEvolving
public | supports |
java | alibaba__nacos | config/src/main/java/com/alibaba/nacos/config/server/remote/ConfigChangeListenContext.java | {
"start": 1209,
"end": 6806
} | class ____ {
/**
* groupKey-> connection set.
*/
private ConcurrentHashMap<String, HashSet<String>> groupKeyContext = new ConcurrentHashMap<>();
/**
* connectionId-> group key set.
*/
private ConcurrentHashMap<String, HashMap<String, ConfigListenState>> connectionIdContext = new ConcurrentHashMap<>();
/**
* add listen.
*
* @param groupKey groupKey.
* @param connectionId connectionId.
*/
public synchronized void addListen(String groupKey, String md5, String connectionId, boolean isNamespaceTransfer) {
// 1.add groupKeyContext
groupKeyContext.computeIfAbsent(groupKey, k -> new HashSet<>()).add(connectionId);
// 2.add connectionIdContext
ConfigListenState listenState = new ConfigListenState(md5);
listenState.setNamespaceTransfer(isNamespaceTransfer);
connectionIdContext.computeIfAbsent(connectionId, k -> new HashMap<>(16)).put(groupKey, listenState);
}
/**
* remove listen context for connection id .
*
* @param groupKey groupKey.
* @param connectionId connection id.
*/
public synchronized void removeListen(String groupKey, String connectionId) {
//1. remove groupKeyContext
Set<String> connectionIds = groupKeyContext.get(groupKey);
if (connectionIds != null) {
connectionIds.remove(connectionId);
if (connectionIds.isEmpty()) {
groupKeyContext.remove(groupKey);
}
}
//2.remove connectionIdContext
HashMap<String, ConfigListenState> groupKeys = connectionIdContext.get(connectionId);
if (groupKeys != null) {
groupKeys.remove(groupKey);
}
}
/**
* get listeners of the group key.
*
* @param groupKey groupKey.
* @return the copy of listeners, may be return null.
*/
public synchronized Set<String> getListeners(String groupKey) {
HashSet<String> strings = groupKeyContext.get(groupKey);
if (CollectionUtils.isNotEmpty(strings)) {
Set<String> listenConnections = new HashSet<>();
safeCopy(strings, listenConnections);
return listenConnections;
}
return null;
}
/**
* copy collections.
*
* @param src may be modified concurrently
* @param dest dest collection
*/
private void safeCopy(Collection src, Collection dest) {
Iterator iterator = src.iterator();
while (iterator.hasNext()) {
dest.add(iterator.next());
}
}
/**
* remove the context related to the connection id.
*
* @param connectionId connectionId.
*/
public synchronized void clearContextForConnectionId(final String connectionId) {
Map<String, String> listenKeys = getListenKeys(connectionId);
if (listenKeys == null) {
connectionIdContext.remove(connectionId);
return;
}
for (Map.Entry<String, String> groupKey : listenKeys.entrySet()) {
Set<String> connectionIds = groupKeyContext.get(groupKey.getKey());
if (CollectionUtils.isNotEmpty(connectionIds)) {
connectionIds.remove(connectionId);
if (connectionIds.isEmpty()) {
groupKeyContext.remove(groupKey.getKey());
}
} else {
groupKeyContext.remove(groupKey.getKey());
}
}
connectionIdContext.remove(connectionId);
}
/**
* get listen keys.
*
* @param connectionId connection id.
* @return listen group keys of the connection id, key:group key,value:md5
*/
public synchronized Map<String, String> getListenKeys(String connectionId) {
HashMap<String, ConfigListenState> stringStringHashMap = connectionIdContext.get(connectionId);
if (stringStringHashMap != null) {
HashMap<String, String> md5Map = new HashMap<>(stringStringHashMap.size());
for (Map.Entry<String, ConfigListenState> entry : stringStringHashMap.entrySet()) {
md5Map.put(entry.getKey(), entry.getValue().getMd5());
}
return md5Map;
} else {
return null;
}
}
/**
* get md5.
*
* @param connectionId connection id.
* @return md5 of the listen group key.
*/
public String getListenKeyMd5(String connectionId, String groupKey) {
Map<String, ConfigListenState> groupKeyContexts = connectionIdContext.get(connectionId);
return groupKeyContexts == null ? null : groupKeyContexts.get(groupKey).getMd5();
}
public ConfigListenState getConfigListenState(String connectionId, String groupKey) {
Map<String, ConfigListenState> groupKeyContexts = connectionIdContext.get(connectionId);
return groupKeyContexts == null ? null : groupKeyContexts.get(groupKey);
}
public synchronized HashMap<String, ConfigListenState> getConfigListenStates(String connectionId) {
HashMap<String, ConfigListenState> configListenStateHashMap = connectionIdContext.get(connectionId);
return configListenStateHashMap == null ? null : new HashMap<>(configListenStateHashMap);
}
/**
* get connection count.
*
* @return count of long connections.
*/
public int getConnectionCount() {
return connectionIdContext.size();
}
}
| ConfigChangeListenContext |
java | elastic__elasticsearch | plugins/repository-hdfs/src/main/java/org/elasticsearch/repositories/hdfs/HdfsRepository.java | {
"start": 2170,
"end": 13476
} | class ____ extends BlobStoreRepository {
private static final int MIN_REPLICATION_FACTOR = 1;
private static final int MAX_REPLICATION_FACTOR = Short.MAX_VALUE;
private static final Logger logger = LogManager.getLogger(HdfsRepository.class);
private static final String CONF_SECURITY_PRINCIPAL = "security.principal";
private final Environment environment;
private final ByteSizeValue chunkSize;
private final URI uri;
private final String pathSetting;
public HdfsRepository(
@Nullable ProjectId projectId,
RepositoryMetadata metadata,
Environment environment,
NamedXContentRegistry namedXContentRegistry,
ClusterService clusterService,
BigArrays bigArrays,
RecoverySettings recoverySettings,
SnapshotMetrics snapshotMetrics
) {
super(projectId, metadata, namedXContentRegistry, clusterService, bigArrays, recoverySettings, BlobPath.EMPTY, snapshotMetrics);
this.environment = environment;
this.chunkSize = metadata.settings().getAsBytesSize("chunk_size", null);
String uriSetting = getMetadata().settings().get("uri");
if (Strings.hasText(uriSetting) == false) {
throw new IllegalArgumentException("No 'uri' defined for hdfs snapshot/restore");
}
uri = URI.create(uriSetting);
if ("hdfs".equalsIgnoreCase(uri.getScheme()) == false) {
throw new IllegalArgumentException(
String.format(
Locale.ROOT,
"Invalid scheme [%s] specified in uri [%s]; only 'hdfs' uri allowed for hdfs snapshot/restore",
uri.getScheme(),
uriSetting
)
);
}
if (Strings.hasLength(uri.getPath()) && uri.getPath().equals("/") == false) {
throw new IllegalArgumentException(
String.format(
Locale.ROOT,
"Use 'path' option to specify a path [%s], not the uri [%s] for hdfs snapshot/restore",
uri.getPath(),
uriSetting
)
);
}
pathSetting = getMetadata().settings().get("path");
// get configuration
if (pathSetting == null) {
throw new IllegalArgumentException("No 'path' defined for hdfs snapshot/restore");
}
}
private HdfsBlobStore createBlobstore(URI blobstoreUri, String path, Settings repositorySettings) {
Configuration hadoopConfiguration = new Configuration(repositorySettings.getAsBoolean("load_defaults", true));
hadoopConfiguration.setClassLoader(HdfsRepository.class.getClassLoader());
hadoopConfiguration.reloadConfiguration();
final Settings confSettings = repositorySettings.getByPrefix("conf.");
for (String key : confSettings.keySet()) {
logger.debug("Adding configuration to HDFS Client Configuration : {} = {}", key, confSettings.get(key));
hadoopConfiguration.set(key, confSettings.get(key));
}
Integer replicationFactor = repositorySettings.getAsInt("replication_factor", null);
if (replicationFactor != null && replicationFactor < MIN_REPLICATION_FACTOR) {
throw new RepositoryException(
metadata.name(),
"Value of replication_factor [{}] must be >= {}",
replicationFactor,
MIN_REPLICATION_FACTOR
);
}
if (replicationFactor != null && replicationFactor > MAX_REPLICATION_FACTOR) {
throw new RepositoryException(
metadata.name(),
"Value of replication_factor [{}] must be <= {}",
replicationFactor,
MAX_REPLICATION_FACTOR
);
}
int minReplicationFactory = hadoopConfiguration.getInt("dfs.replication.min", 0);
int maxReplicationFactory = hadoopConfiguration.getInt("dfs.replication.max", 512);
if (replicationFactor != null && replicationFactor < minReplicationFactory) {
throw new RepositoryException(
metadata.name(),
"Value of replication_factor [{}] must be >= dfs.replication.min [{}]",
replicationFactor,
minReplicationFactory
);
}
if (replicationFactor != null && replicationFactor > maxReplicationFactory) {
throw new RepositoryException(
metadata.name(),
"Value of replication_factor [{}] must be <= dfs.replication.max [{}]",
replicationFactor,
maxReplicationFactory
);
}
// Disable FS cache
hadoopConfiguration.setBoolean("fs.hdfs.impl.disable.cache", true);
// Create a hadoop user
UserGroupInformation ugi = login(hadoopConfiguration, repositorySettings);
// Sense if HA is enabled
// HA requires elevated permissions during regular usage in the event that a failover operation
// occurs and a new connection is required.
String host = blobstoreUri.getHost();
String configKey = HdfsClientConfigKeys.Failover.PROXY_PROVIDER_KEY_PREFIX + "." + host;
Class<?> ret = hadoopConfiguration.getClass(configKey, null, FailoverProxyProvider.class);
boolean haEnabled = ret != null;
// Create the filecontext with our user information
// This will correctly configure the filecontext to have our UGI as its internal user.
FileContext fileContext = ugi.doAs((PrivilegedAction<FileContext>) () -> {
try {
AbstractFileSystem fs = AbstractFileSystem.get(blobstoreUri, hadoopConfiguration);
return FileContext.getFileContext(fs, hadoopConfiguration);
} catch (UnsupportedFileSystemException e) {
throw new UncheckedIOException(e);
}
});
logger.debug(
"Using file-system [{}] for URI [{}], path [{}]",
fileContext.getDefaultFileSystem(),
fileContext.getDefaultFileSystem().getUri(),
path
);
try {
return new HdfsBlobStore(
fileContext,
path,
bufferSize,
isReadOnly(),
haEnabled,
replicationFactor != null ? replicationFactor.shortValue() : null
);
} catch (IOException e) {
throw new UncheckedIOException(String.format(Locale.ROOT, "Cannot create HDFS repository for uri [%s]", blobstoreUri), e);
}
}
private UserGroupInformation login(Configuration hadoopConfiguration, Settings repositorySettings) {
// Validate the authentication method:
AuthenticationMethod authMethod = SecurityUtil.getAuthenticationMethod(hadoopConfiguration);
if (authMethod.equals(AuthenticationMethod.SIMPLE) == false && authMethod.equals(AuthenticationMethod.KERBEROS) == false) {
throw new RuntimeException("Unsupported authorization mode [" + authMethod + "]");
}
// Check if the user added a principal to use, and that there is a keytab file provided
String kerberosPrincipal = repositorySettings.get(CONF_SECURITY_PRINCIPAL);
// Check to see if the authentication method is compatible
if (kerberosPrincipal != null && authMethod.equals(AuthenticationMethod.SIMPLE)) {
logger.warn(
"Hadoop authentication method is set to [SIMPLE], but a Kerberos principal is "
+ "specified. Continuing with [KERBEROS] authentication."
);
SecurityUtil.setAuthenticationMethod(AuthenticationMethod.KERBEROS, hadoopConfiguration);
} else if (kerberosPrincipal == null && authMethod.equals(AuthenticationMethod.KERBEROS)) {
throw new RuntimeException(
"HDFS Repository does not support [KERBEROS] authentication without "
+ "a valid Kerberos principal and keytab. Please specify a principal in the repository settings with ["
+ CONF_SECURITY_PRINCIPAL
+ "]."
);
}
// Now we can initialize the UGI with the configuration.
UserGroupInformation.setConfiguration(hadoopConfiguration);
// Debugging
logger.debug("Hadoop security enabled: [{}]", UserGroupInformation.isSecurityEnabled());
logger.debug("Using Hadoop authentication method: [{}]", SecurityUtil.getAuthenticationMethod(hadoopConfiguration));
// UserGroupInformation (UGI) instance is just a Hadoop specific wrapper around a Java Subject
try {
if (UserGroupInformation.isSecurityEnabled()) {
String principal = preparePrincipal(kerberosPrincipal);
String keytab = HdfsSecurityContext.locateKeytabFile(environment).toString();
logger.debug("Using kerberos principal [{}] and keytab located at [{}]", principal, keytab);
return UserGroupInformation.loginUserFromKeytabAndReturnUGI(principal, keytab);
}
return UserGroupInformation.getCurrentUser();
} catch (IOException e) {
throw new UncheckedIOException("Could not retrieve the current user information", e);
}
}
// Convert principals of the format 'service/_HOST@REALM' by subbing in the local address for '_HOST'.
private static String preparePrincipal(String originalPrincipal) {
String finalPrincipal = originalPrincipal;
// Don't worry about host name resolution if they don't have the _HOST pattern in the name.
if (originalPrincipal.contains("_HOST")) {
try {
finalPrincipal = SecurityUtil.getServerPrincipal(originalPrincipal, getHostName());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
if (originalPrincipal.equals(finalPrincipal) == false) {
logger.debug(
"Found service principal. Converted original principal name [{}] to server principal [{}]",
originalPrincipal,
finalPrincipal
);
}
}
return finalPrincipal;
}
@SuppressForbidden(reason = "InetAddress.getLocalHost(); Needed for filling in hostname for a kerberos principal name pattern.")
private static String getHostName() {
try {
/*
* This should not block since it should already be resolved via Log4J and Netty. The
* host information is cached by the JVM and the TTL for the cache entry is infinite
* when the SecurityManager is activated.
*/
return InetAddress.getLocalHost().getCanonicalHostName();
} catch (UnknownHostException e) {
throw new RuntimeException("Could not locate host information", e);
}
}
@Override
protected HdfsBlobStore createBlobStore() {
return createBlobstore(uri, pathSetting, getMetadata().settings());
}
@Override
protected ByteSizeValue chunkSize() {
return chunkSize;
}
}
| HdfsRepository |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/Mockito.java | {
"start": 96773,
"end": 97302
} | class ____ {
*
* private HttpBuilder builder;
*
* public HttpRequesterWithHeaders(HttpBuilder builder) {
* this.builder = builder;
* }
*
* public String request(String uri) {
* return builder.withUrl(uri)
* .withHeader("Content-type: application/json")
* .withHeader("Authorization: Bearer")
* .request();
* }
* }
*
* private static | HttpRequesterWithHeaders |
java | apache__camel | components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaSslContextParametersVmTest.java | {
"start": 987,
"end": 2030
} | class ____ extends BaseMinaTest {
@Test
public void testMinaRoute() throws Exception {
MockEndpoint endpoint = getMockEndpoint("mock:result");
Object body = "Hello there!";
endpoint.expectedBodiesReceived(body);
template.sendBodyAndHeader(
"mina:vm://localhost:" + getPort() + "?sync=false&minaLogger=true&sslContextParameters=#sslContextParameters",
body, "cheese", 123);
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected boolean isUseSslContext() {
return true;
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
fromF("mina:vm://localhost:%s?sync=false&minaLogger=true&sslContextParameters=#sslContextParameters", getPort())
.to("log:before?showAll=true").to("mock:result")
.to("log:after?showAll=true");
}
};
}
}
| MinaSslContextParametersVmTest |
java | google__guice | extensions/jmx/test/com/google/inject/tools/jmx/JmxTest.java | {
"start": 1021,
"end": 1076
} | class ____ implements Foo {}
@Singleton
static | FooImpl |
java | google__guice | core/test/com/google/inject/MethodInterceptionTest.java | {
"start": 17382,
"end": 17930
} | class ____ implements MethodInterceptor {
private final Queue<Runnable> queue;
public CallLaterInterceptor(Queue<Runnable> queue) {
this.queue = queue;
}
@Override
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
queue.add(
() -> {
try {
methodInvocation.proceed();
} catch (Throwable t) {
throw new RuntimeException(t);
}
});
return null;
}
}
@Retention(RUNTIME)
@ | CallLaterInterceptor |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/config/annotation/ProvidedBy.java | {
"start": 1339,
"end": 1565
} | class ____ {
* @DubboReference(version = "1.0.0")
* private GreetingService greetingService;
* }
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
public @ | GreetingServiceConsumer |
java | apache__camel | components/camel-master/src/test/java/org/apache/camel/component/master/EndpointUriEncodingTest.java | {
"start": 2582,
"end": 3903
} | class ____ extends DefaultComponent {
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) {
return new DefaultEndpoint(uri, this) {
private String foo;
private String bar;
public void setFoo(String foo) {
this.foo = foo;
}
public void setBar(String bar) {
this.bar = bar;
}
@Override
public Producer createProducer() {
return null;
}
@Override
public Consumer createConsumer(Processor processor) {
return new DefaultConsumer(this, processor) {
@Override
protected void doStart() throws Exception {
super.doStart();
Exchange exchange = createExchange(true);
exchange.getMessage().setHeader("foo", foo);
exchange.getMessage().setHeader("bar", bar);
getProcessor().process(exchange);
}
};
}
};
}
}
}
| DummyComponent |
java | elastic__elasticsearch | x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/action/TransformConfigLinter.java | {
"start": 933,
"end": 2883
} | class ____ {
private static final String GROUP_BY_FIELDS_ARE_RUNTIME_FIELDS =
"all the group-by fields are script-based runtime fields, this transform might run slowly, please check your configuration.";
private static final String SYNC_FIELD_IS_RUNTIME_FIELD =
"sync time field is a script-based runtime field, this transform might run slowly, please check your configuration.";
private static final String NOT_OPTIMIZED =
"could not find any optimizations for continuous execution, this transform might run slowly, please check your configuration.";
/**
* Gets the list of warnings for the given config.
*
* @param function transform function
* @param sourceConfig source config
* @param syncConfig synchronization config when the transform is continuous or {@code null} otherwise
* @return list of warnings
*/
static List<String> getWarnings(Function function, SourceConfig sourceConfig, SyncConfig syncConfig) {
if (syncConfig == null) {
return Collections.emptyList();
}
List<String> warnings = new ArrayList<>();
Map<String, Object> scriptBasedRuntimeFieldNames = sourceConfig.getScriptBasedRuntimeMappings();
List<String> performanceCriticalFields = function.getPerformanceCriticalFields();
if (performanceCriticalFields.stream().allMatch(scriptBasedRuntimeFieldNames::containsKey)) {
warnings.add(GROUP_BY_FIELDS_ARE_RUNTIME_FIELDS);
}
if (scriptBasedRuntimeFieldNames.containsKey(syncConfig.getField())) {
warnings.add(SYNC_FIELD_IS_RUNTIME_FIELD);
}
Function.ChangeCollector changeCollector = function.buildChangeCollector(syncConfig.getField());
if (changeCollector.isOptimized() == false) {
warnings.add(NOT_OPTIMIZED);
}
return warnings;
}
private TransformConfigLinter() {}
}
| TransformConfigLinter |
java | qos-ch__slf4j | slf4j-migrator/src/main/java/org/slf4j/migrator/line/RuleSet.java | {
"start": 1272,
"end": 1337
} | interface ____ {
Iterator<ConversionRule> iterator();
}
| RuleSet |
java | google__guava | android/guava/src/com/google/common/collect/ClassToInstanceMap.java | {
"start": 2246,
"end": 2553
} | class ____ mapped to, or {@code null} if no entry for this class
* is present. This will only return a value that was bound to this specific class, not a value
* that may have been bound to a subtype.
*/
<T extends @NonNull B> @Nullable T getInstance(Class<T> type);
/**
* Maps the specified | is |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/properties/OptionalPropertiesDslTest.java | {
"start": 1145,
"end": 2647
} | class ____ extends ContextTestSupport {
@Test
public void testPlaceholderDslTest() throws Exception {
getMockEndpoint("mock:a").expectedMessageCount(1);
getMockEndpoint("mock:b").expectedMessageCount(0);
assertThrows(Exception.class,
() -> template.sendBody("direct:start", "Hello World"),
"Should have thrown an exception");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// START SNIPPET: e1
from("direct:start")
// use a property placeholder for the option stopOnException
// on the Multicast EIP
// which should have the value of {{stop}} key being looked
// up in the properties file
.multicast().stopOnException("{{stop}}").to("mock:a")
.throwException(new IllegalAccessException("Damn")).to("mock:b");
// END SNIPPET: e1
}
};
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
context.getPropertiesComponent().setLocation("classpath:org/apache/camel/component/properties/myproperties.properties");
return context;
}
}
| OptionalPropertiesDslTest |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/handler/IgnoreErrorsBindHandler.java | {
"start": 1252,
"end": 1663
} | class ____ extends AbstractBindHandler {
public IgnoreErrorsBindHandler() {
}
public IgnoreErrorsBindHandler(BindHandler parent) {
super(parent);
}
@Override
public @Nullable Object onFailure(ConfigurationPropertyName name, Bindable<?> target, BindContext context,
Exception error) throws Exception {
return (target.getValue() != null) ? target.getValue().get() : null;
}
}
| IgnoreErrorsBindHandler |
java | quarkusio__quarkus | core/runtime/src/main/java/io/quarkus/runtime/annotations/ConfigDocEnumValue.java | {
"start": 433,
"end": 509
} | enum ____.
*/
@Retention(RUNTIME)
@Target({ FIELD })
@Documented
public @ | values |
java | elastic__elasticsearch | x-pack/plugin/rollup/src/main/java/org/elasticsearch/xpack/rollup/action/RollupInfoTransportAction.java | {
"start": 657,
"end": 1172
} | class ____ extends XPackInfoFeatureTransportAction {
@Inject
public RollupInfoTransportAction(TransportService transportService, ActionFilters actionFilters) {
super(XPackInfoFeatureAction.ROLLUP.name(), transportService, actionFilters);
}
@Override
public String name() {
return XPackField.ROLLUP;
}
@Override
public boolean available() {
return true;
}
@Override
public boolean enabled() {
return true;
}
}
| RollupInfoTransportAction |
java | apache__camel | test-infra/camel-test-infra-redis/src/test/java/org/apache/camel/test/infra/redis/services/RedisServiceFactory.java | {
"start": 947,
"end": 1401
} | class ____ {
private RedisServiceFactory() {
}
public static SimpleTestServiceBuilder<RedisService> builder() {
return new SimpleTestServiceBuilder<>("redis");
}
public static RedisService createService() {
return builder()
.addLocalMapping(RedisLocalContainerService::new)
.addRemoteMapping(RedisRemoteService::new)
.build();
}
public static | RedisServiceFactory |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/mapper/blockloader/docvalues/DenseVectorBlockLoader.java | {
"start": 9207,
"end": 9981
} | class ____<B extends BlockLoader.Builder> extends AbstractVectorValuesReader<
ByteVectorValues,
B> {
ByteDenseVectorValuesBlockReader(ByteVectorValues byteVectorValues, int dimensions, DenseVectorBlockLoaderProcessor<B> processor) {
super(byteVectorValues, processor, dimensions);
}
@Override
protected void processCurrentVector(B builder) throws IOException {
assertDimensions();
byte[] vector = vectorValues.vectorValue(iterator.index());
processor.process(vector, builder);
}
@Override
public String toString() {
return "ByteDenseVectorFromDocValues." + processor.name();
}
}
private static | ByteDenseVectorValuesBlockReader |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/script/ScriptContextInfoTests.java | {
"start": 1368,
"end": 1864
} | interface ____ {
void execute();
}
public void testMinimalContext() {
String name = "minimal_context";
ScriptContextInfo info = new ScriptContextInfo(name, MinimalContext.class);
assertEquals(name, info.name);
assertEquals("execute", info.execute.name);
assertEquals("void", info.execute.returnType);
assertEquals(0, info.execute.parameters.size());
assertEquals(0, info.getters.size());
}
public static | MinimalContext |
java | quarkusio__quarkus | extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/config/ConfigActiveFalseStaticInjectionTest.java | {
"start": 1707,
"end": 1888
} | class ____ {
@Inject
Session session;
@Transactional
public void useHibernate() {
session.find(MyEntity.class, 1L);
}
}
}
| MyBean |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/autodetect/AutodetectCommunicator.java | {
"start": 16063,
"end": 18612
} | class ____ call it wait for all processing to complete first.
* The expectation is that external calls are only made when cleaning up after a fatal
* error.
*/
void destroyCategorizationAnalyzer() {
if (categorizationAnalyzer != null) {
categorizationAnalyzer.close();
categorizationAnalyzer = null;
}
}
private <T> void submitOperation(CheckedSupplier<T, Exception> operation, BiConsumer<T, Exception> handler) {
autodetectWorkerExecutor.execute(new AbstractRunnable() {
@Override
public void onFailure(Exception e) {
if (processKilled) {
handler.accept(
null,
ExceptionsHelper.conflictStatusException(
"[{}] Could not submit operation to process as it has been killed",
job.getId()
)
);
} else {
logger.error(() -> "[" + job.getId() + "] Unexpected exception writing to process", e);
handler.accept(null, e);
}
}
@Override
protected void doRun() throws Exception {
if (processKilled) {
handler.accept(
null,
ExceptionsHelper.conflictStatusException(
"[{}] Could not submit operation to process as it has been killed",
job.getId()
)
);
} else {
checkProcessIsAlive();
handler.accept(operation.get(), null);
}
}
});
}
private void createCategorizationAnalyzer(AnalysisRegistry analysisRegistry) throws IOException {
AnalysisConfig analysisConfig = job.getAnalysisConfig();
CategorizationAnalyzerConfig categorizationAnalyzerConfig = analysisConfig.getCategorizationAnalyzerConfig();
if (categorizationAnalyzerConfig == null) {
categorizationAnalyzerConfig = CategorizationAnalyzerConfig.buildDefaultCategorizationAnalyzer(
analysisConfig.getCategorizationFilters()
);
}
categorizationAnalyzer = new CategorizationAnalyzer(analysisRegistry, categorizationAnalyzerConfig);
}
public void setVacating(boolean vacating) {
autodetectResultProcessor.setVacating(vacating);
}
}
| that |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/MinLongAggregatorFunctionSupplier.java | {
"start": 646,
"end": 1569
} | class ____ implements AggregatorFunctionSupplier {
public MinLongAggregatorFunctionSupplier() {
}
@Override
public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() {
return MinLongAggregatorFunction.intermediateStateDesc();
}
@Override
public List<IntermediateStateDesc> groupingIntermediateStateDesc() {
return MinLongGroupingAggregatorFunction.intermediateStateDesc();
}
@Override
public MinLongAggregatorFunction aggregator(DriverContext driverContext, List<Integer> channels) {
return MinLongAggregatorFunction.create(driverContext, channels);
}
@Override
public MinLongGroupingAggregatorFunction groupingAggregator(DriverContext driverContext,
List<Integer> channels) {
return MinLongGroupingAggregatorFunction.create(channels, driverContext);
}
@Override
public String describe() {
return "min of longs";
}
}
| MinLongAggregatorFunctionSupplier |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/autoflush/JpaAutoflushTest.java | {
"start": 609,
"end": 3343
} | class ____ {
@Test void test1(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
scope.inTransaction( em -> {
em.persist( new Thing( "Widget" ) );
List<?> resultList =
em.createNativeQuery( "select * from Thing", Thing.class )
.getResultList();
// spec says we must flush before native query in tx
assertEquals( 1, resultList.size() );
} );
}
@Test void test2(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
scope.inTransaction( em -> {
em.persist( new Thing("Widget") );
List<?> resultList =
em.createNativeQuery( "select typeOfThing from Thing", String.class )
.getResultList();
// spec says we must flush before native query in tx
assertEquals(1, resultList.size());
} );
}
@Test void test3(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
scope.inEntityManager( em -> {
em.persist( new Thing("Widget") );
List<?> resultList =
em.createNativeQuery( "select * from Thing", Thing.class )
.getResultList();
// spec says we must NOT flush before native query outside tx
assertEquals(0, resultList.size());
} );
}
@Test void test4(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
scope.inTransaction( em -> {
em.setFlushMode( FlushModeType.COMMIT );
em.persist( new Thing("Widget") );
List<?> resultList =
em.createNativeQuery( "select * from Thing", Thing.class )
.getResultList();
// spec says we must NOT flush before native query with FMT.COMMIT
assertEquals(0, resultList.size());
} );
}
@Test void test5(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
scope.inTransaction( em -> {
em.persist( new Thing("Widget") );
List<?> resultList =
em.createNativeQuery( "select * from Thing", Thing.class )
.setHint( HINT_NATIVE_SPACES, "Thing" )
.getResultList();
// we should not flush because user specified that the query touches the table
assertEquals(1, resultList.size());
} );
}
@Test void test6(EntityManagerFactoryScope scope) {
scope.getEntityManagerFactory().getSchemaManager().truncate();
scope.inTransaction( em -> {
em.persist( new Thing("Widget") );
List<?> resultList =
em.createNativeQuery( "select * from Thing", Thing.class )
.setHint( HINT_NATIVE_SPACES, "XXX" )
.getResultList();
// we should not flush because user specified that the query doesn't touch the table
assertEquals(0, resultList.size());
} );
}
@Entity(name="Thing")
public static | JpaAutoflushTest |
java | resilience4j__resilience4j | resilience4j-spring-boot2/src/test/java/io/github/resilience4j/retry/RetryAutoConfigurationReactorTest.java | {
"start": 1716,
"end": 4690
} | class ____ {
@Autowired
RetryRegistry retryRegistry;
@Autowired
RetryProperties retryProperties;
@Autowired
RetryAspect retryAspect;
@Autowired
ReactiveRetryDummyService retryDummyService;
@Autowired
private TestRestTemplate restTemplate;
/**
* The test verifies that a Retry instance is created and configured properly when the
* RetryReactiveDummyService is invoked and that the Retry logic is properly handled
*/
@Test
public void testRetryAutoConfigurationReactor() throws IOException {
assertThat(retryRegistry).isNotNull();
assertThat(retryProperties).isNotNull();
RetryEventsEndpointResponse retryEventListBefore = retryEventListBody(
"/actuator/retryevents");
RetryEventsEndpointResponse retryEventListForCBefore =
retryEventListBody("/actuator/retryevents/" + BACKEND_C);
try {
retryDummyService.doSomethingFlux(true)
.doOnError(throwable -> System.out.println("Exception received:" + throwable.getMessage()))
.blockLast();
} catch (IllegalArgumentException ex) {
// Do nothing. The IllegalArgumentException is recorded by the retry as it is one of failure exceptions
}
// The invocation is recorded by the CircuitBreaker as a success.
retryDummyService.doSomethingFlux(false)
.doOnError(throwable -> System.out.println("Exception received:" + throwable.getMessage()))
.blockLast();
Retry retry = retryRegistry.retry(BACKEND_C);
assertThat(retry).isNotNull();
// expect retry is configured as defined in application.yml
assertThat(retry.getRetryConfig().getMaxAttempts()).isEqualTo(3);
assertThat(retry.getName()).isEqualTo(BACKEND_C);
assertThat(retry.getRetryConfig().getExceptionPredicate().test(new IOException())).isTrue();
// expect retry-event actuator endpoint recorded both events
RetryEventsEndpointResponse retryEventList = retryEventListBody("/actuator/retryevents");
assertThat(retryEventList.getRetryEvents())
.hasSize(retryEventListBefore.getRetryEvents().size() + 3);
retryEventList = retryEventListBody("/actuator/retryevents/" + BACKEND_C);
assertThat(retryEventList.getRetryEvents())
.hasSize(retryEventListForCBefore.getRetryEvents().size() + 3);
assertThat(
retry.getRetryConfig().getExceptionPredicate().test(new IllegalArgumentException()))
.isTrue();
assertThat(retry.getRetryConfig().getExceptionPredicate().test(new IgnoredException()))
.isFalse();
assertThat(retryAspect.getOrder()).isEqualTo(399);
}
private RetryEventsEndpointResponse retryEventListBody(String url) {
return restTemplate.getForEntity(url, RetryEventsEndpointResponse.class).getBody();
}
}
| RetryAutoConfigurationReactorTest |
java | apache__camel | components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/events/KubernetesEventsConsumer.java | {
"start": 1769,
"end": 3153
} | class ____ extends DefaultConsumer {
private static final Logger LOG = LoggerFactory.getLogger(KubernetesEventsConsumer.class);
private final Processor processor;
private ExecutorService executor;
private EventsConsumerTask eventWatcher;
public KubernetesEventsConsumer(AbstractKubernetesEndpoint endpoint, Processor processor) {
super(endpoint, processor);
this.processor = processor;
}
@Override
public AbstractKubernetesEndpoint getEndpoint() {
return (AbstractKubernetesEndpoint) super.getEndpoint();
}
@Override
protected void doStart() throws Exception {
super.doStart();
executor = getEndpoint().createExecutor(this);
eventWatcher = new EventsConsumerTask();
executor.submit(eventWatcher);
}
@Override
protected void doStop() throws Exception {
super.doStop();
LOG.debug("Stopping Kubernetes Event Consumer");
if (executor != null) {
KubernetesHelper.close(eventWatcher, eventWatcher::getWatch);
if (getEndpoint() != null && getEndpoint().getCamelContext() != null) {
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(executor);
} else {
executor.shutdownNow();
}
}
executor = null;
}
| KubernetesEventsConsumer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/LambdaFunctionalInterfaceTest.java | {
"start": 13259,
"end": 13748
} | class ____ {
private <T> int sumAll(Function<T, Integer> sizeConv) {
return sizeConv.apply((T) Integer.valueOf(3));
}
public int getSumAll() {
return sumAll(o -> 2);
}
}
""")
.addOutputLines(
"out/NumbertoT.java",
"""
import java.util.function.Function;
import java.util.function.ToIntFunction;
public | NumbertoT |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/DoubleCheckedLockingTest.java | {
"start": 4703,
"end": 5132
} | class ____ {
public String x;
String m() {
String result = x;
if (result == null) {
synchronized (this) {
if (result == null) {
x = result = "";
}
}
}
return result;
}
}
""")
.doTest();
}
}
| Test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.