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__camel
components/camel-hashicorp-vault/src/main/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultProducer.java
{ "start": 1298, "end": 6162 }
class ____ extends DefaultProducer { public HashicorpVaultProducer(final Endpoint endpoint) { super(endpoint); } @Override public void process(Exchange exchange) throws Exception { HashicorpVaultOperation operation = determineOperation(exchange); switch (operation) { case createSecret: createSecret(exchange); break; case getSecret: getSecret(exchange); break; case deleteSecret: deleteSecret(exchange); break; case listSecrets: listSecrets(exchange); break; default: throw new IllegalArgumentException("Unsupported operation"); } } private void createSecret(Exchange exchange) { String secretPath = getSecretPath(exchange); VaultKeyValueOperations keyValue = getEndpoint().getVaultTemplate().opsForKeyValue(getEndpoint().getConfiguration().getSecretsEngine(), VaultKeyValueOperationsSupport.KeyValueBackend.versioned()); keyValue.put(secretPath, exchange.getMessage().getBody()); } private void getSecret(Exchange exchange) { String secretPath = getSecretPath(exchange); String secretVersion = null; if (ObjectHelper.isNotEmpty(exchange.getMessage().getHeader(HashicorpVaultConstants.SECRET_VERSION))) { secretVersion = exchange.getMessage().getHeader(HashicorpVaultConstants.SECRET_VERSION, String.class); } String completePath = ""; if (!getEndpoint().getConfiguration().isCloud()) { completePath = getEndpoint().getConfiguration().getSecretsEngine() + "/" + "data" + "/" + secretPath; } else { if (ObjectHelper.isNotEmpty(getEndpoint().getConfiguration().getNamespace())) { completePath = getEndpoint().getConfiguration().getNamespace() + "/" + getEndpoint().getConfiguration().getSecretsEngine() + "/" + "data" + "/" + secretPath; } } if (ObjectHelper.isNotEmpty(secretVersion)) { completePath = completePath + "?version=" + secretVersion; } VaultResponse rawSecret = getEndpoint().getVaultTemplate().read(completePath); if (rawSecret != null) { exchange.getMessage().setBody(rawSecret.getData()); } else { exchange.getMessage().setBody(null); } } private void deleteSecret(Exchange exchange) { String secretPath = getSecretPath(exchange); VaultKeyValueOperations keyValue = getEndpoint().getVaultTemplate().opsForKeyValue(getEndpoint().getConfiguration().getSecretsEngine(), VaultKeyValueOperationsSupport.KeyValueBackend.versioned()); keyValue.delete(secretPath); } private void listSecrets(Exchange exchange) { List<String> secretsList = new ArrayList<>(); if (!getEndpoint().getConfiguration().isCloud()) { secretsList = getEndpoint().getVaultTemplate() .list(getEndpoint().getConfiguration().getSecretsEngine() + "/" + "metadata" + "/"); } else { if (ObjectHelper.isNotEmpty(getEndpoint().getConfiguration().getNamespace())) { secretsList = getEndpoint().getVaultTemplate() .list(getEndpoint().getConfiguration().getNamespace() + "/" + getEndpoint().getConfiguration().getSecretsEngine() + "/" + "metadata" + "/"); } } exchange.getMessage().setBody(secretsList); } @Override public HashicorpVaultEndpoint getEndpoint() { return (HashicorpVaultEndpoint) super.getEndpoint(); } public HashicorpVaultConfiguration getConfiguration() { return getEndpoint().getConfiguration(); } public static Message getMessageForResponse(final Exchange exchange) { return exchange.getMessage(); } private HashicorpVaultOperation determineOperation(Exchange exchange) { HashicorpVaultOperation operation = exchange.getIn().getHeader(HashicorpVaultConstants.OPERATION, HashicorpVaultOperation.class); if (operation == null) { operation = getConfiguration().getOperation(); } return operation; } private String getSecretPath(Exchange exchange) { String secretPath = exchange.getMessage().getHeader(HashicorpVaultConstants.SECRET_PATH, getEndpoint().getConfiguration().getSecretPath(), String.class); if (ObjectHelper.isEmpty(secretPath)) { throw new IllegalArgumentException("Secret Path must be specified"); } return secretPath; } }
HashicorpVaultProducer
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/expr/SQLIntervalUnit.java
{ "start": 692, "end": 3845 }
enum ____ { YEAR, YEAR_MONTH, QUARTER, MONTH, WEEK, DAY, DAY_HOUR, DAY_MINUTE, DAY_SECOND, DAY_MICROSECOND, HOUR, HOUR_MINUTE, HOUR_SECOND, HOUR_MICROSECOND, MINUTE, MINUTE_SECOND, MINUTE_MICROSECOND, SECOND, SECOND_MICROSECOND, MICROSECOND, MILLISECOND, DAY_OF_WEEK, DOW, DAY_OF_MONTH, DAY_OF_YEAR, YEAR_OF_WEEK, YOW, TIMEZONE_HOUR, TIMEZONE_MINUTE, DOY, YEAR_TO_MONTH("YEAR TO MONTH"); public final String name; public final String nameLCase; SQLIntervalUnit(String name) { this.name = name; this.nameLCase = name.toLowerCase(); } SQLIntervalUnit() { this.name = name(); this.nameLCase = name.toLowerCase(); } public static boolean add(Calendar calendar, int intervalInt, SQLIntervalUnit unit) { switch (unit) { case YEAR: calendar.add(Calendar.YEAR, intervalInt); return true; case MONTH: calendar.add(Calendar.MONTH, intervalInt); return true; case WEEK: calendar.add(Calendar.WEEK_OF_MONTH, intervalInt); return true; case DAY: calendar.add(Calendar.DAY_OF_MONTH, intervalInt); return true; case HOUR: calendar.add(Calendar.HOUR_OF_DAY, intervalInt); return true; case MINUTE: calendar.add(Calendar.MINUTE, intervalInt); return true; case SECOND: calendar.add(Calendar.SECOND, intervalInt); return true; case MICROSECOND: calendar.add(Calendar.MILLISECOND, intervalInt); return true; default: return false; } } public boolean isDateTime() { switch (this) { case HOUR: case MINUTE: case SECOND: case MICROSECOND: case MILLISECOND: return true; default: return false; } } public static SQLIntervalUnit of(String str) { if (str == null || str.isEmpty()) { return null; } str = str.toUpperCase(); switch (str) { case "YEARS": return YEAR; case "MONTHS": return MONTH; case "WEEKS": return WEEK; case "DAYS": return DAY; case "HOURS": return HOUR; case "MINUTES": return MINUTE; case "SECONDS": return SECOND; case "MILLISECONDS": return MILLISECOND; case "MICROSECOND": return MICROSECOND; default: break; } for (SQLIntervalUnit value : values()) { if (value.name().equals(str)) { return value; } } return null; } }
SQLIntervalUnit
java
google__guava
android/guava-tests/benchmark/com/google/common/collect/HashMultisetAddPresentBenchmark.java
{ "start": 961, "end": 1719 }
class ____ { private static final int ARRAY_MASK = 0x0ffff; private static final int ARRAY_SIZE = 0x10000; List<Multiset<Integer>> multisets = new ArrayList<>(0x10000); int[] queries = new int[ARRAY_SIZE]; @BeforeExperiment void setUp() { Random random = new Random(); multisets.clear(); for (int i = 0; i < ARRAY_SIZE; i++) { HashMultiset<Integer> multiset = HashMultiset.<Integer>create(); multisets.add(multiset); queries[i] = random.nextInt(); multiset.add(queries[i]); } } @Benchmark int add(int reps) { int tmp = 0; for (int i = 0; i < reps; i++) { int j = i & ARRAY_MASK; tmp += multisets.get(j).add(queries[j], 4); } return tmp; } }
HashMultisetAddPresentBenchmark
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java
{ "start": 3674, "end": 4070 }
class ____ to load the * resource (assuming it is prefixed with {@code classpath:}). */ public ResourcePropertySource(String name, String location, ClassLoader classLoader) throws IOException { this(name, new DefaultResourceLoader(classLoader).getResource(location)); } /** * Create a PropertySource based on Properties loaded from the given resource * location and use the given
loader
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/ha/TestRetryCacheWithHA.java
{ "start": 31017, "end": 31974 }
class ____ extends AtMostOnceOp { final String pool; ModifyCachePoolOp(DFSClient client, String pool) { super("modifyCachePool", client); this.pool = pool; } @Override void prepare() throws Exception { expectedUpdateCount++; client.addCachePool(new CachePoolInfo(pool).setLimit(10l)); } @Override void invoke() throws Exception { expectedUpdateCount++; client.modifyCachePool(new CachePoolInfo(pool).setLimit(99l)); } @Override boolean checkNamenodeBeforeReturn() throws Exception { for (int i = 0; i < CHECKTIMES; i++) { RemoteIterator<CachePoolEntry> iter = dfs.listCachePools(); if (iter.hasNext() && iter.next().getInfo().getLimit() == 99) { return true; } Thread.sleep(1000); } return false; } @Override Object getResult() { return null; } } /** removeCachePool */
ModifyCachePoolOp
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/AggregationReduceContext.java
{ "start": 939, "end": 1127 }
class ____ permits AggregationReduceContext.ForPartial, AggregationReduceContext.ForFinal { /** * Builds {@link AggregationReduceContext}s. */ public
AggregationReduceContext
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/body/ConversionTextPlainHandler.java
{ "start": 2113, "end": 4098 }
class ____<T> implements MessageBodyHandler<T> { private final ApplicationConfiguration configuration; private final ConversionService conversionService; ConversionTextPlainHandler(ApplicationConfiguration configuration, ConversionService conversionService) { this.configuration = configuration; this.conversionService = conversionService; } @Override public T read(Argument<T> type, MediaType mediaType, Headers httpHeaders, InputStream inputStream) throws CodecException { String text; try { text = new String(inputStream.readAllBytes(), configuration.getDefaultCharset()); } catch (IOException e) { throw new CodecException("Error reading body text: " + e.getMessage(), e); } return convert(type, text); } @Override public T read(Argument<T> type, MediaType mediaType, Headers httpHeaders, ByteBuffer<?> byteBuffer) throws CodecException { T r = convert(type, byteBuffer.toString(configuration.getDefaultCharset())); if (byteBuffer instanceof ReferenceCounted rc) { rc.release(); } return r; } private T convert(Argument<T> type, String text) { return conversionService.convert(text, type) .orElseThrow(() -> new CodecException("Cannot decode message with value [" + text + "] to type: " + type)); } @Override public void writeTo(Argument<T> type, MediaType mediaType, T object, MutableHeaders outgoingHeaders, OutputStream outputStream) throws CodecException { if (mediaType != null) { outgoingHeaders.setIfMissing(HttpHeaders.CONTENT_TYPE, mediaType); } try { outputStream.write(object.toString().getBytes(MessageBodyWriter.getCharset(mediaType, outgoingHeaders))); } catch (IOException e) { throw new CodecException("Error writing body text: " + e.getMessage(), e); } } }
ConversionTextPlainHandler
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/join/User.java
{ "start": 583, "end": 1313 }
class ____ extends Person { private String login; private Double passwordExpiryDays; private String silly; @Column(table = "t_user", name = "u_login") public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } @Column(table = "t_user", name = "pwd_expiry_weeks") @ColumnTransformer( read = "pwd_expiry_weeks * 7.0E0", write = "? / 7.0E0") public Double getPasswordExpiryDays() { return passwordExpiryDays; } public void setPasswordExpiryDays(Double passwordExpiryDays) { this.passwordExpiryDays = passwordExpiryDays; } @Column(table = "t_silly") public String getSilly() { return silly; } public void setSilly(String silly) { this.silly = silly; } }
User
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/UserDefinedFunctionHelper.java
{ "start": 13640, "end": 20081 }
class ____ usage in the runtime. * * <p>Note: This is for the final validation when actual {@link DataType}s for arguments and * result are known. */ public static void validateClassForRuntime( Class<? extends UserDefinedFunction> functionClass, String methodName, Class<?>[] argumentClasses, Class<?> outputClass, String functionName) { final List<Method> methods = ExtractionUtils.collectMethods(functionClass, methodName); // verifies regular JVM calling semantics final boolean isMatching = methods.stream() .anyMatch( method -> // Strict autoboxing is disabled for backwards compatibility ExtractionUtils.isInvokable( Autoboxing.JVM, method, argumentClasses) && ExtractionUtils.isAssignable( outputClass, method.getReturnType(), Autoboxing.JVM)); if (!isMatching) { throw new ValidationException( String.format( "Could not find an implementation method '%s' in class '%s' for function '%s' that " + "matches the following signature:\n%s", methodName, functionClass.getName(), functionName, ExtractionUtils.createMethodSignatureString( methodName, argumentClasses, outputClass))); } } /** * Creates the runtime implementation of a {@link FunctionDefinition} as an instance of {@link * UserDefinedFunction}. * * @see SpecializedFunction */ public static UserDefinedFunction createSpecializedFunction( String functionName, FunctionDefinition definition, CallContext callContext, ClassLoader builtInClassLoader, @Nullable ReadableConfig configuration, @Nullable ExpressionEvaluatorFactory evaluatorFactory) { if (definition instanceof SpecializedFunction) { final SpecializedFunction specialized = (SpecializedFunction) definition; final SpecializedContext specializedContext = new SpecializedContext() { @Override public CallContext getCallContext() { return callContext; } @Override public ReadableConfig getConfiguration() { if (configuration == null) { throw new TableException( "Access to configuration is currently not supported for all kinds of calls."); } return configuration; } @Override public ClassLoader getBuiltInClassLoader() { return builtInClassLoader; } @Override public ExpressionEvaluator createEvaluator( Expression expression, DataType outputDataType, DataTypes.Field... args) { if (evaluatorFactory == null) { throw new TableException( "Access to expression evaluation is currently not supported " + "for all kinds of calls."); } return evaluatorFactory.createEvaluator( expression, outputDataType, args); } @Override public ExpressionEvaluator createEvaluator( String sqlExpression, DataType outputDataType, DataTypes.Field... args) { if (evaluatorFactory == null) { throw new TableException( "Access to expression evaluation is currently not supported " + "for all kinds of calls."); } return evaluatorFactory.createEvaluator( sqlExpression, outputDataType, args); } @Override public ExpressionEvaluator createEvaluator( BuiltInFunctionDefinition function, DataType outputDataType, DataType... args) { if (evaluatorFactory == null) { throw new TableException( "Access to expression evaluation is currently not supported " + "for all kinds of calls."); } return evaluatorFactory.createEvaluator(function, outputDataType, args); } }; final UserDefinedFunction udf = specialized.specialize(specializedContext); checkState( udf.getKind() == definition.getKind(), "Function kind must not change during specialization."); return udf; } else if (definition instanceof UserDefinedFunction) { return (UserDefinedFunction) definition; } else { throw new TableException( String.format( "Could not find a runtime implementation for function definition '%s'.", functionName)); } } /** Validates a {@link UserDefinedFunction}
for
java
apache__camel
components/camel-sql/src/main/java/org/apache/camel/component/sql/DefaultSqlEndpoint.java
{ "start": 7293, "end": 7797 }
class ____ a default constructor to create instance with." + " d) If the query resulted in more than one rows, it throws an non-unique result exception." + " StreamList streams the result of the query using an Iterator. This can be used with the Splitter EIP in streaming mode to process the ResultSet in streaming fashion.") private SqlOutputType outputType = SqlOutputType.SelectList; @UriParam(description = "Specify the full package and
has
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/support/ReflectionSupport.java
{ "start": 29889, "end": 30879 }
interface ____ which to find the methods; never {@code null} * @param predicate the method filter; never {@code null} * @param traversalMode the hierarchy traversal mode; never {@code null} * @return a stream of all such methods found; never {@code null} * but potentially empty * @since 1.10 */ @API(status = MAINTAINED, since = "1.10") public static Stream<Method> streamMethods(Class<?> clazz, Predicate<Method> predicate, HierarchyTraversalMode traversalMode) { Preconditions.notNull(traversalMode, "HierarchyTraversalMode must not be null"); return ReflectionUtils.streamMethods(clazz, predicate, ReflectionUtils.HierarchyTraversalMode.valueOf(traversalMode.name())); } /** * Find all nested classes within the supplied class, or inherited by the * supplied class, that conform to the supplied predicate. * * <p>This method does <strong>not</strong> search for nested classes * recursively. * * <p>Nested classes declared in the same enclosing
in
java
apache__kafka
metadata/src/test/java/org/apache/kafka/metadata/BrokerStateTest.java
{ "start": 1000, "end": 1389 }
class ____ { @Test public void testFromValue() { for (BrokerState state : BrokerState.values()) { BrokerState state2 = BrokerState.fromValue(state.value()); assertEquals(state, state2); } } @Test public void testUnknownValues() { assertEquals(BrokerState.UNKNOWN, BrokerState.fromValue((byte) 126)); } }
BrokerStateTest
java
quarkusio__quarkus
extensions/spring-scheduled/deployment/src/test/java/io/quarkus/spring/scheduled/deployment/SpringScheduledMethodTest.java
{ "start": 385, "end": 1127 }
class ____ { @RegisterExtension static final QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(SpringScheduledMethodsBean.class) .addAsResource( new StringAsset( "springScheduledSimpleJobs.cron=0/1 * * * * ?\nspringScheduledSimpleJobs.fixedRate=1000"), "application.properties")); @Test public void testSpringScheduledMethods() throws InterruptedException { for (CountDownLatch latch : SpringScheduledMethodsBean.LATCHES.values()) { assertTrue(latch.await(5, TimeUnit.SECONDS)); } } }
SpringScheduledMethodTest
java
spring-projects__spring-boot
module/spring-boot-session/src/main/java/org/springframework/boot/session/actuate/endpoint/SessionsDescriptor.java
{ "start": 1017, "end": 1532 }
class ____ implements OperationResponseBody { private final List<SessionDescriptor> sessions; public SessionsDescriptor(Map<String, ? extends Session> sessions) { this.sessions = sessions.values().stream().map(SessionDescriptor::new).toList(); } public List<SessionDescriptor> getSessions() { return this.sessions; } /** * A description of user's {@link Session session} exposed by {@code sessions} * endpoint. Primarily intended for serialization to JSON. */ public static final
SessionsDescriptor
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFileJournalManager.java
{ "start": 2332, "end": 20310 }
class ____ { static final Logger LOG = LoggerFactory.getLogger(TestFileJournalManager.class); private Configuration conf; static { // No need to fsync for the purposes of tests. This makes // the tests run much faster. EditLogFileOutputStream.setShouldSkipFsyncForTesting(true); } @BeforeEach public void setUp() { conf = new Configuration(); } /** * Find out how many transactions we can read from a * FileJournalManager, starting at a given transaction ID. * * @param jm The journal manager * @param fromTxId Transaction ID to start at * @param inProgressOk Should we consider edit logs that are not finalized? * @return The number of transactions * @throws IOException */ static long getNumberOfTransactions(FileJournalManager jm, long fromTxId, boolean inProgressOk, boolean abortOnGap) throws IOException { long numTransactions = 0, txId = fromTxId; final PriorityQueue<EditLogInputStream> allStreams = new PriorityQueue<EditLogInputStream>(64, JournalSet.EDIT_LOG_INPUT_STREAM_COMPARATOR); jm.selectInputStreams(allStreams, fromTxId, inProgressOk); EditLogInputStream elis = null; try { while ((elis = allStreams.poll()) != null) { try { elis.skipUntil(txId); while (true) { FSEditLogOp op = elis.readOp(); if (op == null) { break; } if (abortOnGap && (op.getTransactionId() != txId)) { LOG.info("getNumberOfTransactions: detected gap at txId " + fromTxId); return numTransactions; } txId = op.getTransactionId() + 1; numTransactions++; } } finally { IOUtils.cleanupWithLogger(LOG, elis); } } } finally { IOUtils.cleanupWithLogger( LOG, allStreams.toArray(new EditLogInputStream[0])); } return numTransactions; } /** * Test the normal operation of loading transactions from * file journal manager. 3 edits directories are setup without any * failures. Test that we read in the expected number of transactions. */ @Test public void testNormalOperation() throws IOException { File f1 = new File(TestEditLog.TEST_DIR + "/normtest0"); File f2 = new File(TestEditLog.TEST_DIR + "/normtest1"); File f3 = new File(TestEditLog.TEST_DIR + "/normtest2"); List<URI> editUris = ImmutableList.of(f1.toURI(), f2.toURI(), f3.toURI()); NNStorage storage = setupEdits(editUris, 5); long numJournals = 0; for (StorageDirectory sd : storage.dirIterable(NameNodeDirType.EDITS)) { FileJournalManager jm = new FileJournalManager(conf, sd, storage); assertEquals(6*TXNS_PER_ROLL, getNumberOfTransactions(jm, 1, true, false)); numJournals++; } assertEquals(3, numJournals); } /** * Test that inprogress files are handled correct. Set up a single * edits directory. Fail on after the last roll. Then verify that the * logs have the expected number of transactions. */ @Test public void testInprogressRecovery() throws IOException { File f = new File(TestEditLog.TEST_DIR + "/inprogressrecovery"); // abort after the 5th roll NNStorage storage = setupEdits(Collections.<URI>singletonList(f.toURI()), 5, new AbortSpec(5, 0)); StorageDirectory sd = storage.dirIterator(NameNodeDirType.EDITS).next(); FileJournalManager jm = new FileJournalManager(conf, sd, storage); assertEquals(5 * TXNS_PER_ROLL + TXNS_PER_FAIL, getNumberOfTransactions(jm, 1, true, false)); } /** * Test a mixture of inprogress files and finalised. Set up 3 edits * directories and fail the second on the last roll. Verify that reading * the transactions, reads from the finalised directories. */ @Test public void testInprogressRecoveryMixed() throws IOException { File f1 = new File(TestEditLog.TEST_DIR + "/mixtest0"); File f2 = new File(TestEditLog.TEST_DIR + "/mixtest1"); File f3 = new File(TestEditLog.TEST_DIR + "/mixtest2"); List<URI> editUris = ImmutableList.of(f1.toURI(), f2.toURI(), f3.toURI()); // abort after the 5th roll NNStorage storage = setupEdits(editUris, 5, new AbortSpec(5, 1)); Iterator<StorageDirectory> dirs = storage.dirIterator(NameNodeDirType.EDITS); StorageDirectory sd = dirs.next(); FileJournalManager jm = new FileJournalManager(conf, sd, storage); assertEquals(6*TXNS_PER_ROLL, getNumberOfTransactions(jm, 1, true, false)); sd = dirs.next(); jm = new FileJournalManager(conf, sd, storage); assertEquals(5 * TXNS_PER_ROLL + TXNS_PER_FAIL, getNumberOfTransactions(jm, 1, true, false)); sd = dirs.next(); jm = new FileJournalManager(conf, sd, storage); assertEquals(6*TXNS_PER_ROLL, getNumberOfTransactions(jm, 1, true, false)); } /** * Test that FileJournalManager behaves correctly despite inprogress * files in all its edit log directories. Set up 3 directories and fail * all on the last roll. Verify that the correct number of transaction * are then loaded. */ @Test public void testInprogressRecoveryAll() throws IOException { File f1 = new File(TestEditLog.TEST_DIR + "/failalltest0"); File f2 = new File(TestEditLog.TEST_DIR + "/failalltest1"); File f3 = new File(TestEditLog.TEST_DIR + "/failalltest2"); List<URI> editUris = ImmutableList.of(f1.toURI(), f2.toURI(), f3.toURI()); // abort after the 5th roll NNStorage storage = setupEdits(editUris, 5, new AbortSpec(5, 0), new AbortSpec(5, 1), new AbortSpec(5, 2)); Iterator<StorageDirectory> dirs = storage.dirIterator(NameNodeDirType.EDITS); StorageDirectory sd = dirs.next(); FileJournalManager jm = new FileJournalManager(conf, sd, storage); assertEquals(5 * TXNS_PER_ROLL + TXNS_PER_FAIL, getNumberOfTransactions(jm, 1, true, false)); sd = dirs.next(); jm = new FileJournalManager(conf, sd, storage); assertEquals(5 * TXNS_PER_ROLL + TXNS_PER_FAIL, getNumberOfTransactions(jm, 1, true, false)); sd = dirs.next(); jm = new FileJournalManager(conf, sd, storage); assertEquals(5 * TXNS_PER_ROLL + TXNS_PER_FAIL, getNumberOfTransactions(jm, 1, true, false)); } /** * Corrupt an edit log file after the start segment transaction */ private void corruptAfterStartSegment(File f) throws IOException { RandomAccessFile raf = new RandomAccessFile(f, "rw"); raf.seek(0x20); // skip version and first tranaction and a bit of next transaction for (int i = 0; i < 1000; i++) { raf.writeInt(0xdeadbeef); } raf.close(); } @Test public void testFinalizeErrorReportedToNNStorage() throws IOException, InterruptedException { assertThrows(IllegalStateException.class, () -> { File f = new File(TestEditLog.TEST_DIR + "/filejournaltestError"); NNStorage storage = setupEdits(Collections.<URI>singletonList(f.toURI()), 10, new AbortSpec(10, 0)); StorageDirectory sd = storage.dirIterator(NameNodeDirType.EDITS).next(); FileJournalManager jm = new FileJournalManager(conf, sd, storage); String sdRootPath = sd.getRoot().getAbsolutePath(); FileUtil.chmod(sdRootPath, "-w", true); try { jm.finalizeLogSegment(0, 1); } finally { FileUtil.chmod(sdRootPath, "+w", true); assertTrue(storage.getRemovedStorageDirs().contains(sd)); } }); } /** * Test that we can read from a stream created by FileJournalManager. * Create a single edits directory, failing it on the final roll. * Then try loading from the point of the 3rd roll. Verify that we read * the correct number of transactions from this point. */ @Test public void testReadFromStream() throws IOException { File f = new File(TestEditLog.TEST_DIR + "/readfromstream"); // abort after 10th roll NNStorage storage = setupEdits(Collections.<URI>singletonList(f.toURI()), 10, new AbortSpec(10, 0)); StorageDirectory sd = storage.dirIterator(NameNodeDirType.EDITS).next(); FileJournalManager jm = new FileJournalManager(conf, sd, storage); long expectedTotalTxnCount = TXNS_PER_ROLL*10 + TXNS_PER_FAIL; assertEquals(expectedTotalTxnCount, getNumberOfTransactions(jm, 1, true, false)); long skippedTxns = (3*TXNS_PER_ROLL); // skip first 3 files long startingTxId = skippedTxns + 1; long numLoadable = getNumberOfTransactions(jm, startingTxId, true, false); assertEquals(expectedTotalTxnCount - skippedTxns, numLoadable); } /** * Make requests with starting transaction ids which don't match the beginning * txid of some log segments. * * This should succeed. */ @Test public void testAskForTransactionsMidfile() throws IOException { File f = new File(TestEditLog.TEST_DIR + "/askfortransactionsmidfile"); NNStorage storage = setupEdits(Collections.<URI>singletonList(f.toURI()), 10); StorageDirectory sd = storage.dirIterator(NameNodeDirType.EDITS).next(); FileJournalManager jm = new FileJournalManager(conf, sd, storage); // 10 rolls, so 11 rolled files, 110 txids total. final int TOTAL_TXIDS = 10 * 11; for (int txid = 1; txid <= TOTAL_TXIDS; txid++) { assertEquals((TOTAL_TXIDS - txid) + 1, getNumberOfTransactions(jm, txid, true, false)); } } /** * Test that we receive the correct number of transactions when we count * the number of transactions around gaps. * Set up a single edits directory, with no failures. Delete the 4th logfile. * Test that getNumberOfTransactions returns the correct number of * transactions before this gap and after this gap. Also verify that if you * try to count on the gap that an exception is thrown. */ @Test public void testManyLogsWithGaps() throws IOException { File f = new File(TestEditLog.TEST_DIR + "/manylogswithgaps"); NNStorage storage = setupEdits(Collections.<URI>singletonList(f.toURI()), 10); StorageDirectory sd = storage.dirIterator(NameNodeDirType.EDITS).next(); final long startGapTxId = 3*TXNS_PER_ROLL + 1; final long endGapTxId = 4*TXNS_PER_ROLL; File[] files = new File(f, "current").listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.startsWith(NNStorage.getFinalizedEditsFileName(startGapTxId, endGapTxId))) { return true; } return false; } }); assertEquals(1, files.length); assertTrue(files[0].delete()); FileJournalManager jm = new FileJournalManager(conf, sd, storage); assertEquals(startGapTxId-1, getNumberOfTransactions(jm, 1, true, true)); assertEquals(0, getNumberOfTransactions(jm, startGapTxId, true, true)); // rolled 10 times so there should be 11 files. assertEquals(11 * TXNS_PER_ROLL - endGapTxId, getNumberOfTransactions(jm, endGapTxId + 1, true, true)); } /** * Test that we can load an edits directory with a corrupt inprogress file. * The corrupt inprogress file should be moved to the side. */ @Test public void testManyLogsWithCorruptInprogress() throws IOException { File f = new File(TestEditLog.TEST_DIR + "/manylogswithcorruptinprogress"); NNStorage storage = setupEdits(Collections.<URI>singletonList(f.toURI()), 10, new AbortSpec(10, 0)); StorageDirectory sd = storage.dirIterator(NameNodeDirType.EDITS).next(); File[] files = new File(f, "current").listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (name.startsWith("edits_inprogress")) { return true; } return false; } }); assertEquals(files.length, 1); corruptAfterStartSegment(files[0]); FileJournalManager jm = new FileJournalManager(conf, sd, storage); assertEquals(10 * TXNS_PER_ROLL + 1, getNumberOfTransactions(jm, 1, true, false)); } @Test public void testGetRemoteEditLog() throws IOException { StorageDirectory sd = FSImageTestUtil.mockStorageDirectory( NameNodeDirType.EDITS, false, NNStorage.getFinalizedEditsFileName(1, 100), NNStorage.getFinalizedEditsFileName(101, 200), NNStorage.getInProgressEditsFileName(201), NNStorage.getFinalizedEditsFileName(1001, 1100)); // passing null for NNStorage because this unit test will not use it FileJournalManager fjm = new FileJournalManager(conf, sd, null); assertEquals("[1,100],[101,200],[1001,1100]", getLogsAsString(fjm, 1)); assertEquals("[101,200],[1001,1100]", getLogsAsString(fjm, 101)); assertEquals("[101,200],[1001,1100]", getLogsAsString(fjm, 150)); assertEquals("[1001,1100]", getLogsAsString(fjm, 201)); assertEquals("", getLogsAsString(fjm, 9999), "Asking for a newer log than exists should return empty list"); } /** * tests that passing an invalid dir to matchEditLogs throws IOException */ @Test public void testMatchEditLogInvalidDirThrowsIOException() throws IOException { assertThrows(IOException.class, () -> { File badDir = new File("does not exist"); FileJournalManager.matchEditLogs(badDir); }); } private static EditLogInputStream getJournalInputStream(FileJournalManager jm, long txId, boolean inProgressOk) throws IOException { final PriorityQueue<EditLogInputStream> allStreams = new PriorityQueue<EditLogInputStream>(64, JournalSet.EDIT_LOG_INPUT_STREAM_COMPARATOR); jm.selectInputStreams(allStreams, txId, inProgressOk); EditLogInputStream elis = null, ret; try { while ((elis = allStreams.poll()) != null) { if (elis.getFirstTxId() > txId) { break; } if (elis.getLastTxId() < txId) { elis.close(); continue; } elis.skipUntil(txId); ret = elis; elis = null; return ret; } } finally { IOUtils.cleanupWithLogger( LOG, allStreams.toArray(new EditLogInputStream[0])); IOUtils.cleanupWithLogger(LOG, elis); } return null; } /** * Make sure that we starting reading the correct op when we request a stream * with a txid in the middle of an edit log file. */ @Test public void testReadFromMiddleOfEditLog() throws CorruptionException, IOException { File f = new File(TestEditLog.TEST_DIR + "/readfrommiddleofeditlog"); NNStorage storage = setupEdits(Collections.<URI>singletonList(f.toURI()), 10); StorageDirectory sd = storage.dirIterator(NameNodeDirType.EDITS).next(); FileJournalManager jm = new FileJournalManager(conf, sd, storage); EditLogInputStream elis = getJournalInputStream(jm, 5, true); try { FSEditLogOp op = elis.readOp(); assertEquals(op.getTransactionId(), 5, "read unexpected op"); } finally { IOUtils.cleanupWithLogger(LOG, elis); } } /** * Make sure that in-progress streams aren't counted if we don't ask for * them. */ @Test public void testExcludeInProgressStreams() throws CorruptionException, IOException { File f = new File(TestEditLog.TEST_DIR + "/excludeinprogressstreams"); // Don't close the edit log once the files have been set up. NNStorage storage = setupEdits(Collections.<URI>singletonList(f.toURI()), 10, false); StorageDirectory sd = storage.dirIterator(NameNodeDirType.EDITS).next(); FileJournalManager jm = new FileJournalManager(conf, sd, storage); // If we exclude the in-progess stream, we should only have 100 tx. assertEquals(100, getNumberOfTransactions(jm, 1, false, false)); EditLogInputStream elis = getJournalInputStream(jm, 90, false); try { FSEditLogOp lastReadOp = null; while ((lastReadOp = elis.readOp()) != null) { assertTrue(lastReadOp.getTransactionId() <= 100); } } finally { IOUtils.cleanupWithLogger(LOG, elis); } } /** * Tests that internal renames are done using native code on platforms that * have it. The native rename includes more detailed information about the * failure, which can be useful for troubleshooting. */ @Test public void testDoPreUpgradeIOError() throws IOException { File storageDir = new File(TestEditLog.TEST_DIR, "preupgradeioerror"); List<URI> editUris = Collections.singletonList(storageDir.toURI()); NNStorage storage = setupEdits(editUris, 5); StorageDirectory sd = storage.dirIterator(NameNodeDirType.EDITS).next(); assertNotNull(sd); // Change storage directory so that renaming current to previous.tmp fails. FileUtil.setWritable(storageDir, false); FileJournalManager jm = null; try { jm = new FileJournalManager(conf, sd, storage); final FileJournalManager j = jm; IOException ex = assertThrows(IOException.class, () -> j.doPreUpgrade()); if (NativeCodeLoader.isNativeCodeLoaded()) { assertTrue(ex.getMessage().contains("failure in native rename")); } } finally { IOUtils.cleanupWithLogger(LOG, jm); // Restore permissions on storage directory and make sure we can delete. FileUtil.setWritable(storageDir, true); FileUtil.fullyDelete(storageDir); } } private static String getLogsAsString( FileJournalManager fjm, long firstTxId) throws IOException { return Joiner.on(",").join(fjm.getRemoteEditLogs(firstTxId, false)); } }
TestFileJournalManager
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumeHiddenFilesTest.java
{ "start": 1238, "end": 2386 }
class ____ extends ContextTestSupport { @Test public void testConsumeHiddenFiles() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceivedInAnyOrder("Report 123", "Hidden report 123"); template.sendBodyAndHeader(fileUri(), "Report 123", Exchange.FILE_NAME, "report.txt"); template.sendBodyAndHeader(fileUri(), "Hidden report 123", Exchange.FILE_NAME, ".report.hidden"); assertMockEndpointsSatisfied(); Awaitility.await().untilAsserted(() -> { // file should be deleted assertFalse(Files.exists(testFile("report.txt")), "File should been deleted"); assertFalse(Files.exists(testFile(".report.hidden")), "File should been deleted"); }); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(fileUri("?initialDelay=0&delay=10&delete=true&includeHiddenFiles=true")) .convertBodyTo(String.class).to("mock:result"); } }; } }
FileConsumeHiddenFilesTest
java
reactor__reactor-core
reactor-core/src/test/java/reactor/ReactorTestExecutionListener.java
{ "start": 1692, "end": 2425 }
class ____ implements TestExecutionListener { private static void resetHooksAndSchedulers() { Hooks.resetOnOperatorDebug(); Hooks.resetOnEachOperator(); Hooks.resetOnLastOperator(); Hooks.resetOnErrorDropped(); Hooks.resetOnNextDropped(); Hooks.resetOnNextError(); Hooks.resetOnOperatorError(); Hooks.removeQueueWrappers(); Hooks.disableAutomaticContextPropagation(); Schedulers.resetOnHandleError(); Schedulers.resetFactory(); Schedulers.resetOnScheduleHooks(); // TODO capture non-default schedulers and shutdown them } @Override public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) { resetHooksAndSchedulers(); } }
ReactorTestExecutionListener
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/checkpointing/StatefulJobWBroadcastStateMigrationITCase.java
{ "start": 19051, "end": 21804 }
class ____ extends KeyedBroadcastProcessFunction< Long, Tuple2<Long, Long>, Tuple2<Long, Long>, Tuple2<Long, Long>> { private static final long serialVersionUID = 1333992081671604521L; private final Map<Long, Long> expectedFirstState; private final Map<String, Long> expectedSecondState; private MapStateDescriptor<Long, Long> firstStateDesc; private MapStateDescriptor<String, Long> secondStateDesc; CheckingKeyedBroadcastFunction(Map<Long, Long> firstState, Map<String, Long> secondState) { this.expectedFirstState = firstState; this.expectedSecondState = secondState; } @Override public void open(OpenContext openContext) throws Exception { super.open(openContext); firstStateDesc = new MapStateDescriptor<>( "broadcast-state-1", BasicTypeInfo.LONG_TYPE_INFO, BasicTypeInfo.LONG_TYPE_INFO); secondStateDesc = new MapStateDescriptor<>( "broadcast-state-2", BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.LONG_TYPE_INFO); } @Override public void processElement( Tuple2<Long, Long> value, ReadOnlyContext ctx, Collector<Tuple2<Long, Long>> out) throws Exception { final Map<Long, Long> actualFirstState = new HashMap<>(); for (Map.Entry<Long, Long> entry : ctx.getBroadcastState(firstStateDesc).immutableEntries()) { actualFirstState.put(entry.getKey(), entry.getValue()); } Assert.assertEquals(expectedFirstState, actualFirstState); final Map<String, Long> actualSecondState = new HashMap<>(); for (Map.Entry<String, Long> entry : ctx.getBroadcastState(secondStateDesc).immutableEntries()) { actualSecondState.put(entry.getKey(), entry.getValue()); } Assert.assertEquals(expectedSecondState, actualSecondState); out.collect(value); } @Override public void processBroadcastElement( Tuple2<Long, Long> value, Context ctx, Collector<Tuple2<Long, Long>> out) throws Exception { // now we do nothing as we just want to verify the contents of the broadcast state. } } /** * A simple {@link KeyedBroadcastProcessFunction} that verifies the contents of the broadcast * state after recovery. */ private static
CheckingKeyedBroadcastFunction
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/cluster/coordination/LinearizabilityChecker.java
{ "start": 10833, "end": 17968 }
class ____ extends Exception {} private static boolean isLinearizable(SequentialSpec spec, List<Event> history, BooleanSupplier terminateEarly) { logger.debug("Checking history of size: {}: {}", history.size(), history); Object state = spec.initialState(); // the current state of the datatype final FixedBitSet linearized = new FixedBitSet(history.size() / 2); // the linearized prefix of the history final Cache cache = new Cache(); // cache of explored <state, linearized prefix> pairs final Deque<Tuple<Entry, Object>> calls = new LinkedList<>(); // path we're currently exploring final Entry headEntry = createLinkedEntries(history); Entry entry = headEntry.next; // current entry while (headEntry.next != null) { if (terminateEarly.getAsBoolean()) { return false; } if (entry.match != null) { final Optional<Object> maybeNextState = spec.nextState(state, entry.event.value, entry.match.event.value); boolean shouldExploreNextState = false; if (maybeNextState.isPresent()) { // check if we have already explored this linearization final FixedBitSet updatedLinearized = linearized.clone(); updatedLinearized.set(entry.id); shouldExploreNextState = cache.add(maybeNextState.get(), updatedLinearized); } if (shouldExploreNextState) { calls.push(new Tuple<>(entry, state)); state = maybeNextState.get(); linearized.set(entry.id); entry.lift(); entry = headEntry.next; } else { entry = entry.next; } } else { if (calls.isEmpty()) { return false; } final Tuple<Entry, Object> top = calls.pop(); entry = top.v1(); state = top.v2(); linearized.clear(entry.id); entry.unlift(); entry = entry.next; } } return true; } /** * Return a visual representation of the history */ public static String visualize(SequentialSpec spec, History history, Function<Object, Object> missingResponseGenerator) { final var writer = new StringWriter(); writeVisualisation(spec, history, missingResponseGenerator, writer); return writer.toString(); } /** * Write a visual representation of the history to the given writer */ public static void writeVisualisation( SequentialSpec spec, History history, Function<Object, Object> missingResponseGenerator, Writer writer ) { history = history.clone(); history.complete(missingResponseGenerator); final Collection<List<Event>> partitions = spec.partition(history.copyEvents()); try { int index = 0; for (List<Event> partition : partitions) { writer.write("Partition "); writer.write(Integer.toString(index++)); writer.append('\n'); visualizePartition(partition, writer); } } catch (IOException e) { logger.error("unexpected writeVisualisation failure", e); assert false : e; // not really doing any IO } } private static void visualizePartition(List<Event> events, Writer writer) throws IOException { Entry entry = createLinkedEntries(events).next; Map<Tuple<EventType, Integer>, Integer> eventToPosition = new HashMap<>(); for (Event event : events) { eventToPosition.put(Tuple.tuple(event.type, event.id), eventToPosition.size()); } while (entry != null) { if (entry.match != null) { visualizeEntry(entry, eventToPosition, writer); writer.append('\n'); } entry = entry.next; } } private static void visualizeEntry(Entry entry, Map<Tuple<EventType, Integer>, Integer> eventToPosition, Writer writer) throws IOException { String input = String.valueOf(entry.event.value); String output = String.valueOf(entry.match.event.value); int id = entry.event.id; int beginIndex = eventToPosition.get(Tuple.tuple(EventType.INVOCATION, id)); int endIndex = eventToPosition.get(Tuple.tuple(EventType.RESPONSE, id)); input = input.substring(0, Math.min(beginIndex + 25, input.length())); writer.write(Strings.padStart(input, beginIndex + 25, ' ')); writer.write(" "); writer.write(Strings.padStart("", endIndex - beginIndex, 'X')); writer.write(" "); writer.write(output); writer.write(" ("); writer.write(Integer.toString(entry.event.id)); writer.write(")"); } /** * Creates the internal linked data structure used by the linearizability checker. * Generates contiguous internal ids for the events so that they can be efficiently recorded in bit sets. */ private static Entry createLinkedEntries(List<Event> history) { if (history.size() % 2 != 0) { throw new IllegalArgumentException("mismatch between number of invocations and responses"); } // first, create entries and link response events to invocation events final Map<Integer, Entry> matches = new HashMap<>(); // map from event id to matching response entry final Entry[] entries = new Entry[history.size()]; int nextInternalId = (history.size() / 2) - 1; for (int i = history.size() - 1; i >= 0; i--) { final Event elem = history.get(i); if (elem.type == EventType.RESPONSE) { final Entry entry = entries[i] = new Entry(elem, null, nextInternalId--); final Entry prev = matches.put(elem.id, entry); if (prev != null) { throw new IllegalArgumentException("duplicate response with id " + elem.id); } } else { final Entry matchingResponse = matches.get(elem.id); if (matchingResponse == null) { throw new IllegalArgumentException("no matching response found for " + elem); } entries[i] = new Entry(elem, matchingResponse, matchingResponse.id); } } // sanity check if (nextInternalId != -1) { throw new IllegalArgumentException("id mismatch"); } // now link entries together in history order, and add a sentinel node at the beginning Entry first = new Entry(null, null, -1); Entry lastEntry = first; for (Entry entry : entries) { lastEntry.next = entry; entry.prev = lastEntry; lastEntry = entry; } return first; } public
LinearizabilityCheckAborted
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/uri/UriAssert_hasParameter_String_String_Test.java
{ "start": 782, "end": 1204 }
class ____ extends UriAssertBaseTest { private final String name = "article"; private final String value = "10"; @Override protected UriAssert invoke_api_method() { return assertions.hasParameter(name, value); } @Override protected void verify_internal_effects() { verify(uris).assertHasParameter(getInfo(assertions), getActual(assertions), name, value); } }
UriAssert_hasParameter_String_String_Test
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/propagation/reactor/HelloController.java
{ "start": 586, "end": 1053 }
class ____ { @Get("/hello") Mono<String> hello(@QueryValue("name") String name) { PropagatedContext propagatedContext = PropagatedContext.get().plus(new MyContextElement(name)); // <1> return Mono.just("Hello, " + name) .contextWrite(ctx -> ReactorPropagation.addPropagatedContext(ctx, propagatedContext)); // <2> } } record MyContextElement(String value) implements PropagatedContextElement { } // end::example[]
HelloController
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginManager.java
{ "start": 4594, "end": 5179 }
class ____ for the plugin, may be {@code null} to use the Maven core realm. * @param imports The packages/types to import from the parent realm, may be {@code null}. * @param filter The filter used to exclude certain plugin dependencies, may be {@code null}. */ void setupPluginRealm( PluginDescriptor pluginDescriptor, MavenSession session, ClassLoader parent, List<String> imports, DependencyFilter filter) throws PluginResolutionException, PluginContainerException; /** * Sets up
realm
java
apache__camel
components/camel-nats/src/test/java/org/apache/camel/component/nats/integration/NatsAuthProducerIT.java
{ "start": 1014, "end": 1437 }
class ____ extends NatsAuthITSupport { @Test public void sendTest() { assertDoesNotThrow(() -> template.sendBody("direct:send", "pippo")); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:send").to("nats:test"); } }; } }
NatsAuthProducerIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/NaiveEqualsHashCodeEntityTest.java
{ "start": 951, "end": 3006 }
class ____ { @BeforeEach public void init(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { Library library = new Library(); library.setId(1L); library.setName("Amazon"); entityManager.persist(library); }); } @AfterEach public void tearDown(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { scope.getEntityManagerFactory().getSchemaManager().truncate(); } ); } @Test public void testPersist(EntityManagerFactoryScope scope) { //tag::entity-pojo-naive-equals-hashcode-persist-example[] Book book1 = new Book(); book1.setTitle("High-Performance Java Persistence"); Book book2 = new Book(); book2.setTitle("Java Persistence with Hibernate"); Library library = scope.fromTransaction( entityManager -> { Library _library = entityManager.find(Library.class, 1L); _library.getBooks().add(book1); _library.getBooks().add(book2); return _library; }); assertFalse(library.getBooks().contains(book1)); assertFalse(library.getBooks().contains(book2)); //end::entity-pojo-naive-equals-hashcode-persist-example[] } @Test public void testPersistForceFlush(EntityManagerFactoryScope scope) { //tag::entity-pojo-naive-equals-hashcode-persist-force-flush-example[] Book book1 = new Book(); book1.setTitle("High-Performance Java Persistence"); Book book2 = new Book(); book2.setTitle("Java Persistence with Hibernate"); Library library = scope.fromTransaction( entityManager -> { Library _library = entityManager.find(Library.class, 1L); entityManager.persist(book1); entityManager.persist(book2); entityManager.flush(); _library.getBooks().add(book1); _library.getBooks().add(book2); return _library; }); assertTrue(library.getBooks().contains(book1)); assertTrue(library.getBooks().contains(book2)); //end::entity-pojo-naive-equals-hashcode-persist-force-flush-example[] } //tag::entity-pojo-naive-equals-hashcode-example[] @Entity(name = "MyLibrary") public static
NaiveEqualsHashCodeEntityTest
java
quarkusio__quarkus
core/builder/src/main/java/io/quarkus/builder/BuildChain.java
{ "start": 322, "end": 1837 }
class ____ { private final Set<ItemId> initialIds; private final Set<ItemId> finalIds; private final List<StepInfo> startSteps; private final List<BuildProvider> providers; private final int endStepCount; private final ClassLoader classLoader; BuildChain(final Set<StepInfo> startSteps, BuildChainBuilder builder, final int endStepCount) { providers = builder.getProviders(); initialIds = builder.getInitialIds(); finalIds = builder.getFinalIds(); this.startSteps = new ArrayList<>(startSteps); this.endStepCount = endStepCount; this.classLoader = builder.getClassLoader(); } /** * Create a new execution builder for this build chain. * * @param name the name of the build target for diagnostic purposes (must not be {@code null}) * @return the new build execution builder (not {@code null}) */ public BuildExecutionBuilder createExecutionBuilder(String name) { final BuildExecutionBuilder builder = new BuildExecutionBuilder(this, name); for (BuildProvider provider : providers) { provider.prepareExecution(builder); } return builder; } /** * Get a new build chain builder. * * @return the build chain builder (not {@code null}) */ public static BuildChainBuilder builder() { return new BuildChainBuilder(); } /** * Construct a build chain with the given name from providers found in the given
BuildChain
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/annotation/FilterAnnotationsTests.java
{ "start": 1606, "end": 3685 }
class ____ { @Test void filterAnnotation() throws Exception { FilterAnnotations filterAnnotations = get(FilterByAnnotation.class); assertThat(match(filterAnnotations, ExampleWithAnnotation.class)).isTrue(); assertThat(match(filterAnnotations, ExampleWithoutAnnotation.class)).isFalse(); } @Test void filterAssignableType() throws Exception { FilterAnnotations filterAnnotations = get(FilterByType.class); assertThat(match(filterAnnotations, ExampleWithAnnotation.class)).isFalse(); assertThat(match(filterAnnotations, ExampleWithoutAnnotation.class)).isTrue(); } @Test void filterCustom() throws Exception { FilterAnnotations filterAnnotations = get(FilterByCustom.class); assertThat(match(filterAnnotations, ExampleWithAnnotation.class)).isFalse(); assertThat(match(filterAnnotations, ExampleWithoutAnnotation.class)).isTrue(); } @Test void filterAspectJ() throws Exception { FilterAnnotations filterAnnotations = get(FilterByAspectJ.class); assertThat(match(filterAnnotations, ExampleWithAnnotation.class)).isFalse(); assertThat(match(filterAnnotations, ExampleWithoutAnnotation.class)).isTrue(); } @Test void filterRegex() throws Exception { FilterAnnotations filterAnnotations = get(FilterByRegex.class); assertThat(match(filterAnnotations, ExampleWithAnnotation.class)).isFalse(); assertThat(match(filterAnnotations, ExampleWithoutAnnotation.class)).isTrue(); } private FilterAnnotations get(Class<?> type) { Filters filters = AnnotatedElementUtils.getMergedAnnotation(type, Filters.class); assertThat(filters).isNotNull(); return new FilterAnnotations(getClass().getClassLoader(), filters.value()); } private boolean match(FilterAnnotations filterAnnotations, Class<?> type) throws IOException { MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(); MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(type.getName()); return filterAnnotations.anyMatches(metadataReader, metadataReaderFactory); } @Filters(@Filter(Service.class)) static
FilterAnnotationsTests
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/VersionTests.java
{ "start": 1100, "end": 12920 }
class ____ extends ESTestCase { public void testVersionComparison() { Version V_7_2_0 = Version.fromString("7.2.0"); Version V_8_0_0 = Version.fromString("8.0.0"); assertThat(V_7_2_0.before(V_8_0_0), is(true)); assertThat(V_7_2_0.before(V_7_2_0), is(false)); assertThat(V_8_0_0.before(V_7_2_0), is(false)); assertThat(V_7_2_0.onOrBefore(V_8_0_0), is(true)); assertThat(V_7_2_0.onOrBefore(V_7_2_0), is(true)); assertThat(V_8_0_0.onOrBefore(V_7_2_0), is(false)); assertThat(V_7_2_0.after(V_8_0_0), is(false)); assertThat(V_7_2_0.after(V_7_2_0), is(false)); assertThat(V_8_0_0.after(V_7_2_0), is(true)); assertThat(V_7_2_0.onOrAfter(V_8_0_0), is(false)); assertThat(V_7_2_0.onOrAfter(V_7_2_0), is(true)); assertThat(V_8_0_0.onOrAfter(V_7_2_0), is(true)); assertThat(V_7_2_0, is(lessThan(V_8_0_0))); assertThat(V_7_2_0.compareTo(V_7_2_0), is(0)); assertThat(V_8_0_0, is(greaterThan(V_7_2_0))); } public void testMin() { assertEquals(VersionUtils.getPreviousVersion(), Version.min(Version.CURRENT, VersionUtils.getPreviousVersion())); assertEquals(Version.fromString("1.0.1"), Version.min(Version.fromString("1.0.1"), Version.CURRENT)); Version version = VersionUtils.randomVersion(random()); Version version1 = VersionUtils.randomVersion(random()); if (version.id <= version1.id) { assertEquals(version, Version.min(version1, version)); } else { assertEquals(version1, Version.min(version1, version)); } } public void testMax() { assertEquals(Version.CURRENT, Version.max(Version.CURRENT, VersionUtils.getPreviousVersion())); assertEquals(Version.CURRENT, Version.max(Version.fromString("1.0.1"), Version.CURRENT)); Version version = VersionUtils.randomVersion(random()); Version version1 = VersionUtils.randomVersion(random()); if (version.id >= version1.id) { assertEquals(version, Version.max(version1, version)); } else { assertEquals(version1, Version.max(version1, version)); } } public void testVersionConstantPresent() { assertThat(Version.CURRENT, sameInstance(Version.fromId(Version.CURRENT.id))); final int iters = scaledRandomIntBetween(20, 100); for (int i = 0; i < iters; i++) { Version version = randomVersion(random()); assertThat(version, sameInstance(Version.fromId(version.id))); } } public void testCURRENTIsLatest() { final int iters = scaledRandomIntBetween(100, 1000); for (int i = 0; i < iters; i++) { Version version = randomVersion(random()); if (version != Version.CURRENT) { assertThat( "Version: " + version + " should be before: " + Version.CURRENT + " but wasn't", version.before(Version.CURRENT), is(true) ); } } } public void testVersionFromString() { final int iters = scaledRandomIntBetween(100, 1000); for (int i = 0; i < iters; i++) { Version version = randomVersion(random()); assertThat(Version.fromString(version.toString()), sameInstance(version)); } } public void testTooLongVersionFromString() { Exception e = expectThrows(IllegalArgumentException.class, () -> Version.fromString("1.0.0.1.3")); assertThat(e.getMessage(), containsString("needs to contain major, minor, and revision")); } public void testTooShortVersionFromString() { Exception e = expectThrows(IllegalArgumentException.class, () -> Version.fromString("1.0")); assertThat(e.getMessage(), containsString("needs to contain major, minor, and revision")); } public void testWrongVersionFromString() { Exception e = expectThrows(IllegalArgumentException.class, () -> Version.fromString("WRONG.VERSION")); assertThat(e.getMessage(), containsString("needs to contain major, minor, and revision")); } public void testMinCompatVersion() { Version major = Version.fromString("2.0.0"); assertThat(Version.fromString("2.0.0").minimumCompatibilityVersion(), equalTo(major)); assertThat(Version.fromString("2.2.0").minimumCompatibilityVersion(), equalTo(major)); assertThat(Version.fromString("2.3.0").minimumCompatibilityVersion(), equalTo(major)); Version major5x = Version.fromString("5.0.0"); assertThat(Version.fromString("5.0.0").minimumCompatibilityVersion(), equalTo(major5x)); assertThat(Version.fromString("5.2.0").minimumCompatibilityVersion(), equalTo(major5x)); assertThat(Version.fromString("5.3.0").minimumCompatibilityVersion(), equalTo(major5x)); Version major56x = Version.fromString("5.6.0"); assertThat(Version.fromString("6.4.0").minimumCompatibilityVersion(), equalTo(major56x)); assertThat(Version.fromString("6.3.1").minimumCompatibilityVersion(), equalTo(major56x)); // from 7.0 on we are supporting the latest minor of the previous major... this might fail once we add a new version ie. 5.x is // released since we need to bump the supported minor in Version#minimumCompatibilityVersion() Version lastVersion = Version.fromString("6.8.0"); // TODO: remove this once min compat version is a constant instead of method assertEquals(lastVersion.major, Version.V_7_0_0.minimumCompatibilityVersion().major); assertEquals( "did you miss to bump the minor in Version#minimumCompatibilityVersion()", lastVersion.minor, Version.V_7_0_0.minimumCompatibilityVersion().minor ); assertEquals(0, Version.V_7_0_0.minimumCompatibilityVersion().revision); } public void testToString() { assertEquals("5.0.0", Version.fromId(5000099).toString()); assertEquals("2.3.0", Version.fromString("2.3.0").toString()); assertEquals("0.90.0", Version.fromString("0.90.0").toString()); assertEquals("1.0.0", Version.fromString("1.0.0").toString()); assertEquals("2.0.0", Version.fromString("2.0.0").toString()); assertEquals("5.0.0", Version.fromString("5.0.0").toString()); } public void testParseVersion() { final int iters = scaledRandomIntBetween(100, 1000); for (int i = 0; i < iters; i++) { Version version = randomVersion(random()); if (random().nextBoolean()) { version = new Version(version.id); } Version parsedVersion = Version.fromString(version.toString()); assertEquals(version, parsedVersion); } expectThrows(IllegalArgumentException.class, () -> { Version.fromString("5.0.0-alph2"); }); assertSame(Version.CURRENT, Version.fromString(Version.CURRENT.toString())); assertEquals(Version.fromString("2.0.0-SNAPSHOT"), Version.fromId(2000099)); expectThrows(IllegalArgumentException.class, () -> { Version.fromString("5.0.0-SNAPSHOT"); }); } public void testAllVersionsMatchId() throws Exception { final Set<Version> versions = new HashSet<>(VersionUtils.allVersions()); Map<String, Version> maxBranchVersions = new HashMap<>(); for (java.lang.reflect.Field field : Version.class.getFields()) { if (field.getName().matches("_ID")) { assertTrue(field.getName() + " should be static", Modifier.isStatic(field.getModifiers())); assertTrue(field.getName() + " should be final", Modifier.isFinal(field.getModifiers())); int versionId = (Integer) field.get(Version.class); String constantName = field.getName().substring(0, field.getName().indexOf("_ID")); java.lang.reflect.Field versionConstant = Version.class.getField(constantName); assertTrue(constantName + " should be static", Modifier.isStatic(versionConstant.getModifiers())); assertTrue(constantName + " should be final", Modifier.isFinal(versionConstant.getModifiers())); Version v = (Version) versionConstant.get(null); logger.debug("Checking {}", v); assertTrue(versions.contains(v)); assertEquals("Version id " + field.getName() + " does not point to " + constantName, v, Version.fromId(versionId)); assertEquals("Version " + constantName + " does not have correct id", versionId, v.id); String number = v.toString(); assertEquals("V_" + number.replace('.', '_'), constantName); } } } public void testIsCompatible() { assertTrue(isCompatible(Version.CURRENT, Version.CURRENT.minimumCompatibilityVersion())); assertFalse(isCompatible(Version.V_7_0_0, Version.V_8_0_0)); assertTrue(isCompatible(Version.fromString("6.8.0"), Version.fromString("7.0.0"))); assertFalse(isCompatible(Version.fromId(2000099), Version.V_7_0_0)); assertFalse(isCompatible(Version.fromId(2000099), Version.fromString("6.5.0"))); final Version currentMajorVersion = Version.fromId(Version.CURRENT.major * 1000000 + 99); final Version currentOrNextMajorVersion; if (Version.CURRENT.minor > 0) { currentOrNextMajorVersion = Version.fromId((Version.CURRENT.major + 1) * 1000000 + 99); } else { currentOrNextMajorVersion = currentMajorVersion; } final Version lastMinorFromPreviousMajor = VersionUtils.allVersions() .stream() .filter(v -> v.major == currentOrNextMajorVersion.major - 1) .max(Version::compareTo) .orElseThrow(() -> new IllegalStateException("expected previous minor version for [" + currentOrNextMajorVersion + "]")); final Version previousMinorVersion = VersionUtils.getPreviousMinorVersion(); boolean isCompatible = previousMinorVersion.major == currentOrNextMajorVersion.major || previousMinorVersion.minor == lastMinorFromPreviousMajor.minor; final String message = String.format( Locale.ROOT, "[%s] should %s be compatible with [%s]", previousMinorVersion, isCompatible ? "" : " not", currentOrNextMajorVersion ); assertThat(message, isCompatible(VersionUtils.getPreviousMinorVersion(), currentOrNextMajorVersion), equalTo(isCompatible)); assertFalse(isCompatible(Version.fromId(5000099), Version.fromString("6.0.0"))); assertFalse(isCompatible(Version.fromId(5000099), Version.fromString("7.0.0"))); Version a = randomVersion(random()); Version b = randomVersion(random()); assertThat(a.isCompatible(b), equalTo(b.isCompatible(a))); } public boolean isCompatible(Version left, Version right) { boolean result = left.isCompatible(right); assert result == right.isCompatible(left); return result; } public void testIllegalMinorAndPatchNumbers() { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> Version.fromString("8.2.999")); assertThat( e.getMessage(), containsString("illegal revision version format - only one or two digit numbers are supported but found 999") ); e = expectThrows(IllegalArgumentException.class, () -> Version.fromString("8.888.99")); assertThat( e.getMessage(), containsString("illegal minor version format - only one or two digit numbers are supported but found 888") ); } }
VersionTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/JoinedSubclassTest.java
{ "start": 1110, "end": 3002 }
class ____ { @Test public void testDefaultValues(SessionFactoryScope scope) { Ferry ferry = new Ferry(); scope.inTransaction( s -> { ferry.setSize( 2 ); ferry.setSea( "Channel" ); s.persist( ferry ); } ); scope.inTransaction( s -> { Ferry f = s.get( Ferry.class, ferry.getId() ); assertNotNull( f ); assertEquals( "Channel", f.getSea() ); assertEquals( 2, f.getSize() ); s.remove( f ); } ); } @Test public void testDeclaredValues(SessionFactoryScope scope) { Country country = new Country(); AmericaCupClass americaCupClass = new AmericaCupClass(); scope.inTransaction( s -> { country.setName( "France" ); americaCupClass.setSize( 2 ); americaCupClass.setCountry( country ); s.persist( country ); s.persist( americaCupClass ); } ); scope.inTransaction( s -> { AmericaCupClass f = s.get( AmericaCupClass.class, americaCupClass.getId() ); assertNotNull( f ); assertEquals( country, f.getCountry() ); assertEquals( 2, f.getSize() ); s.remove( f ); s.remove( f.getCountry() ); } ); } @Test public void testCompositePk(SessionFactoryScope scope) { scope.inTransaction( s -> { Carrot c = new Carrot(); VegetablePk pk = new VegetablePk(); pk.setFarmer( "Bill" ); pk.setHarvestDate( "2004-08-15" ); c.setId( pk ); c.setLength( 23 ); s.persist( c ); } ); scope.inTransaction( s -> { CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery<Vegetable> criteria = criteriaBuilder.createQuery( Vegetable.class ); criteria.from( Vegetable.class ); Vegetable v = s.createQuery( criteria ).uniqueResult(); assertInstanceOf( Carrot.class, v ); Carrot result = (Carrot) v; assertEquals( 23, result.getLength() ); } ); } }
JoinedSubclassTest
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/rank/async/AsyncStateFastTop1Function.java
{ "start": 6093, "end": 6926 }
class ____ extends FastTop1Helper { public AsyncStateFastTop1Helper() { super( AsyncStateFastTop1Function.this, inputRowSer, cacheSize, AsyncStateFastTop1Function.this.getDefaultTopNSize()); } @Override public void flushBufferToState(RowData currentKey, RowData value) throws Exception { ((AsyncKeyOrderedProcessingOperator) keyContext) .asyncProcessWithKey( currentKey, () -> { // no need to wait this async request to end AsyncStateFastTop1Function.this.dataState.asyncUpdate(value); }); } } }
AsyncStateFastTop1Helper
java
apache__camel
components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpConfiguration.java
{ "start": 11307, "end": 14609 }
interface ____ which the connection should bind. */ public void setBindAddress(String bindAddress) { this.bindAddress = bindAddress; } public String getBindAddress() { return bindAddress; } public boolean isExistDirCheckUsingLs() { return existDirCheckUsingLs; } /** * Whether to check for existing directory using LS command or CD. By default LS is used which is safer as otherwise * Camel needs to change the directory back after checking. However LS has been reported to cause a problem on * windows system in some situations and therefore you can disable this option to use CD. */ public void setExistDirCheckUsingLs(boolean existDirCheckUsingLs) { this.existDirCheckUsingLs = existDirCheckUsingLs; } public String getKeyExchangeProtocols() { return keyExchangeProtocols; } /** * Set a comma separated list of key exchange protocols that will be used in order of preference. Possible cipher * names are defined by JCraft JSCH. Some examples include: * diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1,diffie-hellman-group14-sha1, * diffie-hellman-group-exchange-sha256,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521. If not specified * the default list from JSCH will be used. */ public void setKeyExchangeProtocols(String keyExchangeProtocols) { this.keyExchangeProtocols = keyExchangeProtocols; } public String getServerHostKeys() { return serverHostKeys; } /** * Set a comma separated list of algorithms supported for the server host key. Some examples include: * ssh-dss,ssh-rsa,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521. If not specified the default list * from JSCH will be used. */ public void setServerHostKeys(String serverHostKeys) { this.serverHostKeys = serverHostKeys; } public String getPublicKeyAcceptedAlgorithms() { return publicKeyAcceptedAlgorithms; } /** * Set a comma separated list of public key accepted algorithms. Some examples include: * ssh-dss,ssh-rsa,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521. If not specified the default list * from JSCH will be used. */ public void setPublicKeyAcceptedAlgorithms(String publicKeyAcceptedAlgorithms) { this.publicKeyAcceptedAlgorithms = publicKeyAcceptedAlgorithms; } public String getFilenameEncoding() { return filenameEncoding; } /** * Encoding to use for FTP client when parsing filenames. By default, UTF-8 is used. */ public void setFilenameEncoding(String filenameEncoding) { this.filenameEncoding = filenameEncoding; } public LoggingLevel getServerMessageLoggingLevel() { return serverMessageLoggingLevel; } /** * The logging level used for various human intended log messages from the FTP server. * * This can be used during troubleshooting to raise the logging level and inspect the logs received from the FTP * server. */ public void setServerMessageLoggingLevel(LoggingLevel serverMessageLoggingLevel) { this.serverMessageLoggingLevel = serverMessageLoggingLevel; } }
against
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/BasicTestEntity3.java
{ "start": 333, "end": 1725 }
class ____ { @Id @GeneratedValue private Integer id; private String str1; private String str2; public BasicTestEntity3() { } public BasicTestEntity3(String str1, String str2) { this.str1 = str1; this.str2 = str2; } public BasicTestEntity3(Integer id, String str1, String str2) { this.id = id; this.str1 = str1; this.str2 = str2; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getStr1() { return str1; } public void setStr1(String str1) { this.str1 = str1; } public String getStr2() { return str2; } public void setStr2(String str2) { this.str2 = str2; } public boolean equals(Object o) { if ( this == o ) { return true; } if ( !(o instanceof BasicTestEntity3) ) { return false; } BasicTestEntity3 that = (BasicTestEntity3) o; if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; } if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { return false; } if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { return false; } return true; } public int hashCode() { int result; result = (id != null ? id.hashCode() : 0); result = 31 * result + (str1 != null ? str1.hashCode() : 0); result = 31 * result + (str2 != null ? str2.hashCode() : 0); return result; } }
BasicTestEntity3
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/TestException.java
{ "start": 138, "end": 617 }
class ____ extends TestCase { public void test_0() throws Exception { Exception error = null; try { f(); } catch (Exception ex) { error = ex; } String text = JSON.toJSONString(new Exception[] { error }); List<RuntimeException> list = JSON.parseArray(text, RuntimeException.class); JSON.toJSONString(list); } public void f() { throw new RuntimeException(); } }
TestException
java
netty__netty
transport-classes-epoll/src/main/java/io/netty/channel/epoll/EpollServerDomainSocketChannel.java
{ "start": 1094, "end": 3418 }
class ____ extends AbstractEpollServerChannel implements ServerDomainSocketChannel { private static final InternalLogger logger = InternalLoggerFactory.getInstance( EpollServerDomainSocketChannel.class); private final EpollServerChannelConfig config = new EpollServerChannelConfig(this); private volatile DomainSocketAddress local; public EpollServerDomainSocketChannel() { super(newSocketDomain(), false); } public EpollServerDomainSocketChannel(int fd) { super(fd); } public EpollServerDomainSocketChannel(int fd, boolean active) { super(new LinuxSocket(fd), active); } EpollServerDomainSocketChannel(LinuxSocket fd) { super(fd); } EpollServerDomainSocketChannel(LinuxSocket fd, boolean active) { super(fd, active); } @Override protected Channel newChildChannel(int fd, byte[] addr, int offset, int len) throws Exception { return new EpollDomainSocketChannel(this, new Socket(fd)); } @Override protected DomainSocketAddress localAddress0() { return local; } @Override protected void doBind(SocketAddress localAddress) throws Exception { socket.bind(localAddress); socket.listen(config.getBacklog()); local = (DomainSocketAddress) localAddress; active = true; } @Override protected void doClose() throws Exception { try { super.doClose(); } finally { DomainSocketAddress local = this.local; if (local != null) { // Delete the socket file if possible. File socketFile = new File(local.path()); boolean success = socketFile.delete(); if (!success && logger.isDebugEnabled()) { logger.debug("Failed to delete a domain socket file: {}", local.path()); } } } } @Override public EpollServerChannelConfig config() { return config; } @Override public DomainSocketAddress remoteAddress() { return (DomainSocketAddress) super.remoteAddress(); } @Override public DomainSocketAddress localAddress() { return (DomainSocketAddress) super.localAddress(); } }
EpollServerDomainSocketChannel
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/cli/EnvironmentAwareCommandTests.java
{ "start": 1028, "end": 6126 }
class ____ extends CommandTestCase { private Build.Type buildType; private Consumer<Environment> callback; @Before public void resetHooks() { buildType = Build.Type.TAR; callback = null; } @Override protected Command newCommand() { return new EnvironmentAwareCommand("test command") { @Override public void execute(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) { if (callback != null) { callback.accept(env); } } @Override protected Build.Type getBuildType() { return buildType; } }; } // Check that for non-Docker, environment variables are not translated into settings public void testNonDockerEnvVarSettingsIgnored() throws Exception { envVars.put("ES_SETTING_FOO_BAR", "baz"); envVars.put("some.setting", "1"); callback = env -> { Settings settings = env.settings(); assertThat(settings.hasValue("foo.bar"), is(false)); assertThat(settings.hasValue("some.settings"), is(false)); }; execute(); } // Check that for Docker, environment variables that do not match the criteria for translation to settings are ignored. public void testDockerEnvVarSettingsIgnored() throws Exception { // No ES_SETTING_ prefix envVars.put("XPACK_SECURITY_FIPS__MODE_ENABLED", "false"); // Incomplete prefix envVars.put("ES_XPACK_SECURITY_FIPS__MODE_ENABLED", "false"); // Not underscore-separated envVars.put("ES.SETTING.XPACK.SECURITY.FIPS_MODE.ENABLED", "false"); // Not uppercase envVars.put("es_setting_xpack_security_fips__mode_enabled", "false"); // single word is not translated, it must contain a dot envVars.put("singleword", "value"); // any uppercase letters cause the var to be ignored envVars.put("setting.Ignored", "value"); callback = env -> { Settings settings = env.settings(); assertThat(settings.hasValue("xpack.security.fips_mode.enabled"), is(false)); assertThat(settings.hasValue("singleword"), is(false)); assertThat(settings.hasValue("setting.Ignored"), is(false)); assertThat(settings.hasValue("setting.ignored"), is(false)); }; execute(); } // Check that for Docker builds, various env vars are translated correctly to settings public void testDockerEnvVarSettingsTranslated() throws Exception { buildType = Build.Type.DOCKER; // normal setting with a dot envVars.put("ES_SETTING_SIMPLE_SETTING", "value"); // double underscore is translated to literal underscore envVars.put("ES_SETTING_UNDERSCORE__HERE", "value"); // literal underscore and a dot envVars.put("ES_SETTING_UNDERSCORE__DOT_BAZ", "value"); // two literal underscores envVars.put("ES_SETTING_DOUBLE____UNDERSCORE", "value"); // literal underscore followed by a dot (not valid setting, but translated nonetheless envVars.put("ES_SETTING_TRIPLE___BAZ", "value"); // lowercase envVars.put("lowercase.setting", "value"); callback = env -> { Settings settings = env.settings(); assertThat(settings.get("simple.setting"), equalTo("value")); assertThat(settings.get("underscore_here"), equalTo("value")); assertThat(settings.get("underscore_dot.baz"), equalTo("value")); assertThat(settings.get("triple_.baz"), equalTo("value")); assertThat(settings.get("double__underscore"), equalTo("value")); assertThat(settings.get("lowercase.setting"), equalTo("value")); }; execute(); } // Check that for Docker builds, env vars takes precedence over settings on the command line. public void testDockerEnvVarSettingsOverrideCommandLine() throws Exception { // docker env takes precedence over settings on the command line buildType = Build.Type.DOCKER; envVars.put("ES_SETTING_SIMPLE_SETTING", "override"); callback = env -> { Settings settings = env.settings(); assertThat(settings.get("simple.setting"), equalTo("override")); }; execute("-Esimple.setting=original"); } public void testDuplicateCommandLineSetting() { var e = expectThrows(UserException.class, () -> execute("-E", "my.setting=foo", "-E", "my.setting=bar")); assertThat(e.getMessage(), equalTo("setting [my.setting] set twice via command line -E")); } public void testConflictingPathCommandLineSettingWithSysprop() { sysprops.put("es.path.data", "foo"); var e = expectThrows(UserException.class, () -> execute("-E", "path.data=bar")); assertThat(e.getMessage(), equalTo("setting [path.data] found via command-line -E and system property [es.path.data]")); } }
EnvironmentAwareCommandTests
java
netty__netty
codec-base/src/main/java/io/netty/handler/codec/HeadersUtils.java
{ "start": 4765, "end": 5752 }
class ____ implements Entry<String, String> { private final Entry<CharSequence, CharSequence> entry; private String name; private String value; StringEntry(Entry<CharSequence, CharSequence> entry) { this.entry = entry; } @Override public String getKey() { if (name == null) { name = entry.getKey().toString(); } return name; } @Override public String getValue() { if (value == null && entry.getValue() != null) { value = entry.getValue().toString(); } return value; } @Override public String setValue(String value) { String old = getValue(); entry.setValue(value); return old; } @Override public String toString() { return entry.toString(); } } private static final
StringEntry
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptSendToEndpointWithStopTest.java
{ "start": 1041, "end": 2369 }
class ____ extends ContextTestSupport { @Test public void testInterceptSendToEndpointWithStop() throws Exception { getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:b").expectedMessageCount(0); getMockEndpoint("mock:c").expectedMessageCount(0); getMockEndpoint("mock:result").expectedMessageCount(0); template.sendBody("direct:start", "stop"); assertMockEndpointsSatisfied(); } @Test public void testInterceptSendToEndpointWithNoStop() throws Exception { getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:b").expectedMessageCount(1); getMockEndpoint("mock:c").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { interceptSendToEndpoint("mock:b").choice().when(body().isEqualTo("stop")).stop().otherwise().to("mock:c"); from("direct:start").to("mock:a").to("mock:b").to("mock:result"); } }; } }
InterceptSendToEndpointWithStopTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/RoundToInt4Evaluator.java
{ "start": 1085, "end": 4211 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(RoundToInt4Evaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator field; private final int p0; private final int p1; private final int p2; private final int p3; private final DriverContext driverContext; private Warnings warnings; public RoundToInt4Evaluator(Source source, EvalOperator.ExpressionEvaluator field, int p0, int p1, int p2, int p3, DriverContext driverContext) { this.source = source; this.field = field; this.p0 = p0; this.p1 = p1; this.p2 = p2; this.p3 = p3; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (IntBlock fieldBlock = (IntBlock) field.eval(page)) { IntVector fieldVector = fieldBlock.asVector(); if (fieldVector == null) { return eval(page.getPositionCount(), fieldBlock); } return eval(page.getPositionCount(), fieldVector).asBlock(); } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += field.baseRamBytesUsed(); return baseRamBytesUsed; } public IntBlock eval(int positionCount, IntBlock fieldBlock) { try(IntBlock.Builder result = driverContext.blockFactory().newIntBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { switch (fieldBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } int field = fieldBlock.getInt(fieldBlock.getFirstValueIndex(p)); result.appendInt(RoundToInt.process(field, this.p0, this.p1, this.p2, this.p3)); } return result.build(); } } public IntVector eval(int positionCount, IntVector fieldVector) { try(IntVector.FixedBuilder result = driverContext.blockFactory().newIntVectorFixedBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { int field = fieldVector.getInt(p); result.appendInt(p, RoundToInt.process(field, this.p0, this.p1, this.p2, this.p3)); } return result.build(); } } @Override public String toString() { return "RoundToInt4Evaluator[" + "field=" + field + ", p0=" + p0 + ", p1=" + p1 + ", p2=" + p2 + ", p3=" + p3 + "]"; } @Override public void close() { Releasables.closeExpectNoException(field); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
RoundToInt4Evaluator
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/annotation/AnnotationTypeMappingsTests.java
{ "start": 29416, "end": 29574 }
interface ____ { String a(); String b() default ""; } @Retention(RetentionPolicy.RUNTIME) @DefinedAttributesTarget(a = "test") @
DefinedAttributesTarget
java
apache__kafka
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/GroupCoordinatorRecordSerde.java
{ "start": 1208, "end": 1872 }
class ____ extends CoordinatorRecordSerde { @Override protected ApiMessage apiMessageKeyFor(short recordType) { try { return CoordinatorRecordType.fromId(recordType).newRecordKey(); } catch (UnsupportedVersionException ex) { throw new UnknownRecordTypeException(recordType); } } @Override protected ApiMessage apiMessageValueFor(short recordType) { try { return CoordinatorRecordType.fromId(recordType).newRecordValue(); } catch (UnsupportedVersionException ex) { throw new UnknownRecordTypeException(recordType); } } }
GroupCoordinatorRecordSerde
java
apache__rocketmq
broker/src/test/java/org/apache/rocketmq/broker/subscription/RocksdbGroupConfigTransferTest.java
{ "start": 1851, "end": 15678 }
class ____ { private final String basePath = Paths.get(System.getProperty("user.home"), "unit-test-store", UUID.randomUUID().toString().substring(0, 16).toUpperCase()).toString(); private RocksDBSubscriptionGroupManager rocksDBSubscriptionGroupManager; private SubscriptionGroupManager jsonSubscriptionGroupManager; @Mock private BrokerController brokerController; @Mock private DefaultMessageStore defaultMessageStore; @Before public void init() { if (notToBeExecuted()) { return; } BrokerConfig brokerConfig = new BrokerConfig(); Mockito.lenient().when(brokerController.getBrokerConfig()).thenReturn(brokerConfig); MessageStoreConfig messageStoreConfig = new MessageStoreConfig(); messageStoreConfig.setStorePathRootDir(basePath); Mockito.lenient().when(brokerController.getMessageStoreConfig()).thenReturn(messageStoreConfig); Mockito.lenient().when(brokerController.getMessageStore()).thenReturn(defaultMessageStore); when(defaultMessageStore.getStateMachineVersion()).thenReturn(0L); } @After public void destroy() { if (notToBeExecuted()) { return; } Path pathToBeDeleted = Paths.get(basePath); try { Files.walk(pathToBeDeleted) .sorted(Comparator.reverseOrder()) .forEach(path -> { try { Files.delete(path); } catch (IOException e) { // ignore } }); } catch (IOException e) { // ignore } if (rocksDBSubscriptionGroupManager != null) { rocksDBSubscriptionGroupManager.stop(); } } public void initRocksDBSubscriptionGroupManager() { if (rocksDBSubscriptionGroupManager == null) { rocksDBSubscriptionGroupManager = new RocksDBSubscriptionGroupManager(brokerController); rocksDBSubscriptionGroupManager.load(); } } public void initJsonSubscriptionGroupManager() { if (jsonSubscriptionGroupManager == null) { jsonSubscriptionGroupManager = new SubscriptionGroupManager(brokerController); jsonSubscriptionGroupManager.load(); } } @Test public void theFirstTimeLoadJsonSubscriptionGroupManager() { if (notToBeExecuted()) { return; } initJsonSubscriptionGroupManager(); DataVersion dataVersion = jsonSubscriptionGroupManager.getDataVersion(); Assert.assertNotNull(dataVersion); Assert.assertEquals(0L, dataVersion.getCounter().get()); Assert.assertEquals(0L, dataVersion.getStateVersion()); Assert.assertNotEquals(0, jsonSubscriptionGroupManager.getSubscriptionGroupTable().size()); } @Test public void theFirstTimeLoadRocksDBSubscriptionGroupManager() { if (notToBeExecuted()) { return; } initRocksDBSubscriptionGroupManager(); DataVersion dataVersion = rocksDBSubscriptionGroupManager.getDataVersion(); Assert.assertNotNull(dataVersion); Assert.assertEquals(0L, dataVersion.getCounter().get()); Assert.assertEquals(0L, dataVersion.getStateVersion()); Assert.assertNotEquals(0, rocksDBSubscriptionGroupManager.getSubscriptionGroupTable().size()); } @Test public void addGroupLoadJsonSubscriptionGroupManager() { if (notToBeExecuted()) { return; } initJsonSubscriptionGroupManager(); int beforeSize = jsonSubscriptionGroupManager.getSubscriptionGroupTable().size(); String groupName = "testAddGroupConfig-" + System.currentTimeMillis(); Map<String, String> attributes = new HashMap<>(); SubscriptionGroupConfig subscriptionGroupConfig = new SubscriptionGroupConfig(); subscriptionGroupConfig.setGroupName(groupName); subscriptionGroupConfig.setAttributes(attributes); DataVersion beforeDataVersion = jsonSubscriptionGroupManager.getDataVersion(); long beforeDataVersionCounter = beforeDataVersion.getCounter().get(); long beforeTimestamp = beforeDataVersion.getTimestamp(); jsonSubscriptionGroupManager.updateSubscriptionGroupConfig(subscriptionGroupConfig); int afterSize = jsonSubscriptionGroupManager.getSubscriptionGroupTable().size(); DataVersion afterDataVersion = jsonSubscriptionGroupManager.getDataVersion(); long afterDataVersionCounter = afterDataVersion.getCounter().get(); long afterTimestamp = afterDataVersion.getTimestamp(); Assert.assertEquals(0, beforeDataVersionCounter); Assert.assertEquals(1, afterDataVersionCounter); Assert.assertEquals(1, afterSize - beforeSize); Assert.assertTrue(afterTimestamp >= beforeTimestamp); } @Test public void addForbiddenGroupLoadJsonSubscriptionGroupManager() { if (notToBeExecuted()) { return; } initJsonSubscriptionGroupManager(); int beforeSize = jsonSubscriptionGroupManager.getForbiddenTable().size(); String groupName = "testAddGroupConfig-" + System.currentTimeMillis(); Map<String, String> attributes = new HashMap<>(); SubscriptionGroupConfig subscriptionGroupConfig = new SubscriptionGroupConfig(); subscriptionGroupConfig.setGroupName(groupName); subscriptionGroupConfig.setAttributes(attributes); DataVersion beforeDataVersion = jsonSubscriptionGroupManager.getDataVersion(); long beforeDataVersionCounter = beforeDataVersion.getCounter().get(); long beforeTimestamp = beforeDataVersion.getTimestamp(); jsonSubscriptionGroupManager.setForbidden(groupName, "topic", 0); int afterSize = jsonSubscriptionGroupManager.getForbiddenTable().size(); DataVersion afterDataVersion = jsonSubscriptionGroupManager.getDataVersion(); long afterDataVersionCounter = afterDataVersion.getCounter().get(); long afterTimestamp = afterDataVersion.getTimestamp(); Assert.assertEquals(1, afterDataVersionCounter - beforeDataVersionCounter); Assert.assertEquals(1, afterSize - beforeSize); Assert.assertTrue(afterTimestamp >= beforeTimestamp); } @Test public void addGroupLoadRocksdbSubscriptionGroupManager() { if (notToBeExecuted()) { return; } initRocksDBSubscriptionGroupManager(); int beforeSize = rocksDBSubscriptionGroupManager.getSubscriptionGroupTable().size(); String groupName = "testAddGroupConfig-" + System.currentTimeMillis(); Map<String, String> attributes = new HashMap<>(); SubscriptionGroupConfig subscriptionGroupConfig = new SubscriptionGroupConfig(); subscriptionGroupConfig.setGroupName(groupName); subscriptionGroupConfig.setAttributes(attributes); DataVersion beforeDataVersion = rocksDBSubscriptionGroupManager.getDataVersion(); long beforeDataVersionCounter = beforeDataVersion.getCounter().get(); long beforeTimestamp = beforeDataVersion.getTimestamp(); rocksDBSubscriptionGroupManager.updateSubscriptionGroupConfig(subscriptionGroupConfig); int afterSize = rocksDBSubscriptionGroupManager.getSubscriptionGroupTable().size(); DataVersion afterDataVersion = rocksDBSubscriptionGroupManager.getDataVersion(); long afterDataVersionCounter = afterDataVersion.getCounter().get(); long afterTimestamp = afterDataVersion.getTimestamp(); Assert.assertEquals(1, afterDataVersionCounter); Assert.assertEquals(0, beforeDataVersionCounter); Assert.assertEquals(1, afterSize - beforeSize); Assert.assertTrue(afterTimestamp >= beforeTimestamp); } @Test public void addForbiddenLoadRocksdbSubscriptionGroupManager() { if (notToBeExecuted()) { return; } initRocksDBSubscriptionGroupManager(); int beforeSize = rocksDBSubscriptionGroupManager.getForbiddenTable().size(); String groupName = "testAddGroupConfig-" + System.currentTimeMillis(); Map<String, String> attributes = new HashMap<>(); SubscriptionGroupConfig subscriptionGroupConfig = new SubscriptionGroupConfig(); subscriptionGroupConfig.setGroupName(groupName); subscriptionGroupConfig.setAttributes(attributes); DataVersion beforeDataVersion = rocksDBSubscriptionGroupManager.getDataVersion(); long beforeDataVersionCounter = beforeDataVersion.getCounter().get(); long beforeTimestamp = beforeDataVersion.getTimestamp(); rocksDBSubscriptionGroupManager.updateForbidden(groupName, "topic", 0, true); int afterSize = rocksDBSubscriptionGroupManager.getForbiddenTable().size(); DataVersion afterDataVersion = rocksDBSubscriptionGroupManager.getDataVersion(); long afterDataVersionCounter = afterDataVersion.getCounter().get(); long afterTimestamp = afterDataVersion.getTimestamp(); Assert.assertEquals(1, afterDataVersionCounter - beforeDataVersionCounter); Assert.assertEquals(1, afterSize - beforeSize); Assert.assertTrue(afterTimestamp >= beforeTimestamp); Assert.assertNotEquals(0, rocksDBSubscriptionGroupManager.getSubscriptionGroupTable().size()); } @Test public void theSecondTimeLoadJsonSubscriptionGroupManager() { if (notToBeExecuted()) { return; } addGroupLoadJsonSubscriptionGroupManager(); jsonSubscriptionGroupManager.stop(); rocksDBSubscriptionGroupManager = null; addForbiddenGroupLoadJsonSubscriptionGroupManager(); jsonSubscriptionGroupManager.stop(); rocksDBSubscriptionGroupManager = null; jsonSubscriptionGroupManager = new SubscriptionGroupManager(brokerController); jsonSubscriptionGroupManager.load(); DataVersion dataVersion = jsonSubscriptionGroupManager.getDataVersion(); Assert.assertNotNull(dataVersion); Assert.assertEquals(2L, dataVersion.getCounter().get()); Assert.assertEquals(0L, dataVersion.getStateVersion()); Assert.assertNotEquals(0, jsonSubscriptionGroupManager.getSubscriptionGroupTable().size()); Assert.assertNotEquals(0, jsonSubscriptionGroupManager.getForbiddenTable().size()); Assert.assertNotEquals(0, jsonSubscriptionGroupManager.getSubscriptionGroupTable().size()); } @Test public void theSecondTimeLoadRocksdbTopicConfigManager() { if (notToBeExecuted()) { return; } addGroupLoadRocksdbSubscriptionGroupManager(); rocksDBSubscriptionGroupManager.stop(); rocksDBSubscriptionGroupManager = null; addForbiddenLoadRocksdbSubscriptionGroupManager(); rocksDBSubscriptionGroupManager.stop(); rocksDBSubscriptionGroupManager = null; rocksDBSubscriptionGroupManager = new RocksDBSubscriptionGroupManager(brokerController); rocksDBSubscriptionGroupManager.load(); DataVersion dataVersion = rocksDBSubscriptionGroupManager.getDataVersion(); Assert.assertNotNull(dataVersion); Assert.assertEquals(2L, dataVersion.getCounter().get()); Assert.assertEquals(0L, dataVersion.getStateVersion()); Assert.assertNotEquals(0, rocksDBSubscriptionGroupManager.getSubscriptionGroupTable().size()); Assert.assertNotEquals(0, rocksDBSubscriptionGroupManager.getForbiddenTable().size()); Assert.assertNotEquals(0, rocksDBSubscriptionGroupManager.getSubscriptionGroupTable().size()); } @Test public void jsonUpgradeToRocksdb() { if (notToBeExecuted()) { return; } addGroupLoadJsonSubscriptionGroupManager(); addForbiddenGroupLoadJsonSubscriptionGroupManager(); initRocksDBSubscriptionGroupManager(); DataVersion dataVersion = rocksDBSubscriptionGroupManager.getDataVersion(); Assert.assertNotNull(dataVersion); Assert.assertEquals(3L, dataVersion.getCounter().get()); Assert.assertEquals(0L, dataVersion.getStateVersion()); Assert.assertNotEquals(0, rocksDBSubscriptionGroupManager.getForbiddenTable().size()); Assert.assertNotEquals(0, rocksDBSubscriptionGroupManager.getSubscriptionGroupTable().size()); Assert.assertEquals(rocksDBSubscriptionGroupManager.getSubscriptionGroupTable().size(), jsonSubscriptionGroupManager.getSubscriptionGroupTable().size()); Assert.assertEquals(rocksDBSubscriptionGroupManager.getForbiddenTable().size(), jsonSubscriptionGroupManager.getForbiddenTable().size()); rocksDBSubscriptionGroupManager.stop(); rocksDBSubscriptionGroupManager = new RocksDBSubscriptionGroupManager(brokerController); rocksDBSubscriptionGroupManager.load(); dataVersion = rocksDBSubscriptionGroupManager.getDataVersion(); Assert.assertEquals(3L, dataVersion.getCounter().get()); Assert.assertEquals(0L, dataVersion.getStateVersion()); Assert.assertNotEquals(0, rocksDBSubscriptionGroupManager.getForbiddenTable().size()); Assert.assertNotEquals(0, rocksDBSubscriptionGroupManager.getSubscriptionGroupTable().size()); Assert.assertEquals(rocksDBSubscriptionGroupManager.getSubscriptionGroupTable().size(), jsonSubscriptionGroupManager.getSubscriptionGroupTable().size()); Assert.assertEquals(rocksDBSubscriptionGroupManager.getForbiddenTable().size(), jsonSubscriptionGroupManager.getForbiddenTable().size()); } private boolean notToBeExecuted() { return MixAll.isMac() || MixAll.isWindows(); } }
RocksdbGroupConfigTransferTest
java
qos-ch__slf4j
slf4j-ext/src/test/java/org/slf4j/profiler/NestedProfilerDemo2.java
{ "start": 1523, "end": 2415 }
class ____ { static Logger logger = LoggerFactory.getLogger(NestedProfilerDemo2.class); public static void main(String[] args) { Profiler profiler = new Profiler("DEMO"); // associate a logger with the profiler profiler.setLogger(logger); ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance(); profiler.registerWith(profilerRegistry); profiler.start("RANDOM"); RandomIntegerArrayGenerator riaGenerator = new RandomIntegerArrayGenerator(); int n = 10 * 1000; int[] randomArray = riaGenerator.generate(n); profiler.startNested(SortAndPruneComposites.NESTED_PROFILER_NAME); SortAndPruneComposites pruner = new SortAndPruneComposites(randomArray); pruner.sortAndPruneComposites(); // stop and log profiler.stop().log(); } }
NestedProfilerDemo2
java
apache__camel
test-infra/camel-test-infra-ibmmq/src/main/java/org/apache/camel/test/infra/ibmmq/services/IbmMQInfraService.java
{ "start": 980, "end": 1118 }
interface ____ extends InfrastructureService { String channel(); String queueManager(); int listenerPort(); }
IbmMQInfraService
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/io/VFSTest.java
{ "start": 3070, "end": 3243 }
class ____ implements Runnable { volatile VFS instanceGot; @Override public void run() { instanceGot = VFS.getInstance(); } } }
InstanceGetterProcedure
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/config/DubboConfigDefaultPropertyValueBeanPostProcessor.java
{ "start": 2121, "end": 4722 }
class ____ extends GenericBeanPostProcessorAdapter<AbstractConfig> implements MergedBeanDefinitionPostProcessor, PriorityOrdered { /** * The bean name of {@link DubboConfigDefaultPropertyValueBeanPostProcessor} */ public static final String BEAN_NAME = "dubboConfigDefaultPropertyValueBeanPostProcessor"; @Override protected void processBeforeInitialization(AbstractConfig dubboConfigBean, String beanName) throws BeansException { // ignore auto generate bean name if (!beanName.contains("#")) { // [Feature] https://github.com/apache/dubbo/issues/5721 setPropertyIfAbsent(dubboConfigBean, Constants.ID, beanName); // beanName should not be used as config name, fix https://github.com/apache/dubbo/pull/7624 // setPropertyIfAbsent(dubboConfigBean, "name", beanName); } } @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) { // DO NOTHING } protected void setPropertyIfAbsent(Object bean, String propertyName, String beanName) { Class<?> beanClass = getTargetClass(bean); PropertyDescriptor propertyDescriptor = getPropertyDescriptor(beanClass, propertyName); if (propertyDescriptor != null) { // the property is present Method getterMethod = propertyDescriptor.getReadMethod(); if (getterMethod == null) { // if The getter method is absent return; } Object propertyValue = invokeMethod(getterMethod, bean); if (propertyValue != null) { // If The return value of "getId" method is not null return; } Method setterMethod = propertyDescriptor.getWriteMethod(); if (setterMethod != null) { // the getter and setter methods are present if (Arrays.equals( ObjectUtils.of(String.class), setterMethod.getParameterTypes())) { // the param type is String // set bean name to the value of the property invokeMethod(setterMethod, bean, beanName); } } } } /** * @return Higher than {@link InitDestroyAnnotationBeanPostProcessor#getOrder()} * @see InitDestroyAnnotationBeanPostProcessor * @see CommonAnnotationBeanPostProcessor * @see PostConstruct */ @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE + 1; } }
DubboConfigDefaultPropertyValueBeanPostProcessor
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/consumer/KafkaShareConsumerMetricsTest.java
{ "start": 3246, "end": 21565 }
class ____ { private final String topic = "test"; private final Uuid topicId = Uuid.randomUuid(); private final Map<String, Uuid> topicIds = Stream.of( new AbstractMap.SimpleEntry<>(topic, topicId)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); private final Time time = new MockTime(); private final SubscriptionState subscription = new SubscriptionState(new LogContext(), AutoOffsetResetStrategy.EARLIEST); private final String groupId = "mock-group"; @Test public void testPollTimeMetrics() { ShareConsumerMetadata metadata = createMetadata(subscription); MockClient client = new MockClient(time, metadata); initMetadata(client, Collections.singletonMap(topic, 1)); KafkaShareConsumer<String, String> consumer = newShareConsumer(time, client, subscription, metadata); consumer.subscribe(Collections.singletonList(topic)); // MetricName objects to check Metrics metrics = consumer.metricsRegistry(); MetricName lastPollSecondsAgoName = metrics.metricName("last-poll-seconds-ago", CONSUMER_SHARE_METRIC_GROUP_PREFIX + "-metrics"); MetricName timeBetweenPollAvgName = metrics.metricName("time-between-poll-avg", CONSUMER_SHARE_METRIC_GROUP_PREFIX + "-metrics"); MetricName timeBetweenPollMaxName = metrics.metricName("time-between-poll-max", CONSUMER_SHARE_METRIC_GROUP_PREFIX + "-metrics"); // Test default values assertEquals(-1.0d, consumer.metrics().get(lastPollSecondsAgoName).metricValue()); assertEquals(Double.NaN, consumer.metrics().get(timeBetweenPollAvgName).metricValue()); assertEquals(Double.NaN, consumer.metrics().get(timeBetweenPollMaxName).metricValue()); // Call first poll consumer.poll(Duration.ZERO); assertEquals(0.0d, consumer.metrics().get(lastPollSecondsAgoName).metricValue()); assertEquals(0.0d, consumer.metrics().get(timeBetweenPollAvgName).metricValue()); assertEquals(0.0d, consumer.metrics().get(timeBetweenPollMaxName).metricValue()); // Advance time by 5,000 (total time = 5,000) time.sleep(5 * 1000L); assertEquals(5.0d, consumer.metrics().get(lastPollSecondsAgoName).metricValue()); // Call second poll consumer.poll(Duration.ZERO); assertEquals(2.5 * 1000d, consumer.metrics().get(timeBetweenPollAvgName).metricValue()); assertEquals(5 * 1000d, consumer.metrics().get(timeBetweenPollMaxName).metricValue()); // Advance time by 10,000 (total time = 15,000) time.sleep(10 * 1000L); assertEquals(10.0d, consumer.metrics().get(lastPollSecondsAgoName).metricValue()); // Call third poll consumer.poll(Duration.ZERO); assertEquals(5 * 1000d, consumer.metrics().get(timeBetweenPollAvgName).metricValue()); assertEquals(10 * 1000d, consumer.metrics().get(timeBetweenPollMaxName).metricValue()); // Advance time by 5,000 (total time = 20,000) time.sleep(5 * 1000L); assertEquals(5.0d, consumer.metrics().get(lastPollSecondsAgoName).metricValue()); // Call fourth poll consumer.poll(Duration.ZERO); assertEquals(5 * 1000d, consumer.metrics().get(timeBetweenPollAvgName).metricValue()); assertEquals(10 * 1000d, consumer.metrics().get(timeBetweenPollMaxName).metricValue()); } @Test public void testPollIdleRatio() { ShareConsumerMetadata metadata = createMetadata(subscription); MockClient client = new MockClient(time, metadata); initMetadata(client, Collections.singletonMap(topic, 1)); KafkaShareConsumer<String, String> consumer = newShareConsumer(time, client, subscription, metadata); // MetricName object to check Metrics metrics = consumer.metricsRegistry(); MetricName pollIdleRatio = metrics.metricName("poll-idle-ratio-avg", CONSUMER_SHARE_METRIC_GROUP_PREFIX + "-metrics"); // Test default value assertEquals(Double.NaN, consumer.metrics().get(pollIdleRatio).metricValue()); // 1st poll // Spend 50ms in poll so value = 1.0 consumer.kafkaShareConsumerMetrics().recordPollStart(time.milliseconds()); time.sleep(50); consumer.kafkaShareConsumerMetrics().recordPollEnd(time.milliseconds()); assertEquals(1.0d, consumer.metrics().get(pollIdleRatio).metricValue()); // 2nd poll // Spend 50m outside poll and 0ms in poll so value = 0.0 time.sleep(50); consumer.kafkaShareConsumerMetrics().recordPollStart(time.milliseconds()); consumer.kafkaShareConsumerMetrics().recordPollEnd(time.milliseconds()); // Avg of first two data points assertEquals((1.0d + 0.0d) / 2, consumer.metrics().get(pollIdleRatio).metricValue()); // 3rd poll // Spend 25ms outside poll and 25ms in poll so value = 0.5 time.sleep(25); consumer.kafkaShareConsumerMetrics().recordPollStart(time.milliseconds()); time.sleep(25); consumer.kafkaShareConsumerMetrics().recordPollEnd(time.milliseconds()); // Avg of three data points assertEquals((1.0d + 0.0d + 0.5d) / 3, consumer.metrics().get(pollIdleRatio).metricValue()); } private static boolean consumerMetricPresent(KafkaShareConsumer<String, String> consumer, String name) { MetricName metricName = new MetricName(name, CONSUMER_SHARE_METRIC_GROUP_PREFIX + "-metrics", "", Collections.emptyMap()); return consumer.metricsRegistry().metrics().containsKey(metricName); } @Test public void testClosingConsumerUnregistersConsumerMetrics() { Time time = new MockTime(1L); ShareConsumerMetadata metadata = createMetadata(subscription); MockClient client = new MockClient(time, metadata); initMetadata(client, Collections.singletonMap(topic, 1)); KafkaShareConsumer<String, String> consumer = newShareConsumer(time, client, subscription, metadata); consumer.subscribe(Collections.singletonList(topic)); assertTrue(consumerMetricPresent(consumer, "last-poll-seconds-ago")); assertTrue(consumerMetricPresent(consumer, "time-between-poll-avg")); assertTrue(consumerMetricPresent(consumer, "time-between-poll-max")); consumer.close(); assertFalse(consumerMetricPresent(consumer, "last-poll-seconds-ago")); assertFalse(consumerMetricPresent(consumer, "time-between-poll-avg")); assertFalse(consumerMetricPresent(consumer, "time-between-poll-max")); } @Test public void testRegisteringCustomMetricsDoesntAffectConsumerMetrics() { Time time = new MockTime(1L); ShareConsumerMetadata metadata = createMetadata(subscription); MockClient client = new MockClient(time, metadata); initMetadata(client, Collections.singletonMap(topic, 1)); KafkaShareConsumer<String, String> consumer = newShareConsumer(time, client, subscription, metadata); Map<MetricName, KafkaMetric> customMetrics = customMetrics(); customMetrics.forEach((name, metric) -> consumer.registerMetricForSubscription(metric)); Map<MetricName, ? extends Metric> consumerMetrics = consumer.metrics(); customMetrics.forEach((name, metric) -> assertFalse(consumerMetrics.containsKey(name))); } @Test public void testRegisteringCustomMetricsWithSameNameDoesntAffectConsumerMetrics() { try (final LogCaptureAppender appender = LogCaptureAppender.createAndRegister()) { appender.setClassLogger(ShareConsumerImpl.class, Level.DEBUG); Time time = new MockTime(1L); ShareConsumerMetadata metadata = createMetadata(subscription); MockClient client = new MockClient(time, metadata); initMetadata(client, Collections.singletonMap(topic, 1)); KafkaShareConsumer<String, String> consumer = newShareConsumer(time, client, subscription, metadata); KafkaMetric existingMetricToAdd = (KafkaMetric) consumer.metrics().entrySet().iterator().next().getValue(); consumer.registerMetricForSubscription(existingMetricToAdd); final String expectedMessage = String.format("Skipping registration for metric %s. Existing consumer metrics cannot be overwritten.", existingMetricToAdd.metricName()); assertTrue(appender.getMessages().stream().anyMatch(m -> m.contains(expectedMessage))); } } @Test public void testUnregisteringCustomMetricsWithSameNameDoesntAffectConsumerMetrics() { try (final LogCaptureAppender appender = LogCaptureAppender.createAndRegister()) { appender.setClassLogger(ShareConsumerImpl.class, Level.DEBUG); Time time = new MockTime(1L); ShareConsumerMetadata metadata = createMetadata(subscription); MockClient client = new MockClient(time, metadata); initMetadata(client, Collections.singletonMap(topic, 1)); KafkaShareConsumer<String, String> consumer = newShareConsumer(time, client, subscription, metadata); KafkaMetric existingMetricToRemove = (KafkaMetric) consumer.metrics().entrySet().iterator().next().getValue(); consumer.unregisterMetricFromSubscription(existingMetricToRemove); final String expectedMessage = String.format("Skipping unregistration for metric %s. Existing consumer metrics cannot be removed.", existingMetricToRemove.metricName()); assertTrue(appender.getMessages().stream().anyMatch(m -> m.contains(expectedMessage))); } } @Test public void testShouldOnlyCallMetricReporterMetricChangeOnceWithExistingConsumerMetric() { try (MockedStatic<CommonClientConfigs> mockedCommonClientConfigs = mockStatic(CommonClientConfigs.class, new CallsRealMethods())) { ClientTelemetryReporter clientTelemetryReporter = mock(ClientTelemetryReporter.class); clientTelemetryReporter.configure(any()); mockedCommonClientConfigs.when(() -> CommonClientConfigs.telemetryReporter(anyString(), any())).thenReturn(Optional.of(clientTelemetryReporter)); Time time = new MockTime(1L); ShareConsumerMetadata metadata = createMetadata(subscription); MockClient client = new MockClient(time, metadata); initMetadata(client, Collections.singletonMap(topic, 1)); KafkaShareConsumer<String, String> consumer = newShareConsumer(time, client, subscription, metadata); KafkaMetric existingMetric = (KafkaMetric) consumer.metrics().entrySet().iterator().next().getValue(); consumer.registerMetricForSubscription(existingMetric); // This test would fail without the check as the existing metric is registered in the consumer on startup Mockito.verify(clientTelemetryReporter, atMostOnce()).metricChange(existingMetric); } } @Test public void testShouldNotCallMetricReporterMetricRemovalWithExistingConsumerMetric() { try (MockedStatic<CommonClientConfigs> mockedCommonClientConfigs = mockStatic(CommonClientConfigs.class, new CallsRealMethods())) { ClientTelemetryReporter clientTelemetryReporter = mock(ClientTelemetryReporter.class); clientTelemetryReporter.configure(any()); mockedCommonClientConfigs.when(() -> CommonClientConfigs.telemetryReporter(anyString(), any())).thenReturn(Optional.of(clientTelemetryReporter)); Time time = new MockTime(1L); ShareConsumerMetadata metadata = createMetadata(subscription); MockClient client = new MockClient(time, metadata); initMetadata(client, Collections.singletonMap(topic, 1)); KafkaShareConsumer<String, String> consumer = newShareConsumer(time, client, subscription, metadata); KafkaMetric existingMetric = (KafkaMetric) consumer.metrics().entrySet().iterator().next().getValue(); consumer.unregisterMetricFromSubscription(existingMetric); Mockito.verify(clientTelemetryReporter, never()).metricRemoval(existingMetric); } } @Test public void testUnregisteringNonexistingMetricsDoesntCauseError() { Time time = new MockTime(1L); ShareConsumerMetadata metadata = createMetadata(subscription); MockClient client = new MockClient(time, metadata); initMetadata(client, Collections.singletonMap(topic, 1)); KafkaShareConsumer<String, String> consumer = newShareConsumer(time, client, subscription, metadata); Map<MetricName, KafkaMetric> customMetrics = customMetrics(); // Metrics never registered but removed should not cause an error customMetrics.forEach((name, metric) -> assertDoesNotThrow(() -> consumer.unregisterMetricFromSubscription(metric))); } private ShareConsumerMetadata createMetadata(SubscriptionState subscription) { return new ShareConsumerMetadata(0, 0, Long.MAX_VALUE, false, subscription, new LogContext(), new ClusterResourceListeners()); } private KafkaShareConsumer<String, String> newShareConsumer(Time time, KafkaClient client, SubscriptionState subscription, ShareConsumerMetadata metadata) { return newShareConsumer( time, client, subscription, metadata, groupId, Optional.of(new StringDeserializer()) ); } private KafkaShareConsumer<String, String> newShareConsumer(Time time, KafkaClient client, SubscriptionState subscriptions, ShareConsumerMetadata metadata, String groupId, Optional<Deserializer<String>> valueDeserializerOpt) { String clientId = "mock-consumer"; Deserializer<String> keyDeserializer = new StringDeserializer(); Deserializer<String> valueDeserializer = valueDeserializerOpt.orElse(new StringDeserializer()); LogContext logContext = new LogContext(); ShareConsumerConfig config = newConsumerConfig(groupId, valueDeserializer); return new KafkaShareConsumer<>( logContext, clientId, groupId, config, keyDeserializer, valueDeserializer, time, client, subscriptions, metadata ); } private ShareConsumerConfig newConsumerConfig(String groupId, Deserializer<String> valueDeserializer) { String clientId = "mock-consumer"; long retryBackoffMs = 100; long retryBackoffMaxMs = 1000; int minBytes = 1; int maxBytes = Integer.MAX_VALUE; int maxWaitMs = 500; int fetchSize = 1024 * 1024; int maxPollRecords = Integer.MAX_VALUE; boolean checkCrcs = true; int rebalanceTimeoutMs = 60000; int defaultApiTimeoutMs = 60000; int requestTimeoutMs = defaultApiTimeoutMs / 2; Map<String, Object> configs = new HashMap<>(); configs.put(ConsumerConfig.CHECK_CRCS_CONFIG, checkCrcs); configs.put(ConsumerConfig.CLIENT_ID_CONFIG, clientId); configs.put(ConsumerConfig.CLIENT_RACK_CONFIG, CommonClientConfigs.DEFAULT_CLIENT_RACK); configs.put(ConsumerConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, defaultApiTimeoutMs); configs.put(ConsumerConfig.FETCH_MAX_BYTES_CONFIG, maxBytes); configs.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, maxWaitMs); configs.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, minBytes); configs.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); configs.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, fetchSize); configs.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, rebalanceTimeoutMs); configs.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords); configs.put(ConsumerConfig.REQUEST_TIMEOUT_MS_CONFIG, requestTimeoutMs); configs.put(ConsumerConfig.RETRY_BACKOFF_MAX_MS_CONFIG, retryBackoffMaxMs); configs.put(ConsumerConfig.RETRY_BACKOFF_MS_CONFIG, retryBackoffMs); configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializer.getClass()); configs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); return new ShareConsumerConfig(configs); } private void initMetadata(MockClient mockClient, Map<String, Integer> partitionCounts) { Map<String, Uuid> metadataIds = new HashMap<>(); for (String name : partitionCounts.keySet()) { metadataIds.put(name, topicIds.get(name)); } MetadataResponse initialMetadata = RequestTestUtils.metadataUpdateWithIds(1, partitionCounts, metadataIds); mockClient.updateMetadata(initialMetadata); } private Map<MetricName, KafkaMetric> customMetrics() { MetricConfig metricConfig = new MetricConfig(); Object lock = new Object(); MetricName metricNameOne = new MetricName("metricOne", "stream-metrics", "description for metric one", new HashMap<>()); MetricName metricNameTwo = new MetricName("metricTwo", "stream-metrics", "description for metric two", new HashMap<>()); KafkaMetric streamClientMetricOne = new KafkaMetric(lock, metricNameOne, (Measurable) (m, now) -> 1.0, metricConfig, Time.SYSTEM); KafkaMetric streamClientMetricTwo = new KafkaMetric(lock, metricNameTwo, (Measurable) (m, now) -> 2.0, metricConfig, Time.SYSTEM); return Map.of(metricNameOne, streamClientMetricOne, metricNameTwo, streamClientMetricTwo); } }
KafkaShareConsumerMetricsTest
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/configproperties/MyConfigWithConstructorConfigurationInject.java
{ "start": 3457, "end": 3492 }
class ____ { } @Singleton
CI_OtherBean
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/window/groupwindow/operator/WindowOperatorTest.java
{ "start": 92510, "end": 93421 }
class ____ extends SumAndCountAggBase<CountWindow> implements NamespaceTableAggsHandleFunction<CountWindow> { private static final long serialVersionUID = -2634639678371135643L; @Override public void emitValue(CountWindow namespace, RowData key, Collector<RowData> out) throws Exception { if (!openCalled) { fail("Open was not called"); } GenericRowData row = new GenericRowData(3); if (!sumIsNull) { row.setField(0, sum); } if (!countIsNull) { row.setField(1, count); } row.setField(2, namespace.getId()); result.replace(key, row); // Simply output two lines out.collect(result); out.collect(result); } } private static
SumAndCountTableAggCountWindow
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/converter/AbstractKotlinSerializationHttpMessageConverter.java
{ "start": 2031, "end": 7420 }
class ____<T extends SerialFormat> extends AbstractSmartHttpMessageConverter<Object> { private final Map<KType, KSerializer<Object>> kTypeSerializerCache = new ConcurrentReferenceHashMap<>(); private final Map<Type, KSerializer<Object>> typeSerializerCache = new ConcurrentReferenceHashMap<>(); private final T format; private final Predicate<ResolvableType> typePredicate; /** * Creates a new instance with the given format and supported mime types * which only converters types annotated with * {@link kotlinx.serialization.Serializable @Serializable} at type or * generics level. */ protected AbstractKotlinSerializationHttpMessageConverter(T format, MediaType... supportedMediaTypes) { super(supportedMediaTypes); this.typePredicate = KotlinDetector::hasSerializableAnnotation; this.format = format; } /** * Creates a new instance with the given format and supported mime types * which only converts types for which the specified predicate returns * {@code true}. * @since 7.0 */ protected AbstractKotlinSerializationHttpMessageConverter(T format, Predicate<ResolvableType> typePredicate, MediaType... supportedMediaTypes) { super(supportedMediaTypes); this.typePredicate = typePredicate; this.format = format; } @Override public List<MediaType> getSupportedMediaTypes(Class<?> clazz) { return getSupportedMediaTypes(); } @Override protected boolean supports(Class<?> clazz) { ResolvableType type = ResolvableType.forClass(clazz); if (!this.typePredicate.test(type)) { return false; } return serializer(type, null) != null; } @Override public boolean canRead(ResolvableType type, @Nullable MediaType mediaType) { if (!this.typePredicate.test(type) || ResolvableType.NONE.equals(type)) { return false; } return serializer(type, null) != null && canRead(mediaType); } @Override public boolean canWrite(ResolvableType type, Class<?> valueClass, @Nullable MediaType mediaType) { ResolvableType resolvableType = (ResolvableType.NONE.equals(type) ? ResolvableType.forClass(valueClass) : type); if (!this.typePredicate.test(resolvableType)) { return false; } return serializer(resolvableType, null) != null && canWrite(mediaType); } @Override public final Object read(ResolvableType type, HttpInputMessage inputMessage, @Nullable Map<String, Object> hints) throws IOException, HttpMessageNotReadableException { KSerializer<Object> serializer = serializer(type, hints); if (serializer == null) { throw new HttpMessageNotReadableException("Could not find KSerializer for " + type, inputMessage); } return readInternal(serializer, this.format, inputMessage); } /** * Reads the given input message with the given serializer and format. */ protected abstract Object readInternal(KSerializer<Object> serializer, T format, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException; @Override protected final void writeInternal(Object object, ResolvableType type, HttpOutputMessage outputMessage, @Nullable Map<String, Object> hints) throws IOException, HttpMessageNotWritableException { ResolvableType resolvableType = (ResolvableType.NONE.equals(type) ? ResolvableType.forInstance(object) : type); KSerializer<Object> serializer = serializer(resolvableType, hints); if (serializer == null) { throw new HttpMessageNotWritableException("Could not find KSerializer for " + resolvableType); } writeInternal(object, serializer, this.format, outputMessage); } /** * Write the given object to the output message with the given serializer and format. */ protected abstract void writeInternal(Object object, KSerializer<Object> serializer, T format, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException; /** * Tries to find a serializer that can marshall or unmarshall instances of the given type * using kotlinx.serialization. If no serializer can be found, {@code null} is returned. * <p>Resolved serializers are cached and cached results are returned on successive calls. * @param resolvableType the type to find a serializer for * @return a resolved serializer for the given type, or {@code null} */ private @Nullable KSerializer<Object> serializer(ResolvableType resolvableType, @Nullable Map<String, Object> hints) { if (hints != null && hints.containsKey(KType.class.getName())) { KType type = (KType) hints.get(KType.class.getName()); KSerializer<Object> serializer = this.kTypeSerializerCache.get(type); if (serializer == null) { try { serializer = SerializersKt.serializerOrNull(this.format.getSerializersModule(), type); } catch (IllegalArgumentException ignored) { } if (serializer != null) { this.kTypeSerializerCache.put(type, serializer); } } return serializer; } Type type = resolvableType.getType(); KSerializer<Object> serializer = this.typeSerializerCache.get(type); if (serializer == null) { try { serializer = SerializersKt.serializerOrNull(this.format.getSerializersModule(), type); } catch (IllegalArgumentException ignored) { } if (serializer != null) { this.typeSerializerCache.put(type, serializer); } } return serializer; } @Override protected boolean supportsRepeatableWrites(Object object) { return true; } }
AbstractKotlinSerializationHttpMessageConverter
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/producer/disposer/illegal/DisposerInjectTest.java
{ "start": 610, "end": 1143 }
class ____ { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(ProducerDisposer.class) .shouldFail() .build(); @Test public void trigger() { Throwable error = container.getFailure(); assertNotNull(error); assertInstanceOf(DefinitionException.class, error); assertTrue(error.getMessage().contains("Initializer method must not have a @Disposes parameter")); } @Dependent static
DisposerInjectTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/test/java/org/apache/hadoop/yarn/service/TestServiceAM.java
{ "start": 15464, "end": 23933 }
class ____ extends ServiceScheduler { private AsyncDispatcher dispatcher; private AMRMClientCallback callbackHandler = new AMRMClientCallback(); MockServiceScheduler(ServiceContext context) { super(context); } @Override protected AsyncDispatcher createAsyncDispatcher() { dispatcher = Mockito.mock(AsyncDispatcher.class); EventHandler<Event> handler = Mockito.mock(EventHandler.class); Mockito.doReturn(handler).when(dispatcher).getEventHandler(); return dispatcher; } @Override protected AMRMClientAsync<AMRMClient.ContainerRequest> createAMRMClient() { return AMRMClientAsync.createAMRMClientAsync(1000, callbackHandler); } } @Test public void testRecordTokensForContainers() throws Exception { ApplicationId applicationId = ApplicationId.newInstance(123456, 1); Service exampleApp = new Service(); exampleApp.setId(applicationId.toString()); exampleApp.setName("testContainerCompleted"); exampleApp.addComponent(createComponent("compa", 1, "pwd")); String json = "{\"auths\": " + "{\"https://index.docker.io/v1/\": " + "{\"auth\": \"foobarbaz\"}," + "\"registry.example.com\": " + "{\"auth\": \"bazbarfoo\"}}}"; File dockerTmpDir = new File("target", "docker-tmp"); FileUtils.deleteQuietly(dockerTmpDir); dockerTmpDir.mkdirs(); String dockerConfig = dockerTmpDir + "/config.json"; BufferedWriter bw = new BufferedWriter(new FileWriter(dockerConfig)); bw.write(json); bw.close(); Credentials dockerCred = DockerClientConfigHandler.readCredentialsFromConfigFile( new Path(dockerConfig), conf, applicationId.toString()); MockServiceAM am = new MockServiceAM(exampleApp, dockerCred); ByteBuffer amCredBuffer = am.recordTokensForContainers(); Credentials amCreds = DockerClientConfigHandler.getCredentialsFromTokensByteBuffer( amCredBuffer); assertEquals(2, amCreds.numberOfTokens()); for (Token<? extends TokenIdentifier> tk : amCreds.getAllTokens()) { assertTrue(tk.getKind().equals(DockerCredentialTokenIdentifier.KIND)); } am.stop(); } @Test public void testIPChange() throws TimeoutException, InterruptedException { ApplicationId applicationId = ApplicationId.newInstance(123456, 1); String comp1Name = "comp1"; String comp1InstName = "comp1-0"; Service exampleApp = new Service(); exampleApp.setId(applicationId.toString()); exampleApp.setVersion("v1"); exampleApp.setName("testIPChange"); Component comp1 = createComponent(comp1Name, 1, "sleep 60"); comp1.setArtifact(new Artifact().type(Artifact.TypeEnum.DOCKER)); exampleApp.addComponent(comp1); MockServiceAM am = new MockServiceAM(exampleApp); am.init(conf); am.start(); ComponentInstance comp1inst0 = am.getCompInstance(comp1Name, comp1InstName); // allocate a container am.feedContainerToComp(exampleApp, 1, comp1Name); GenericTestUtils.waitFor(() -> comp1inst0.getContainerStatus() != null, 2000, 200000); // first host status will match the container nodeId assertEquals("localhost", comp1inst0.getContainerStatus().getHost()); LOG.info("Change the IP and host"); // change the container status am.updateContainerStatus(exampleApp, 1, comp1Name, "new.host"); GenericTestUtils.waitFor(() -> comp1inst0.getContainerStatus().getHost() .equals("new.host"), 2000, 200000); LOG.info("Change the IP and host again"); // change the container status am.updateContainerStatus(exampleApp, 1, comp1Name, "newer.host"); GenericTestUtils.waitFor(() -> comp1inst0.getContainerStatus().getHost() .equals("newer.host"), 2000, 200000); am.stop(); } /** This test verifies that the containers are released and the component instance is added to the pending queue when building the launch context fails. Here, we intentionally have an artifact that doesn't have an id. This will cause TarballProviderService.processArtifact to throw an IllegalArgumentException because the Path object is constructed from the id of the artifact. In case the id is set to null or unset so it is effectively null, Path.checkPathArg throws an IllegalArgumentException. **/ @Test @Timeout(value = 30) public void testContainersReleasedWhenPreLaunchFails() throws Exception { ApplicationId applicationId = ApplicationId.newInstance( System.currentTimeMillis(), 1); Service exampleApp = new Service(); exampleApp.setId(applicationId.toString()); exampleApp.setVersion("v1"); exampleApp.setName("testContainersReleasedWhenPreLaunchFails"); Component compA = createComponent("compa", 1, "pwd"); Artifact artifact = new Artifact(); artifact.setType(Artifact.TypeEnum.TARBALL); compA.artifact(artifact); exampleApp.addComponent(compA); MockServiceAM am = new MockServiceAM(exampleApp); am.init(conf); am.start(); ContainerId containerId = am.createContainerId(1); // allocate a container am.feedContainerToComp(exampleApp, containerId, "compa"); am.waitForContainerToRelease(containerId); ComponentInstance compAinst0 = am.getCompInstance(compA.getName(), "compa-0"); GenericTestUtils.waitFor(() -> am.getComponent(compA.getName()).getPendingInstances() .contains(compAinst0), 2000, 30000); assertEquals(1, am.getComponent("compa").getPendingInstances().size()); am.stop(); } @Test @Timeout(value = 30) public void testSyncSysFS() { ApplicationId applicationId = ApplicationId.newInstance( System.currentTimeMillis(), 1); Service exampleApp = new Service(); exampleApp.setId(applicationId.toString()); exampleApp.setVersion("v1"); exampleApp.setName("tensorflow"); Component compA = createComponent("compa", 1, "pwd"); compA.getConfiguration().getEnv().put( "YARN_CONTAINER_RUNTIME_YARN_SYSFS_ENABLE", "true"); Artifact artifact = new Artifact(); artifact.setType(Artifact.TypeEnum.TARBALL); compA.artifact(artifact); exampleApp.addComponent(compA); try { MockServiceAM am = new MockServiceAM(exampleApp); am.init(conf); am.start(); ServiceScheduler scheduler = am.context.scheduler; scheduler.syncSysFs(exampleApp); scheduler.close(); am.stop(); am.close(); } catch (Exception e) { LOG.error("Fail to sync sysfs.", e); fail("Fail to sync sysfs."); } } @Test public void testScheduleWithResourceAttributes() throws Exception { ApplicationId applicationId = ApplicationId.newInstance(123456, 1); Service exampleApp = new Service(); exampleApp.setId(applicationId.toString()); exampleApp.setName("testScheduleWithResourceAttributes"); exampleApp.setVersion("v1"); List<ResourceTypeInfo> resourceTypeInfos = new ArrayList<>( ResourceUtils.getResourcesTypeInfo()); // Add 3rd resource type. resourceTypeInfos.add(ResourceTypeInfo .newInstance("test-resource", "", ResourceTypes.COUNTABLE)); // Reinitialize resource types ResourceUtils.reinitializeResources(resourceTypeInfos); Component serviceCompoent = createComponent("compa", 1, "pwd"); serviceCompoent.getResource().setResourceInformations( ImmutableMap.of("test-resource", new ResourceInformation() .value(1234L) .unit("Gi") .attributes(ImmutableMap.of("k1", "v1", "k2", "v2")))); exampleApp.addComponent(serviceCompoent); MockServiceAM am = new MockServiceAM(exampleApp); am.init(conf); am.start(); ServiceScheduler serviceScheduler = am.context.scheduler; AMRMClientAsync<AMRMClient.ContainerRequest> amrmClientAsync = serviceScheduler.getAmRMClient(); Collection<AMRMClient.ContainerRequest> rr = amrmClientAsync.getMatchingRequests(0); assertEquals(1, rr.size()); org.apache.hadoop.yarn.api.records.Resource capability = rr.iterator().next().getCapability(); assertEquals(1234L, capability.getResourceValue("test-resource")); assertEquals("Gi", capability.getResourceInformation("test-resource").getUnits()); assertEquals(2, capability.getResourceInformation("test-resource") .getAttributes().size()); am.stop(); } }
MockServiceScheduler
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/VoteRequest.java
{ "start": 1251, "end": 3675 }
class ____ extends AbstractRequest.Builder<VoteRequest> { private final VoteRequestData data; public Builder(VoteRequestData data) { super(ApiKeys.VOTE); this.data = data; } @Override public VoteRequest build(short version) { return new VoteRequest(data, version); } @Override public String toString() { return data.toString(); } } private final VoteRequestData data; private VoteRequest(VoteRequestData data, short version) { super(ApiKeys.VOTE, version); this.data = data; } @Override public VoteRequestData data() { return data; } @Override public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) { return new VoteResponse(new VoteResponseData() .setErrorCode(Errors.forException(e).code())); } public static VoteRequest parse(Readable readable, short version) { return new VoteRequest(new VoteRequestData(readable, version), version); } public static VoteRequestData singletonRequest(TopicPartition topicPartition, String clusterId, int replicaEpoch, int replicaId, int lastEpoch, long lastEpochEndOffset, boolean preVote) { return new VoteRequestData() .setClusterId(clusterId) .setTopics(Collections.singletonList( new VoteRequestData.TopicData() .setTopicName(topicPartition.topic()) .setPartitions(Collections.singletonList( new VoteRequestData.PartitionData() .setPartitionIndex(topicPartition.partition()) .setReplicaEpoch(replicaEpoch) .setReplicaId(replicaId) .setLastOffsetEpoch(lastEpoch) .setLastOffset(lastEpochEndOffset) .setPreVote(preVote)) ))); } }
Builder
java
apache__avro
lang/java/ipc/src/test/java/org/apache/avro/TestProtocolGeneric.java
{ "start": 1721, "end": 2177 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(TestProtocolGeneric.class); protected static final File FILE = new File("../../../share/test/schemas/simple.avpr"); protected static final Protocol PROTOCOL; static { try { PROTOCOL = Protocol.parse(FILE); } catch (IOException e) { throw new RuntimeException(e); } } private static boolean throwUndeclaredError; protected static
TestProtocolGeneric
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/MapKeyClassJpaAnnotation.java
{ "start": 464, "end": 1370 }
class ____ implements MapKeyClass { private java.lang.Class<?> value; /** * Used in creating dynamic annotation instances (e.g. from XML) */ public MapKeyClassJpaAnnotation(ModelsContext modelContext) { } /** * Used in creating annotation instances from JDK variant */ public MapKeyClassJpaAnnotation(MapKeyClass annotation, ModelsContext modelContext) { this.value = annotation.value(); } /** * Used in creating annotation instances from Jandex variant */ public MapKeyClassJpaAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) { this.value = (Class<?>) attributeValues.get( "value" ); } @Override public Class<? extends Annotation> annotationType() { return MapKeyClass.class; } @Override public java.lang.Class<?> value() { return value; } public void value(java.lang.Class<?> value) { this.value = value; } }
MapKeyClassJpaAnnotation
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/BatchTask.java
{ "start": 18033, "end": 27680 }
class ____ null, the driver has no user code if (userCodeFunctionType != null) { this.stub = initStub(userCodeFunctionType); } } catch (Exception e) { throw new RuntimeException( "Initializing the UDF" + (e.getMessage() == null ? "." : ": " + e.getMessage()), e); } } protected <X> void readAndSetBroadcastInput( int inputNum, String bcVarName, DistributedRuntimeUDFContext context, int superstep) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug( formatLogString( "Setting broadcast variable '" + bcVarName + "'" + (superstep > 1 ? ", superstep " + superstep : ""))); } @SuppressWarnings("unchecked") final TypeSerializerFactory<X> serializerFactory = (TypeSerializerFactory<X>) this.broadcastInputSerializers[inputNum]; final MutableReader<?> reader = this.broadcastInputReaders[inputNum]; BroadcastVariableMaterialization<X, ?> variable = getEnvironment() .getBroadcastVariableManager() .materializeBroadcastVariable( bcVarName, superstep, this, reader, serializerFactory); context.setBroadcastVariable(bcVarName, variable); } protected void releaseBroadcastVariables( String bcVarName, int superstep, DistributedRuntimeUDFContext context) { if (LOG.isDebugEnabled()) { LOG.debug( formatLogString( "Releasing broadcast variable '" + bcVarName + "'" + (superstep > 1 ? ", superstep " + superstep : ""))); } getEnvironment().getBroadcastVariableManager().releaseReference(bcVarName, superstep, this); context.clearBroadcastVariable(bcVarName); } protected void run() throws Exception { // ---------------------------- Now, the actual processing starts ------------------------ // check for asynchronous canceling if (!this.running) { return; } boolean stubOpen = false; try { // run the data preparation try { this.driver.prepare(); } catch (Throwable t) { // if the preparation caused an error, clean up // errors during clean-up are swallowed, because we have already a root exception throw new Exception( "The data preparation for task '" + this.getEnvironment().getTaskInfo().getTaskName() + "' , caused an error: " + t.getMessage(), t); } // check for canceling if (!this.running) { return; } // start all chained tasks BatchTask.openChainedTasks(this.chainedTasks, this); // open stub implementation if (this.stub != null) { try { Configuration stubConfig = this.config.getStubParameters(); FunctionUtils.openFunction(this.stub, DefaultOpenContext.INSTANCE); stubOpen = true; } catch (Throwable t) { throw new Exception( "The user defined 'open()' method caused an exception: " + t.getMessage(), t); } } // run the user code this.driver.run(); // close. We close here such that a regular close throwing an exception marks a task as // failed. if (this.running && this.stub != null) { FunctionUtils.closeFunction(this.stub); stubOpen = false; } // close all chained tasks letting them report failure BatchTask.closeChainedTasks(this.chainedTasks, this); // close the output collector this.output.close(); } catch (Exception ex) { // close the input, but do not report any exceptions, since we already have another root // cause if (stubOpen) { try { FunctionUtils.closeFunction(this.stub); } catch (Throwable t) { // do nothing } } // if resettable driver invoke teardown if (this.driver instanceof ResettableDriver) { final ResettableDriver<?, ?> resDriver = (ResettableDriver<?, ?>) this.driver; try { resDriver.teardown(); } catch (Throwable t) { throw new Exception( "Error while shutting down an iterative operator: " + t.getMessage(), t); } } BatchTask.cancelChainedTasks(this.chainedTasks); ex = ExceptionInChainedStubException.exceptionUnwrap(ex); if (ex instanceof CancelTaskException) { // forward canceling exception throw ex; } else if (this.running) { // throw only if task was not cancelled. in the case of canceling, exceptions are // expected BatchTask.logAndThrowException(ex, this); } } finally { this.driver.cleanup(); } } protected void closeLocalStrategiesAndCaches() { // make sure that all broadcast variable references held by this task are released if (LOG.isDebugEnabled()) { LOG.debug(formatLogString("Releasing all broadcast variables.")); } getEnvironment().getBroadcastVariableManager().releaseAllReferencesFromTask(this); if (runtimeUdfContext != null) { runtimeUdfContext.clearAllBroadcastVariables(); } // clean all local strategies and caches/pipeline breakers. if (this.localStrategies != null) { for (int i = 0; i < this.localStrategies.length; i++) { if (this.localStrategies[i] != null) { try { this.localStrategies[i].close(); } catch (Throwable t) { LOG.error("Error closing local strategy for input " + i, t); } } } } if (this.tempBarriers != null) { for (int i = 0; i < this.tempBarriers.length; i++) { if (this.tempBarriers[i] != null) { try { this.tempBarriers[i].close(); } catch (Throwable t) { LOG.error("Error closing temp barrier for input " + i, t); } } } } if (this.resettableInputs != null) { for (int i = 0; i < this.resettableInputs.length; i++) { if (this.resettableInputs[i] != null) { try { this.resettableInputs[i].close(); } catch (Throwable t) { LOG.error("Error closing cache for input " + i, t); } } } } } // -------------------------------------------------------------------------------------------- // Task Setup and Teardown // -------------------------------------------------------------------------------------------- /** * @return the last output collector in the collector chain */ @SuppressWarnings("unchecked") protected Collector<OT> getLastOutputCollector() { int numChained = this.chainedTasks.size(); return (numChained == 0) ? output : (Collector<OT>) chainedTasks.get(numChained - 1).getOutputCollector(); } /** * Sets the last output {@link Collector} of the collector chain of this {@link BatchTask}. * * <p>In case of chained tasks, the output collector of the last {@link ChainedDriver} is set. * Otherwise it is the single collector of the {@link BatchTask}. * * @param newOutputCollector new output collector to set as last collector */ protected void setLastOutputCollector(Collector<OT> newOutputCollector) { int numChained = this.chainedTasks.size(); if (numChained == 0) { output = newOutputCollector; return; } chainedTasks.get(numChained - 1).setOutputCollector(newOutputCollector); } public TaskConfig getLastTasksConfig() { int numChained = this.chainedTasks.size(); return (numChained == 0) ? config : chainedTasks.get(numChained - 1).getTaskConfig(); } protected S initStub(Class<? super S> stubSuperClass) throws Exception { try { ClassLoader userCodeClassLoader = getUserCodeClassLoader(); S stub = config.<S>getStubWrapper(userCodeClassLoader) .getUserCodeObject(stubSuperClass, userCodeClassLoader); // check if the
is
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/main/java/org/hibernate/processor/validation/MockEntityPersister.java
{ "start": 1204, "end": 6432 }
class ____ implements EntityPersister, Joinable { private static final String[] ID_COLUMN = {"id"}; private final String entityName; private final MockSessionFactory factory; private final List<MockEntityPersister> subclassPersisters = new ArrayList<>(); final AccessType defaultAccessType; private final Map<String,Type> propertyTypesByName = new HashMap<>(); public MockEntityPersister(String entityName, AccessType defaultAccessType, MockSessionFactory factory) { this.entityName = entityName; this.factory = factory; this.defaultAccessType = defaultAccessType; } void initSubclassPersisters() { for (MockEntityPersister other: factory.getMockEntityPersisters()) { other.addPersister(this); this.addPersister(other); } } private void addPersister(MockEntityPersister entityPersister) { if (isSubclassPersister(entityPersister)) { subclassPersisters.add(entityPersister); } } private Type getSubclassPropertyType(String propertyPath) { return subclassPersisters.stream() .map(sp -> sp.getPropertyType(propertyPath)) .filter(Objects::nonNull) .findAny() .orElse(null); } abstract boolean isSamePersister(MockEntityPersister entityPersister); abstract boolean isSubclassPersister(MockEntityPersister entityPersister); @Override public boolean isSubclassEntityName(String name) { return isSubclassPersister(subclassPersisters.stream() .filter(persister -> persister.entityName.equals(name)) .findFirst().orElseThrow()); } @Override public SessionFactoryImplementor getFactory() { return factory; } @Override public EntityMetamodel getEntityMetamodel() { throw new UnsupportedOperationException("operation not supported"); } @Override public String getEntityName() { return entityName; } @Override public final Type getPropertyType(String propertyPath) { final Type cached = propertyTypesByName.get(propertyPath); if ( cached == null ) { final Type type = propertyType( propertyPath ); if ( type != null ) { propertyTypesByName.put( propertyPath, type ); } return type; } else { return cached; } } private Type propertyType(String propertyPath) { final Type type = createPropertyType( propertyPath ); if ( type != null ) { return type; } //check subclasses, needed for treat() final Type typeFromSubclass = getSubclassPropertyType( propertyPath ); if ( typeFromSubclass != null ) { return typeFromSubclass; } if ( "id".equals( propertyPath ) ) { return identifierType(); } return null; } abstract Type createPropertyType(String propertyPath); /** * Override on subclasses! */ @Override public String getIdentifierPropertyName() { return getRootEntityPersister().identifierPropertyName(); } protected abstract String identifierPropertyName(); /** * Override on subclasses! */ @Override public Type getIdentifierType() { return getRootEntityPersister().identifierType(); } protected abstract Type identifierType(); /** * Override on subclasses! */ @Override public BasicType<?> getVersionType() { return getRootEntityPersister().versionType(); } protected abstract BasicType<?> versionType(); @Override public abstract String getRootEntityName(); public MockEntityPersister getRootEntityPersister() { return factory.createMockEntityPersister(getRootEntityName()); } @Override public Set<String> getSubclassEntityNames() { final Set<String> names = new HashSet<>(); names.add( entityName ); for (MockEntityPersister persister : factory.getMockEntityPersisters()) { if (persister.isSubclassPersister(this)) { names.add(persister.entityName); } } return names; } @Override public String[] toColumns(String propertyName) { return new String[] { "" }; } @Override public String[] getPropertySpaces() { return new String[] {entityName}; } @Override public Serializable[] getQuerySpaces() { return new Serializable[] {entityName}; } @Override public EntityPersister getEntityPersister() { return this; } @Override public String[] getIdentifierColumnNames() { return ID_COLUMN; } @Override public DiscriminatorType<?> getDiscriminatorDomainType() { var type = getDiscriminatorType(); return new DiscriminatorTypeImpl<>( type, new UnifiedAnyDiscriminatorConverter<>( new NavigableRole( entityName ) .append( EntityDiscriminatorMapping.DISCRIMINATOR_ROLE_NAME ), type.getJavaTypeDescriptor(), type.getRelationalJavaType(), emptyMap(), ShortNameImplicitDiscriminatorStrategy.SHORT_NAME_STRATEGY, factory.getMetamodel() ) ); } @Override public String getTableName() { return entityName; } @Override public String toString() { return "MockEntityPersister[" + entityName + "]"; } @Override public int getVersionPropertyIndex() { return 0; } @Override public boolean isVersioned() { return true; } @Override public String getMappedSuperclass() { return null; } @Override public BasicType<String> getDiscriminatorType() { return factory.getTypeConfiguration().getBasicTypeForJavaType(String.class); } @Override public boolean isMutable() { return true; } }
MockEntityPersister
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/access/hierarchicalroles/TestHelperTests.java
{ "start": 1140, "end": 7730 }
class ____ { @Test public void testContainTheSameGrantedAuthorities() { List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B"); List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_B", "ROLE_A"); List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_C"); List<GrantedAuthority> authorities4 = AuthorityUtils.createAuthorityList("ROLE_A"); List<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_A"); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, null)).isTrue(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities1)).isTrue(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities2)).isTrue(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities2, authorities1)).isTrue(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, authorities1)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, null)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities3)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities3, authorities1)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities4)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities4, authorities1)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities4, authorities5)).isFalse(); } // SEC-863 @Test public void testToListOfAuthorityStrings() { Collection<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B"); Collection<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_B", "ROLE_A"); Collection<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_C"); Collection<GrantedAuthority> authorities4 = AuthorityUtils.createAuthorityList("ROLE_A"); Collection<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_A"); List<String> authoritiesStrings1 = new ArrayList<>(); authoritiesStrings1.add("ROLE_A"); authoritiesStrings1.add("ROLE_B"); List<String> authoritiesStrings2 = new ArrayList<>(); authoritiesStrings2.add("ROLE_B"); authoritiesStrings2.add("ROLE_A"); List<String> authoritiesStrings3 = new ArrayList<>(); authoritiesStrings3.add("ROLE_A"); authoritiesStrings3.add("ROLE_C"); List<String> authoritiesStrings4 = new ArrayList<>(); authoritiesStrings4.add("ROLE_A"); List<String> authoritiesStrings5 = new ArrayList<>(); authoritiesStrings5.add("ROLE_A"); authoritiesStrings5.add("ROLE_A"); assertThat(CollectionUtils.isEqualCollection( HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities1), authoritiesStrings1)) .isTrue(); assertThat(CollectionUtils.isEqualCollection( HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities2), authoritiesStrings2)) .isTrue(); assertThat(CollectionUtils.isEqualCollection( HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities3), authoritiesStrings3)) .isTrue(); assertThat(CollectionUtils.isEqualCollection( HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities4), authoritiesStrings4)) .isTrue(); assertThat(CollectionUtils.isEqualCollection( HierarchicalRolesTestHelper.toCollectionOfAuthorityStrings(authorities5), authoritiesStrings5)) .isTrue(); } // SEC-863 @Test public void testContainTheSameGrantedAuthoritiesCompareByAuthorityString() { List<GrantedAuthority> authorities1 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B"); List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_B", "ROLE_A"); List<GrantedAuthority> authorities3 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_C"); List<GrantedAuthority> authorities4 = AuthorityUtils.createAuthorityList("ROLE_A"); List<GrantedAuthority> authorities5 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_A"); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, null)).isTrue(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities1)).isTrue(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities2)).isTrue(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities2, authorities1)).isTrue(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(null, authorities1)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, null)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities3)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities3, authorities1)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities1, authorities4)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities4, authorities1)).isFalse(); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthorities(authorities4, authorities5)).isFalse(); } // SEC-863 @Test public void testContainTheSameGrantedAuthoritiesCompareByAuthorityStringWithAuthorityLists() { List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_A", "ROLE_B"); List<GrantedAuthority> authorities2 = AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B"); assertThat(HierarchicalRolesTestHelper.containTheSameGrantedAuthoritiesCompareByAuthorityString(authorities1, authorities2)) .isTrue(); } // SEC-863 @Test public void testCreateAuthorityList() { List<GrantedAuthority> authorities1 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_A"); assertThat(authorities1).hasSize(1); assertThat(authorities1.get(0).getAuthority()).isEqualTo("ROLE_A"); List<GrantedAuthority> authorities2 = HierarchicalRolesTestHelper.createAuthorityList("ROLE_A", "ROLE_C"); assertThat(authorities2).hasSize(2); assertThat(authorities2.get(0).getAuthority()).isEqualTo("ROLE_A"); assertThat(authorities2.get(1).getAuthority()).isEqualTo("ROLE_C"); } }
TestHelperTests
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit4/rules/TimedSpringRuleTests.java
{ "start": 1255, "end": 1658 }
class ____ extends TimedSpringRunnerTests { // All tests are in superclass. @Override protected Class<?> getTestCase() { return TimedSpringRuleTestCase.class; } @Override protected Class<? extends Runner> getRunnerClass() { return JUnit4.class; } @Ignore("TestCase classes are run manually by the enclosing test class") @TestExecutionListeners({}) public static final
TimedSpringRuleTests
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/recovery/NMMemoryStateStoreService.java
{ "start": 21765, "end": 22019 }
class ____ { Map<Path, LocalResourceProto> inProgressMap = new HashMap<Path, LocalResourceProto>(); Map<Path, LocalizedResourceProto> localizedResources = new HashMap<Path, LocalizedResourceProto>(); } private static
TrackerState
java
quarkusio__quarkus
extensions/container-image/container-image-podman/deployment/src/main/java/io/quarkus/container/image/podman/deployment/PodmanConfig.java
{ "start": 454, "end": 847 }
interface ____ extends CommonConfig { /** * Which platform(s) to target during the build. See * https://docs.podman.io/en/latest/markdown/podman-build.1.html#platform-os-arch-variant */ Optional<List<String>> platform(); /** * Require HTTPS and verify certificates when contacting registries */ @WithDefault("true") boolean tlsVerify(); }
PodmanConfig
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/analysis/PreBuiltAnalyzerProviderFactory.java
{ "start": 1091, "end": 3516 }
class ____ extends PreConfiguredAnalysisComponent<AnalyzerProvider<?>> implements Closeable { private final Function<IndexVersion, Analyzer> create; private final PreBuiltAnalyzerProvider current; /** * This constructor only exists to expose analyzers defined in {@link PreBuiltAnalyzers} as {@link PreBuiltAnalyzerProviderFactory}. */ PreBuiltAnalyzerProviderFactory(String name, PreBuiltAnalyzers preBuiltAnalyzer) { super(name, new PreBuiltAnalyzersDelegateCache(name, preBuiltAnalyzer)); this.create = preBuiltAnalyzer::getAnalyzer; Analyzer analyzer = preBuiltAnalyzer.getAnalyzer(IndexVersion.current()); current = new PreBuiltAnalyzerProvider(name, AnalyzerScope.INDICES, analyzer); } public PreBuiltAnalyzerProviderFactory(String name, PreBuiltCacheFactory.CachingStrategy cache, Supplier<Analyzer> create) { super(name, cache); this.create = version -> create.get(); Analyzer analyzer = create.get(); this.current = new PreBuiltAnalyzerProvider(name, AnalyzerScope.INDICES, analyzer); } @Override public AnalyzerProvider<?> get(IndexSettings indexSettings, Environment environment, String name, Settings settings) throws IOException { IndexVersion versionCreated = indexSettings.getIndexVersionCreated(); if (IndexVersion.current().equals(versionCreated) == false) { return super.get(indexSettings, environment, name, settings); } else { return current; } } @Override protected AnalyzerProvider<?> create(IndexVersion version) { assert IndexVersion.current().equals(version) == false; Analyzer analyzer = create.apply(version); return new PreBuiltAnalyzerProvider(getName(), AnalyzerScope.INDICES, analyzer); } @Override public void close() throws IOException { List<Closeable> closeables = cache.values().stream().<Closeable>map(AnalyzerProvider::get).toList(); IOUtils.close(current.get(), () -> IOUtils.close(closeables)); } /** * A special cache that closes the gap between PreBuiltAnalyzers and PreBuiltAnalyzerProviderFactory. * * This can be removed when all analyzers have been moved away from PreBuiltAnalyzers to * PreBuiltAnalyzerProviderFactory either in server or analysis-common. */ static
PreBuiltAnalyzerProviderFactory
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskMultipleInputSelectiveReadingTest.java
{ "start": 15108, "end": 15672 }
class ____ extends AbstractStreamOperatorFactory<String> { @Override public <T extends StreamOperator<String>> T createStreamOperator( StreamOperatorParameters<String> parameters) { return (T) new TestReadFinishedInputStreamOperator(parameters); } @Override public Class<? extends StreamOperator> getStreamOperatorClass(ClassLoader classLoader) { return TestReadFinishedInputStreamOperator.class; } } private static
TestReadFinishedInputStreamOperatorFactory
java
spring-projects__spring-boot
module/spring-boot-session-jdbc/src/test/java/org/springframework/boot/session/jdbc/autoconfigure/JdbcSessionAutoConfigurationTests.java
{ "start": 2926, "end": 12031 }
class ____ extends AbstractSessionAutoConfigurationTests { @BeforeEach void prepareRunner() { this.contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class, SessionAutoConfiguration.class, JdbcSessionAutoConfiguration.class)) .withPropertyValues("spring.datasource.generate-unique-name=true"); } @Test void defaultConfig() { this.contextRunner.run((context) -> { JdbcIndexedSessionRepository repository = validateSessionRepository(context, JdbcIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", new ServerProperties().getServlet().getSession().getTimeout()); assertThat(repository).hasFieldOrPropertyWithValue("tableName", "SPRING_SESSION"); assertThat(repository).hasFieldOrPropertyWithValue("cleanupCron", "0 * * * * *"); assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) .isEqualTo(DatabaseInitializationMode.EMBEDDED); assertThat(context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")).isEmpty(); }); } @Test void disableDataSourceInitializer() { this.contextRunner.withPropertyValues("spring.session.jdbc.initialize-schema=never").run((context) -> { assertThat(context).doesNotHaveBean(JdbcSessionDataSourceScriptDatabaseInitializer.class); JdbcIndexedSessionRepository repository = validateSessionRepository(context, JdbcIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("tableName", "SPRING_SESSION"); assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) .isEqualTo(DatabaseInitializationMode.NEVER); assertThatExceptionOfType(BadSqlGrammarException.class) .isThrownBy(() -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); }); } @Test void customTimeout() { this.contextRunner.withPropertyValues("spring.session.timeout=1m").run((context) -> { JdbcIndexedSessionRepository repository = validateSessionRepository(context, JdbcIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", Duration.ofMinutes(1)); }); } @Test void customTableName() { this.contextRunner.withPropertyValues("spring.session.jdbc.table-name=FOO_BAR", "spring.session.jdbc.schema=classpath:org/springframework/boot/session/jdbc/autoconfigure/custom-schema-h2.sql") .run((context) -> { JdbcIndexedSessionRepository repository = validateSessionRepository(context, JdbcIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("tableName", "FOO_BAR"); assertThat(context.getBean(JdbcSessionProperties.class).getInitializeSchema()) .isEqualTo(DatabaseInitializationMode.EMBEDDED); assertThat(context.getBean(JdbcOperations.class).queryForList("select * from FOO_BAR")).isEmpty(); }); } @Test void customCleanupCron() { this.contextRunner.withPropertyValues("spring.session.jdbc.cleanup-cron=0 0 12 * * *").run((context) -> { assertThat(context.getBean(JdbcSessionProperties.class).getCleanupCron()).isEqualTo("0 0 12 * * *"); JdbcIndexedSessionRepository repository = validateSessionRepository(context, JdbcIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("cleanupCron", "0 0 12 * * *"); }); } @Test void customFlushMode() { this.contextRunner.withPropertyValues("spring.session.jdbc.flush-mode=immediate").run((context) -> { JdbcIndexedSessionRepository repository = validateSessionRepository(context, JdbcIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("flushMode", FlushMode.IMMEDIATE); }); } @Test void customSaveMode() { this.contextRunner.withPropertyValues("spring.session.jdbc.save-mode=on-get-attribute").run((context) -> { JdbcIndexedSessionRepository repository = validateSessionRepository(context, JdbcIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("saveMode", SaveMode.ON_GET_ATTRIBUTE); }); } @Test void sessionDataSourceIsUsedWhenAvailable() { this.contextRunner.withUserConfiguration(SessionDataSourceConfiguration.class).run((context) -> { JdbcIndexedSessionRepository repository = validateSessionRepository(context, JdbcIndexedSessionRepository.class); DataSource sessionDataSource = context.getBean("sessionDataSource", DataSource.class); assertThat(repository).extracting("jdbcOperations.dataSource").isEqualTo(sessionDataSource); assertThat(context.getBean(JdbcSessionDataSourceScriptDatabaseInitializer.class)) .hasFieldOrPropertyWithValue("dataSource", sessionDataSource); assertThatExceptionOfType(BadSqlGrammarException.class) .isThrownBy(() -> context.getBean(JdbcOperations.class).queryForList("select * from SPRING_SESSION")); }); } @Test void sessionRepositoryBeansDependOnJdbcSessionDataSourceInitializer() { this.contextRunner.run((context) -> { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); String[] sessionRepositoryNames = beanFactory.getBeanNamesForType(JdbcIndexedSessionRepository.class); assertThat(sessionRepositoryNames).isNotEmpty(); for (String sessionRepositoryName : sessionRepositoryNames) { assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()) .contains("jdbcSessionDataSourceScriptDatabaseInitializer"); } }); } @Test void sessionRepositoryBeansDependOnFlyway() { this.contextRunner.withConfiguration(AutoConfigurations.of(FlywayAutoConfiguration.class)) .withPropertyValues("spring.session.jdbc.initialize-schema=never") .run((context) -> { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); String[] sessionRepositoryNames = beanFactory.getBeanNamesForType(JdbcIndexedSessionRepository.class); assertThat(sessionRepositoryNames).isNotEmpty(); for (String sessionRepositoryName : sessionRepositoryNames) { assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()).contains("flyway", "flywayInitializer"); } }); } @Test @WithResource(name = "db/changelog/db.changelog-master.yaml", content = "databaseChangeLog:") void sessionRepositoryBeansDependOnLiquibase() { this.contextRunner.withConfiguration(AutoConfigurations.of(LiquibaseAutoConfiguration.class)) .withPropertyValues("spring.session.jdbc.initialize-schema=never") .run((context) -> { ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); String[] sessionRepositoryNames = beanFactory.getBeanNamesForType(JdbcIndexedSessionRepository.class); assertThat(sessionRepositoryNames).isNotEmpty(); for (String sessionRepositoryName : sessionRepositoryNames) { assertThat(beanFactory.getBeanDefinition(sessionRepositoryName).getDependsOn()) .contains("liquibase"); } }); } @Test void whenTheUserDefinesTheirOwnJdbcSessionDatabaseInitializerThenTheAutoConfiguredInitializerBacksOff() { this.contextRunner.withUserConfiguration(CustomJdbcSessionDatabaseInitializerConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class)) .run((context) -> assertThat(context).hasSingleBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) .doesNotHaveBean("jdbcSessionDataSourceScriptDatabaseInitializer") .hasBean("customInitializer")); } @Test void whenTheUserDefinesTheirOwnDatabaseInitializerThenTheAutoConfiguredJdbcSessionInitializerRemains() { this.contextRunner.withUserConfiguration(CustomDatabaseInitializerConfiguration.class) .withConfiguration(AutoConfigurations.of(DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class)) .run((context) -> assertThat(context).hasSingleBean(JdbcSessionDataSourceScriptDatabaseInitializer.class) .hasBean("customInitializer")); } @Test void whenTheUserDefinesTheirOwnJdbcIndexedSessionRepositoryCustomizerThenDefaultConfigurationIsOverwritten() { String expectedCreateSessionAttributeQuery = """ INSERT INTO SPRING_SESSION_ATTRIBUTES (SESSION_PRIMARY_ID, ATTRIBUTE_NAME, ATTRIBUTE_BYTES) VALUES (?, ?, ?) ON CONFLICT (SESSION_PRIMARY_ID, ATTRIBUTE_NAME) DO UPDATE SET ATTRIBUTE_BYTES = EXCLUDED.ATTRIBUTE_BYTES """; this.contextRunner.withUserConfiguration(CustomJdbcIndexedSessionRepositoryCustomizerConfiguration.class) .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class)) .run((context) -> { JdbcIndexedSessionRepository repository = validateSessionRepository(context, JdbcIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("createSessionAttributeQuery", expectedCreateSessionAttributeQuery); }); } @Configuration static
JdbcSessionAutoConfigurationTests
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/support/DefaultTimeoutMap.java
{ "start": 2338, "end": 9865 }
class ____<K, V> extends ServiceSupport implements TimeoutMap<K, V> { protected final Logger log = LoggerFactory.getLogger(getClass()); private final ConcurrentMap<K, TimeoutMapEntry<K, V>> map = new ConcurrentHashMap<>(); private final ScheduledExecutorService executor; private volatile ScheduledFuture<?> future; private final long purgePollTime; private final Lock lock; private final List<Listener<K, V>> listeners = new ArrayList<>(2); public DefaultTimeoutMap(ScheduledExecutorService executor) { this(executor, 1000); } public DefaultTimeoutMap(ScheduledExecutorService executor, long requestMapPollTimeMillis) { this(executor, requestMapPollTimeMillis, true); } public DefaultTimeoutMap(ScheduledExecutorService executor, long requestMapPollTimeMillis, boolean useLock) { this(executor, requestMapPollTimeMillis, useLock ? new ReentrantLock() : NoLock.INSTANCE); } public DefaultTimeoutMap(ScheduledExecutorService executor, long requestMapPollTimeMillis, Lock lock) { ObjectHelper.notNull(executor, "ScheduledExecutorService"); this.executor = executor; this.purgePollTime = requestMapPollTimeMillis; this.lock = lock; } @Override public V get(K key) { TimeoutMapEntry<K, V> entry; // if no contains, the lock is not necessary if (!map.containsKey(key)) { return null; } lock.lock(); try { entry = map.get(key); if (entry == null) { return null; } updateExpireTime(entry); } finally { lock.unlock(); } return entry.getValue(); } @Override public V put(K key, V value, long timeoutMillis) { TimeoutMapEntry<K, V> entry = new TimeoutMapEntry<>(key, value, timeoutMillis); lock.lock(); try { updateExpireTime(entry); TimeoutMapEntry<K, V> result = map.put(key, entry); return unwrap(result); } finally { lock.unlock(); emitEvent(Put, key, value); } } @Override public V putIfAbsent(K key, V value, long timeoutMillis) { TimeoutMapEntry<K, V> entry = new TimeoutMapEntry<>(key, value, timeoutMillis); TimeoutMapEntry<K, V> result = null; lock.lock(); try { updateExpireTime(entry); //Just make sure we don't override the old entry result = map.putIfAbsent(key, entry); return unwrap(result); } finally { lock.unlock(); if (result != entry) { emitEvent(Put, key, value); // conditional on map being changed } } } @Override public V remove(K key) { // if no contains, the lock is not necessary if (!map.containsKey(key)) { return null; } V value = null; lock.lock(); try { value = unwrap(map.remove(key)); return value; } finally { lock.unlock(); if (value != null) { emitEvent(Remove, key, value); // conditional on map being changed } } } @Override public int size() { return map.size(); } /** * The timer task which purges old requests and schedules another poll */ private void purgeTask() { // only purge if allowed if (!isRunAllowed()) { log.trace("Purge task not allowed to run"); return; } log.trace("Running purge task to see if any entries have been timed out"); try { purge(); } catch (Exception t) { // must catch and log exception otherwise the executor will now schedule next purgeTask log.warn("Exception occurred during purge task. This exception will be ignored.", t); } } protected void purge() { log.trace("There are {} in the timeout map", map.size()); if (map.isEmpty()) { return; } long now = currentTime(); List<TimeoutMapEntry<K, V>> expired = new ArrayList<>(map.size()); lock.lock(); try { // need to find the expired entries and add to the expired list for (Map.Entry<K, TimeoutMapEntry<K, V>> entry : map.entrySet()) { if (entry.getValue().getExpireTime() < now) { if (isValidForEviction(entry.getValue())) { log.debug("Evicting inactive entry ID: {}", entry.getValue()); expired.add(entry.getValue()); } } } // if we found any expired then we need to sort, onEviction and remove if (!expired.isEmpty()) { // sort according to the expired time so we got the first expired first expired.sort(comparing(TimeoutMapEntry::getExpireTime)); // and must remove from list after we have fired the notifications for (TimeoutMapEntry<K, V> entry : expired) { map.remove(entry.getKey()); } } } finally { lock.unlock(); for (TimeoutMapEntry<K, V> entry : expired) { emitEvent(Evict, entry.getKey(), entry.getValue()); } } } // Properties // ------------------------------------------------------------------------- public long getPurgePollTime() { return purgePollTime; } public ScheduledExecutorService getExecutor() { return executor; } // Implementation methods // ------------------------------------------------------------------------- private static <K, V> V unwrap(TimeoutMapEntry<K, V> entry) { return entry == null ? null : entry.getValue(); } @Override public void addListener(Listener<K, V> listener) { this.listeners.add(listener); } private void emitEvent(Listener.Type type, K key, V value) { for (Listener<K, V> listener : listeners) { try { listener.timeoutMapEvent(type, key, value); } catch (Exception t) { // Ignore } } } /** * lets schedule each time to allow folks to change the time at runtime */ protected void schedulePoll() { future = executor.scheduleWithFixedDelay(this::purgeTask, 0, purgePollTime, TimeUnit.MILLISECONDS); } /** * A hook to allow derivations to avoid evicting the current entry */ protected boolean isValidForEviction(TimeoutMapEntry<K, V> entry) { return true; } protected void updateExpireTime(TimeoutMapEntry<K, V> entry) { long now = currentTime(); entry.setExpireTime(entry.getTimeout() + now); } protected long currentTime() { return System.currentTimeMillis(); } @Override protected void doStart() throws Exception { if (executor.isShutdown()) { throw new IllegalStateException("The ScheduledExecutorService is shutdown"); } schedulePoll(); } @Override protected void doStop() throws Exception { if (future != null) { future.cancel(false); future = null; } // clear map if we stop map.clear(); } }
DefaultTimeoutMap
java
spring-projects__spring-boot
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/using/springbeansanddependencyinjection/multipleconstructors/MyAccountService.java
{ "start": 883, "end": 1340 }
class ____ implements AccountService { @SuppressWarnings("unused") private final RiskAssessor riskAssessor; @SuppressWarnings("unused") private final PrintStream out; @Autowired public MyAccountService(RiskAssessor riskAssessor) { this.riskAssessor = riskAssessor; this.out = System.out; } public MyAccountService(RiskAssessor riskAssessor, PrintStream out) { this.riskAssessor = riskAssessor; this.out = out; } // ... }
MyAccountService
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/layout/MarkerPatternSelector.java
{ "start": 2228, "end": 9795 }
class ____ implements org.apache.logging.log4j.core.util.Builder<MarkerPatternSelector> { @PluginElement("PatternMatch") private PatternMatch[] properties; @PluginBuilderAttribute("defaultPattern") private String defaultPattern; @PluginBuilderAttribute(value = "alwaysWriteExceptions") private boolean alwaysWriteExceptions = true; @PluginBuilderAttribute(value = "disableAnsi") private boolean disableAnsi; @PluginBuilderAttribute(value = "noConsoleNoAnsi") private boolean noConsoleNoAnsi; @PluginConfiguration private Configuration configuration; @Override public MarkerPatternSelector build() { if (defaultPattern == null) { defaultPattern = PatternLayout.DEFAULT_CONVERSION_PATTERN; } if (properties == null || properties.length == 0) { LOGGER.warn("No marker patterns were provided with PatternMatch"); return null; } return new MarkerPatternSelector( properties, defaultPattern, alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi, configuration); } public Builder setProperties(final PatternMatch[] properties) { this.properties = properties; return this; } public Builder setDefaultPattern(final String defaultPattern) { this.defaultPattern = defaultPattern; return this; } public Builder setAlwaysWriteExceptions(final boolean alwaysWriteExceptions) { this.alwaysWriteExceptions = alwaysWriteExceptions; return this; } public Builder setDisableAnsi(final boolean disableAnsi) { this.disableAnsi = disableAnsi; return this; } public Builder setNoConsoleNoAnsi(final boolean noConsoleNoAnsi) { this.noConsoleNoAnsi = noConsoleNoAnsi; return this; } public Builder setConfiguration(final Configuration configuration) { this.configuration = configuration; return this; } } private final Map<String, PatternFormatter[]> formatterMap = new HashMap<>(); private final Map<String, String> patternMap = new HashMap<>(); private final PatternFormatter[] defaultFormatters; private final String defaultPattern; private static Logger LOGGER = StatusLogger.getLogger(); private final boolean requiresLocation; /** * @deprecated Use {@link #newBuilder()} instead. This will be private in a future version. */ @Deprecated public MarkerPatternSelector( final PatternMatch[] properties, final String defaultPattern, final boolean alwaysWriteExceptions, final boolean noConsoleNoAnsi, final Configuration config) { this(properties, defaultPattern, alwaysWriteExceptions, false, noConsoleNoAnsi, config); } private MarkerPatternSelector( final PatternMatch[] properties, final String defaultPattern, final boolean alwaysWriteExceptions, final boolean disableAnsi, final boolean noConsoleNoAnsi, final Configuration config) { boolean needsLocation = false; final PatternParser parser = PatternLayout.createPatternParser(config); for (final PatternMatch property : properties) { try { final List<PatternFormatter> list = parser.parse(property.getPattern(), alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi); final PatternFormatter[] formatters = list.toArray(PatternFormatter.EMPTY_ARRAY); formatterMap.put(property.getKey(), formatters); for (int i = 0; !needsLocation && i < formatters.length; ++i) { needsLocation = formatters[i].requiresLocation(); } patternMap.put(property.getKey(), property.getPattern()); } catch (final RuntimeException ex) { throw new IllegalArgumentException("Cannot parse pattern '" + property.getPattern() + "'", ex); } } try { final List<PatternFormatter> list = parser.parse(defaultPattern, alwaysWriteExceptions, disableAnsi, noConsoleNoAnsi); defaultFormatters = list.toArray(PatternFormatter.EMPTY_ARRAY); this.defaultPattern = defaultPattern; for (int i = 0; !needsLocation && i < defaultFormatters.length; ++i) { needsLocation = defaultFormatters[i].requiresLocation(); } } catch (final RuntimeException ex) { throw new IllegalArgumentException("Cannot parse pattern '" + defaultPattern + "'", ex); } requiresLocation = needsLocation; } @Override public boolean requiresLocation() { return requiresLocation; } @Override public PatternFormatter[] getFormatters(final LogEvent event) { final Marker marker = event.getMarker(); if (marker == null) { return defaultFormatters; } for (final String key : formatterMap.keySet()) { if (marker.isInstanceOf(key)) { return formatterMap.get(key); } } return defaultFormatters; } /** * Creates a builder for a custom ScriptPatternSelector. * * @return a ScriptPatternSelector builder. */ @PluginBuilderFactory public static Builder newBuilder() { return new Builder(); } /** * Deprecated, use {@link #newBuilder()} instead. * @param properties PatternMatch configuration items * @param defaultPattern the default pattern * @param alwaysWriteExceptions To always write exceptions even if the pattern contains no exception conversions. * @param noConsoleNoAnsi Do not output ANSI escape codes if System.console() is null. * @param configuration the current configuration * @return a new MarkerPatternSelector. * @deprecated Use {@link #newBuilder()} instead. */ @Deprecated public static MarkerPatternSelector createSelector( final PatternMatch[] properties, final String defaultPattern, final boolean alwaysWriteExceptions, final boolean noConsoleNoAnsi, final Configuration configuration) { final Builder builder = newBuilder(); builder.setProperties(properties); builder.setDefaultPattern(defaultPattern); builder.setAlwaysWriteExceptions(alwaysWriteExceptions); builder.setNoConsoleNoAnsi(noConsoleNoAnsi); builder.setConfiguration(configuration); return builder.build(); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); boolean first = true; for (final Map.Entry<String, String> entry : patternMap.entrySet()) { if (!first) { sb.append(", "); } sb.append("key=\"") .append(entry.getKey()) .append("\", pattern=\"") .append(entry.getValue()) .append("\""); first = false; } if (!first) { sb.append(", "); } sb.append("default=\"").append(defaultPattern).append("\""); return sb.toString(); } }
Builder
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
{ "start": 3956, "end": 4183 }
class ____ parameterizable by the callback interfaces and * the {@link org.springframework.jdbc.support.SQLExceptionTranslator} * interface, there should be no need to subclass it. * * <p>All SQL operations performed by this
is
java
alibaba__fastjson
src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectZ1.java
{ "start": 94, "end": 1383 }
class ____ { private int a; private int b; private int c; private int d; private int e; private List<Integer> f; private List<Integer> g; private List<Integer> h; private List<ObjectZ1_A> i; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public int getD() { return d; } public void setD(int d) { this.d = d; } public int getE() { return e; } public void setE(int e) { this.e = e; } public List<Integer> getF() { return f; } public void setF(List<Integer> f) { this.f = f; } public List<Integer> getG() { return g; } public void setG(List<Integer> g) { this.g = g; } public List<Integer> getH() { return h; } public void setH(List<Integer> h) { this.h = h; } public List<ObjectZ1_A> getI() { return i; } public void setI(List<ObjectZ1_A> i) { this.i = i; } }
ObjectZ1
java
apache__camel
components/camel-optaplanner/src/main/java/org/apache/camel/component/optaplanner/OptaplannerSolutionEventListener.java
{ "start": 913, "end": 1044 }
interface ____ extends EventListener { void bestSolutionChanged(OptaplannerSolutionEvent event); }
OptaplannerSolutionEventListener
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectArtifactFactory.java
{ "start": 1067, "end": 1188 }
interface ____ for creation of MavenProject#dependencyArtifacts instances. * </p> * <strong>NOTE:</strong> This
responsible
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/ShutdownCallbackRegistry.java
{ "start": 1097, "end": 1297 }
interface ____ provided for customizing how to register shutdown hook * callbacks. Implementations may optionally implement {@link org.apache.logging.log4j.core.LifeCycle}. * * @since 2.1 */ public
is
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/sql/ast/SybaseASESqlAstTranslator.java
{ "start": 2430, "end": 18039 }
class ____<T extends JdbcOperation> extends AbstractSqlAstTranslator<T> { private static final String UNION_ALL = " union all "; public SybaseASESqlAstTranslator(SessionFactoryImplementor sessionFactory, Statement statement) { super( sessionFactory, statement ); } @Override protected void visitInsertStatementOnly(InsertSelectStatement statement) { if ( statement.getConflictClause() == null || statement.getConflictClause().isDoNothing() ) { // Render plain insert statement and possibly run into unique constraint violation super.visitInsertStatementOnly( statement ); } else { visitInsertStatementEmulateMerge( statement ); } } @Override protected void renderDeleteClause(DeleteStatement statement) { appendSql( "delete " ); final Stack<Clause> clauseStack = getClauseStack(); try { clauseStack.push( Clause.DELETE ); renderDmlTargetTableExpression( statement.getTargetTable() ); if ( statement.getFromClause().getRoots().isEmpty() ) { appendSql( " from " ); renderDmlTargetTableExpression( statement.getTargetTable() ); renderTableReferenceIdentificationVariable( statement.getTargetTable() ); } else { visitFromClause( statement.getFromClause() ); } } finally { clauseStack.pop(); } } @Override protected void renderFromClauseAfterUpdateSet(UpdateStatement statement) { if ( statement.getFromClause().getRoots().isEmpty() ) { appendSql( " from " ); renderDmlTargetTableExpression( statement.getTargetTable() ); renderTableReferenceIdentificationVariable( statement.getTargetTable() ); } else { visitFromClause( statement.getFromClause() ); } } @Override protected void visitConflictClause(ConflictClause conflictClause) { if ( conflictClause != null ) { if ( conflictClause.isDoUpdate() && conflictClause.getConstraintName() != null ) { throw new IllegalQueryOperationException( "Insert conflict 'do update' clause with constraint name is not supported" ); } } } // Sybase ASE does not allow CASE expressions where all result arms contain plain parameters. // At least one result arm must provide some type context for inference, // so we cast the first result arm if we encounter this condition @Override protected void visitAnsiCaseSearchedExpression( CaseSearchedExpression caseSearchedExpression, Consumer<Expression> resultRenderer) { if ( getParameterRenderingMode() == SqlAstNodeRenderingMode.DEFAULT && areAllResultsParameters( caseSearchedExpression ) ) { final List<CaseSearchedExpression.WhenFragment> whenFragments = caseSearchedExpression.getWhenFragments(); final Expression firstResult = whenFragments.get( 0 ).getResult(); super.visitAnsiCaseSearchedExpression( caseSearchedExpression, e -> { if ( e == firstResult ) { renderCasted( e ); } else { resultRenderer.accept( e ); } } ); } else { super.visitAnsiCaseSearchedExpression( caseSearchedExpression, resultRenderer ); } } @Override protected void visitAnsiCaseSimpleExpression( CaseSimpleExpression caseSimpleExpression, Consumer<Expression> resultRenderer) { if ( getParameterRenderingMode() == SqlAstNodeRenderingMode.DEFAULT && areAllResultsParameters( caseSimpleExpression ) ) { final List<CaseSimpleExpression.WhenFragment> whenFragments = caseSimpleExpression.getWhenFragments(); final Expression firstResult = whenFragments.get( 0 ).getResult(); super.visitAnsiCaseSimpleExpression( caseSimpleExpression, e -> { if ( e == firstResult ) { renderCasted( e ); } else { resultRenderer.accept( e ); } } ); } else { super.visitAnsiCaseSimpleExpression( caseSimpleExpression, resultRenderer ); } } @Override protected boolean renderNamedTableReference(NamedTableReference tableReference, LockMode lockMode) { final String tableExpression = tableReference.getTableExpression(); if ( tableReference instanceof UnionTableReference && lockMode != LockMode.NONE && tableExpression.charAt( 0 ) == '(' ) { // SQL Server requires to push down the lock hint to the actual table names int searchIndex = 0; int unionIndex; while ( ( unionIndex = tableExpression.indexOf( UNION_ALL, searchIndex ) ) != -1 ) { append( tableExpression, searchIndex, unionIndex ); renderLockHint( lockMode ); appendSql( UNION_ALL ); searchIndex = unionIndex + UNION_ALL.length(); } append( tableExpression, searchIndex, tableExpression.length() - 1 ); renderLockHint( lockMode ); appendSql( " )" ); registerAffectedTable( tableReference ); renderTableReferenceIdentificationVariable( tableReference ); } else { super.renderNamedTableReference( tableReference, lockMode ); renderLockHint( lockMode ); } // Just always return true because SQL Server doesn't support the FOR UPDATE clause return true; } private void renderLockHint(LockMode lockMode) { append( determineLockHint( lockMode, getEffectiveLockTimeout( lockMode ) ) ); } @Internal public static String determineLockHint(LockMode lockMode, int effectiveLockTimeout) { // NOTE: exposed for tests switch ( lockMode ) { case PESSIMISTIC_READ: case PESSIMISTIC_WRITE: case WRITE: { if ( effectiveLockTimeout == SKIP_LOCKED_MILLI ) { return " holdlock readpast"; } else { return " holdlock"; } } case UPGRADE_SKIPLOCKED: { return " holdlock readpast"; } case UPGRADE_NOWAIT: { return " holdlock"; } default: { return ""; } } } @Override protected LockStrategy determineLockingStrategy( QuerySpec querySpec, Locking.FollowOn followOnStrategy) { // No need for follow on locking return LockStrategy.CLAUSE; } @Override protected void visitSqlSelections(SelectClause selectClause) { renderTopClause( (QuerySpec) getQueryPartStack().getCurrent(), true, false ); super.visitSqlSelections( selectClause ); } @Override protected void renderFetchPlusOffsetExpression( Expression fetchClauseExpression, Expression offsetClauseExpression, int offset) { renderFetchPlusOffsetExpressionAsLiteral( fetchClauseExpression, offsetClauseExpression, offset ); } @Override public void visitQueryGroup(QueryGroup queryGroup) { if ( queryGroup.hasSortSpecifications() || queryGroup.hasOffsetOrFetchClause() ) { appendSql( "select " ); renderTopClause( queryGroup.getOffsetClauseExpression(), queryGroup.getFetchClauseExpression(), queryGroup.getFetchClauseType(), true, false ); appendSql( "* from (" ); renderQueryGroup( queryGroup, false ); appendSql( ") grp_(c0" ); // Sybase doesn't have implicit names for non-column select expressions, so we need to assign names final int itemCount = queryGroup.getFirstQuerySpec().getSelectClause().getSqlSelections().size(); for (int i = 1; i < itemCount; i++) { appendSql( ",c" ); appendSql( i ); } appendSql( ')' ); visitOrderBy( queryGroup.getSortSpecifications() ); } else { super.visitQueryGroup( queryGroup ); } } @Override protected void visitValuesList(List<Values> valuesList) { visitValuesListEmulateSelectUnion( valuesList ); } @Override public void visitValuesTableReference(ValuesTableReference tableReference) { append( '(' ); visitValuesListEmulateSelectUnion( tableReference.getValuesList() ); append( ')' ); renderDerivedTableReferenceIdentificationVariable( tableReference ); } @Override public void visitOffsetFetchClause(QueryPart queryPart) { assertRowsOnlyFetchClauseType( queryPart ); if ( !queryPart.isRoot() && queryPart.hasOffsetOrFetchClause() ) { if ( queryPart.getFetchClauseExpression() != null && queryPart.getOffsetClauseExpression() != null ) { throw new IllegalArgumentException( "Can't emulate offset fetch clause in subquery" ); } } } @Override protected void renderFetchExpression(Expression fetchExpression) { if ( supportsParameterOffsetFetchExpression() ) { super.renderFetchExpression( fetchExpression ); } else { renderExpressionAsLiteral( fetchExpression, getJdbcParameterBindings() ); } } @Override protected void renderOffsetExpression(Expression offsetExpression) { if ( supportsParameterOffsetFetchExpression() ) { super.renderOffsetExpression( offsetExpression ); } else { renderExpressionAsLiteral( offsetExpression, getJdbcParameterBindings() ); } } @Override protected void renderComparison(Expression lhs, ComparisonOperator operator, Expression rhs) { // In Sybase ASE, XMLTYPE is not "comparable", so we have to cast the two parts to varchar for this purpose final boolean isLob = isLob( lhs.getExpressionType() ); final boolean ansiNullOn = ((SybaseASEDialect) getDialect()).isAnsiNullOn(); if ( isLob ) { switch ( operator ) { case DISTINCT_FROM: if ( ansiNullOn ) { appendSql( "case when " ); lhs.accept( this ); appendSql( " like " ); rhs.accept( this ); appendSql( " or " ); lhs.accept( this ); appendSql( " is null and " ); rhs.accept( this ); appendSql( " is null then 0 else 1 end=1" ); } else { lhs.accept( this ); appendSql( " not like " ); rhs.accept( this ); appendSql( " and (" ); lhs.accept( this ); appendSql( " is not null or " ); rhs.accept( this ); appendSql( " is not null)" ); } return; case NOT_DISTINCT_FROM: if ( ansiNullOn ) { appendSql( "case when " ); lhs.accept( this ); appendSql( " like " ); rhs.accept( this ); appendSql( " or " ); lhs.accept( this ); appendSql( " is null and " ); rhs.accept( this ); appendSql( " is null then 0 else 1 end=0" ); } else { lhs.accept( this ); appendSql( " like " ); rhs.accept( this ); appendSql( " or " ); lhs.accept( this ); appendSql( " is null and " ); rhs.accept( this ); appendSql( " is null" ); } return; case EQUAL: lhs.accept( this ); appendSql( " like " ); rhs.accept( this ); return; case NOT_EQUAL: lhs.accept( this ); appendSql( " not like " ); rhs.accept( this ); if ( !ansiNullOn ) { appendSql( " and " ); lhs.accept( this ); appendSql( " is not null and " ); rhs.accept( this ); appendSql( " is not null" ); } return; default: // Fall through break; } } // I think intersect is only supported in 16.0 SP3 if ( ansiNullOn ) { if ( getDialect().supportsDistinctFromPredicate() ) { renderComparisonEmulateIntersect( lhs, operator, rhs ); } else { renderComparisonEmulateCase( lhs, operator, rhs ); } } else { // The ansinull setting only matters if using a parameter or literal and the eq operator according to the docs // http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc32300.1570/html/sqlug/sqlug89.htm boolean lhsAffectedByAnsiNullOff = lhs instanceof Literal || isParameter( lhs ); boolean rhsAffectedByAnsiNullOff = rhs instanceof Literal || isParameter( rhs ); if ( lhsAffectedByAnsiNullOff || rhsAffectedByAnsiNullOff ) { lhs.accept( this ); switch ( operator ) { case DISTINCT_FROM: // Since this is the ansinull=off case, this comparison is enough appendSql( "<>" ); break; case NOT_DISTINCT_FROM: // Since this is the ansinull=off case, this comparison is enough appendSql( '=' ); break; default: appendSql( operator.sqlText() ); break; } rhs.accept( this ); if ( operator == ComparisonOperator.EQUAL || operator == ComparisonOperator.NOT_EQUAL ) { appendSql( " and " ); lhs.accept( this ); appendSql( " is not null and " ); rhs.accept( this ); appendSql( " is not null" ); } } else { if ( getDialect().supportsDistinctFromPredicate() ) { renderComparisonEmulateIntersect( lhs, operator, rhs ); } else { renderComparisonEmulateCase( lhs, operator, rhs ); } } } } public static boolean isLob(JdbcMappingContainer expressionType) { return expressionType != null && expressionType.getJdbcTypeCount() == 1 && switch ( expressionType.getSingleJdbcMapping().getJdbcType().getDdlTypeCode() ) { case SqlTypes.LONG32NVARCHAR, SqlTypes.LONG32VARCHAR, SqlTypes.LONGNVARCHAR, SqlTypes.LONGVARCHAR, SqlTypes.LONG32VARBINARY, SqlTypes.LONGVARBINARY, SqlTypes.CLOB, SqlTypes.NCLOB, SqlTypes.BLOB -> true; default -> false; }; } @Override protected void renderSelectTupleComparison( List<SqlSelection> lhsExpressions, SqlTuple tuple, ComparisonOperator operator) { emulateSelectTupleComparison( lhsExpressions, tuple.getExpressions(), operator, true ); } @Override protected void renderPartitionItem(Expression expression) { if ( expression instanceof Literal ) { // Note that this depends on the SqmToSqlAstConverter to add a dummy table group appendSql( "dummy_.x" ); } else if ( expression instanceof Summarization ) { // This could theoretically be emulated by rendering all grouping variations of the query and // connect them via union all but that's probably pretty inefficient and would have to happen // on the query spec level throw new UnsupportedOperationException( "Summarization is not supported by DBMS" ); } else { expression.accept( this ); } } @Override public void visitBinaryArithmeticExpression(BinaryArithmeticExpression arithmeticExpression) { appendSql( OPEN_PARENTHESIS ); visitArithmeticOperand( arithmeticExpression.getLeftHandOperand() ); appendSql( arithmeticExpression.getOperator().getOperatorSqlTextString() ); visitArithmeticOperand( arithmeticExpression.getRightHandOperand() ); appendSql( CLOSE_PARENTHESIS ); } @Override protected String determineColumnReferenceQualifier(ColumnReference columnReference) { final DmlTargetColumnQualifierSupport qualifierSupport = getDialect().getDmlTargetColumnQualifierSupport(); final MutationStatement currentDmlStatement; final String dmlAlias; if ( qualifierSupport == DmlTargetColumnQualifierSupport.TABLE_ALIAS || ( currentDmlStatement = getCurrentDmlStatement() ) == null || ( dmlAlias = currentDmlStatement.getTargetTable().getIdentificationVariable() ) == null || !dmlAlias.equals( columnReference.getQualifier() ) ) { return columnReference.getQualifier(); } // Sybase needs a table name prefix // but not if this is a restricted union table reference subquery final QuerySpec currentQuerySpec = (QuerySpec) getQueryPartStack().getCurrent(); final List<TableGroup> roots; if ( currentQuerySpec != null && !currentQuerySpec.isRoot() && (roots = currentQuerySpec.getFromClause().getRoots()).size() == 1 && roots.get( 0 ).getPrimaryTableReference() instanceof UnionTableReference ) { return columnReference.getQualifier(); } else if ( columnReference.isColumnExpressionFormula() ) { // For formulas, we have to replace the qualifier as the alias was already rendered into the formula // This is fine for now as this is only temporary anyway until we render aliases for table references return null; } else { return getCurrentDmlStatement().getTargetTable().getTableExpression(); } } @Override protected boolean needsRowsToSkip() { return true; } private boolean supportsParameterOffsetFetchExpression() { return false; } }
SybaseASESqlAstTranslator
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1247/DtoIn.java
{ "start": 232, "end": 537 }
class ____ { private final String data; private final String data2; public DtoIn(String data, String data2) { this.data = data; this.data2 = data2; } public String getData() { return data; } public String getData2() { return data2; } }
DtoIn
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/junit/jupiter/BDDSoftAssertionsExtensionIntegrationTest.java
{ "start": 4091, "end": 4253 }
class ____ extends AbstractSoftAssertionsExample { } } @TestInstance(PER_CLASS) @Disabled("Executed via the JUnit Platform Test Kit") static
InnerExample
java
grpc__grpc-java
services/src/main/java/io/grpc/protobuf/services/BinlogHelper.java
{ "start": 3207, "end": 3613 }
class ____. // See StatusProto.java static final Metadata.Key<byte[]> STATUS_DETAILS_KEY = Metadata.Key.of( "grpc-status-details-bin", Metadata.BINARY_BYTE_MARSHALLER); @VisibleForTesting final SinkWriter writer; @VisibleForTesting BinlogHelper(SinkWriter writer) { this.writer = writer; } // TODO(zpencer): move proto related static helpers into this
treatment
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/BlockingFlowableNext.java
{ "start": 1736, "end": 4604 }
class ____<T> implements Iterator<T> { private final NextSubscriber<T> subscriber; private final Publisher<? extends T> items; private T next; private boolean hasNext = true; private boolean isNextConsumed = true; private Throwable error; private boolean started; NextIterator(Publisher<? extends T> items, NextSubscriber<T> subscriber) { this.items = items; this.subscriber = subscriber; } @Override public boolean hasNext() { if (error != null) { // If any error has already been thrown, throw it again. throw ExceptionHelper.wrapOrThrow(error); } // Since an iterator should not be used in different thread, // so we do not need any synchronization. if (!hasNext) { // the iterator has reached the end. return false; } // next has not been used yet. return !isNextConsumed || moveToNext(); } private boolean moveToNext() { try { if (!started) { started = true; // if not started, start now subscriber.setWaiting(); Flowable.<T>fromPublisher(items) .materialize().subscribe(subscriber); } Notification<T> nextNotification = subscriber.takeNext(); if (nextNotification.isOnNext()) { isNextConsumed = false; next = nextNotification.getValue(); return true; } // If an observable is completed or fails, // hasNext() always return false. hasNext = false; if (nextNotification.isOnComplete()) { return false; } error = nextNotification.getError(); throw ExceptionHelper.wrapOrThrow(error); } catch (InterruptedException e) { subscriber.dispose(); error = e; throw ExceptionHelper.wrapOrThrow(e); } } @Override public T next() { if (error != null) { // If any error has already been thrown, throw it again. throw ExceptionHelper.wrapOrThrow(error); } if (hasNext()) { isNextConsumed = true; return next; } else { throw new NoSuchElementException("No more elements"); } } @Override public void remove() { throw new UnsupportedOperationException("Read only iterator"); } } static final
NextIterator
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/dataformat/ForyDataFormat.java
{ "start": 1468, "end": 4431 }
class ____ extends DataFormatDefinition { @XmlTransient private Class<?> unmarshalType; @XmlAttribute(name = "unmarshalType") @Metadata(description = "Class of the java type to use when unmarshalling") private String unmarshalTypeName; @XmlAttribute @Metadata(label = "advanced", description = "Whether to require register classes", defaultValue = "true", javaType = "java.lang.Boolean") private String requireClassRegistration; @XmlAttribute @Metadata(label = "advanced", description = "Whether to use the threadsafe Fory", defaultValue = "true", javaType = "java.lang.Boolean") private String threadSafe; @XmlAttribute @Metadata(label = "advanced", description = "Whether to auto-discover Fory from the registry", defaultValue = "true", javaType = "java.lang.Boolean") private String allowAutoWiredFory; public ForyDataFormat() { super("fory"); } public ForyDataFormat(ForyDataFormat source) { super(source); this.unmarshalType = source.unmarshalType; this.unmarshalTypeName = source.unmarshalTypeName; this.requireClassRegistration = source.requireClassRegistration; this.threadSafe = source.threadSafe; this.allowAutoWiredFory = source.allowAutoWiredFory; } private ForyDataFormat(Builder builder) { this.unmarshalType = builder.unmarshalType; this.unmarshalTypeName = builder.unmarshalTypeName; this.requireClassRegistration = builder.requireClassRegistration; this.threadSafe = builder.threadSafe; this.allowAutoWiredFory = builder.allowAutoWiredFory; } @Override public ForyDataFormat copyDefinition() { return new ForyDataFormat(this); } public Class<?> getUnmarshalType() { return unmarshalType; } public void setUnmarshalType(final Class<?> unmarshalType) { this.unmarshalType = unmarshalType; } public String getUnmarshalTypeName() { return unmarshalTypeName; } public void setUnmarshalTypeName(final String unmarshalTypeName) { this.unmarshalTypeName = unmarshalTypeName; } public String getRequireClassRegistration() { return requireClassRegistration; } public void setRequireClassRegistration(String requireClassRegistration) { this.requireClassRegistration = requireClassRegistration; } public String getThreadSafe() { return threadSafe; } public void setThreadSafe(String threadSafe) { this.threadSafe = threadSafe; } public String getAllowAutoWiredFory() { return allowAutoWiredFory; } public void setAllowAutoWiredFory(String allowAutoWiredFory) { this.allowAutoWiredFory = allowAutoWiredFory; } /** * {@code Builder} is a specific builder for {@link ForyDataFormat}. */ @XmlTransient public static
ForyDataFormat
java
elastic__elasticsearch
x-pack/plugin/repositories-metering-api/src/main/java/org/elasticsearch/xpack/repositories/metering/rest/RestClearRepositoriesMeteringArchiveAction.java
{ "start": 969, "end": 1988 }
class ____ extends BaseRestHandler { @Override public String getName() { return "clear_repositories_metrics_archive_action"; } @Override public List<Route> routes() { return List.of(new Route(DELETE, "/_nodes/{nodeId}/_repositories_metering/{maxVersionToClear}")); } @Override protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) { String[] nodesIds = Strings.splitStringByCommaToArray(request.param("nodeId")); long maxVersionToClear = request.paramAsLong("maxVersionToClear", -1); ClearRepositoriesMeteringArchiveRequest clearArchivesRequest = new ClearRepositoriesMeteringArchiveRequest( maxVersionToClear, nodesIds ); return channel -> client.execute( ClearRepositoriesMeteringArchiveAction.INSTANCE, clearArchivesRequest, new RestActions.NodesResponseRestListener<>(channel) ); } }
RestClearRepositoriesMeteringArchiveAction
java
dropwizard__dropwizard
dropwizard-client/src/test/java/io/dropwizard/client/JerseyClientBuilderTest.java
{ "start": 3500, "end": 15662 }
class ____ { private final MetricRegistry metricRegistry = new MetricRegistry(); private final JerseyClientBuilder builder = new JerseyClientBuilder(metricRegistry); private final LifecycleEnvironment lifecycleEnvironment = spy(new LifecycleEnvironment(metricRegistry)); private final Environment environment = mock(); private final ExecutorService executorService = Executors.newSingleThreadExecutor(); private final ObjectMapper objectMapper = mock(); private final Validator validator = Validators.newValidator(); private final HttpClientBuilder apacheHttpClientBuilder = mock(); @BeforeEach void setUp() { when(environment.lifecycle()).thenReturn(lifecycleEnvironment); when(environment.getObjectMapper()).thenReturn(objectMapper); when(environment.getValidator()).thenReturn(validator); builder.setApacheHttpClientBuilder(apacheHttpClientBuilder); } @AfterEach void tearDown() { executorService.shutdown(); } @Test void throwsAnExceptionWithoutAnEnvironmentOrAThreadPoolAndObjectMapper() { assertThatIllegalStateException() .isThrownBy(() -> builder.build("test")) .withMessage("Must have either an environment or both an executor service and an object mapper"); } @Test void throwsAnExceptionWithoutAnEnvironmentAndOnlyObjectMapper() { JerseyClientBuilder configuredBuilder = builder.using(objectMapper); assertThatIllegalStateException() .isThrownBy(() -> configuredBuilder.build("test")) .withMessage("Must have either an environment or both an executor service and an object mapper"); } @Test void throwsAnExceptionWithoutAnEnvironmentAndOnlyAThreadPool() { JerseyClientBuilder configuredBuilder = builder.using(executorService); assertThatIllegalStateException() .isThrownBy(() -> configuredBuilder.build("test")) .withMessage("Must have either an environment or both an executor service and an object mapper"); } @Test void includesJerseyProperties() { final Client client = builder.withProperty("poop", true) .using(executorService, objectMapper) .build("test"); assertThat(client.getConfiguration().getProperty("poop")).isEqualTo(Boolean.TRUE); } @Test void includesJerseyProviderSingletons() { final FakeMessageBodyReader provider = new FakeMessageBodyReader(); final Client client = builder.withProvider(provider) .using(executorService, objectMapper) .build("test"); assertThat(client.getConfiguration().isRegistered(provider)).isTrue(); } @Test void includesJerseyProviderClasses() { @SuppressWarnings("unused") final Client client = builder.withProvider(FakeMessageBodyReader.class) .using(executorService, objectMapper) .build("test"); assertThat(client.getConfiguration().isRegistered(FakeMessageBodyReader.class)).isTrue(); } @Test void createsAnRxEnabledClient() { final Client client = builder.using(executorService, objectMapper) .buildRx("test", RxFlowableInvokerProvider.class); for (Object o : client.getConfiguration().getInstances()) { if (o instanceof DropwizardExecutorProvider) { final DropwizardExecutorProvider provider = (DropwizardExecutorProvider) o; assertThat(provider.getExecutorService()).isSameAs(executorService); } } } @Test void usesTheGivenThreadPool() { final Client client = builder.using(executorService, objectMapper).build("test"); for (Object o : client.getConfiguration().getInstances()) { if (o instanceof DropwizardExecutorProvider) { final DropwizardExecutorProvider provider = (DropwizardExecutorProvider) o; assertThat(provider.getExecutorService()).isSameAs(executorService); } } } @Test void usesTheGivenThreadPoolAndEnvironmentsObjectMapper() { final Client client = builder.using(environment).using(executorService).build("test"); for (Object o : client.getConfiguration().getInstances()) { if (o instanceof DropwizardExecutorProvider) { final DropwizardExecutorProvider provider = (DropwizardExecutorProvider) o; assertThat(provider.getExecutorService()).isSameAs(executorService); } } } @Test void createsNewConnectorProvider() { final JerseyClient clientA = (JerseyClient) builder.using(executorService, objectMapper).build("testA"); final JerseyClient clientB = (JerseyClient) builder.build("testB"); assertThat(clientA.getConfiguration().getConnectorProvider()) .isNotSameAs(clientB.getConfiguration().getConnectorProvider()); } @Test void usesSameConnectorProvider() { final JerseyClient clientA = (JerseyClient) builder.using(executorService, objectMapper) .using(mock(ConnectorProvider.class)) .build("testA"); final JerseyClient clientB = (JerseyClient) builder.build("testB"); assertThat(clientA.getConfiguration().getConnectorProvider()) .isSameAs(clientB.getConfiguration().getConnectorProvider()); } @Test void addBidirectionalGzipSupportIfEnabled() { final JerseyClientConfiguration configuration = new JerseyClientConfiguration(); configuration.setGzipEnabled(true); final Client client = builder.using(configuration) .using(executorService, objectMapper).build("test"); assertThat(client.getConfiguration().getInstances()) .anyMatch(element -> element instanceof GZipDecoder); assertThat(client.getConfiguration().getInstances()) .anyMatch(element -> element instanceof ConfiguredGZipEncoder); verify(apacheHttpClientBuilder, never()).disableContentCompression(true); } @Test void disablesGzipSupportIfDisabled() { final JerseyClientConfiguration configuration = new JerseyClientConfiguration(); configuration.setGzipEnabled(false); final Client client = builder.using(configuration) .using(executorService, objectMapper).build("test"); assertThat(client.getConfiguration().getInstances()) .noneMatch(element -> element instanceof GZipDecoder); assertThat(client.getConfiguration().getInstances()) .noneMatch(element -> element instanceof ConfiguredGZipEncoder); verify(apacheHttpClientBuilder).disableContentCompression(true); } @Test @SuppressWarnings("unchecked") void usesAnExecutorServiceFromTheEnvironment() { final JerseyClientConfiguration configuration = new JerseyClientConfiguration(); configuration.setMinThreads(7); configuration.setMaxThreads(532); configuration.setWorkQueueSize(16); final ExecutorServiceBuilder executorServiceBuilderMock = mock(); when(lifecycleEnvironment.executorService("jersey-client-test-%d")).thenReturn(executorServiceBuilderMock); when(executorServiceBuilderMock.minThreads(7)).thenReturn(executorServiceBuilderMock); when(executorServiceBuilderMock.maxThreads(532)).thenReturn(executorServiceBuilderMock); when(executorServiceBuilderMock.workQueue(any(ArrayBlockingQueue.class))) .thenReturn(executorServiceBuilderMock); when(executorServiceBuilderMock.build()).thenReturn(mock()); builder.using(configuration).using(environment).build("test"); verify(executorServiceBuilderMock).workQueue(assertArg(queue -> assertThat(queue.remainingCapacity()).isEqualTo(16))); } @Test void usesACustomHttpClientMetricNameStrategy() { final HttpClientMetricNameStrategy customStrategy = HttpClientMetricNameStrategies.HOST_AND_METHOD; builder.using(customStrategy); verify(apacheHttpClientBuilder).using(customStrategy); } @Test void usesACustomHttpRequestRetryHandler() { final HttpRequestRetryStrategy customRetryHandler = new DefaultHttpRequestRetryStrategy(2, TimeValue.ofSeconds(1)); builder.using(customRetryHandler); verify(apacheHttpClientBuilder).using(customRetryHandler); } @Test void usesACustomDnsResolver() { final DnsResolver customDnsResolver = new SystemDefaultDnsResolver(); builder.using(customDnsResolver); verify(apacheHttpClientBuilder).using(customDnsResolver); } @Test void usesACustomHostnameVerifier() { final HostnameVerifier customHostnameVerifier = new NoopHostnameVerifier(); builder.using(customHostnameVerifier); verify(apacheHttpClientBuilder).using(customHostnameVerifier); } @Test void usesACustomConnectionFactoryRegistry() throws Exception { final SSLContext ctx = SSLContext.getInstance("TLSv1.2"); ctx.init(null, new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] xcs, String string) { } @Override public void checkServerTrusted(X509Certificate[] xcs, String string) { } @Override @Nullable public X509Certificate @Nullable [] getAcceptedIssuers() { return null; } } }, null); final Registry<ConnectionSocketFactory> customRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", new SSLConnectionSocketFactory(ctx, new NoopHostnameVerifier())) .build(); builder.using(customRegistry); verify(apacheHttpClientBuilder).using(customRegistry); } @Test void usesACustomEnvironmentName() { final String userAgent = "Dropwizard Jersey Client"; builder.name(userAgent); verify(apacheHttpClientBuilder).name(userAgent); } @Test void usesACustomHttpRoutePlanner() { final HttpRoutePlanner customHttpRoutePlanner = new SystemDefaultRoutePlanner(new ProxySelector() { @Override public List<Proxy> select(URI uri) { return Collections.singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.53.12", 8080))); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { } }); builder.using(customHttpRoutePlanner); verify(apacheHttpClientBuilder).using(customHttpRoutePlanner); } @Test void usesACustomCredentialsProvider() { CredentialsStore customCredentialsProvider = new SystemDefaultCredentialsProvider(); builder.using(customCredentialsProvider); verify(apacheHttpClientBuilder).using(customCredentialsProvider); } @Test void apacheConnectorCanOverridden() { assertThat(new JerseyClientBuilder(new MetricRegistry()) { @Override protected DropwizardApacheConnector createDropwizardApacheConnector(ConfiguredCloseableHttpClient configuredClient) { return new DropwizardApacheConnector(configuredClient.getClient(), configuredClient.getDefaultRequestConfig(), true) { @Override protected HttpEntity getHttpEntity(ClientRequest jerseyRequest) { return new GzipCompressingEntity(new ByteArrayEntity((byte[]) jerseyRequest.getEntity(), ContentType.DEFAULT_BINARY)); } }; } }.using(environment).build("test")).isNotNull(); } @Provider @Consumes(MediaType.APPLICATION_SVG_XML) public static
JerseyClientBuilderTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/TruthIncompatibleTypeTest.java
{ "start": 17108, "end": 17795 }
class ____ { void test(TestFieldProtoMessage a, TestProtoMessage b) { // BUG: Diagnostic contains: assertThat(a).ignoringFields(1).isNotEqualTo(b); } } """) .doTest(); } @Test public void protoTruth_contains() { compilationHelper .addSourceLines( "Test.java", """ import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat; import com.google.errorprone.bugpatterns.proto.ProtoTest.TestFieldProtoMessage; import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage; final
Test
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/mapperconfig/FooEntity.java
{ "start": 236, "end": 474 }
class ____ { private String createdBy; public FooEntity() { } public FooEntity( String createdBy ) { this.createdBy = createdBy; } public String getCreatedBy() { return createdBy; } }
FooEntity
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/join/AsyncLookupJoinHarnessTest.java
{ "start": 15202, "end": 15331 }
enum ____ { INNER_JOIN, LEFT_JOIN } /** Whether there is a filter on temporal table. */ private
JoinType
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SnmpEndpointBuilderFactory.java
{ "start": 73204, "end": 73511 }
class ____ extends AbstractEndpointBuilder implements SnmpEndpointBuilder, AdvancedSnmpEndpointBuilder { public SnmpEndpointBuilderImpl(String path) { super(componentName, path); } } return new SnmpEndpointBuilderImpl(path); } }
SnmpEndpointBuilderImpl
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java
{ "start": 11223, "end": 11262 }
class ____ or name"); } static
reference
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/network/EchoServer.java
{ "start": 1503, "end": 5912 }
class ____ extends Thread { // JDK has a bug where sockets may get blocked on a read operation if they are closed during a TLS handshake. // While rare, this would cause the CI pipeline to hang. We set a reasonably high SO_TIMEOUT to avoid blocking reads // indefinitely. // The JDK bug is similar to JDK-8274524, but it affects the else branch of SSLSocketImpl::bruteForceCloseInput // which wasn't fixed in it. Please refer to the comments in KAFKA-16219 for more information. private static final int SO_TIMEOUT_MS = 30_000; public final int port; private final ServerSocket serverSocket; private final List<Thread> threads; private final List<Socket> sockets; private volatile boolean closing = false; private final SslFactory sslFactory; private final AtomicBoolean renegotiate = new AtomicBoolean(); public EchoServer(SecurityProtocol securityProtocol, Map<String, ?> configs) throws Exception { switch (securityProtocol) { case SSL: this.sslFactory = new SslFactory(ConnectionMode.SERVER); this.sslFactory.configure(configs); SSLContext sslContext = ((DefaultSslEngineFactory) this.sslFactory.sslEngineFactory()).sslContext(); this.serverSocket = sslContext.getServerSocketFactory().createServerSocket(0); this.serverSocket.setSoTimeout(SO_TIMEOUT_MS); break; case PLAINTEXT: this.serverSocket = new ServerSocket(0); this.sslFactory = null; break; default: throw new IllegalArgumentException("Unsupported securityProtocol " + securityProtocol); } this.port = this.serverSocket.getLocalPort(); this.threads = Collections.synchronizedList(new ArrayList<>()); this.sockets = Collections.synchronizedList(new ArrayList<>()); } public void renegotiate() { renegotiate.set(true); } @Override public void run() { try { while (!closing) { final Socket socket = serverSocket.accept(); if (sslFactory != null) { socket.setSoTimeout(SO_TIMEOUT_MS); } synchronized (sockets) { if (closing) { socket.close(); break; } sockets.add(socket); Thread thread = new Thread(() -> { try { DataInputStream input = new DataInputStream(socket.getInputStream()); DataOutputStream output = new DataOutputStream(socket.getOutputStream()); while (socket.isConnected() && !socket.isClosed()) { int size = input.readInt(); if (renegotiate.get()) { renegotiate.set(false); ((SSLSocket) socket).startHandshake(); } byte[] bytes = new byte[size]; input.readFully(bytes); output.writeInt(size); output.write(bytes); output.flush(); } } catch (IOException e) { // ignore } finally { try { socket.close(); } catch (IOException e) { // ignore } } }); thread.start(); threads.add(thread); } } } catch (IOException e) { // ignore } } public void closeConnections() throws IOException { synchronized (sockets) { for (Socket socket : sockets) socket.close(); } } public void close() throws IOException, InterruptedException { closing = true; this.serverSocket.close(); closeConnections(); for (Thread t : threads) t.join(); join(); } }
EchoServer
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/src/assigners/LocalityAwareSplitAssigner.java
{ "start": 8101, "end": 9481 }
class ____ { private final FileSourceSplit split; private final String[] normalizedHosts; private int localCount; public SplitWithInfo(FileSourceSplit split) { this.split = split; this.normalizedHosts = normalizeHostNames(split.hostnames()); this.localCount = 0; } public void incrementLocalCount() { this.localCount++; } public int getLocalCount() { return localCount; } public FileSourceSplit getSplit() { return split; } public String[] getNormalizedHosts() { return normalizedHosts; } } // ------------------------------------------------------------------------ /** * Holds a list of LocatableInputSplits and returns the split with the lowest local count. The * rational is that splits which are local on few hosts should be preferred over others which * have more degrees of freedom for local assignment. * * <p>Internally, the splits are stored in a linked list. Sorting the list is not a good * solution, as local counts are updated whenever a previously unseen host requests a split. * Instead, we track the minimum local count and iteratively look for splits with that minimum * count. */ private static
SplitWithInfo
java
google__dagger
javatests/dagger/internal/codegen/ComponentValidationTest.java
{ "start": 3623, "end": 4353 }
interface ____ {", " @Provides", " static String provideString() { return \"test\"; }", "}"); CompilerTests.daggerCompiler(componentFile, moduleFile) .compile( subject -> { subject.hasErrorCount(1); subject.hasErrorContaining( "The method test.TestComponent.create() conflicts with a method"); }); } @Test public void subcomponentMethodNameBuilder_succeeds() { Source componentFile = CompilerTests.javaSource( "test.TestComponent", "package test;", "", "import dagger.Component;", "", "@Component", "
TestModule
java
google__guice
core/test/com/google/inject/RequestInjectionTest.java
{ "start": 8509, "end": 8698 }
class ____<T> { static int injectedCount = 0; T thing; @Inject void register(T thing) { this.thing = thing; injectedCount++; } } private static
NeedsThing
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocolPB/DatanodeProtocolClientSideTranslatorPB.java
{ "start": 4608, "end": 13924 }
class ____ implements ProtocolMetaInterface, DatanodeProtocol, Closeable { /** RpcController is not used and hence is set to null */ private final DatanodeProtocolPB rpcProxy; private static final VersionRequestProto VOID_VERSION_REQUEST = VersionRequestProto.newBuilder().build(); private final static RpcController NULL_CONTROLLER = null; @VisibleForTesting public DatanodeProtocolClientSideTranslatorPB(DatanodeProtocolPB rpcProxy) { this.rpcProxy = rpcProxy; } public DatanodeProtocolClientSideTranslatorPB(InetSocketAddress nameNodeAddr, Configuration conf) throws IOException { RPC.setProtocolEngine(conf, DatanodeProtocolPB.class, ProtobufRpcEngine2.class); UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); rpcProxy = createNamenode(nameNodeAddr, conf, ugi); } private static DatanodeProtocolPB createNamenode( InetSocketAddress nameNodeAddr, Configuration conf, UserGroupInformation ugi) throws IOException { return RPC.getProxy(DatanodeProtocolPB.class, RPC.getProtocolVersion(DatanodeProtocolPB.class), nameNodeAddr, ugi, conf, NetUtils.getSocketFactory(conf, DatanodeProtocolPB.class)); } @Override public void close() throws IOException { RPC.stopProxy(rpcProxy); } @Override public DatanodeRegistration registerDatanode(DatanodeRegistration registration ) throws IOException { RegisterDatanodeRequestProto.Builder builder = RegisterDatanodeRequestProto .newBuilder().setRegistration(PBHelper.convert(registration)); RegisterDatanodeResponseProto resp; resp = ipc(() -> rpcProxy.registerDatanode(NULL_CONTROLLER, builder.build())); return PBHelper.convert(resp.getRegistration()); } @Override public HeartbeatResponse sendHeartbeat(DatanodeRegistration registration, StorageReport[] reports, long cacheCapacity, long cacheUsed, int xmitsInProgress, int xceiverCount, int failedVolumes, VolumeFailureSummary volumeFailureSummary, boolean requestFullBlockReportLease, @Nonnull SlowPeerReports slowPeers, @Nonnull SlowDiskReports slowDisks) throws IOException { HeartbeatRequestProto.Builder builder = HeartbeatRequestProto.newBuilder() .setRegistration(PBHelper.convert(registration)) .setXmitsInProgress(xmitsInProgress).setXceiverCount(xceiverCount) .setFailedVolumes(failedVolumes) .setRequestFullBlockReportLease(requestFullBlockReportLease); builder.addAllReports(PBHelperClient.convertStorageReports(reports)); if (cacheCapacity != 0) { builder.setCacheCapacity(cacheCapacity); } if (cacheUsed != 0) { builder.setCacheUsed(cacheUsed); } if (volumeFailureSummary != null) { builder.setVolumeFailureSummary(PBHelper.convertVolumeFailureSummary( volumeFailureSummary)); } if (slowPeers.haveSlowPeers()) { builder.addAllSlowPeers(PBHelper.convertSlowPeerInfo(slowPeers)); } if (slowDisks.haveSlowDisks()) { builder.addAllSlowDisks(PBHelper.convertSlowDiskInfo(slowDisks)); } HeartbeatResponseProto resp; resp = ipc(() -> rpcProxy.sendHeartbeat(NULL_CONTROLLER, builder.build())); DatanodeCommand[] cmds = new DatanodeCommand[resp.getCmdsList().size()]; int index = 0; for (DatanodeCommandProto p : resp.getCmdsList()) { cmds[index] = PBHelper.convert(p); index++; } RollingUpgradeStatus rollingUpdateStatus = null; // Use v2 semantics if available. if (resp.hasRollingUpgradeStatusV2()) { rollingUpdateStatus = PBHelperClient.convert(resp.getRollingUpgradeStatusV2()); } else if (resp.hasRollingUpgradeStatus()) { rollingUpdateStatus = PBHelperClient.convert(resp.getRollingUpgradeStatus()); } return new HeartbeatResponse(cmds, PBHelper.convert(resp.getHaStatus()), rollingUpdateStatus, resp.getFullBlockReportLeaseId(), resp.getIsSlownode()); } @Override public DatanodeCommand blockReport(DatanodeRegistration registration, String poolId, StorageBlockReport[] reports, BlockReportContext context) throws IOException { BlockReportRequestProto.Builder builder = BlockReportRequestProto .newBuilder().setRegistration(PBHelper.convert(registration)) .setBlockPoolId(poolId); boolean useBlocksBuffer = registration.getNamespaceInfo() .isCapabilitySupported(Capability.STORAGE_BLOCK_REPORT_BUFFERS); for (StorageBlockReport r : reports) { StorageBlockReportProto.Builder reportBuilder = StorageBlockReportProto .newBuilder().setStorage(PBHelperClient.convert(r.getStorage())); BlockListAsLongs blocks = r.getBlocks(); if (useBlocksBuffer) { reportBuilder.setNumberOfBlocks(blocks.getNumberOfBlocks()); reportBuilder.addAllBlocksBuffers(blocks.getBlocksBuffers()); } else { for (long value : blocks.getBlockListAsLongs()) { reportBuilder.addBlocks(value); } } builder.addReports(reportBuilder.build()); } builder.setContext(PBHelper.convert(context)); BlockReportResponseProto resp; resp = ipc(() -> rpcProxy.blockReport(NULL_CONTROLLER, builder.build())); return resp.hasCmd() ? PBHelper.convert(resp.getCmd()) : null; } @Override public DatanodeCommand cacheReport(DatanodeRegistration registration, String poolId, List<Long> blockIds) throws IOException { CacheReportRequestProto.Builder builder = CacheReportRequestProto.newBuilder() .setRegistration(PBHelper.convert(registration)) .setBlockPoolId(poolId); for (Long blockId : blockIds) { builder.addBlocks(blockId); } CacheReportResponseProto resp; resp = ipc(() -> rpcProxy.cacheReport(NULL_CONTROLLER, builder.build())); if (resp.hasCmd()) { return PBHelper.convert(resp.getCmd()); } return null; } @Override public void blockReceivedAndDeleted(DatanodeRegistration registration, String poolId, StorageReceivedDeletedBlocks[] receivedAndDeletedBlocks) throws IOException { BlockReceivedAndDeletedRequestProto.Builder builder = BlockReceivedAndDeletedRequestProto.newBuilder() .setRegistration(PBHelper.convert(registration)) .setBlockPoolId(poolId); for (StorageReceivedDeletedBlocks storageBlock : receivedAndDeletedBlocks) { StorageReceivedDeletedBlocksProto.Builder repBuilder = StorageReceivedDeletedBlocksProto.newBuilder(); repBuilder.setStorageUuid(storageBlock.getStorage().getStorageID()); // Set for wire compatibility. repBuilder.setStorage(PBHelperClient.convert(storageBlock.getStorage())); for (ReceivedDeletedBlockInfo rdBlock : storageBlock.getBlocks()) { repBuilder.addBlocks(PBHelper.convert(rdBlock)); } builder.addBlocks(repBuilder.build()); } ipc(() -> rpcProxy.blockReceivedAndDeleted(NULL_CONTROLLER, builder.build())); } @Override public void errorReport(DatanodeRegistration registration, int errorCode, String msg) throws IOException { ErrorReportRequestProto req = ErrorReportRequestProto.newBuilder() .setRegistartion(PBHelper.convert(registration)) .setErrorCode(errorCode).setMsg(msg).build(); ipc(() -> rpcProxy.errorReport(NULL_CONTROLLER, req)); } @Override public NamespaceInfo versionRequest() throws IOException { return PBHelper.convert(ipc(() -> rpcProxy.versionRequest(NULL_CONTROLLER, VOID_VERSION_REQUEST).getInfo())); } @Override public void reportBadBlocks(LocatedBlock[] blocks) throws IOException { ReportBadBlocksRequestProto.Builder builder = ReportBadBlocksRequestProto .newBuilder(); for (int i = 0; i < blocks.length; i++) { builder.addBlocks(i, PBHelperClient.convertLocatedBlock(blocks[i])); } ReportBadBlocksRequestProto req = builder.build(); ipc(() -> rpcProxy.reportBadBlocks(NULL_CONTROLLER, req)); } @Override public void commitBlockSynchronization(ExtendedBlock block, long newgenerationstamp, long newlength, boolean closeFile, boolean deleteblock, DatanodeID[] newtargets, String[] newtargetstorages ) throws IOException { CommitBlockSynchronizationRequestProto.Builder builder = CommitBlockSynchronizationRequestProto.newBuilder() .setBlock(PBHelperClient.convert(block)).setNewGenStamp(newgenerationstamp) .setNewLength(newlength).setCloseFile(closeFile) .setDeleteBlock(deleteblock); for (int i = 0; i < newtargets.length; i++) { if (newtargets[i] == null) { continue; } builder.addNewTaragets(PBHelperClient.convert(newtargets[i])); builder.addNewTargetStorages(newtargetstorages[i]); } CommitBlockSynchronizationRequestProto req = builder.build(); ipc(() -> rpcProxy.commitBlockSynchronization(NULL_CONTROLLER, req)); } @Override // ProtocolMetaInterface public boolean isMethodSupported(String methodName) throws IOException { return RpcClientUtil.isMethodSupported(rpcProxy, DatanodeProtocolPB.class, RPC.RpcKind.RPC_PROTOCOL_BUFFER, RPC.getProtocolVersion(DatanodeProtocolPB.class), methodName); } }
DatanodeProtocolClientSideTranslatorPB
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1801/Issue1801BuilderProvider.java
{ "start": 641, "end": 1194 }
class ____ extends ImmutablesBuilderProvider implements BuilderProvider { @Override protected BuilderInfo findBuilderInfo(TypeElement typeElement) { Name name = typeElement.getQualifiedName(); if ( name.toString().endsWith( ".Item" ) ) { BuilderInfo info = findBuilderInfoFromInnerBuilderClass( typeElement ); if ( info != null ) { return info; } } return super.findBuilderInfo( typeElement ); } /** * Looks for inner builder
Issue1801BuilderProvider
java
apache__maven
impl/maven-testing/src/main/java/org/apache/maven/api/plugin/testing/stubs/RepositorySystemSupplier.java
{ "start": 11576, "end": 11785 }
class ____ * sure that these (potentially overridden) methods are invoked only once, and instance created by those methods are * memorized and kept as long as supplier instance is kept open. * <p> * This
makes
java
apache__flink
flink-core/src/test/java/org/apache/flink/types/parser/LongParserTest.java
{ "start": 847, "end": 2315 }
class ____ extends ParserTestBase<Long> { @Override public String[] getValidTestValues() { return new String[] { "0", "1", "576", "-877678", String.valueOf(Integer.MAX_VALUE), String.valueOf(Integer.MIN_VALUE), String.valueOf(Long.MAX_VALUE), String.valueOf(Long.MIN_VALUE), "7656", "1239" }; } @Override public Long[] getValidTestResults() { return new Long[] { 0L, 1L, 576L, -877678L, (long) Integer.MAX_VALUE, (long) Integer.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE, 7656L, 1239L }; } @Override public String[] getInvalidTestValues() { return new String[] { "a", "1569a86", "-57-6", "7-877678", Long.MAX_VALUE + "0", Long.MIN_VALUE + "0", "9223372036854775808", "-9223372036854775809", " 1", "2 ", " ", "\t" }; } @Override public boolean allowsEmptyField() { return false; } @Override public FieldParser<Long> getParser() { return new LongParser(); } @Override public Class<Long> getTypeClass() { return Long.class; } }
LongParserTest
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/state/ValueStateDescriptor.java
{ "start": 1524, "end": 5366 }
class ____<T> extends StateDescriptor<ValueState<T>, T> { private static final long serialVersionUID = 1L; /** * Creates a new {@code ValueStateDescriptor} with the given name, type, and default value. * * <p>If this constructor fails (because it is not possible to describe the type via a class), * consider using the {@link #ValueStateDescriptor(String, TypeInformation, Object)} * constructor. * * @deprecated Use {@link #ValueStateDescriptor(String, Class)} instead and manually manage the * default value by checking whether the contents of the state is {@code null}. * @param name The (unique) name for the state. * @param typeClass The type of the values in the state. * @param defaultValue The default value that will be set when requesting state without setting * a value before. */ @Deprecated public ValueStateDescriptor(String name, Class<T> typeClass, T defaultValue) { super(name, typeClass, defaultValue); } /** * Creates a new {@code ValueStateDescriptor} with the given name and default value. * * @deprecated Use {@link #ValueStateDescriptor(String, TypeInformation)} instead and manually * manage the default value by checking whether the contents of the state is {@code null}. * @param name The (unique) name for the state. * @param typeInfo The type of the values in the state. * @param defaultValue The default value that will be set when requesting state without setting * a value before. */ @Deprecated public ValueStateDescriptor(String name, TypeInformation<T> typeInfo, T defaultValue) { super(name, typeInfo, defaultValue); } /** * Creates a new {@code ValueStateDescriptor} with the given name, default value, and the * specific serializer. * * @deprecated Use {@link #ValueStateDescriptor(String, TypeSerializer)} instead and manually * manage the default value by checking whether the contents of the state is {@code null}. * @param name The (unique) name for the state. * @param typeSerializer The type serializer of the values in the state. * @param defaultValue The default value that will be set when requesting state without setting * a value before. */ @Deprecated public ValueStateDescriptor(String name, TypeSerializer<T> typeSerializer, T defaultValue) { super(name, typeSerializer, defaultValue); } /** * Creates a new {@code ValueStateDescriptor} with the given name and type * * <p>If this constructor fails (because it is not possible to describe the type via a class), * consider using the {@link #ValueStateDescriptor(String, TypeInformation)} constructor. * * @param name The (unique) name for the state. * @param typeClass The type of the values in the state. */ public ValueStateDescriptor(String name, Class<T> typeClass) { super(name, typeClass, null); } /** * Creates a new {@code ValueStateDescriptor} with the given name and type. * * @param name The (unique) name for the state. * @param typeInfo The type of the values in the state. */ public ValueStateDescriptor(String name, TypeInformation<T> typeInfo) { super(name, typeInfo, null); } /** * Creates a new {@code ValueStateDescriptor} with the given name and the specific serializer. * * @param name The (unique) name for the state. * @param typeSerializer The type serializer of the values in the state. */ public ValueStateDescriptor(String name, TypeSerializer<T> typeSerializer) { super(name, typeSerializer, null); } @Override public Type getType() { return Type.VALUE; } }
ValueStateDescriptor
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/io/benchmark/StreamNetworkBroadcastThroughputBenchmark.java
{ "start": 1084, "end": 1866 }
class ____ extends StreamNetworkThroughputBenchmark { /** * Same as {@link StreamNetworkThroughputBenchmark#setUp(int, int, int, boolean, int, int)} but * also setups broadcast mode. */ @Override public void setUp( int recordWriters, int channels, int flushTimeout, boolean localMode, int senderBufferPoolSize, int receiverBufferPoolSize) throws Exception { setUp( recordWriters, channels, flushTimeout, true, localMode, senderBufferPoolSize, receiverBufferPoolSize, new Configuration()); } }
StreamNetworkBroadcastThroughputBenchmark
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/struct/TestParentChildReferences.java
{ "start": 3417, "end": 3647 }
class ____ { public String name; @JsonBackReference public NodeMap parent; public NodeForMap() { this(null); } public NodeForMap(String n) { name = n; } } public static
NodeForMap
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adapter/DefaultExecutionTopologyTest.java
{ "start": 3883, "end": 20326 }
class ____ { @RegisterExtension private static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE = TestingUtils.defaultExecutorExtension(); private DefaultExecutionGraph executionGraph; private DefaultExecutionTopology adapter; @BeforeEach void setUp() throws Exception { JobVertex[] jobVertices = new JobVertex[2]; int parallelism = 3; jobVertices[0] = createNoOpVertex(parallelism); jobVertices[1] = createNoOpVertex(parallelism); connectNewDataSetAsInput(jobVertices[1], jobVertices[0], ALL_TO_ALL, PIPELINED); executionGraph = createExecutionGraph(EXECUTOR_RESOURCE.getExecutor(), jobVertices); adapter = DefaultExecutionTopology.fromExecutionGraph(executionGraph); } @Test void testConstructor() { // implicitly tests order constraint of getVertices() assertGraphEquals(executionGraph, adapter); } @Test void testGetResultPartition() { for (ExecutionVertex vertex : executionGraph.getAllExecutionVertices()) { for (Map.Entry<IntermediateResultPartitionID, IntermediateResultPartition> entry : vertex.getProducedPartitions().entrySet()) { IntermediateResultPartition partition = entry.getValue(); DefaultResultPartition schedulingResultPartition = adapter.getResultPartition(entry.getKey()); assertPartitionEquals(partition, schedulingResultPartition); } } } @Test void testResultPartitionStateSupplier() throws Exception { final JobVertex[] jobVertices = createJobVertices(BLOCKING); executionGraph = createExecutionGraph(EXECUTOR_RESOURCE.getExecutor(), jobVertices); adapter = DefaultExecutionTopology.fromExecutionGraph(executionGraph); final ExecutionJobVertex ejv = executionGraph.getJobVertex(jobVertices[0].getID()); ExecutionVertex ev = ejv.getTaskVertices()[0]; IntermediateResultPartition intermediateResultPartition = ev.getProducedPartitions().values().stream().findAny().get(); final DefaultResultPartition schedulingResultPartition = adapter.getResultPartition(intermediateResultPartition.getPartitionId()); assertThat(schedulingResultPartition.getState()).isEqualTo(ResultPartitionState.CREATED); ev.finishPartitionsIfNeeded(); assertThat(schedulingResultPartition.getState()) .isEqualTo(ResultPartitionState.ALL_DATA_PRODUCED); } @Test void testGetVertexOrThrow() { assertThatThrownBy(() -> adapter.getVertex(new ExecutionVertexID(new JobVertexID(), 0))) .isInstanceOf(IllegalArgumentException.class); } @Test void testResultPartitionOrThrow() { assertThatThrownBy(() -> adapter.getResultPartition(new IntermediateResultPartitionID())) .isInstanceOf(IllegalArgumentException.class); } @Test void testGetAllPipelinedRegions() { final Iterable<DefaultSchedulingPipelinedRegion> allPipelinedRegions = adapter.getAllPipelinedRegions(); assertThat(allPipelinedRegions).hasSize(1); } @Test void testGetPipelinedRegionOfVertex() { for (DefaultExecutionVertex vertex : adapter.getVertices()) { final DefaultSchedulingPipelinedRegion pipelinedRegion = adapter.getPipelinedRegionOfVertex(vertex.getId()); assertRegionContainsAllVertices(pipelinedRegion); } } @Test void testErrorIfCoLocatedTasksAreNotInSameRegion() { int parallelism = 3; final JobVertex v1 = createNoOpVertex(parallelism); final JobVertex v2 = createNoOpVertex(parallelism); SlotSharingGroup slotSharingGroup = new SlotSharingGroup(); v1.setSlotSharingGroup(slotSharingGroup); v2.setSlotSharingGroup(slotSharingGroup); v1.setStrictlyCoLocatedWith(v2); assertThatThrownBy(() -> createExecutionGraph(EXECUTOR_RESOURCE.getExecutor(), v1, v2)) .isInstanceOf(IllegalStateException.class); } @Test void testUpdateTopologyWithInitializedJobVertices() throws Exception { final JobVertex[] jobVertices = createJobVertices(BLOCKING); executionGraph = createDynamicGraph(jobVertices); adapter = DefaultExecutionTopology.fromExecutionGraph(executionGraph); final ExecutionJobVertex ejv1 = executionGraph.getJobVertex(jobVertices[0].getID()); final ExecutionJobVertex ejv2 = executionGraph.getJobVertex(jobVertices[1].getID()); executionGraph.initializeJobVertex(ejv1, 0L); adapter.notifyExecutionGraphUpdatedWithInitializedJobVertices( executionGraph, Collections.singletonList(ejv1)); assertThat(adapter.getVertices()).hasSize(3); executionGraph.initializeJobVertex(ejv2, 0L); adapter.notifyExecutionGraphUpdatedWithInitializedJobVertices( executionGraph, Collections.singletonList(ejv2)); assertThat(adapter.getVertices()).hasSize(6); assertGraphEquals(executionGraph, adapter); } @Test void testUpdateTopologyWithNewlyAddedJobVertices() throws Exception { final int parallelism = 3; JobVertex jobVertex1 = createNoOpVertex("v1", parallelism); IntermediateDataSetID dataSetId = new IntermediateDataSetID(); IntermediateDataSet dataSet = jobVertex1.getOrCreateResultDataSet(dataSetId, BLOCKING); dataSet.configure(ALL_TO_ALL, false, false); executionGraph = createDynamicGraph( new TestingExecutionPlanSchedulingContext(parallelism, parallelism), jobVertex1); adapter = DefaultExecutionTopology.fromExecutionGraph(executionGraph); // 1. Initialize job vertex1 assertThat(executionGraph.getAllVertices()).hasSize(1); final ExecutionJobVertex ejv1 = executionGraph.getJobVertex(jobVertex1.getID()); executionGraph.initializeJobVertex(ejv1, 0L); // 2. Add job vertex2 JobVertex jobVertex2 = createNoOpVertex("v2", parallelism); connectNewDataSetAsInput(jobVertex2, jobVertex1, ALL_TO_ALL, BLOCKING, dataSetId, false); // 3. Initialize job vertex2 List<JobVertex> newJobVertices = Collections.singletonList(jobVertex2); executionGraph.addNewJobVertices( newJobVertices, UnregisteredMetricGroups.createUnregisteredJobManagerJobMetricGroup(), computeVertexParallelismStoreForDynamicGraph(newJobVertices, parallelism)); final ExecutionJobVertex ejv2 = executionGraph.getJobVertex(jobVertex2.getID()); executionGraph.initializeJobVertex(ejv2, 0L); // Operating execution topology graph: 1. notify job vertex1 initialized adapter.notifyExecutionGraphUpdatedWithInitializedJobVertices( executionGraph, Collections.singletonList(ejv1)); // Operating execution topology graph: 2. notify job vertex2 added adapter.notifyExecutionGraphUpdatedWithNewJobVertices( Arrays.asList(jobVertex1, jobVertex2)); // Operating execution topology graph: 3. notify job vertex2 initialized adapter.notifyExecutionGraphUpdatedWithInitializedJobVertices( executionGraph, Collections.singletonList(ejv2)); assertGraphEquals(executionGraph, adapter); } @Test void testErrorIfUpdateTopologyWithNewVertexPipelinedConnectedToOldOnes() throws Exception { final JobVertex[] jobVertices = createJobVertices(PIPELINED); executionGraph = createDynamicGraph(jobVertices); adapter = DefaultExecutionTopology.fromExecutionGraph(executionGraph); final ExecutionJobVertex ejv1 = executionGraph.getJobVertex(jobVertices[0].getID()); final ExecutionJobVertex ejv2 = executionGraph.getJobVertex(jobVertices[1].getID()); executionGraph.initializeJobVertex(ejv1, 0L); adapter.notifyExecutionGraphUpdatedWithInitializedJobVertices( executionGraph, Collections.singletonList(ejv1)); executionGraph.initializeJobVertex(ejv2, 0L); assertThatThrownBy( () -> adapter.notifyExecutionGraphUpdatedWithInitializedJobVertices( executionGraph, Collections.singletonList(ejv2))) .isInstanceOf(IllegalStateException.class); } @Test void testExistingRegionsAreNotAffectedDuringTopologyUpdate() throws Exception { final JobVertex[] jobVertices = createJobVertices(BLOCKING); executionGraph = createDynamicGraph(jobVertices); adapter = DefaultExecutionTopology.fromExecutionGraph(executionGraph); final ExecutionJobVertex ejv1 = executionGraph.getJobVertex(jobVertices[0].getID()); final ExecutionJobVertex ejv2 = executionGraph.getJobVertex(jobVertices[1].getID()); executionGraph.initializeJobVertex(ejv1, 0L); adapter.notifyExecutionGraphUpdatedWithInitializedJobVertices( executionGraph, Collections.singletonList(ejv1)); SchedulingPipelinedRegion regionOld = adapter.getPipelinedRegionOfVertex(new ExecutionVertexID(ejv1.getJobVertexId(), 0)); executionGraph.initializeJobVertex(ejv2, 0L); adapter.notifyExecutionGraphUpdatedWithInitializedJobVertices( executionGraph, Collections.singletonList(ejv2)); SchedulingPipelinedRegion regionNew = adapter.getPipelinedRegionOfVertex(new ExecutionVertexID(ejv1.getJobVertexId(), 0)); assertThat(regionNew).isSameAs(regionOld); } private JobVertex[] createJobVertices(ResultPartitionType resultPartitionType) { final JobVertex[] jobVertices = new JobVertex[2]; final int parallelism = 3; jobVertices[0] = createNoOpVertex(parallelism); jobVertices[1] = createNoOpVertex(parallelism); connectNewDataSetAsInput(jobVertices[1], jobVertices[0], ALL_TO_ALL, resultPartitionType); return jobVertices; } private DefaultExecutionGraph createDynamicGraph(JobVertex... jobVertices) throws Exception { return TestingDefaultExecutionGraphBuilder.newBuilder() .setJobGraph(new JobGraph(new JobID(), "TestJob", jobVertices)) .buildDynamicGraph(EXECUTOR_RESOURCE.getExecutor()); } private DefaultExecutionGraph createDynamicGraph( ExecutionPlanSchedulingContext executionPlanSchedulingContext, JobVertex... jobVertices) throws Exception { return TestingDefaultExecutionGraphBuilder.newBuilder() .setJobGraph(new JobGraph(new JobID(), "TestJob", jobVertices)) .setExecutionPlanSchedulingContext(executionPlanSchedulingContext) .buildDynamicGraph(EXECUTOR_RESOURCE.getExecutor()); } private void assertRegionContainsAllVertices( final DefaultSchedulingPipelinedRegion pipelinedRegionOfVertex) { final Set<DefaultExecutionVertex> allVertices = Sets.newHashSet(pipelinedRegionOfVertex.getVertices()); assertThat(allVertices).isEqualTo(Sets.newHashSet(adapter.getVertices())); } private static void assertGraphEquals( ExecutionGraph originalGraph, DefaultExecutionTopology adaptedTopology) { Iterator<ExecutionVertex> originalVertices = originalGraph.getAllExecutionVertices().iterator(); Iterator<DefaultExecutionVertex> adaptedVertices = adaptedTopology.getVertices().iterator(); while (originalVertices.hasNext()) { ExecutionVertex originalVertex = originalVertices.next(); DefaultExecutionVertex adaptedVertex = adaptedVertices.next(); assertThat(adaptedVertex.getId()).isEqualTo(originalVertex.getID()); List<IntermediateResultPartition> originalConsumedPartitions = new ArrayList<>(); for (ConsumedPartitionGroup consumedPartitionGroup : originalVertex.getAllConsumedPartitionGroups()) { for (IntermediateResultPartitionID partitionId : consumedPartitionGroup) { IntermediateResultPartition partition = originalVertex .getExecutionGraphAccessor() .getResultPartitionOrThrow(partitionId); originalConsumedPartitions.add(partition); } } Iterable<DefaultResultPartition> adaptedConsumedPartitions = adaptedVertex.getConsumedResults(); assertPartitionsEquals(originalConsumedPartitions, adaptedConsumedPartitions); Collection<IntermediateResultPartition> originalProducedPartitions = originalVertex.getProducedPartitions().values(); Iterable<DefaultResultPartition> adaptedProducedPartitions = adaptedVertex.getProducedResults(); assertPartitionsEquals(originalProducedPartitions, adaptedProducedPartitions); } assertThat(adaptedVertices) .as("Number of adapted vertices exceeds number of original vertices.") .isExhausted(); } private static void assertPartitionsEquals( Iterable<IntermediateResultPartition> originalResultPartitions, Iterable<DefaultResultPartition> adaptedResultPartitions) { assertThat(originalResultPartitions).hasSameSizeAs(adaptedResultPartitions); for (IntermediateResultPartition originalPartition : originalResultPartitions) { DefaultResultPartition adaptedPartition = IterableUtils.toStream(adaptedResultPartitions) .filter( adapted -> adapted.getId() .equals(originalPartition.getPartitionId())) .findAny() .orElseThrow( () -> new AssertionError( "Could not find matching adapted partition for " + originalPartition)); assertPartitionEquals(originalPartition, adaptedPartition); List<ExecutionVertexID> originalConsumerIds = new ArrayList<>(); for (ConsumerVertexGroup consumerVertexGroup : originalPartition.getConsumerVertexGroups()) { for (ExecutionVertexID executionVertexId : consumerVertexGroup) { originalConsumerIds.add(executionVertexId); } } List<ConsumerVertexGroup> adaptedConsumers = adaptedPartition.getConsumerVertexGroups(); assertThat(adaptedConsumers).isNotEmpty(); for (ExecutionVertexID originalId : originalConsumerIds) { // it is sufficient to verify that some vertex exists with the correct ID here, // since deep equality is verified later in the main loop // this DOES rely on an implicit assumption that the vertices objects returned by // the topology are // identical to those stored in the partition assertThat(adaptedConsumers.stream().flatMap(IterableUtils::toStream)) .contains(originalId); } } } private static void assertPartitionEquals( IntermediateResultPartition originalPartition, DefaultResultPartition adaptedPartition) { assertThat(adaptedPartition.getId()).isEqualTo(originalPartition.getPartitionId()); assertThat(adaptedPartition.getResultId()) .isEqualTo(originalPartition.getIntermediateResult().getId()); assertThat(adaptedPartition.getResultType()).isEqualTo(originalPartition.getResultType()); assertThat(adaptedPartition.getProducer().getId()) .isEqualTo(originalPartition.getProducer().getID()); } private static
DefaultExecutionTopologyTest
java
google__dagger
javatests/dagger/internal/codegen/kotlin/KspComponentProcessorTest.java
{ "start": 21770, "end": 21915 }
class ____ @Inject constructor() {", " @Inject @Named(\"key\") lateinit var bar: Bar", "}", "", "
Foo
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_hasToString_Test.java
{ "start": 798, "end": 1157 }
class ____ extends AbstractAssertBaseTest { @Override protected ConcreteAssert invoke_api_method() { return assertions.hasToString("some description"); } @Override protected void verify_internal_effects() { verify(objects).assertHasToString(getInfo(assertions), getActual(assertions), "some description"); } }
AbstractAssert_hasToString_Test
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/DescribeStreamsGroupsResult.java
{ "start": 1311, "end": 2758 }
class ____ { private final Map<String, KafkaFuture<StreamsGroupDescription>> futures; public DescribeStreamsGroupsResult(final Map<String, KafkaFuture<StreamsGroupDescription>> futures) { this.futures = Map.copyOf(futures); } /** * Return a map from group id to futures which yield streams group descriptions. */ public Map<String, KafkaFuture<StreamsGroupDescription>> describedGroups() { return new HashMap<>(futures); } /** * Return a future which yields all StreamsGroupDescription objects, if all the describes succeed. */ public KafkaFuture<Map<String, StreamsGroupDescription>> all() { return KafkaFuture.allOf(futures.values().toArray(new KafkaFuture<?>[0])).thenApply( nil -> { Map<String, StreamsGroupDescription> descriptions = new HashMap<>(futures.size()); futures.forEach((key, future) -> { try { descriptions.put(key, future.get()); } catch (InterruptedException | ExecutionException e) { // This should be unreachable, since the KafkaFuture#allOf already ensured // that all of the futures completed successfully. throw new RuntimeException(e); } }); return descriptions; }); } }
DescribeStreamsGroupsResult
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableElementAtMaybe.java
{ "start": 1596, "end": 3467 }
class ____<T> implements FlowableSubscriber<T>, Disposable { final MaybeObserver<? super T> downstream; final long index; Subscription upstream; long count; boolean done; ElementAtSubscriber(MaybeObserver<? super T> actual, long index) { this.downstream = actual; this.index = index; } @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { this.upstream = s; downstream.onSubscribe(this); s.request(index + 1); } } @Override public void onNext(T t) { if (done) { return; } long c = count; if (c == index) { done = true; upstream.cancel(); upstream = SubscriptionHelper.CANCELLED; downstream.onSuccess(t); return; } count = c + 1; } @Override public void onError(Throwable t) { if (done) { RxJavaPlugins.onError(t); return; } done = true; upstream = SubscriptionHelper.CANCELLED; downstream.onError(t); } @Override public void onComplete() { upstream = SubscriptionHelper.CANCELLED; if (!done) { done = true; downstream.onComplete(); } } @Override public void dispose() { upstream.cancel(); upstream = SubscriptionHelper.CANCELLED; } @Override public boolean isDisposed() { return upstream == SubscriptionHelper.CANCELLED; } } }
ElementAtSubscriber
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/common/network/ThreadWatchdogHelper.java
{ "start": 543, "end": 757 }
class ____ { // exposes this package-private method to tests public static List<String> getStuckThreadNames(ThreadWatchdog watchdog) { return watchdog.getStuckThreadNames(); } }
ThreadWatchdogHelper