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
square__retrofit
samples/src/main/java/com/example/retrofit/ErrorHandlingAdapter.java
{ "start": 3517, "end": 5523 }
class ____<T> implements MyCall<T> { private final Call<T> call; private final Executor callbackExecutor; MyCallAdapter(Call<T> call, Executor callbackExecutor) { this.call = call; this.callbackExecutor = callbackExecutor; } @Override public void cancel() { call.cancel(); } @Override public void enqueue(final MyCallback<T> callback) { call.enqueue( new Callback<T>() { @Override public void onResponse(Call<T> call, Response<T> response) { // TODO if 'callbackExecutor' is not null, the 'callback' methods should be executed // on that executor by submitting a Runnable. This is left as an exercise for the // reader. int code = response.code(); if (code >= 200 && code < 300) { callback.success(response); } else if (code == 401) { callback.unauthenticated(response); } else if (code >= 400 && code < 500) { callback.clientError(response); } else if (code >= 500 && code < 600) { callback.serverError(response); } else { callback.unexpectedError(new RuntimeException("Unexpected response " + response)); } } @Override public void onFailure(Call<T> call, Throwable t) { // TODO if 'callbackExecutor' is not null, the 'callback' methods should be executed // on that executor by submitting a Runnable. This is left as an exercise for the // reader. if (t instanceof IOException) { callback.networkError((IOException) t); } else { callback.unexpectedError(t); } } }); } @Override public MyCall<T> clone() { return new MyCallAdapter<>(call.clone(), callbackExecutor); } }
MyCallAdapter
java
elastic__elasticsearch
test/fixtures/azure-fixture/src/main/java/fixture/azure/MockAzureBlobStore.java
{ "start": 18676, "end": 18894 }
class ____ extends AzureBlobStoreError { public ConflictException(String errorCode, String message) { super(RestStatus.CONFLICT, errorCode, message); } } public static
ConflictException
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/function/FailableIntToDoubleFunction.java
{ "start": 917, "end": 1098 }
interface ____ {@link IntToDoubleFunction} that declares a {@link Throwable}. * * @param <E> The kind of thrown exception or error. * @since 3.11 */ @FunctionalInterface public
like
java
apache__flink
flink-core/src/main/java/org/apache/flink/types/parser/FieldParser.java
{ "start": 1959, "end": 9421 }
enum ____ { /** No error occurred. */ NONE, /** The domain of the numeric type is not large enough to hold the parsed value. */ NUMERIC_VALUE_OVERFLOW_UNDERFLOW, /** A stand-alone sign was encountered while parsing a numeric type. */ NUMERIC_VALUE_ORPHAN_SIGN, /** An illegal character was encountered while parsing a numeric type. */ NUMERIC_VALUE_ILLEGAL_CHARACTER, /** The field was not in a correct format for the numeric type. */ NUMERIC_VALUE_FORMAT_ERROR, /** A quoted string was not terminated until the line end. */ UNTERMINATED_QUOTED_STRING, /** The parser found characters between the end of the quoted string and the delimiter. */ UNQUOTED_CHARS_AFTER_QUOTED_STRING, /** The column is empty. */ EMPTY_COLUMN, /** Invalid Boolean value * */ BOOLEAN_INVALID } private Charset charset = StandardCharsets.UTF_8; private ParseErrorState errorState = ParseErrorState.NONE; /** * Parses the value of a field from the byte array, taking care of properly reset the state of * this parser. The start position within the byte array and the array's valid length is given. * The content of the value is delimited by a field delimiter. * * @param bytes The byte array that holds the value. * @param startPos The index where the field starts * @param limit The limit unto which the byte contents is valid for the parser. The limit is the * position one after the last valid byte. * @param delim The field delimiter character * @param reuse An optional reusable field to hold the value * @return The index of the next delimiter, if the field was parsed correctly. A value less than * 0 otherwise. */ public int resetErrorStateAndParse( byte[] bytes, int startPos, int limit, byte[] delim, T reuse) { resetParserState(); return parseField(bytes, startPos, limit, delim, reuse); } /** Each parser's logic should be implemented inside this method */ protected abstract int parseField(byte[] bytes, int startPos, int limit, byte[] delim, T reuse); /** * Reset the state of the parser. Called as the very first method inside {@link * FieldParser#resetErrorStateAndParse(byte[], int, int, byte[], Object)}, by default it just * reset its error state. */ protected void resetParserState() { this.errorState = ParseErrorState.NONE; } /** * Gets the parsed field. This method returns the value parsed by the last successful invocation * of {@link #parseField(byte[], int, int, byte[], Object)}. It objects are mutable and reused, * it will return the object instance that was passed the parse function. * * @return The latest parsed field. */ public abstract T getLastResult(); /** * Returns an instance of the parsed value type. * * @return An instance of the parsed value type. */ public abstract T createValue(); /** * Checks if the delimiter starts at the given start position of the byte array. * * <p>Attention: This method assumes that enough characters follow the start position for the * delimiter check! * * @param bytes The byte array that holds the value. * @param startPos The index of the byte array where the check for the delimiter starts. * @param delim The delimiter to check for. * @return true if a delimiter starts at the given start position, false otherwise. */ public static final boolean delimiterNext(byte[] bytes, int startPos, byte[] delim) { for (int pos = 0; pos < delim.length; pos++) { // check each position if (delim[pos] != bytes[startPos + pos]) { return false; } } return true; } /** * Checks if the given bytes ends with the delimiter at the given end position. * * @param bytes The byte array that holds the value. * @param endPos The index of the byte array where the check for the delimiter ends. * @param delim The delimiter to check for. * @return true if a delimiter ends at the given end position, false otherwise. */ public static final boolean endsWithDelimiter(byte[] bytes, int endPos, byte[] delim) { if (endPos < delim.length - 1) { return false; } for (int pos = 0; pos < delim.length; ++pos) { if (delim[pos] != bytes[endPos - delim.length + 1 + pos]) { return false; } } return true; } /** * Sets the error state of the parser. Called by subclasses of the parser to set the type of * error when failing a parse. * * @param error The error state to set. */ protected void setErrorState(ParseErrorState error) { this.errorState = error; } /** * Gets the error state of the parser, as a value of the enumeration {@link ParseErrorState}. If * no error occurred, the error state will be {@link ParseErrorState#NONE}. * * @return The current error state of the parser. */ public ParseErrorState getErrorState() { return this.errorState; } /** * Returns the end position of a string. Sets the error state if the column is empty. * * @return the end position of the string or -1 if an error occurred */ protected final int nextStringEndPos(byte[] bytes, int startPos, int limit, byte[] delimiter) { int endPos = startPos; final int delimLimit = limit - delimiter.length + 1; while (endPos < limit) { if (endPos < delimLimit && delimiterNext(bytes, endPos, delimiter)) { break; } endPos++; } if (endPos == startPos) { setErrorState(ParseErrorState.EMPTY_COLUMN); return -1; } return endPos; } /** * Returns the length of a string. Throws an exception if the column is empty. * * @return the length of the string */ protected static final int nextStringLength( byte[] bytes, int startPos, int length, char delimiter) { if (length <= 0) { throw new IllegalArgumentException("Invalid input: Empty string"); } int limitedLength = 0; final byte delByte = (byte) delimiter; while (limitedLength < length && bytes[startPos + limitedLength] != delByte) { limitedLength++; } return limitedLength; } /** * Gets the character set used for this parser. * * @return the charset used for this parser. */ public Charset getCharset() { return this.charset; } /** * Sets the character set used for this parser. * * @param charset charset used for this parser. */ public void setCharset(Charset charset) { this.charset = charset; } // -------------------------------------------------------------------------------------------- // Mapping from types to parsers // -------------------------------------------------------------------------------------------- /** * Gets the parser for the type specified by the given class. Returns null, if no parser for * that
ParseErrorState
java
apache__camel
components/camel-ai/camel-langchain4j-embeddings/src/main/java/org/apache/camel/component/langchain4j/embeddings/LangChain4jEmbeddings.java
{ "start": 970, "end": 1177 }
class ____ { public static final String SCHEME = "langchain4j-embeddings"; private LangChain4jEmbeddings() { } /** * @deprecated As of Camel 4.15, this nested Headers
LangChain4jEmbeddings
java
grpc__grpc-java
api/src/main/java/io/grpc/InternalServerProvider.java
{ "start": 750, "end": 1151 }
class ____ { private InternalServerProvider() { } public static ServerBuilder<?> builderForPort(ServerProvider provider, int port) { return provider.builderForPort(port); } public static NewServerBuilderResult newServerBuilderForPort(ServerProvider provider, int port, ServerCredentials creds) { return provider.newServerBuilderForPort(port, creds); } }
InternalServerProvider
java
quarkusio__quarkus
extensions/panache/hibernate-orm-rest-data-panache/deployment/src/test/java/io/quarkus/hibernate/orm/rest/data/panache/deployment/entity/ProjectResource.java
{ "start": 383, "end": 460 }
interface ____ extends PanacheEntityResource<Project, String> { }
ProjectResource
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/assignment/Java8FunctionWrapper.java
{ "start": 476, "end": 1406 }
class ____ extends AssignmentWrapper { private final Type functionType; public Java8FunctionWrapper(Assignment decoratedAssignment) { this( decoratedAssignment, null ); } public Java8FunctionWrapper(Assignment decoratedAssignment, Type functionType) { super( decoratedAssignment, false ); this.functionType = functionType; } @Override public Set<Type> getImportTypes() { Set<Type> imported = new HashSet<>( super.getImportTypes() ); if ( isDirectAssignment() && functionType != null ) { imported.add( functionType ); } return imported; } /** * * @return {@code true} if the wrapped assignment is * {@link Assignment.AssignmentType#DIRECT}, {@code false} otherwise */ public boolean isDirectAssignment() { return getAssignment().getType() == AssignmentType.DIRECT; } }
Java8FunctionWrapper
java
spring-projects__spring-boot
build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/bundling/CacheSpec.java
{ "start": 1115, "end": 2336 }
class ____ { private final ObjectFactory objectFactory; private @Nullable Cache cache; @Inject public CacheSpec(ObjectFactory objectFactory) { this.objectFactory = objectFactory; } public @Nullable Cache asCache() { return this.cache; } /** * Configures a volume cache using the given {@code action}. * @param action the action */ public void volume(Action<VolumeCacheSpec> action) { if (this.cache != null) { throw new GradleException("Each image building cache can be configured only once"); } VolumeCacheSpec spec = this.objectFactory.newInstance(VolumeCacheSpec.class); action.execute(spec); this.cache = Cache.volume(spec.getName().get()); } /** * Configures a bind cache using the given {@code action}. * @param action the action */ public void bind(Action<BindCacheSpec> action) { if (this.cache != null) { throw new GradleException("Each image building cache can be configured only once"); } BindCacheSpec spec = this.objectFactory.newInstance(BindCacheSpec.class); action.execute(spec); this.cache = Cache.bind(spec.getSource().get()); } /** * Configuration for an image building cache stored in a Docker volume. */ public abstract static
CacheSpec
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/external/request/RequestUtils.java
{ "start": 734, "end": 1968 }
class ____ { public static Header createAuthBearerHeader(SecureString apiKey) { return new BasicHeader(HttpHeaders.AUTHORIZATION, bearerToken(apiKey.toString())); } public static String bearerToken(String apiKey) { return "Bearer " + apiKey; } public static Header createAuthApiKeyHeader(SecureString apiKey) { return new BasicHeader(HttpHeaders.AUTHORIZATION, apiKey(apiKey.toString())); } public static String apiKey(String apiKey) { return "ApiKey " + apiKey; } public static URI buildUri(URI accountUri, String service, CheckedSupplier<URI, URISyntaxException> uriBuilder) { try { return accountUri == null ? uriBuilder.get() : accountUri; } catch (URISyntaxException e) { // using bad request here so that potentially sensitive URL information does not get logged throw new ElasticsearchStatusException(Strings.format("Failed to construct %s URL", service), RestStatus.BAD_REQUEST, e); } } public static URI buildUri(String service, CheckedSupplier<URI, URISyntaxException> uriBuilder) { return buildUri(null, service, uriBuilder); } private RequestUtils() {} }
RequestUtils
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/jmx/export/annotation/EnableMBeanExportConfigurationTests.java
{ "start": 8205, "end": 8485 }
class ____ { private String name; @ManagedAttribute public String getName() { return this.name; } @ManagedAttribute public void setName(String name) { this.name = name; } } @Configuration @EnableMBeanExport(server = "server") static
PackagePrivateTestBean
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/service/repository/ConfigInfoTagPersistService.java
{ "start": 1453, "end": 5878 }
interface ____ { /** * create Pagination utils. * * @param <E> Generic object * @return {@link PaginationHelper} */ <E> PaginationHelper<E> createPaginationHelper(); //------------------------------------------insert---------------------------------------------// /** * get config info state. * * @param dataId dataId. * @param group group. * @param tenant tenant. * @param tag tag. * @return config info state. */ ConfigInfoStateWrapper findConfigInfo4TagState(final String dataId, final String group, final String tenant, String tag); /** * Add tag configuration information and publish data change events. * * @param configInfo config info * @param tag tag * @param srcIp remote ip * @param srcUser user * @return config operation result. */ ConfigOperateResult addConfigInfo4Tag(ConfigInfo configInfo, String tag, String srcIp, String srcUser); /** * insert or update tag config. * * @param configInfo config info * @param tag tag * @param srcIp remote ip * @param srcUser user * @return config operation result. */ ConfigOperateResult insertOrUpdateTag(final ConfigInfo configInfo, final String tag, final String srcIp, final String srcUser); /** * insert or update tag config cas. * * @param configInfo config info. * @param tag tag. * @param srcIp remote ip. * @param srcUser user. * @return config operation result. */ ConfigOperateResult insertOrUpdateTagCas(final ConfigInfo configInfo, final String tag, final String srcIp, final String srcUser); //------------------------------------------delete---------------------------------------------// /** * Delete configuration; database atomic operation, minimum SQL action, no business encapsulation. * * @param dataId dataId * @param group group * @param tenant tenant * @param tag tag * @param srcIp remote ip * @param srcUser user */ void removeConfigInfoTag(final String dataId, final String group, final String tenant, final String tag, final String srcIp, final String srcUser); //------------------------------------------update---------------------------------------------// /** * Update tag configuration information. * * @param configInfo config info * @param tag tag * @param srcIp remote ip * @param srcUser user * @return config operation result. */ ConfigOperateResult updateConfigInfo4Tag(ConfigInfo configInfo, String tag, String srcIp, String srcUser); /** * Update tag configuration information. * * @param configInfo config info * @param tag tag * @param srcIp remote ip * @param srcUser user * @return success or not. */ ConfigOperateResult updateConfigInfo4TagCas(ConfigInfo configInfo, String tag, String srcIp, String srcUser); //------------------------------------------select---------------------------------------------// /** * Query tag configuration information based on dataId and group. * * @param dataId data id * @param group group * @param tenant tenant * @param tag tag * @return {@link ConfigInfo4Tag} */ ConfigInfoTagWrapper findConfigInfo4Tag(final String dataId, final String group, final String tenant, final String tag); /** * Returns the number of beta configuration items. * * @return number of configuration items.. */ int configInfoTagCount(); /** * Query all tag config info for dump task. * * @param pageNo page numbser * @param pageSize page sizxe * @return {@link Page} with {@link ConfigInfoWrapper} generation */ Page<ConfigInfoTagWrapper> findAllConfigInfoTagForDumpAll(final int pageNo, final int pageSize); /** * found all config tags. * * @param dataId dataId. * @param group group. * @param tenant tenant. * @return */ List<String> findConfigInfoTags(final String dataId, final String group, final String tenant); }
ConfigInfoTagPersistService
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/impl/engine/IntrospectionSupportTest.java
{ "start": 4538, "end": 4915 }
class ____ { private ExampleBean bean; public void setBean(ExampleBean bean) { this.bean = bean; } public void setBean(String name) { bean = new ExampleBean(); bean.setName(name); } public String getName() { return bean.getName(); } } public static
MyOverloadedBean
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/informix/parser/InformixSelectParser.java
{ "start": 369, "end": 1061 }
class ____ extends SQLSelectParser { public InformixSelectParser(SQLExprParser exprParser, SQLSelectListCache selectListCache) { super(exprParser, selectListCache); } protected void querySelectListBefore(SQLSelectQueryBlock queryBlock) { if (lexer.identifierEquals(FnvHash.Constants.SKIP)) { lexer.nextToken(); SQLExpr offset = this.exprParser.primary(); queryBlock.setOffset(offset); } if (lexer.identifierEquals(FnvHash.Constants.FIRST)) { lexer.nextToken(); SQLExpr first = this.exprParser.primary(); queryBlock.setFirst(first); } } }
InformixSelectParser
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RMultimapReactive.java
{ "start": 841, "end": 4825 }
interface ____<K, V> extends RExpirableReactive { /** * Returns the number of key-value pairs in this multimap. * * @return size of multimap */ Mono<Integer> size(); /** * Returns {@code true} if this multimap contains at least one key-value pair * with the key {@code key}. * * @param key - map key * @return <code>true</code> if contains a key */ Mono<Boolean> containsKey(Object key); /** * Returns {@code true} if this multimap contains at least one key-value pair * with the value {@code value}. * * @param value - map value * @return <code>true</code> if contains a value */ Mono<Boolean> containsValue(Object value); /** * Returns {@code true} if this multimap contains at least one key-value pair * with the key {@code key} and the value {@code value}. * * @param key - map key * @param value - map value * @return <code>true</code> if contains an entry */ Mono<Boolean> containsEntry(Object key, Object value); /** * Stores a key-value pair in this multimap. * * <p>Some multimap implementations allow duplicate key-value pairs, in which * case {@code put} always adds a new key-value pair and increases the * multimap size by 1. Other implementations prohibit duplicates, and storing * a key-value pair that's already in the multimap has no effect. * * @param key - map key * @param value - map value * @return {@code true} if the method increased the size of the multimap, or * {@code false} if the multimap already contained the key-value pair and * doesn't allow duplicates */ Mono<Boolean> put(K key, V value); /** * Removes a single key-value pair with the key {@code key} and the value * {@code value} from this multimap, if such exists. If multiple key-value * pairs in the multimap fit this description, which one is removed is * unspecified. * * @param key - map key * @param value - map value * @return {@code true} if the multimap changed */ Mono<Boolean> remove(Object key, Object value); // Bulk Operations /** * Stores a key-value pair in this multimap for each of {@code values}, all * using the same key, {@code key}. Equivalent to (but expected to be more * efficient than): <pre> {@code * * for (V value : values) { * put(key, value); * }}</pre> * * <p>In particular, this is a no-op if {@code values} is empty. * * @param key - map key * @param values - map values * @return {@code true} if the multimap changed */ Mono<Boolean> putAll(K key, Iterable<? extends V> values); /** * Returns the number of key-value pairs in this multimap. * * @return keys amount */ Mono<Integer> keySize(); /** * Stores a collection of values with the same key, replacing any existing * values for that key. Is faster by not returning the values. * * @param key - map key * @param values - map values */ Mono<Void> fastReplaceValues(K key, Iterable<? extends V> values); /** * Removes <code>keys</code> from map by one operation * * Works faster than <code>RMultimap.remove</code> but not returning * the value associated with <code>key</code> * * @param keys - map keys * @return the number of keys that were removed from the hash, not including specified but non existing keys */ Mono<Long> fastRemove(K... keys); /** * Removes <code>values</code> from map by one operation * * @param values map values * @return the number of values that were removed from the map */ Mono<Long> fastRemoveValue(V... values); /** * Read all keys at once * * @return keys */ Mono<Set<K>> readAllKeySet(); }
RMultimapReactive
java
apache__kafka
server-common/src/main/java/org/apache/kafka/server/common/UnitTestFeatureVersion.java
{ "start": 937, "end": 1088 }
class ____ { /** * The feature is used for testing latest production is not one of the feature versions. */ public
UnitTestFeatureVersion
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/util/Table.java
{ "start": 895, "end": 1930 }
class ____<R, C, V> { private final Map<R, Map<C, V>> table = new HashMap<>(); public V put(R row, C column, V value) { Map<C, V> columns = table.computeIfAbsent(row, k -> new HashMap<>()); return columns.put(column, value); } public V get(R row, C column) { Map<C, V> columns = table.get(row); if (columns == null) return null; return columns.get(column); } public Map<C, V> remove(R row) { return table.remove(row); } public V remove(R row, C column) { Map<C, V> columns = table.get(row); if (columns == null) return null; V value = columns.remove(column); if (columns.isEmpty()) table.remove(row); return value; } public Map<C, V> row(R row) { Map<C, V> columns = table.get(row); if (columns == null) return Map.of(); return Map.copyOf(columns); } public boolean isEmpty() { return table.isEmpty(); } }
Table
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/observers/DeferredScalarObserverTest.java
{ "start": 4736, "end": 13437 }
class ____ extends DeferredScalarObserver<Integer, Integer> { private static final long serialVersionUID = -2793723002312330530L; TakeLast(Observer<? super Integer> downstream) { super(downstream); } @Override public void onNext(Integer value) { this.value = value; } } @Test public void nonfusedTerminateMore() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { TestObserverEx<Integer> to = new TestObserverEx<>(QueueFuseable.NONE); TakeLast source = new TakeLast(to); Disposable d = Disposable.empty(); source.onSubscribe(d); source.onNext(1); source.onComplete(); source.onComplete(); source.onError(new TestException()); to.assertResult(1); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void nonfusedError() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { TestObserverEx<Integer> to = new TestObserverEx<>(QueueFuseable.NONE); TakeLast source = new TakeLast(to); Disposable d = Disposable.empty(); source.onSubscribe(d); source.onNext(1); source.onError(new TestException()); source.onError(new TestException("second")); source.onComplete(); to.assertFailure(TestException.class); TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); } finally { RxJavaPlugins.reset(); } } @Test public void fusedTerminateMore() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { TestObserverEx<Integer> to = new TestObserverEx<>(QueueFuseable.ANY); TakeLast source = new TakeLast(to); Disposable d = Disposable.empty(); source.onSubscribe(d); source.onNext(1); source.onComplete(); source.onComplete(); source.onError(new TestException()); to.assertResult(1); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void fusedError() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { TestObserverEx<Integer> to = new TestObserverEx<>(QueueFuseable.ANY); TakeLast source = new TakeLast(to); Disposable d = Disposable.empty(); source.onSubscribe(d); source.onNext(1); source.onError(new TestException()); source.onError(new TestException("second")); source.onComplete(); to.assertFailure(TestException.class); TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); } finally { RxJavaPlugins.reset(); } } @Test public void disposed() { TestObserverEx<Integer> to = new TestObserverEx<>(QueueFuseable.NONE); TakeLast source = new TakeLast(to); Disposable d = Disposable.empty(); source.onSubscribe(d); to.dispose(); source.onNext(1); source.onComplete(); to.assertNoValues().assertNoErrors().assertNotComplete(); } @Test public void disposedAfterOnNext() { final TestObserver<Integer> to = new TestObserver<>(); TakeLast source = new TakeLast(new Observer<Integer>() { Disposable upstream; @Override public void onSubscribe(Disposable d) { this.upstream = d; to.onSubscribe(d); } @Override public void onNext(Integer value) { to.onNext(value); upstream.dispose(); } @Override public void onError(Throwable e) { to.onError(e); } @Override public void onComplete() { to.onComplete(); } }); source.onSubscribe(Disposable.empty()); source.onNext(1); source.onComplete(); to.assertValue(1).assertNoErrors().assertNotComplete(); } @Test public void fusedEmpty() { TestObserverEx<Integer> to = new TestObserverEx<>(QueueFuseable.ANY); TakeLast source = new TakeLast(to); Disposable d = Disposable.empty(); source.onSubscribe(d); source.onComplete(); to.assertResult(); } @Test public void nonfusedEmpty() { TestObserverEx<Integer> to = new TestObserverEx<>(QueueFuseable.NONE); TakeLast source = new TakeLast(to); Disposable d = Disposable.empty(); source.onSubscribe(d); source.onComplete(); to.assertResult(); } @Test public void customFusion() { final TestObserver<Integer> to = new TestObserver<>(); TakeLast source = new TakeLast(new Observer<Integer>() { QueueDisposable<Integer> d; @SuppressWarnings("unchecked") @Override public void onSubscribe(Disposable d) { this.d = (QueueDisposable<Integer>)d; to.onSubscribe(d); this.d.requestFusion(QueueFuseable.ANY); } @Override public void onNext(Integer value) { if (!d.isEmpty()) { Integer v = null; try { to.onNext(d.poll()); v = d.poll(); } catch (Throwable ex) { to.onError(ex); } assertNull(v); assertTrue(d.isEmpty()); } } @Override public void onError(Throwable e) { to.onError(e); } @Override public void onComplete() { to.onComplete(); } }); source.onSubscribe(Disposable.empty()); source.onNext(1); source.onComplete(); to.assertResult(1); } @Test public void customFusionClear() { final TestObserver<Integer> to = new TestObserver<>(); TakeLast source = new TakeLast(new Observer<Integer>() { QueueDisposable<Integer> d; @SuppressWarnings("unchecked") @Override public void onSubscribe(Disposable d) { this.d = (QueueDisposable<Integer>)d; to.onSubscribe(d); this.d.requestFusion(QueueFuseable.ANY); } @Override public void onNext(Integer value) { d.clear(); assertTrue(d.isEmpty()); } @Override public void onError(Throwable e) { to.onError(e); } @Override public void onComplete() { to.onComplete(); } }); source.onSubscribe(Disposable.empty()); source.onNext(1); source.onComplete(); to.assertNoValues().assertNoErrors().assertComplete(); } @Test public void offerThrow() { TestObserverEx<Integer> to = new TestObserverEx<>(QueueFuseable.NONE); TakeLast source = new TakeLast(to); TestHelper.assertNoOffer(source); } @Test public void customFusionDontConsume() { final TestObserver<Integer> to = new TestObserver<>(); TakeFirst source = new TakeFirst(new Observer<Integer>() { QueueDisposable<Integer> d; @SuppressWarnings("unchecked") @Override public void onSubscribe(Disposable d) { this.d = (QueueDisposable<Integer>)d; to.onSubscribe(d); this.d.requestFusion(QueueFuseable.ANY); } @Override public void onNext(Integer value) { // not consuming } @Override public void onError(Throwable e) { to.onError(e); } @Override public void onComplete() { to.onComplete(); } }); source.onSubscribe(Disposable.empty()); source.onNext(1); to.assertNoValues().assertNoErrors().assertComplete(); } }
TakeLast
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/diagnostics/FailureAnalyzersTests.java
{ "start": 4166, "end": 4394 }
class ____ implements FailureAnalyzer { static { Object foo = null; foo.toString(); } @Override public FailureAnalysis analyze(Throwable failure) { return null; } } static
BrokenInitializationFailureAnalyzer
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MethodCanBeStaticTest.java
{ "start": 6716, "end": 7008 }
class ____ { public String toString() { return ""; } } """) .doTest(); } @Test public void negativeSynchronized() { testHelper .addSourceLines( "Test.java", """
Test
java
quarkusio__quarkus
extensions/smallrye-metrics/runtime/src/main/java/io/quarkus/smallrye/metrics/runtime/TagHolder.java
{ "start": 334, "end": 946 }
class ____ { private String name; private String value; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public static TagHolder from(Tag tag) { TagHolder result = new TagHolder(); result.setName(tag.getTagName()); result.setValue(tag.getTagValue()); return result; } public Tag toTag() { return new Tag(name, value); } }
TagHolder
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_JSONObject.java
{ "start": 231, "end": 476 }
class ____ extends TestCase { public void test_0 () throws Exception { JSONSerializer ser = new JSONSerializer(); ser.config(SerializerFeature.WriteClassName, true); ser.write(new JSONObject()); } }
Bug_for_JSONObject
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-router/src/test/java/org/apache/hadoop/yarn/server/router/webapp/TestRouterWebAppProxy.java
{ "start": 3199, "end": 14148 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(TestRouterWebAppProxy.class); public static final String AM_PREFIX = "AM"; public static final String RM_PREFIX = "RM"; public static final String AHS_PREFIX = "AHS"; /* * Mocked Server is used for simulating the web of AppMaster, ResourceMamanger or TimelineServer. * */ private static Server mockServer; private static int mockServerPort = 0; /** * Simple http server. Server should send answer with status 200 */ @BeforeAll public static void setUp() throws Exception { mockServer = new Server(0); ((QueuedThreadPool) mockServer.getThreadPool()).setMaxThreads(20); ServletContextHandler context = new ServletContextHandler(); context.setContextPath("/"); context.addServlet(new ServletHolder(new MockWebServlet(AM_PREFIX)), "/amweb/*"); context.addServlet(new ServletHolder(new MockWebServlet(RM_PREFIX)), "/cluster/app/*"); context.addServlet(new ServletHolder(new MockWebServlet(AHS_PREFIX)), "/applicationhistory/app/*"); mockServer.setHandler(context); ((ServerConnector) mockServer.getConnectors()[0]).setHost("localhost"); mockServer.start(); mockServerPort = ((ServerConnector) mockServer.getConnectors()[0]).getLocalPort(); LOG.info("Running embedded servlet container at: http://localhost:" + mockServerPort); } @Test @Timeout(value = 10) public void testRouterWebAppProxyFed() throws Exception { Configuration conf = new Configuration(); conf.set(YarnConfiguration.ROUTER_WEBAPP_ADDRESS, "localhost:9090"); conf.setBoolean(YarnConfiguration.FEDERATION_ENABLED, true); conf.setBoolean(YarnConfiguration.APPLICATION_HISTORY_ENABLED, true); conf.set(YarnConfiguration.TIMELINE_SERVICE_WEBAPP_ADDRESS, "localhost:" + mockServerPort); // overriding num of web server threads, see HttpServer.HTTP_MAXTHREADS conf.setInt("hadoop.http.max.threads", 10); // Create sub cluster information. SubClusterId subClusterId1 = SubClusterId.newInstance("scid1"); SubClusterId subClusterId2 = SubClusterId.newInstance("scid2"); SubClusterInfo subClusterInfo1 = SubClusterInfo.newInstance(subClusterId1, "10.0.0.1:1", "10.0.0.1:1", "10.0.0.1:1", "localhost:" + mockServerPort, SubClusterState.SC_RUNNING, 0, ""); SubClusterInfo subClusterInfo2 = SubClusterInfo.newInstance(subClusterId2, "10.0.0.2:1", "10.0.0.2:1", "10.0.0.2:1", "10.0.0.2:1", SubClusterState.SC_RUNNING, 0, ""); // App1 and App2 is running applications. ApplicationId appId1 = ApplicationId.newInstance(0, 1); ApplicationId appId2 = ApplicationId.newInstance(0, 2); String appUrl1 = "http://localhost:" + mockServerPort + "/amweb/" + appId1; String proxyAppUrl1 = "http://localhost:" + mockServerPort + "/proxy/" + appId1; String appUrl2 = "http://localhost:" + mockServerPort + "/amweb/" + appId2; String proxyAppUrl2 = "http://localhost:" + mockServerPort + "/proxy/" + appId2; // App3 is accepted application, has not registered original url to am. ApplicationId appId3 = ApplicationId.newInstance(0, 3); String proxyAppUrl3 = "http://localhost:" + mockServerPort + "/proxy/" + appId3; // App4 is finished application, has remove from rm, but not remove from timeline server. ApplicationId appId4 = ApplicationId.newInstance(0, 4); String proxyAppUrl4 = "http://localhost:" + mockServerPort + "/proxy/" + appId4; // Mock for application ApplicationClientProtocol appManager1 = mock(ApplicationClientProtocol.class); when(appManager1.getApplicationReport(GetApplicationReportRequest.newInstance(appId1))) .thenReturn(GetApplicationReportResponse.newInstance( newApplicationReport(appId1, YarnApplicationState.RUNNING, proxyAppUrl1, appUrl1))); when(appManager1.getApplicationReport(GetApplicationReportRequest.newInstance(appId3))) .thenReturn(GetApplicationReportResponse.newInstance( newApplicationReport(appId3, YarnApplicationState.ACCEPTED, proxyAppUrl2, null))); ApplicationClientProtocol appManager2 = mock(ApplicationClientProtocol.class); when(appManager2.getApplicationReport(GetApplicationReportRequest.newInstance(appId2))) .thenReturn(GetApplicationReportResponse.newInstance( newApplicationReport(appId2, YarnApplicationState.RUNNING, proxyAppUrl3, appUrl2))); when(appManager2.getApplicationReport(GetApplicationReportRequest.newInstance(appId4))) .thenThrow(new ApplicationNotFoundException("APP NOT FOUND")); ApplicationHistoryProtocol historyManager = mock(ApplicationHistoryProtocol.class); when( historyManager.getApplicationReport(GetApplicationReportRequest.newInstance(appId4))) .thenReturn(GetApplicationReportResponse.newInstance( newApplicationReport(appId4, YarnApplicationState.FINISHED, proxyAppUrl4, null))); // Initial federation store. FederationStateStoreFacade facade = FederationStateStoreFacade.getInstance(conf); facade.getStateStore() .registerSubCluster(SubClusterRegisterRequest.newInstance(subClusterInfo1)); facade.getStateStore() .registerSubCluster(SubClusterRegisterRequest.newInstance(subClusterInfo2)); facade.addApplicationHomeSubCluster( ApplicationHomeSubCluster.newInstance(appId1, subClusterId1)); facade.addApplicationHomeSubCluster( ApplicationHomeSubCluster.newInstance(appId2, subClusterId2)); facade.addApplicationHomeSubCluster( ApplicationHomeSubCluster.newInstance(appId3, subClusterId1)); facade.addApplicationHomeSubCluster( ApplicationHomeSubCluster.newInstance(appId4, subClusterId2)); // Start router for test Router router = new Router(); router.init(conf); router.start(); String user = UserGroupInformation.getCurrentUser().getUserName(); RequestInterceptorChainWrapper wrapper = mock(RequestInterceptorChainWrapper.class); FederationClientInterceptor interceptor = mock(FederationClientInterceptor.class); when(interceptor.getApplicationReport(GetApplicationReportRequest.newInstance(appId1))) .thenReturn(GetApplicationReportResponse.newInstance( newApplicationReport(appId1, YarnApplicationState.RUNNING, proxyAppUrl1, appUrl1))); when(interceptor.getApplicationReport(GetApplicationReportRequest.newInstance(appId2))) .thenReturn(GetApplicationReportResponse.newInstance( newApplicationReport(appId2, YarnApplicationState.RUNNING, proxyAppUrl2, appUrl2))); when(interceptor.getApplicationReport(GetApplicationReportRequest.newInstance(appId3))) .thenReturn(GetApplicationReportResponse.newInstance( newApplicationReport(appId3, YarnApplicationState.ACCEPTED, proxyAppUrl3, null))); when(interceptor.getApplicationReport(GetApplicationReportRequest.newInstance(appId4))) .thenReturn(GetApplicationReportResponse.newInstance( newApplicationReport(appId4, YarnApplicationState.FINISHED, proxyAppUrl4, null))); when(wrapper.getRootInterceptor()).thenReturn(interceptor); router.getClientRMProxyService().getUserPipelineMap().put(user, wrapper); try { // set Mocked rm and timeline FedAppReportFetcher appReportFetcher = router.getFetcher(); appReportFetcher.registerSubCluster(subClusterInfo1, appManager1); appReportFetcher.registerSubCluster(subClusterInfo2, appManager2); appReportFetcher.setHistoryManager(historyManager); // App1 is running in subcluster1, and original url is registered in rm of subCluster1. // So router will get original url from rm by getApplicationReport. Then router // will fetch the webapp directly. GetApplicationReportResponse response = router.getClientRMProxyService() .getApplicationReport(GetApplicationReportRequest.newInstance(appId1)); URL url = new URL(response.getApplicationReport().getTrackingUrl()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); assertEquals(AM_PREFIX + "/" + appId1, readResponse(conn)); conn.disconnect(); // App2 is running in subcluster2, and original url is registered // in rm of subCluster2. So router will get original url from rm by // getApplicationReport. Then router will fetch the webapp directly. response = router.getClientRMProxyService() .getApplicationReport(GetApplicationReportRequest.newInstance(appId2)); url = new URL(response.getApplicationReport().getTrackingUrl()); conn = (HttpURLConnection) url.openConnection(); conn.connect(); assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); assertEquals(AM_PREFIX + "/" + appId2, readResponse(conn)); conn.disconnect(); // App3 is accepted in subcluster1, and original url is not registered // yet. So router will fetch the application web from rm. response = router.getClientRMProxyService() .getApplicationReport(GetApplicationReportRequest.newInstance(appId3)); url = new URL(response.getApplicationReport().getTrackingUrl()); conn = (HttpURLConnection) url.openConnection(); conn.connect(); assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); assertEquals(RM_PREFIX + "/" + appId3, readResponse(conn)); conn.disconnect(); // App4 is finished in subcluster2, and have removed from rm, but not // removed from timeline server. So rouer will fetch the // application web from timeline server. response = router.getClientRMProxyService() .getApplicationReport(GetApplicationReportRequest.newInstance(appId4)); url = new URL(response.getApplicationReport().getTrackingUrl()); conn = (HttpURLConnection) url.openConnection(); conn.connect(); assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); assertEquals(AHS_PREFIX + "/" + appId4, readResponse(conn)); conn.disconnect(); } finally { router.close(); } } private ApplicationReport newApplicationReport(ApplicationId appId, YarnApplicationState state, String trackingUrl, String origTrackingUrl) { return ApplicationReport.newInstance(appId, null, "testuser", null, null, null, 0, null, state, null, trackingUrl, 0, 0, 0, null, null, origTrackingUrl, 0f, null, null); } private String readResponse(HttpURLConnection conn) throws IOException { InputStream input = conn.getInputStream(); byte[] bytes = new byte[input.available()]; input.read(bytes); return new String(bytes); } /* * This servlet is used for simulate the web of AppMaster, ResourceManager, * TimelineServer and so on. * */ public static
TestRouterWebAppProxy
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/coordination/ElasticsearchNodeCommandTests.java
{ "start": 2292, "end": 10334 }
class ____ extends ESTestCase { public void testLoadStateWithoutMissingCustomsButPreserved() throws IOException { runLoadStateTest(false); } public void testLoadStateWithMissingCustomsButPreserved() throws IOException { runLoadStateTest(true); } @Override public Settings buildEnvSettings(Settings settings) { // we control the data path in the tests, so we don't need to set it here return settings; } private void runLoadStateTest(boolean hasMissingCustoms) throws IOException { final var dataPath = createTempDir(); final Settings settings = Settings.builder() .putList(Environment.PATH_DATA_SETTING.getKey(), List.of(dataPath.toString())) .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath()) .build(); try (var nodeEnvironment = newNodeEnvironment(settings)) { final var persistedClusterStateServiceWithFullRegistry = new PersistedClusterStateService( nodeEnvironment, xContentRegistry(), new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), () -> 0L, () -> false ); // 1. Simulating persisting cluster state by a running node final long initialTerm = randomNonNegativeLong(); final Metadata initialMetadata = randomMeta(hasMissingCustoms); final ClusterState initialState = ClusterState.builder(ClusterState.EMPTY_STATE).metadata(initialMetadata).build(); try (var writer = persistedClusterStateServiceWithFullRegistry.createWriter()) { writer.writeFullStateAndCommit(initialTerm, initialState); } // 2. Simulating loading the persisted cluster state by the CLI final var persistedClusterStateServiceForNodeCommand = ElasticsearchNodeCommand.createPersistedClusterStateService( Settings.EMPTY, new Path[] { dataPath } ); final Tuple<Long, ClusterState> loadedTermAndClusterState = ElasticsearchNodeCommand.loadTermAndClusterState( persistedClusterStateServiceForNodeCommand, TestEnvironment.newEnvironment(settings) ); assertThat(loadedTermAndClusterState.v1(), equalTo(initialTerm)); final var loadedMetadata = loadedTermAndClusterState.v2().metadata(); assertThat(loadedMetadata.clusterUUID(), not(equalTo("_na_"))); assertThat(loadedMetadata.clusterUUID(), equalTo(initialMetadata.clusterUUID())); assertThat(loadedMetadata.getProject().dataStreams(), equalTo(initialMetadata.getProject().dataStreams())); assertNotNull(loadedMetadata.getProject().custom(IndexGraveyard.TYPE)); assertThat( loadedMetadata.getProject().custom(IndexGraveyard.TYPE), instanceOf(ElasticsearchNodeCommand.UnknownProjectCustom.class) ); if (hasMissingCustoms) { assertThat( loadedMetadata.getProject().custom(TestMissingProjectCustomMetadata.TYPE), instanceOf(ElasticsearchNodeCommand.UnknownProjectCustom.class) ); assertThat( loadedMetadata.custom(TestMissingClusterCustomMetadata.TYPE), instanceOf(ElasticsearchNodeCommand.UnknownClusterCustom.class) ); } else { assertNull(loadedMetadata.getProject().custom(TestMissingProjectCustomMetadata.TYPE)); assertNull(loadedMetadata.custom(TestMissingClusterCustomMetadata.TYPE)); } final long newTerm = initialTerm + 1; try (var writer = persistedClusterStateServiceForNodeCommand.createWriter()) { writer.writeFullStateAndCommit(newTerm, ClusterState.builder(ClusterState.EMPTY_STATE).metadata(loadedMetadata).build()); } // 3. Simulate node restart after updating on-disk state with the CLI tool final var bestOnDiskState = persistedClusterStateServiceWithFullRegistry.loadBestOnDiskState(); assertThat(bestOnDiskState.currentTerm, equalTo(newTerm)); final Metadata reloadedMetadata = bestOnDiskState.metadata; assertThat(reloadedMetadata.getProject().indexGraveyard(), equalTo(initialMetadata.getProject().indexGraveyard())); if (hasMissingCustoms) { assertThat( reloadedMetadata.getProject().custom(TestMissingProjectCustomMetadata.TYPE), equalTo(initialMetadata.getProject().custom(TestMissingProjectCustomMetadata.TYPE)) ); } else { assertNull(reloadedMetadata.getProject().custom(TestMissingProjectCustomMetadata.TYPE)); } } } private Metadata randomMeta(boolean hasMissingCustoms) { Metadata.Builder mdBuilder = Metadata.builder(); mdBuilder.generateClusterUuidIfNeeded(); @FixForMultiProject(description = "Pass random project ID when usages are namespaced") ProjectMetadata.Builder projectBuilder = ProjectMetadata.builder(ProjectId.DEFAULT); int numDelIndices = randomIntBetween(0, 5); final IndexGraveyard.Builder graveyard = IndexGraveyard.builder(); for (int i = 0; i < numDelIndices; i++) { graveyard.addTombstone(new Index(randomAlphaOfLength(10) + "del-idx-" + i, UUIDs.randomBase64UUID())); } if (randomBoolean()) { int numDataStreams = randomIntBetween(0, 5); for (int i = 0; i < numDataStreams; i++) { String dataStreamName = "name" + 1; IndexMetadata backingIndex = createFirstBackingIndex(dataStreamName).build(); projectBuilder.put(newInstance(dataStreamName, List.of(backingIndex.getIndex()))); } } projectBuilder.indexGraveyard(graveyard.build()); if (hasMissingCustoms) { projectBuilder.putCustom( TestMissingProjectCustomMetadata.TYPE, new TestMissingProjectCustomMetadata("test missing project custom metadata") ); mdBuilder.putCustom( TestMissingClusterCustomMetadata.TYPE, new TestMissingClusterCustomMetadata("test missing cluster custom metadata") ); } return mdBuilder.put(projectBuilder).build(); } @Override protected NamedXContentRegistry xContentRegistry() { return new NamedXContentRegistry( Stream.of( ClusterModule.getNamedXWriteables().stream(), IndicesModule.getNamedXContents().stream(), Stream.of( new NamedXContentRegistry.Entry( Metadata.ProjectCustom.class, new ParseField(TestMissingProjectCustomMetadata.TYPE), parser -> TestMissingProjectCustomMetadata.fromXContent(TestMissingProjectCustomMetadata::new, parser) ), new NamedXContentRegistry.Entry( Metadata.ClusterCustom.class, new ParseField(TestMissingClusterCustomMetadata.TYPE), parser -> TestMissingClusterCustomMetadata.fromXContent(TestMissingClusterCustomMetadata::new, parser) ) ) ).flatMap(Function.identity()).toList() ); } // "Missing" really means _not_ registered in ElasticsearchNodeCommand's xContentRegistry so that it will be read and written // as a generic unknown project custom, see also ElasticsearchNodeCommand.UnknownProjectCustom. Note it is registered in the // full xContentRegistry used by the Elasticsearch node. That is how it got written in the first place. private static
ElasticsearchNodeCommandTests
java
grpc__grpc-java
grpclb/src/main/java/io/grpc/grpclb/GrpclbState.java
{ "start": 22717, "end": 23175 }
class ____ implements Runnable { private final Status reason; private FallbackModeTask(Status reason) { this.reason = reason; } @Override public void run() { // Timer should have been cancelled if entered fallback early. checkState(!usingFallbackBackends, "already in fallback"); fallbackReason = reason; maybeUseFallbackBackends(); maybeUpdatePicker(); } } @VisibleForTesting
FallbackModeTask
java
google__guice
core/test/com/google/inject/ProvisionExceptionTest.java
{ "start": 14361, "end": 14483 }
class ____ implements D { @Inject RealD() { throw new UnsupportedOperationException(); } } static
RealD
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 28717, "end": 28893 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return definesFunction( dialect, "json_object" ); } } public static
SupportsJsonObject
java
apache__camel
components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpBasicAuthCustomSecurityAuthenticatorTest.java
{ "start": 1444, "end": 3215 }
class ____ extends BaseNettyTest { @BindToRegistry("myAuthenticator") private MyAuthenticator auth = new MyAuthenticator(); @Test public void testBasicAuth() throws Exception { try { template.requestBody("netty-http:http://localhost:{{port}}/foo", "Hello World", String.class); fail("Should send back 401"); } catch (CamelExecutionException e) { NettyHttpOperationFailedException cause = assertIsInstanceOf(NettyHttpOperationFailedException.class, e.getCause()); assertEquals(401, cause.getStatusCode()); } // wait a little bit before next as the connection was closed when // denied String auth = "Basic c2NvdHQ6c2VjcmV0"; getMockEndpoint("mock:input").expectedBodiesReceived("Hello World"); await().atMost(500, TimeUnit.MILLISECONDS) .untilAsserted(() -> { String out = template.requestBodyAndHeader("netty-http:http://localhost:{{port}}/foo", "Hello World", "Authorization", auth, String.class); assertEquals("Bye World", out); }); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("netty-http:http://0.0.0.0:{{port}}/foo?securityConfiguration.realm=foo&securityConfiguration.securityAuthenticator=#myAuthenticator") .to("mock:input") .transform().constant("Bye World"); } }; } private static final
NettyHttpBasicAuthCustomSecurityAuthenticatorTest
java
apache__flink
flink-core/src/test/java/org/apache/flink/core/state/StateFutureTest.java
{ "start": 11312, "end": 12316 }
class ____ { AtomicInteger value = new AtomicInteger(0); ExecutorService stateExecutor = Executors.newFixedThreadPool(3); AsyncFutureImpl.CallbackRunner runner; MockValueState(ExecutorService executor) { this.runner = new TestCallbackRunner(executor); } StateFuture<Integer> get() { AsyncFutureImpl<Integer> ret = new AsyncFutureImpl<>(runner, exceptionHandler); stateExecutor.submit( () -> { int a = ThreadLocalRandom.current().nextInt(); if (a > 0) { try { Thread.sleep(a % 1000); } catch (Throwable e) { // ignore } } ret.complete(value.getAndIncrement()); }); return ret; } } private static
MockValueState
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/spi/metrics/TCPMetrics.java
{ "start": 695, "end": 812 }
interface ____<S> extends TransportMetrics<S> { @Override default String type() { return "tcp"; } }
TCPMetrics
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase/hadoop-yarn-server-timelineservice-hbase-common/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/flow/FlowActivityRowKey.java
{ "start": 4712, "end": 9817 }
class ____ implements KeyConverter<FlowActivityRowKey>, KeyConverterToString<FlowActivityRowKey> { private FlowActivityRowKeyConverter() { } /** * The flow activity row key is of the form * clusterId!dayTimestamp!user!flowName with each segment separated by !. * The sizes below indicate sizes of each one of these segements in * sequence. clusterId, user and flowName are strings. Top of the day * timestamp is a long hence 8 bytes in size. Strings are variable in size * (i.e. they end whenever separator is encountered). This is used while * decoding and helps in determining where to split. */ private static final int[] SEGMENT_SIZES = {Separator.VARIABLE_SIZE, Bytes.SIZEOF_LONG, Separator.VARIABLE_SIZE, Separator.VARIABLE_SIZE }; /* * (non-Javadoc) * * Encodes FlowActivityRowKey object into a byte array with each * component/field in FlowActivityRowKey separated by Separator#QUALIFIERS. * This leads to an flow activity table row key of the form * clusterId!dayTimestamp!user!flowName. If dayTimestamp in passed * FlowActivityRowKey object is null and clusterId is not null, then this * returns a row key prefix as clusterId! and if userId in * FlowActivityRowKey is null (and the fields preceding it i.e. clusterId * and dayTimestamp are not null), this returns a row key prefix as * clusterId!dayTimeStamp! dayTimestamp is inverted while encoding as it * helps maintain a descending order for row keys in flow activity table. * * @see org.apache.hadoop.yarn.server.timelineservice.storage.common * .KeyConverter#encode(java.lang.Object) */ @Override public byte[] encode(FlowActivityRowKey rowKey) { if (rowKey.getDayTimestamp() == null) { return Separator.QUALIFIERS.join(Separator.encode( rowKey.getClusterId(), Separator.SPACE, Separator.TAB, Separator.QUALIFIERS), Separator.EMPTY_BYTES); } if (rowKey.getUserId() == null) { return Separator.QUALIFIERS.join(Separator.encode( rowKey.getClusterId(), Separator.SPACE, Separator.TAB, Separator.QUALIFIERS), Bytes.toBytes(LongConverter .invertLong(rowKey.getDayTimestamp())), Separator.EMPTY_BYTES); } return Separator.QUALIFIERS.join(Separator.encode(rowKey.getClusterId(), Separator.SPACE, Separator.TAB, Separator.QUALIFIERS), Bytes .toBytes(LongConverter.invertLong(rowKey.getDayTimestamp())), Separator.encode(rowKey.getUserId(), Separator.SPACE, Separator.TAB, Separator.QUALIFIERS), Separator.encode(rowKey.getFlowName(), Separator.SPACE, Separator.TAB, Separator.QUALIFIERS)); } /* * (non-Javadoc) * * @see * org.apache.hadoop.yarn.server.timelineservice.storage.common * .KeyConverter#decode(byte[]) */ @Override public FlowActivityRowKey decode(byte[] rowKey) { byte[][] rowKeyComponents = Separator.QUALIFIERS.split(rowKey, SEGMENT_SIZES); if (rowKeyComponents.length != 4) { throw new IllegalArgumentException("the row key is not valid for " + "a flow activity"); } String clusterId = Separator.decode(Bytes.toString(rowKeyComponents[0]), Separator.QUALIFIERS, Separator.TAB, Separator.SPACE); Long dayTs = LongConverter.invertLong(Bytes.toLong(rowKeyComponents[1])); String userId = Separator.decode(Bytes.toString(rowKeyComponents[2]), Separator.QUALIFIERS, Separator.TAB, Separator.SPACE); String flowName = Separator.decode(Bytes.toString(rowKeyComponents[3]), Separator.QUALIFIERS, Separator.TAB, Separator.SPACE); return new FlowActivityRowKey(clusterId, dayTs, userId, flowName); } @Override public String encodeAsString(FlowActivityRowKey key) { if (key.getDayTimestamp() == null) { return TimelineReaderUtils .joinAndEscapeStrings(new String[] {key.clusterId}); } else if (key.getUserId() == null) { return TimelineReaderUtils.joinAndEscapeStrings( new String[] {key.clusterId, key.dayTs.toString()}); } else if (key.getFlowName() == null) { return TimelineReaderUtils.joinAndEscapeStrings( new String[] {key.clusterId, key.dayTs.toString(), key.userId}); } return TimelineReaderUtils.joinAndEscapeStrings(new String[] { key.clusterId, key.dayTs.toString(), key.userId, key.flowName}); } @Override public FlowActivityRowKey decodeFromString(String encodedRowKey) { List<String> split = TimelineReaderUtils.split(encodedRowKey); if (split == null || split.size() != 4) { throw new IllegalArgumentException( "Invalid row key for flow activity."); } Long dayTs = Long.valueOf(split.get(1)); return new FlowActivityRowKey(split.get(0), dayTs, split.get(2), split.get(3)); } } }
FlowActivityRowKeyConverter
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/aggregate/StringValueMax.java
{ "start": 1021, "end": 1181 }
class ____ a value aggregator that maintain the biggest of * a sequence of strings. * */ @InterfaceAudience.Public @InterfaceStability.Stable public
implements
java
apache__camel
components/camel-aws/camel-aws2-iam/src/test/java/org/apache/camel/component/aws2/iam/AmazonIAMClientMock.java
{ "start": 2979, "end": 7250 }
class ____ implements IamClient { @Override public CreateAccessKeyResponse createAccessKey(CreateAccessKeyRequest createAccessKeyRequest) { CreateAccessKeyResponse.Builder res = CreateAccessKeyResponse.builder(); AccessKey.Builder key = AccessKey.builder(); key.accessKeyId("test"); key.secretAccessKey("testSecret"); res.accessKey(key.build()); return res.build(); } @Override public CreateGroupResponse createGroup(CreateGroupRequest createGroupRequest) { CreateGroupResponse.Builder result = CreateGroupResponse.builder(); Group.Builder group = Group.builder(); group.groupName(createGroupRequest.groupName()); if (createGroupRequest.path() != null) { group.path(createGroupRequest.path()); } group.groupId("TestGroup"); result.group(group.build()); return result.build(); } @Override public CreateUserResponse createUser(CreateUserRequest createUserRequest) { CreateUserResponse.Builder result = CreateUserResponse.builder(); User.Builder user = User.builder(); user.userName("test"); result.user(user.build()); return result.build(); } @Override public DeleteAccessKeyResponse deleteAccessKey(DeleteAccessKeyRequest deleteAccessKeyRequest) { DeleteAccessKeyResponse res = DeleteAccessKeyResponse.builder().build(); return res; } @Override public DeleteGroupResponse deleteGroup(DeleteGroupRequest deleteGroupRequest) { DeleteGroupResponse result = DeleteGroupResponse.builder().build(); return result; } @Override public DeleteUserResponse deleteUser(DeleteUserRequest deleteUserRequest) { DeleteUserResponse res = DeleteUserResponse.builder().build(); return res; } @Override public GetUserResponse getUser(GetUserRequest getUserRequest) { GetUserResponse.Builder builder = GetUserResponse.builder(); User.Builder user = User.builder(); user.userName("test"); builder.user(user.build()); return builder.build(); } @Override public ListAccessKeysResponse listAccessKeys() { ListAccessKeysResponse.Builder result = ListAccessKeysResponse.builder(); Collection<AccessKeyMetadata> accessKeyMetadata = new ArrayList<>(); AccessKeyMetadata.Builder meta = AccessKeyMetadata.builder(); meta.accessKeyId("1"); meta.createDate(Instant.now()); meta.status(StatusType.ACTIVE.name()); meta.userName("test"); accessKeyMetadata.add(meta.build()); result.accessKeyMetadata(accessKeyMetadata); return result.build(); } @Override public ListGroupsResponse listGroups(ListGroupsRequest listGroupsRequest) { Group.Builder group = Group.builder(); group.groupId("TestGroup"); group.groupName("Test"); ListGroupsResponse.Builder res = ListGroupsResponse.builder(); res.groups(Collections.singleton(group.build())); return res.build(); } @Override public ListUsersResponse listUsers() { ListUsersResponse.Builder res = ListUsersResponse.builder(); List<User> list = new ArrayList<>(); User.Builder user = User.builder(); user.userName("test"); list.add(user.build()); res.users(list); return res.build(); } @Override public RemoveUserFromGroupResponse removeUserFromGroup(RemoveUserFromGroupRequest removeUserFromGroupRequest) { RemoveUserFromGroupResponse res = RemoveUserFromGroupResponse.builder().build(); return res; } @Override public UpdateAccessKeyResponse updateAccessKey(UpdateAccessKeyRequest updateAccessKeyRequest) { UpdateAccessKeyResponse result = UpdateAccessKeyResponse.builder().build(); return result; } @Override public IamServiceClientConfiguration serviceClientConfiguration() { return null; } @Override public String serviceName() { // TODO Auto-generated method stub return null; } @Override public void close() { // TODO Auto-generated method stub } }
AmazonIAMClientMock
java
resilience4j__resilience4j
resilience4j-micrometer/src/test/java/io/github/resilience4j/micrometer/tagged/TaggedBulkheadMetricsTest.java
{ "start": 1630, "end": 6980 }
class ____ { private MeterRegistry meterRegistry; private Bulkhead bulkhead; private BulkheadRegistry bulkheadRegistry; private TaggedBulkheadMetrics taggedBulkheadMetrics; @Before public void setUp() { meterRegistry = new SimpleMeterRegistry(); bulkheadRegistry = BulkheadRegistry.ofDefaults(); bulkhead = bulkheadRegistry.bulkhead("backendA"); // record some basic stats bulkhead.tryAcquirePermission(); bulkhead.tryAcquirePermission(); taggedBulkheadMetrics = TaggedBulkheadMetrics.ofBulkheadRegistry(bulkheadRegistry); taggedBulkheadMetrics.bindTo(meterRegistry); } @Test public void shouldAddMetricsForANewlyCreatedRetry() { Bulkhead newBulkhead = bulkheadRegistry.bulkhead("backendB"); assertThat(taggedBulkheadMetrics.meterIdMap).containsKeys("backendA", "backendB"); assertThat(taggedBulkheadMetrics.meterIdMap.get("backendA")).hasSize(2); assertThat(taggedBulkheadMetrics.meterIdMap.get("backendB")).hasSize(2); List<Meter> meters = meterRegistry.getMeters(); assertThat(meters).hasSize(4); Collection<Gauge> gauges = meterRegistry .get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges(); Optional<Gauge> successful = findMeterByNamesTag(gauges, newBulkhead.getName()); assertThat(successful).isPresent(); assertThat(successful.get().value()) .isEqualTo(newBulkhead.getMetrics().getMaxAllowedConcurrentCalls()); } @Test public void shouldRemovedMetricsForRemovedRetry() { List<Meter> meters = meterRegistry.getMeters(); assertThat(meters).hasSize(2); assertThat(taggedBulkheadMetrics.meterIdMap).containsKeys("backendA"); bulkheadRegistry.remove("backendA"); assertThat(taggedBulkheadMetrics.meterIdMap).isEmpty(); meters = meterRegistry.getMeters(); assertThat(meters).isEmpty(); } @Test public void shouldReplaceMetrics() { Collection<Gauge> gauges = meterRegistry .get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauges(); Optional<Gauge> successful = findMeterByNamesTag(gauges, bulkhead.getName()); assertThat(successful).isPresent(); assertThat(successful.get().value()) .isEqualTo(bulkhead.getMetrics().getMaxAllowedConcurrentCalls()); Bulkhead newBulkhead = Bulkhead.of(bulkhead.getName(), BulkheadConfig.custom() .maxConcurrentCalls(100).build()); bulkheadRegistry.replace(bulkhead.getName(), newBulkhead); gauges = meterRegistry.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME) .gauges(); successful = findMeterByNamesTag(gauges, newBulkhead.getName()); assertThat(successful).isPresent(); assertThat(successful.get().value()) .isEqualTo(newBulkhead.getMetrics().getMaxAllowedConcurrentCalls()); } @Test public void availableConcurrentCallsGaugeIsRegistered() { Gauge available = meterRegistry.get(DEFAULT_BULKHEAD_AVAILABLE_CONCURRENT_CALLS_METRIC_NAME) .gauge(); assertThat(available).isNotNull(); assertThat(available.value()) .isEqualTo(bulkhead.getMetrics().getAvailableConcurrentCalls()); } @Test public void maxAllowedConcurrentCallsGaugeIsRegistered() { Gauge maxAllowed = meterRegistry .get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).gauge(); assertThat(maxAllowed).isNotNull(); assertThat(maxAllowed.value()) .isEqualTo(bulkhead.getMetrics().getMaxAllowedConcurrentCalls()); assertThat(maxAllowed.getId().getTag(TagNames.NAME)).isEqualTo(bulkhead.getName()); } @Test public void customTagsShouldBeAdded() { Bulkhead bulkheadC = bulkheadRegistry.bulkhead("backendC", Map.of("key1", "value1")); // record some basic stats bulkheadC.tryAcquirePermission(); bulkheadC.tryAcquirePermission(); List<Meter> meters = meterRegistry.getMeters(); assertThat(meters).hasSize(4); final RequiredSearch match = meterRegistry.get(DEFAULT_BULKHEAD_MAX_ALLOWED_CONCURRENT_CALLS_METRIC_NAME).tags("key1", "value1"); assertThat(match).isNotNull(); } @Test public void customMetricNamesGetApplied() { MeterRegistry meterRegistry = new SimpleMeterRegistry(); BulkheadRegistry bulkheadRegistry = BulkheadRegistry.ofDefaults(); bulkhead = bulkheadRegistry.bulkhead("backendA"); TaggedBulkheadMetrics.ofBulkheadRegistry( BulkheadMetricNames.custom() .availableConcurrentCallsMetricName("custom_available_calls") .maxAllowedConcurrentCallsMetricName("custom_max_allowed_calls") .build(), bulkheadRegistry ).bindTo(meterRegistry); Set<String> metricNames = meterRegistry.getMeters() .stream() .map(Meter::getId) .map(Meter.Id::getName) .collect(Collectors.toSet()); assertThat(metricNames).hasSameElementsAs(Arrays.asList( "custom_available_calls", "custom_max_allowed_calls" )); } }
TaggedBulkheadMetricsTest
java
mapstruct__mapstruct
processor/src/test/resources/fixtures/org/mapstruct/ap/test/subclassmapping/fixture/SubclassAbstractMapperImpl.java
{ "start": 488, "end": 4382 }
class ____ implements SubclassAbstractMapper { @Override public AbstractParentTarget map(AbstractParentSource item) { if ( item == null ) { return null; } if (item instanceof SubSource) { return subSourceToSubTarget( (SubSource) item ); } else if (item instanceof SubSourceOther) { return subSourceOtherToSubTargetOther( (SubSourceOther) item ); } else { throw new IllegalArgumentException("Not all subclasses are supported for this mapping. Missing for " + item.getClass()); } } @Override public AbstractParentSource map(AbstractParentTarget item) { if ( item == null ) { return null; } if (item instanceof SubTargetSeparate) { return subTargetSeparateToSubSourceSeparate( (SubTargetSeparate) item ); } else if (item instanceof SubTargetOther) { return subTargetOtherToSubSourceOverride( (SubTargetOther) item ); } else if (item instanceof SubTarget) { return subTargetToSubSource( (SubTarget) item ); } else { throw new IllegalArgumentException("Not all subclasses are supported for this mapping. Missing for " + item.getClass()); } } protected SubTarget subSourceToSubTarget(SubSource subSource) { if ( subSource == null ) { return null; } SubTarget subTarget = new SubTarget(); subTarget.setParentValue( subSource.getParentValue() ); subTarget.setImplementedParentValue( subSource.getImplementedParentValue() ); subTarget.setValue( subSource.getValue() ); return subTarget; } protected SubTargetOther subSourceOtherToSubTargetOther(SubSourceOther subSourceOther) { if ( subSourceOther == null ) { return null; } String finalValue = null; finalValue = subSourceOther.getFinalValue(); SubTargetOther subTargetOther = new SubTargetOther( finalValue ); subTargetOther.setParentValue( subSourceOther.getParentValue() ); subTargetOther.setImplementedParentValue( subSourceOther.getImplementedParentValue() ); return subTargetOther; } protected SubSourceSeparate subTargetSeparateToSubSourceSeparate(SubTargetSeparate subTargetSeparate) { if ( subTargetSeparate == null ) { return null; } String separateValue = null; separateValue = subTargetSeparate.getSeparateValue(); SubSourceSeparate subSourceSeparate = new SubSourceSeparate( separateValue ); subSourceSeparate.setParentValue( subTargetSeparate.getParentValue() ); subSourceSeparate.setImplementedParentValue( subTargetSeparate.getImplementedParentValue() ); return subSourceSeparate; } protected SubSourceOverride subTargetOtherToSubSourceOverride(SubTargetOther subTargetOther) { if ( subTargetOther == null ) { return null; } String finalValue = null; finalValue = subTargetOther.getFinalValue(); SubSourceOverride subSourceOverride = new SubSourceOverride( finalValue ); subSourceOverride.setParentValue( subTargetOther.getParentValue() ); subSourceOverride.setImplementedParentValue( subTargetOther.getImplementedParentValue() ); return subSourceOverride; } protected SubSource subTargetToSubSource(SubTarget subTarget) { if ( subTarget == null ) { return null; } SubSource subSource = new SubSource(); subSource.setParentValue( subTarget.getParentValue() ); subSource.setImplementedParentValue( subTarget.getImplementedParentValue() ); subSource.setValue( subTarget.getValue() ); return subSource; } }
SubclassAbstractMapperImpl
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StringFormatWithLiteralTest.java
{ "start": 9310, "end": 9592 }
class ____ { String test() { return String.format("Formatting this string: %s;Integer: %d", "data", 1); } } """) .addOutputLines( "ExampleClass.java", """ public
ExampleClass
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/IntArrayFieldTest_primitive.java
{ "start": 246, "end": 1248 }
class ____ extends TestCase { public void test_array() throws Exception { Assert.assertEquals("[1]", JSON.toJSONString(new int[] { 1 })); } public void test_codec_null() throws Exception { V0 v = new V0(); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue); Assert.assertEquals("{\"value\":null}", text); V0 v1 = JSON.parseObject(text, V0.class); Assert.assertEquals(v1.getValue(), v.getValue()); } public void test_codec_null_1() throws Exception { V0 v = new V0(); SerializeConfig mapping = new SerializeConfig(); mapping.setAsmEnable(false); String text = JSON.toJSONString(v, mapping, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty); Assert.assertEquals("{\"value\":[]}", text); } public static
IntArrayFieldTest_primitive
java
netty__netty
common/src/test/java/io/netty/util/internal/TypeParameterMatcherTest.java
{ "start": 2995, "end": 3101 }
class ____<D extends C, E extends A, F extends B> extends TypeX<E, F, D> { } public abstract static
TypeY
java
spring-projects__spring-boot
module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializer.java
{ "start": 9298, "end": 10736 }
class ____ implements ApplicationListener<ApplicationEvent> { private final ApplicationContext parentContext; private final ConfigurableApplicationContext childContext; CloseManagementContextListener(ApplicationContext parentContext, ConfigurableApplicationContext childContext) { this.parentContext = parentContext; this.childContext = childContext; } @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationFailedEvent applicationFailedEvent) { onApplicationFailedEvent(applicationFailedEvent); } } private void onApplicationFailedEvent(ApplicationFailedEvent event) { propagateCloseIfNecessary(event.getApplicationContext()); } private void propagateCloseIfNecessary(@Nullable ApplicationContext applicationContext) { if (applicationContext == this.parentContext) { this.childContext.close(); } } static void addIfPossible(ApplicationContext parentContext, ConfigurableApplicationContext childContext) { if (parentContext instanceof ConfigurableApplicationContext configurableApplicationContext) { add(configurableApplicationContext, childContext); } } private static void add(ConfigurableApplicationContext parentContext, ConfigurableApplicationContext childContext) { parentContext.addApplicationListener(new CloseManagementContextListener(parentContext, childContext)); } } }
CloseManagementContextListener
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByCheckerTest.java
{ "start": 2575, "end": 3113 }
class ____ { @GuardedBy("Test.class") static int x; static synchronized void m() { x++; } } """) .doTest(); } @Test public void monitor() { compilationHelper .addSourceLines( "threadsafety/Test.java", """ package threadsafety; import com.google.errorprone.annotations.concurrent.GuardedBy; import com.google.common.util.concurrent.Monitor;
Test
java
apache__flink
flink-kubernetes/src/main/java/org/apache/flink/kubernetes/kubeclient/parameters/AbstractKubernetesParameters.java
{ "start": 1883, "end": 7631 }
class ____ implements KubernetesParameters { protected final Configuration flinkConfig; public AbstractKubernetesParameters(Configuration flinkConfig) { this.flinkConfig = checkNotNull(flinkConfig); } public Configuration getFlinkConfiguration() { return flinkConfig; } @Override public String getConfigDirectory() { final String configDir = flinkConfig .getOptional(DeploymentOptionsInternal.CONF_DIR) .orElse(flinkConfig.get(KubernetesConfigOptions.FLINK_CONF_DIR)); checkNotNull(configDir); return configDir; } @Override public String getClusterId() { final String clusterId = flinkConfig.get(KubernetesConfigOptions.CLUSTER_ID); if (StringUtils.isBlank(clusterId)) { throw new IllegalArgumentException( KubernetesConfigOptions.CLUSTER_ID.key() + " must not be blank."); } else if (clusterId.length() > Constants.MAXIMUM_CHARACTERS_OF_CLUSTER_ID) { throw new IllegalArgumentException( KubernetesConfigOptions.CLUSTER_ID.key() + " must be no more than " + Constants.MAXIMUM_CHARACTERS_OF_CLUSTER_ID + " characters."); } return clusterId; } @Override public String getNamespace() { final String namespace = flinkConfig.get(KubernetesConfigOptions.NAMESPACE); checkArgument( !namespace.trim().isEmpty(), "Invalid " + KubernetesConfigOptions.NAMESPACE + "."); return namespace; } @Override public String getImage() { final String containerImage = flinkConfig.get(KubernetesConfigOptions.CONTAINER_IMAGE); checkArgument( !containerImage.trim().isEmpty(), "Invalid " + KubernetesConfigOptions.CONTAINER_IMAGE + "."); return containerImage; } @Override public KubernetesConfigOptions.ImagePullPolicy getImagePullPolicy() { return flinkConfig.get(KubernetesConfigOptions.CONTAINER_IMAGE_PULL_POLICY); } @Override public LocalObjectReference[] getImagePullSecrets() { final List<String> imagePullSecrets = flinkConfig.get(CONTAINER_IMAGE_PULL_SECRETS); if (imagePullSecrets == null) { return new LocalObjectReference[0]; } else { return imagePullSecrets.stream() .map(String::trim) .filter(secret -> !secret.isEmpty()) .map(LocalObjectReference::new) .toArray(LocalObjectReference[]::new); } } @Override public Map<String, String> getCommonLabels() { return Collections.unmodifiableMap(KubernetesUtils.getCommonLabels(getClusterId())); } @Override public String getFlinkConfDirInPod() { return flinkConfig.get(KubernetesConfigOptions.FLINK_CONF_DIR); } @Override public Optional<String> getFlinkLogDirInPod() { return Optional.ofNullable(flinkConfig.get(KubernetesConfigOptions.FLINK_LOG_DIR)); } @Override public String getContainerEntrypoint() { return flinkConfig.get(KubernetesConfigOptions.KUBERNETES_ENTRY_PATH); } @Override public boolean hasLogback() { final String confDir = getConfigDirectory(); final File logbackFile = new File(confDir, CONFIG_FILE_LOGBACK_NAME); return logbackFile.exists(); } @Override public boolean hasLog4j() { final String confDir = getConfigDirectory(); final File log4jFile = new File(confDir, CONFIG_FILE_LOG4J_NAME); return log4jFile.exists(); } @Override public Optional<String> getExistingHadoopConfigurationConfigMap() { final String existingHadoopConfigMap = flinkConfig.get(KubernetesConfigOptions.HADOOP_CONF_CONFIG_MAP); if (StringUtils.isBlank(existingHadoopConfigMap)) { return Optional.empty(); } else { return Optional.of(existingHadoopConfigMap.trim()); } } @Override public Optional<String> getLocalHadoopConfigurationDirectory() { final String hadoopConfDirEnv = System.getenv(Constants.ENV_HADOOP_CONF_DIR); if (StringUtils.isNotBlank(hadoopConfDirEnv)) { return Optional.of(hadoopConfDirEnv); } final String hadoopHomeEnv = System.getenv(Constants.ENV_HADOOP_HOME); if (StringUtils.isNotBlank(hadoopHomeEnv)) { // Hadoop 2.2+ final File hadoop2ConfDir = new File(hadoopHomeEnv, "/etc/hadoop"); if (hadoop2ConfDir.exists()) { return Optional.of(hadoop2ConfDir.getAbsolutePath()); } // Hadoop 1.x final File hadoop1ConfDir = new File(hadoopHomeEnv, "/conf"); if (hadoop1ConfDir.exists()) { return Optional.of(hadoop1ConfDir.getAbsolutePath()); } } return Optional.empty(); } public Map<String, String> getSecretNamesToMountPaths() { return flinkConfig .getOptional(KubernetesConfigOptions.KUBERNETES_SECRETS) .orElse(Collections.emptyMap()); } @Override public List<Map<String, String>> getEnvironmentsFromSecrets() { return flinkConfig .getOptional(KubernetesConfigOptions.KUBERNETES_ENV_SECRET_KEY_REF) .orElse(Collections.emptyList()); } public boolean isHostNetworkEnabled() { return flinkConfig.get(KubernetesConfigOptions.KUBERNETES_HOSTNETWORK_ENABLED); } }
AbstractKubernetesParameters
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/JpaqlStrictComplianceAliasTest.java
{ "start": 748, "end": 1499 }
class ____ { @Test public void testAlias(SessionFactoryScope scope) { scope.inTransaction( session -> session.createQuery( "select p.stockNumber as stockNo FROM Part p ORDER BY stockNo" ) .getResultList() ); } @Test public void testAlias2(SessionFactoryScope scope) { scope.inTransaction( session -> session.createQuery( "select p.stockNumber as stockNo FROM Part P ORDER BY stockNo" ) .getResultList() ); } @Test public void testAlias3(SessionFactoryScope scope) { scope.inTransaction( session -> session.createQuery( "select P.stockNumber as stockNo FROM Part P ORDER BY stockNo" ) .getResultList() ); } @Entity(name = "Part") public static
JpaqlStrictComplianceAliasTest
java
grpc__grpc-java
core/src/main/java/io/grpc/internal/RetriableStream.java
{ "start": 24308, "end": 24648 }
class ____ implements BufferEntry { @Override public void runWith(Substream substream) { substream.stream.setMaxInboundMessageSize(maxSize); } } delayOrExecute(new MaxInboundMessageSizeEntry()); } @Override public final void setMaxOutboundMessageSize(final int maxSize) {
MaxInboundMessageSizeEntry
java
apache__camel
components/camel-xchange/src/main/java/org/apache/camel/component/xchange/XChangeConfiguration.java
{ "start": 1177, "end": 1296 }
enum ____ { marketdata, metadata, account } // Available methods public
XChangeService
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/AbstractMavenLifecycleParticipant.java
{ "start": 1318, "end": 2965 }
class ____ { /** * Invoked after all MavenProject instances have been created. * * This callback is intended to allow extensions to manipulate MavenProjects * before they are sorted and actual build execution starts. * * @param session the Maven session * @throws MavenExecutionException in case of issue */ public void afterProjectsRead(MavenSession session) throws MavenExecutionException { // do nothing } /** * Invoked after MavenSession instance has been created. * * This callback is intended to allow extensions to inject execution properties, * activate profiles and perform similar tasks that affect MavenProject * instance construction. * * @param session the Maven session * @throws MavenExecutionException in case of issue */ // TODO This is too early for build extensions, so maybe just remove it? public void afterSessionStart(MavenSession session) throws MavenExecutionException { // do nothing } /** * Invoked after all projects were built. * * This callback is intended to allow extensions to perform cleanup of any * allocated external resources after the build. It is invoked on best-effort * basis and may be missed due to an Error or RuntimeException in Maven core * code. * * @param session the Maven session * @throws MavenExecutionException in case of issue * @since 3.2.1, MNG-5389 */ public void afterSessionEnd(MavenSession session) throws MavenExecutionException { // do nothing } }
AbstractMavenLifecycleParticipant
java
apache__dubbo
dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java
{ "start": 1593, "end": 12028 }
class ____ { @BeforeEach public void setUp() { DubboBootstrap.reset(); SysProps.clear(); SysProps.setProperty("dubbo.metrics.enabled", "false"); SysProps.setProperty("dubbo.metrics.protocol", "disabled"); } @AfterEach public void afterEach() { SysProps.clear(); DubboBootstrap.reset(); } @Test void testTimeout() { SystemPropertyConfigUtils.clearSystemProperty(SYSTEM_TCP_RESPONSE_TIMEOUT); ConsumerConfig consumer = new ConsumerConfig(); consumer.setTimeout(10); assertThat(consumer.getTimeout(), is(10)); assertThat(SystemPropertyConfigUtils.getSystemProperty(SYSTEM_TCP_RESPONSE_TIMEOUT), equalTo("10")); } @Test void testDefault() throws Exception { ConsumerConfig consumer = new ConsumerConfig(); consumer.setDefault(true); assertThat(consumer.isDefault(), is(true)); } @Test void testClient() { ConsumerConfig consumer = new ConsumerConfig(); consumer.setClient("client"); assertThat(consumer.getClient(), equalTo("client")); } @Test void testThreadpool() { ConsumerConfig consumer = new ConsumerConfig(); consumer.setThreadpool("fixed"); assertThat(consumer.getThreadpool(), equalTo("fixed")); } @Test void testCorethreads() { ConsumerConfig consumer = new ConsumerConfig(); consumer.setCorethreads(10); assertThat(consumer.getCorethreads(), equalTo(10)); } @Test void testThreads() { ConsumerConfig consumer = new ConsumerConfig(); consumer.setThreads(20); assertThat(consumer.getThreads(), equalTo(20)); } @Test void testQueues() { ConsumerConfig consumer = new ConsumerConfig(); consumer.setQueues(5); assertThat(consumer.getQueues(), equalTo(5)); } @Test void testOverrideConfigSingle() { SysProps.setProperty("dubbo.consumer.check", "false"); SysProps.setProperty("dubbo.consumer.group", "demo"); SysProps.setProperty("dubbo.consumer.threads", "10"); ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setGroup("groupA"); consumerConfig.setThreads(20); consumerConfig.setCheck(true); DubboBootstrap.getInstance() .application("demo-app") .consumer(consumerConfig) .initialize(); Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel() .getDefaultModule() .getConfigManager() .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(false, consumerConfig.isCheck()); Assertions.assertEquals("demo", consumerConfig.getGroup()); Assertions.assertEquals(10, consumerConfig.getThreads()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigByPluralityId() { SysProps.setProperty("dubbo.consumer.group", "demoA"); // ignore SysProps.setProperty("dubbo.consumers.consumerA.check", "false"); SysProps.setProperty("dubbo.consumers.consumerA.group", "demoB"); SysProps.setProperty("dubbo.consumers.consumerA.threads", "10"); ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setId("consumerA"); consumerConfig.setGroup("groupA"); consumerConfig.setThreads(20); consumerConfig.setCheck(true); DubboBootstrap.getInstance() .application("demo-app") .consumer(consumerConfig) .initialize(); Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel() .getDefaultModule() .getConfigManager() .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(false, consumerConfig.isCheck()); Assertions.assertEquals("demoB", consumerConfig.getGroup()); Assertions.assertEquals(10, consumerConfig.getThreads()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigBySingularId() { // override success SysProps.setProperty("dubbo.consumer.group", "demoA"); SysProps.setProperty("dubbo.consumer.threads", "15"); // ignore singular format: dubbo.{tag-name}.{config-id}.{config-item}={config-value} SysProps.setProperty("dubbo.consumer.consumerA.check", "false"); SysProps.setProperty("dubbo.consumer.consumerA.group", "demoB"); SysProps.setProperty("dubbo.consumer.consumerA.threads", "10"); ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setId("consumerA"); consumerConfig.setGroup("groupA"); consumerConfig.setThreads(20); consumerConfig.setCheck(true); DubboBootstrap.getInstance() .application("demo-app") .consumer(consumerConfig) .initialize(); Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel() .getDefaultModule() .getConfigManager() .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(true, consumerConfig.isCheck()); Assertions.assertEquals("demoA", consumerConfig.getGroup()); Assertions.assertEquals(15, consumerConfig.getThreads()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigByDubboProps() { ApplicationModel.defaultModel().getDefaultModule(); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperty("dubbo.consumers.consumerA.check", "false"); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperty("dubbo.consumers.consumerA.group", "demo"); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperty("dubbo.consumers.consumerA.threads", "10"); try { ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setId("consumerA"); consumerConfig.setGroup("groupA"); DubboBootstrap.getInstance() .application("demo-app") .consumer(consumerConfig) .initialize(); Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel() .getDefaultModule() .getConfigManager() .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(false, consumerConfig.isCheck()); Assertions.assertEquals("groupA", consumerConfig.getGroup()); Assertions.assertEquals(10, consumerConfig.getThreads()); } finally { ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .refresh(); DubboBootstrap.getInstance().destroy(); } } @Test void testReferenceAndConsumerConfigOverlay() { SysProps.setProperty("dubbo.consumer.group", "demo"); SysProps.setProperty("dubbo.consumer.threads", "12"); SysProps.setProperty("dubbo.consumer.timeout", "1234"); SysProps.setProperty("dubbo.consumer.init", "false"); SysProps.setProperty("dubbo.consumer.check", "false"); SysProps.setProperty("dubbo.registry.address", "N/A"); ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setInterface(DemoService.class); DubboBootstrap.getInstance() .application("demo-app") .reference(referenceConfig) .initialize(); Assertions.assertEquals("demo", referenceConfig.getGroup()); Assertions.assertEquals(1234, referenceConfig.getTimeout()); Assertions.assertEquals(false, referenceConfig.isInit()); Assertions.assertEquals(false, referenceConfig.isCheck()); DubboBootstrap.getInstance().destroy(); } @Test void testMetaData() { ConsumerConfig consumerConfig = new ConsumerConfig(); Map<String, String> metaData = consumerConfig.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } @Test void testSerialize() { ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setCorethreads(1); consumerConfig.setQueues(1); consumerConfig.setThreads(1); consumerConfig.setThreadpool("Mock"); consumerConfig.setGroup("Test"); consumerConfig.setMeshEnable(false); consumerConfig.setReferThreadNum(2); consumerConfig.setShareconnections(2); consumerConfig.setTimeout(2); consumerConfig.setUrlMergeProcessor("test"); consumerConfig.setReferBackground(false); consumerConfig.setActives(1); consumerConfig.setAsync(false); consumerConfig.setCache("false"); consumerConfig.setCallbacks(1); consumerConfig.setConnections(1); consumerConfig.setInterfaceClassLoader(Thread.currentThread().getContextClassLoader()); consumerConfig.setApplication(new ApplicationConfig()); consumerConfig.setRegistries(Collections.singletonList(new RegistryConfig())); consumerConfig.setModule(new ModuleConfig()); consumerConfig.setMetadataReportConfig(new MetadataReportConfig()); consumerConfig.setMonitor(new MonitorConfig()); consumerConfig.setConfigCenter(new ConfigCenterConfig()); try { JsonUtils.toJson(consumerConfig); } catch (Throwable t) { Assertions.fail(t); } } }
ConsumerConfigTest
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/FactoryFinder.java
{ "start": 1520, "end": 1688 }
class ____ using the key to lookup * * @param key is the key to add to the path to find a text file containing the factory name * @param type the
instance
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecMultipleInput.java
{ "start": 4315, "end": 13414 }
class ____ extends ExecNodeBase<RowData> implements BatchExecNode<RowData>, SingleTransformationTranslator<RowData> { private final ExecNode<?> rootNode; private final List<ExecNode<?>> memberExecNodes; private final List<ExecEdge> originalEdges; public BatchExecMultipleInput( ReadableConfig tableConfig, List<InputProperty> inputProperties, ExecNode<?> rootNode, List<ExecNode<?>> memberExecNodes, List<ExecEdge> originalEdges, String description) { super( ExecNodeContext.newNodeId(), ExecNodeContext.newContext(BatchExecMultipleInput.class), ExecNodeContext.newPersistedConfig(BatchExecMultipleInput.class, tableConfig), inputProperties, rootNode.getOutputType(), description); this.rootNode = rootNode; this.memberExecNodes = memberExecNodes; checkArgument(inputProperties.size() == originalEdges.size()); this.originalEdges = originalEdges; } @Override protected Transformation<RowData> translateToPlanInternal( PlannerBase planner, ExecNodeConfig config) { List<Transformation<?>> inputTransforms = new ArrayList<>(); for (ExecEdge inputEdge : getInputEdges()) { inputTransforms.add(inputEdge.translateToPlan(planner)); } final Transformation<?> outputTransform = rootNode.translateToPlan(planner); final int[] readOrders = getInputProperties().stream() .map(InputProperty::getPriority) .mapToInt(i -> i) .toArray(); StreamOperatorFactory<RowData> operatorFactory; int parallelism; int maxParallelism; long memoryBytes; ResourceSpec minResources = null; ResourceSpec preferredResources = null; boolean fusionCodegenEnabled = config.get(TABLE_EXEC_OPERATOR_FUSION_CODEGEN_ENABLED); // multiple operator fusion codegen if (fusionCodegenEnabled && allSupportFusionCodegen()) { final List<InputSelectionSpec> inputSelectionSpecs = new ArrayList<>(); int i = 0; for (ExecEdge inputEdge : originalEdges) { int multipleInputId = i + 1; BatchExecNode<RowData> source = (BatchExecNode<RowData>) inputEdge.getSource(); BatchExecInputAdapter inputAdapter = new BatchExecInputAdapter( multipleInputId, TableConfig.getDefault(), InputProperty.builder().priority(readOrders[i]).build(), source.getOutputType(), "BatchInputAdapter"); inputAdapter.setInputEdges( Collections.singletonList( ExecEdge.builder().source(source).target(inputAdapter).build())); BatchExecNode<RowData> target = (BatchExecNode<RowData>) inputEdge.getTarget(); int edgeIdxInTargetNode = target.getInputEdges().indexOf(inputEdge); checkArgument(edgeIdxInTargetNode >= 0); target.replaceInputEdge( edgeIdxInTargetNode, ExecEdge.builder().source(inputAdapter).target(target).build()); // The input id and read order inputSelectionSpecs.add(new InputSelectionSpec(multipleInputId, readOrders[i])); i++; } // Create a parent CodeGeneratorContext to ensure that all codes in multiple operator // fusion codegen share the same ancestors CodeGeneratorContext. This way, we can // avoid naming conflicts. CodeGeneratorContext parentCtx = new CodeGeneratorContext(config, planner.getFlinkContext().getClassLoader()); OpFusionCodegenSpecGenerator inputGenerator = rootNode.translateToFusionCodegenSpec(planner, parentCtx); // wrap output operator spec generator of fusion codegen OpFusionCodegenSpecGenerator outputGenerator = new OneInputOpFusionCodegenSpecGenerator( inputGenerator, 0L, (RowType) getOutputType(), new OutputFusionCodegenSpec( new CodeGeneratorContext( config, planner.getFlinkContext().getClassLoader(), parentCtx))); inputGenerator.addOutput(1, outputGenerator); // generate fusion operator Tuple2<OperatorFusionCodegenFactory<RowData>, Object> multipleOperatorTuple = FusionCodegenUtil.generateFusionOperator( outputGenerator, inputSelectionSpecs, parentCtx); operatorFactory = multipleOperatorTuple._1; Pair<Integer, Integer> parallelismPair = getInputMaxParallelism(inputTransforms); parallelism = parallelismPair.getLeft(); maxParallelism = parallelismPair.getRight(); memoryBytes = (long) multipleOperatorTuple._2; } else { final TableOperatorWrapperGenerator generator = new TableOperatorWrapperGenerator(inputTransforms, outputTransform, readOrders); generator.generate(); final List<Pair<Transformation<?>, InputSpec>> inputTransformAndInputSpecPairs = generator.getInputTransformAndInputSpecPairs(); operatorFactory = new BatchMultipleInputStreamOperatorFactory( inputTransformAndInputSpecPairs.stream() .map(Pair::getValue) .collect(Collectors.toList()), generator.getHeadWrappers(), generator.getTailWrapper()); parallelism = generator.getParallelism(); maxParallelism = generator.getMaxParallelism(); final int memoryWeight = generator.getManagedMemoryWeight(); memoryBytes = (long) memoryWeight << 20; minResources = generator.getMinResources(); preferredResources = generator.getPreferredResources(); // here set the all elements of InputTransformation and its id index indicates the order inputTransforms = inputTransformAndInputSpecPairs.stream() .map(Pair::getKey) .collect(Collectors.toList()); } final MultipleInputTransformation<RowData> multipleInputTransform = new MultipleInputTransformation<>( createTransformationName(config), operatorFactory, InternalTypeInfo.of(getOutputType()), parallelism, false); multipleInputTransform.setDescription(createTransformationDescription(config)); if (maxParallelism > 0) { multipleInputTransform.setMaxParallelism(maxParallelism); } for (Transformation input : inputTransforms) { multipleInputTransform.addInput(input); } // set resources if (minResources != null && preferredResources != null) { multipleInputTransform.setResources(minResources, preferredResources); } multipleInputTransform.setDescription(createTransformationDescription(config)); ExecNodeUtil.setManagedMemoryWeight(multipleInputTransform, memoryBytes); // set chaining strategy for source chaining multipleInputTransform.setChainingStrategy(ChainingStrategy.HEAD_WITH_SOURCES); return multipleInputTransform; } public List<ExecEdge> getOriginalEdges() { return originalEdges; } public List<ExecNode<?>> getMemberExecNodes() { return memberExecNodes; } @VisibleForTesting public ExecNode<?> getRootNode() { return rootNode; } private boolean allSupportFusionCodegen() { return memberExecNodes.stream() .map(ExecNode::supportFusionCodegen) .reduce(true, (n1, n2) -> n1 && n2); } private Pair<Integer, Integer> getInputMaxParallelism( List<Transformation<?>> inputTransformations) { int parallelism = -1; int maxParallelism = -1; for (Transformation<?> transform : inputTransformations) { parallelism = Math.max(parallelism, transform.getParallelism()); maxParallelism = Math.max(maxParallelism, transform.getMaxParallelism()); } return Pair.of(parallelism, maxParallelism); } }
BatchExecMultipleInput
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerPollStrategyPolledMessagesTest.java
{ "start": 1471, "end": 2863 }
class ____ extends ContextTestSupport { private static int maxPolls; private final CountDownLatch latch = new CountDownLatch(1); @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("myPoll", new MyPollStrategy()); return jndi; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(fileUri("?pollStrategy=#myPoll&initialDelay=0&delay=10")).routeId("foo").autoStartup(false) .convertBodyTo(String.class).to("mock:result"); } }; } @Test public void testPolledMessages() throws Exception { template.sendBodyAndHeader(fileUri(), "Hello World", Exchange.FILE_NAME, "hello.txt"); template.sendBodyAndHeader(fileUri(), "Bye World", Exchange.FILE_NAME, "bye.txt"); // start route now files have been created context.getRouteController().startRoute("foo"); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(2); assertMockEndpointsSatisfied(); // wait for commit to be issued assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(2, maxPolls); } private
FileConsumerPollStrategyPolledMessagesTest
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/domain/retail/Vendor.java
{ "start": 609, "end": 1707 }
class ____ { private Integer id; private String name; private String billingEntity; private String supplementalDetail; public Vendor() { } public Vendor(Integer id, String name, String billingEntity) { this.id = id; this.name = name; this.billingEntity = billingEntity; } public Vendor(Integer id, String name, String billingEntity, String supplementalDetail) { this.id = id; this.name = name; this.billingEntity = billingEntity; this.supplementalDetail = supplementalDetail; } @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBillingEntity() { return billingEntity; } public void setBillingEntity(String billingEntity) { this.billingEntity = billingEntity; } @Column(table = "vendor_supp") public String getSupplementalDetail() { return supplementalDetail; } public void setSupplementalDetail(String supplementalDetail) { this.supplementalDetail = supplementalDetail; } }
Vendor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/ElementCollectionInOneToManyTest.java
{ "start": 2565, "end": 2756 }
class ____ { @Id @GeneratedValue long id; String name; @OneToMany(cascade = CascadeType.ALL) List<Book> books = new ArrayList<>(); } @Entity(name = "Book") public static
Author
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/InternalTopicConfig.java
{ "start": 1225, "end": 4248 }
class ____ { final String name; final Map<String, String> topicConfigs; final boolean enforceNumberOfPartitions; private Optional<Integer> numberOfPartitions = Optional.empty(); static final Map<String, String> INTERNAL_TOPIC_DEFAULT_OVERRIDES = new HashMap<>(); static { INTERNAL_TOPIC_DEFAULT_OVERRIDES.put(TopicConfig.MESSAGE_TIMESTAMP_TYPE_CONFIG, "CreateTime"); } InternalTopicConfig(final String name, final Map<String, String> topicConfigs) { this.name = Objects.requireNonNull(name, "name can't be null"); Topic.validate(name); this.topicConfigs = Objects.requireNonNull(topicConfigs, "topicConfigs can't be null"); this.enforceNumberOfPartitions = false; } InternalTopicConfig(final String name, final Map<String, String> topicConfigs, final int numberOfPartitions, final boolean enforceNumberOfPartitions) { this.name = Objects.requireNonNull(name, "name can't be null"); Topic.validate(name); validateNumberOfPartitions(numberOfPartitions); this.topicConfigs = Objects.requireNonNull(topicConfigs, "topicConfigs can't be null"); this.numberOfPartitions = Optional.of(numberOfPartitions); this.enforceNumberOfPartitions = enforceNumberOfPartitions; } /** * Get the configured properties for this topic. If retentionMs is set then * we add additionalRetentionMs to work out the desired retention when cleanup.policy=compact,delete * * @param additionalRetentionMs - added to retention to allow for clock drift etc * @return Properties to be used when creating the topic */ public abstract Map<String, String> properties(final Map<String, String> defaultProperties, final long additionalRetentionMs); public boolean hasEnforcedNumberOfPartitions() { return enforceNumberOfPartitions; } public String name() { return name; } public Optional<Integer> numberOfPartitions() { return numberOfPartitions; } public void setNumberOfPartitions(final int numberOfPartitions) { if (hasEnforcedNumberOfPartitions()) { throw new UnsupportedOperationException("number of partitions are enforced on topic " + name() + " and can't be altered."); } validateNumberOfPartitions(numberOfPartitions); this.numberOfPartitions = Optional.of(numberOfPartitions); } private static void validateNumberOfPartitions(final int numberOfPartitions) { if (numberOfPartitions < 1) { throw new IllegalArgumentException("Number of partitions must be at least 1."); } } @Override public String toString() { return "InternalTopicConfig(" + "name=" + name + ", topicConfigs=" + topicConfigs + ", enforceNumberOfPartitions=" + enforceNumberOfPartitions + ")"; } }
InternalTopicConfig
java
google__guava
guava/src/com/google/common/util/concurrent/FuturesGetChecked.java
{ "start": 4391, "end": 4684 }
class ____ { static final String CLASS_VALUE_VALIDATOR_NAME = GetCheckedTypeValidatorHolder.class.getName() + "$ClassValueValidator"; static final GetCheckedTypeValidator BEST_VALIDATOR = getBestValidator(); @J2ObjCIncompatible // ClassValue
GetCheckedTypeValidatorHolder
java
google__guava
guava/src/com/google/common/hash/LittleEndianByteArray.java
{ "start": 5460, "end": 6367 }
enum ____ implements LittleEndianBytes { INSTANCE { @Override public long getLongLittleEndian(byte[] array, int offset) { return (long) HANDLE.get(array, offset); } @Override public void putLongLittleEndian(byte[] array, int offset, long value) { HANDLE.set(array, offset, value); } }; @Override public boolean usesFastPath() { return true; } /* * non-private so that our `-source 8` build doesn't need to generate a synthetic accessor * method, whose mention of VarHandle would upset WriteReplaceOverridesTest under Java 8. */ static final VarHandle HANDLE = byteArrayViewVarHandle(long[].class, LITTLE_ENDIAN); } /** * The only reference to Unsafe is in this nested class. We set things up so that if * Unsafe.theUnsafe is inaccessible, the attempt to load the nested
VarHandleLittleEndianBytes
java
quarkusio__quarkus
extensions/jackson/runtime/src/main/java/io/quarkus/jackson/runtime/VertxHybridPoolObjectMapperCustomizer.java
{ "start": 259, "end": 876 }
class ____ implements ObjectMapperCustomizer { @Override public void customize(ObjectMapper objectMapper) { var existingMapperPool = objectMapper.getFactory()._getRecyclerPool(); // if the recycler pool in use is the default jackson one it means that user hasn't // explicitly chosen any, so we can replace it with the vert.x virtual thread friendly one if (existingMapperPool.getClass() == JsonRecyclerPools.defaultPool().getClass()) { objectMapper.getFactory().setRecyclerPool(HybridJacksonPool.getInstance()); } } }
VertxHybridPoolObjectMapperCustomizer
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/invocation/InvocationMarker.java
{ "start": 348, "end": 1064 }
class ____ { private InvocationMarker() {} public static void markVerified(List<Invocation> invocations, MatchableInvocation wanted) { for (Invocation invocation : invocations) { markVerified(invocation, wanted); } } public static void markVerified(Invocation invocation, MatchableInvocation wanted) { invocation.markVerified(); wanted.captureArgumentsFrom(invocation); } public static void markVerifiedInOrder( List<Invocation> chunk, MatchableInvocation wanted, InOrderContext context) { markVerified(chunk, wanted); for (Invocation i : chunk) { context.markVerified(i); } } }
InvocationMarker
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/spi/LoggerRegistry.java
{ "start": 2762, "end": 3554 }
class ____<T extends ExtendedLogger> implements MapFactory<T> { @Override public Map<String, T> createInnerMap() { return new ConcurrentHashMap<>(); } @Override public Map<String, Map<String, T>> createOuterMap() { return new ConcurrentHashMap<>(); } @Override public void putIfAbsent(final Map<String, T> innerMap, final String name, final T logger) { innerMap.putIfAbsent(name, logger); } } /** * {@link MapFactory} implementation using {@link WeakHashMap}. * * @param <T> subtype of {@code ExtendedLogger} * @since 2.6 * @deprecated As of version {@code 2.25.0}, planned to be removed! */ @Deprecated public static
ConcurrentMapFactory
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/SynchronousCheckpointTest.java
{ "start": 4942, "end": 5729 }
class ____ extends NoOpStreamTask { private Queue<Event> eventQueue; private volatile boolean stopped; StreamTaskUnderTest(final Environment env, Queue<Event> eventQueue) throws Exception { super(env); this.eventQueue = checkNotNull(eventQueue); } @Override protected void init() { eventQueue.add(Event.TASK_INITIALIZED); } @Override protected void processInput(MailboxDefaultAction.Controller controller) throws Exception { if (stopped || isCanceled()) { controller.suspendDefaultAction(); mailboxProcessor.suspend(); } } void stopTask() { stopped = true; } } }
StreamTaskUnderTest
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-reactive-oauth2-resource-server/src/test/java/smoketest/oauth2/resource/SampleReactiveOAuth2ResourceServerApplicationTests.java
{ "start": 1336, "end": 4989 }
class ____ { @Autowired private WebTestClient webTestClient; private static final MockWebServer server = new MockWebServer(); private static final String VALID_TOKEN = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJzdWJqZWN0Iiwic2NvcGUiOiJtZXNzYWdlOnJlYWQi" + "LCJleHAiOjQ2ODM4MDUxNDF9.h-j6FKRFdnTdmAueTZCdep45e6DPwqM68ZQ8doIJ1exi9YxAlbWzOwId6Bd0L5YmCmp63gGQgsBUBLzwnZQ8kLUgU" + "OBEC3UzSWGRqMskCY9_k9pX0iomX6IfF3N0PaYs0WPC4hO1s8wfZQ-6hKQ4KigFi13G9LMLdH58PRMK0pKEvs3gCbHJuEPw-K5ORlpdnleUTQIwIN" + "afU57cmK3KocTeknPAM_L716sCuSYGvDl6xUTXO7oPdrXhS_EhxLP6KxrpI1uD4Ea_5OWTh7S0Wx5LLDfU6wBG1DowN20d374zepOIEkR-Jnmr_Ql" + "R44vmRqS5ncrF-1R0EGcPX49U6A"; @BeforeAll static void setup() throws Exception { server.start(); String url = server.url("/.well-known/jwks.json").toString(); server.enqueue(mockResponse()); System.setProperty("spring.security.oauth2.resourceserver.jwt.jwk-set-uri", url); } @AfterAll static void shutdown() throws Exception { server.shutdown(); System.clearProperty("spring.security.oauth2.resourceserver.jwt.jwk-set-uri"); } @Test void getWhenValidTokenShouldBeOk() { this.webTestClient.get() .uri("/") .headers((headers) -> headers.setBearerAuth(VALID_TOKEN)) .exchange() .expectStatus() .isOk() .expectBody(String.class) .isEqualTo("Hello, subject!"); } @Test void getWhenNoTokenShouldBeUnauthorized() { this.webTestClient.get() .uri("/") .exchange() .expectStatus() .isUnauthorized() .expectHeader() .valueEquals(HttpHeaders.WWW_AUTHENTICATE, "Bearer"); } private static MockResponse mockResponse() { String body = "{\"keys\":[{\"p\":\"2p-ViY7DE9ZrdWQb544m0Jp7Cv03YCSljqfim9pD4ALhObX0OrAznOiowTjwBky9JGffMw" + "DBVSfJSD9TSU7aH2sbbfi0bZLMdekKAuimudXwUqPDxrrg0BCyvCYgLmKjbVT3zcdylWSog93CNTxGDPzauu-oc0XPNKCXnaDpNvE\"" + ",\"kty\":\"RSA\",\"q\":\"sP_QYavrpBvSJ86uoKVGj2AGl78CSsAtpf1ybSY5TwUlorXSdqapRbY69Y271b0aMLzlleUn9ZTBO" + "1dlKV2_dw_lPADHVia8z3pxL-8sUhIXLsgj4acchMk4c9YX-sFh07xENnyZ-_TXm3llPLuL67HUfBC2eKe800TmCYVWc9U\",\"d\"" + ":\"bn1nFxCQT4KLTHqo8mo9HvHD0cRNRNdWcKNnnEQkCF6tKbt-ILRyQGP8O40axLd7CoNVG9c9p_-g4-2kwCtLJNv_STLtwfpCY7" + "VN5o6-ZIpfTjiW6duoPrLWq64Hm_4LOBQTiZfUPcLhsuJRHbWqakj-kV_YbUyC2Ocf_dd8IAQcSrAU2SCcDebhDCWwRUFvaa9V5eq0" + "851S9goaA-AJz-JXyePH6ZFr8JxmWkWxYZ5kdcMD-sm9ZbxE0CaEk32l4fE4hR-L8x2dDtjWA-ahKCZ091z-gV3HWtR2JOjvxoNRjxUo" + "3UxaGiFJHWNIl0EYUJZu1Cb-5wIlEI7wPx5mwQ\",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"one\",\"qi\":\"qS0OK4" + "8M2CIAA6_4Wdw4EbCaAfcTLf5Oy9t5BOF_PFUKqoSpZ6JsT5H0a_4zkjt-oI969v78OTlvBKbmEyKO-KeytzHBAA5CsLmVcz0THrMSg6o" + "XZqu66MPnvWoZN9FEN5TklPOvBFm8Bg1QZ3k-YMVaM--DLvhaYR95_mqaz50\",\"dp\":\"Too2NozLGD1XrXyhabZvy1E0EuaVFj0UHQ" + "PDLSpkZ_2g3BK6Art6T0xmE8RYtmqrKIEIdlI3IliAvyvAx_1D7zWTTRaj-xlZyqJFrnXWL7zj8UxT8PkB-r2E-ILZ3NAi1gxIWezlBTZ8" + "M6NfObDFmbTc_3tJkN_raISo8z_ziIE\",\"dq\":\"U0yhSkY5yOsa9YcMoigGVBWSJLpNHtbg5NypjHrPv8OhWbkOSq7WvSstBkF" + "k5AtyFvvfZLMLIkWWxxGzV0t6f1MoxBtttLrYYyCxwihiiGFhLbAdSuZ1wnxcqA9bC7UVECvrQmVTpsMs8UupfHKbQBpZ8OWAqrn" + "uYNNtG4_4Bt0\",\"n\":\"lygtuZj0lJjqOqIWocF8Bb583QDdq-aaFg8PesOp2-EDda6GqCpL-_NZVOflNGX7XIgjsWHcPsQHs" + "V9gWuOzSJ0iEuWvtQ6eGBP5M6m7pccLNZfwUse8Cb4Ngx3XiTlyuqM7pv0LPyppZusfEHVEdeelou7Dy9k0OQ_nJTI3b2E1WBoHC5" + "8CJ453lo4gcBm1efURN3LIVc1V9NQY_ESBKVdwqYyoJPEanURLVGRd6cQKn6YrCbbIRHjqAyqOE-z3KmgDJnPriljfR5XhSGyM9eq" + "D9Xpy6zu_MAeMJJfSArp857zLPk-Wf5VP9STAcjyfdBIybMKnwBYr2qHMT675hQ\"}]}"; return new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .setResponseCode(200) .setBody(body); } }
SampleReactiveOAuth2ResourceServerApplicationTests
java
apache__avro
lang/java/mapred/src/main/java/org/apache/avro/hadoop/io/AvroDatumConverterFactory.java
{ "start": 9797, "end": 10310 }
class ____ extends AvroDatumConverter<NullWritable, Object> { private final Schema mSchema; /** Constructor. */ public NullWritableConverter() { mSchema = Schema.create(Schema.Type.NULL); } /** {@inheritDoc} */ @Override public Object convert(NullWritable input) { return null; } /** {@inheritDoc} */ @Override public Schema getWriterSchema() { return mSchema; } } /** Converts Text into CharSequences. */ public static
NullWritableConverter
java
google__truth
core/src/test/java/com/google/common/truth/StandardSubjectBuilderTest.java
{ "start": 938, "end": 1138 }
class ____ { @Test public void failNoMessage() { AssertionError e = expectFailure(whenTesting -> whenTesting.fail()); assertThat(e).hasMessageThat().isEmpty(); } }
StandardSubjectBuilderTest
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/test/rest/transform/RestTestTransform.java
{ "start": 713, "end": 1358 }
interface ____<T extends JsonNode> extends Named { /** * Transform the Json structure per the given {@link RestTestTransform} * Implementations are expected to mutate the parent to satisfy the transformation. * * @param parent The parent of the node to transform. */ void transformTest(T parent); /** * @return true if the transformation should be applied, false otherwise. */ default boolean shouldApply(RestTestContext testContext) { return true; } @Override @Input default String getName() { return this.getClass().getCanonicalName(); } }
RestTestTransform
java
spring-projects__spring-boot
module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/HttpComponentsHttpClientBuilder.java
{ "start": 1791, "end": 10574 }
class ____ { private final Consumer<HttpClientBuilder> customizer; private final Consumer<PoolingHttpClientConnectionManagerBuilder> connectionManagerCustomizer; private final Consumer<SocketConfig.Builder> socketConfigCustomizer; private final Consumer<ConnectionConfig.Builder> connectionConfigCustomizer; private final Consumer<RequestConfig.Builder> defaultRequestConfigCustomizer; private final TlsSocketStrategyFactory tlsSocketStrategyFactory; public HttpComponentsHttpClientBuilder() { this(Empty.consumer(), Empty.consumer(), Empty.consumer(), Empty.consumer(), Empty.consumer(), HttpComponentsSslBundleTlsStrategy::get); } private HttpComponentsHttpClientBuilder(Consumer<HttpClientBuilder> customizer, Consumer<PoolingHttpClientConnectionManagerBuilder> connectionManagerCustomizer, Consumer<SocketConfig.Builder> socketConfigCustomizer, Consumer<ConnectionConfig.Builder> connectionConfigCustomizer, Consumer<RequestConfig.Builder> defaultRequestConfigCustomizer, TlsSocketStrategyFactory tlsSocketStrategyFactory) { this.customizer = customizer; this.connectionManagerCustomizer = connectionManagerCustomizer; this.socketConfigCustomizer = socketConfigCustomizer; this.connectionConfigCustomizer = connectionConfigCustomizer; this.defaultRequestConfigCustomizer = defaultRequestConfigCustomizer; this.tlsSocketStrategyFactory = tlsSocketStrategyFactory; } /** * Return a new {@link HttpComponentsHttpClientBuilder} that applies additional * customization to the underlying {@link HttpClientBuilder}. * @param customizer the customizer to apply * @return a new {@link HttpComponentsHttpClientBuilder} instance */ public HttpComponentsHttpClientBuilder withCustomizer(Consumer<HttpClientBuilder> customizer) { Assert.notNull(customizer, "'customizer' must not be null"); return new HttpComponentsHttpClientBuilder(this.customizer.andThen(customizer), this.connectionManagerCustomizer, this.socketConfigCustomizer, this.connectionConfigCustomizer, this.defaultRequestConfigCustomizer, this.tlsSocketStrategyFactory); } /** * Return a new {@link HttpComponentsHttpClientBuilder} that applies additional * customization to the underlying {@link PoolingHttpClientConnectionManagerBuilder}. * @param connectionManagerCustomizer the customizer to apply * @return a new {@link HttpComponentsHttpClientBuilder} instance */ public HttpComponentsHttpClientBuilder withConnectionManagerCustomizer( Consumer<PoolingHttpClientConnectionManagerBuilder> connectionManagerCustomizer) { Assert.notNull(connectionManagerCustomizer, "'connectionManagerCustomizer' must not be null"); return new HttpComponentsHttpClientBuilder(this.customizer, this.connectionManagerCustomizer.andThen(connectionManagerCustomizer), this.socketConfigCustomizer, this.connectionConfigCustomizer, this.defaultRequestConfigCustomizer, this.tlsSocketStrategyFactory); } /** * Return a new {@link HttpComponentsHttpClientBuilder} that applies additional * customization to the underlying * {@link org.apache.hc.core5.http.io.SocketConfig.Builder}. * @param socketConfigCustomizer the customizer to apply * @return a new {@link HttpComponentsHttpClientBuilder} instance */ public HttpComponentsHttpClientBuilder withSocketConfigCustomizer( Consumer<SocketConfig.Builder> socketConfigCustomizer) { Assert.notNull(socketConfigCustomizer, "'socketConfigCustomizer' must not be null"); return new HttpComponentsHttpClientBuilder(this.customizer, this.connectionManagerCustomizer, this.socketConfigCustomizer.andThen(socketConfigCustomizer), this.connectionConfigCustomizer, this.defaultRequestConfigCustomizer, this.tlsSocketStrategyFactory); } /** * Return a new {@link HttpComponentsHttpClientBuilder} that applies additional * customization to the underlying * {@link org.apache.hc.client5.http.config.ConnectionConfig.Builder}. * @param connectionConfigCustomizer the customizer to apply * @return a new {@link HttpComponentsHttpClientBuilder} instance */ public HttpComponentsHttpClientBuilder withConnectionConfigCustomizer( Consumer<ConnectionConfig.Builder> connectionConfigCustomizer) { Assert.notNull(connectionConfigCustomizer, "'connectionConfigCustomizer' must not be null"); return new HttpComponentsHttpClientBuilder(this.customizer, this.connectionManagerCustomizer, this.socketConfigCustomizer, this.connectionConfigCustomizer.andThen(connectionConfigCustomizer), this.defaultRequestConfigCustomizer, this.tlsSocketStrategyFactory); } /** * Return a new {@link HttpComponentsHttpClientBuilder} with a replacement * {@link TlsSocketStrategy} factory. * @param tlsSocketStrategyFactory the new factory used to create a * {@link TlsSocketStrategy}. The function will be provided with a {@link SslBundle} * or {@code null} if no bundle is selected. Only non {@code null} results will be * applied. * @return a new {@link HttpComponentsHttpClientBuilder} instance */ public HttpComponentsHttpClientBuilder withTlsSocketStrategyFactory( TlsSocketStrategyFactory tlsSocketStrategyFactory) { Assert.notNull(tlsSocketStrategyFactory, "'tlsSocketStrategyFactory' must not be null"); return new HttpComponentsHttpClientBuilder(this.customizer, this.connectionManagerCustomizer, this.socketConfigCustomizer, this.connectionConfigCustomizer, this.defaultRequestConfigCustomizer, tlsSocketStrategyFactory); } /** * Return a new {@link HttpComponentsHttpClientBuilder} that applies additional * customization to the underlying * {@link org.apache.hc.client5.http.config.RequestConfig.Builder} used for default * requests. * @param defaultRequestConfigCustomizer the customizer to apply * @return a new {@link HttpComponentsHttpClientBuilder} instance */ public HttpComponentsHttpClientBuilder withDefaultRequestConfigCustomizer( Consumer<RequestConfig.Builder> defaultRequestConfigCustomizer) { Assert.notNull(defaultRequestConfigCustomizer, "'defaultRequestConfigCustomizer' must not be null"); return new HttpComponentsHttpClientBuilder(this.customizer, this.connectionManagerCustomizer, this.socketConfigCustomizer, this.connectionConfigCustomizer, this.defaultRequestConfigCustomizer.andThen(defaultRequestConfigCustomizer), this.tlsSocketStrategyFactory); } /** * Build a new {@link HttpClient} instance with the given settings applied. * @param settings the settings to apply * @return a new {@link HttpClient} instance */ public CloseableHttpClient build(@Nullable HttpClientSettings settings) { settings = (settings != null) ? settings : HttpClientSettings.defaults(); HttpClientBuilder builder = HttpClientBuilder.create() .useSystemProperties() .setRedirectStrategy(HttpComponentsRedirectStrategy.get(settings.redirects())) .setConnectionManager(createConnectionManager(settings)) .setDefaultRequestConfig(createDefaultRequestConfig()); this.customizer.accept(builder); return builder.build(); } private PoolingHttpClientConnectionManager createConnectionManager(HttpClientSettings settings) { PoolingHttpClientConnectionManagerBuilder builder = PoolingHttpClientConnectionManagerBuilder.create() .useSystemProperties(); PropertyMapper map = PropertyMapper.get(); builder.setDefaultSocketConfig(createSocketConfig()); builder.setDefaultConnectionConfig(createConnectionConfig(settings)); map.from(settings::sslBundle) .always() .as(this.tlsSocketStrategyFactory::getTlsSocketStrategy) .to(builder::setTlsSocketStrategy); this.connectionManagerCustomizer.accept(builder); return builder.build(); } private SocketConfig createSocketConfig() { SocketConfig.Builder builder = SocketConfig.custom(); this.socketConfigCustomizer.accept(builder); return builder.build(); } private ConnectionConfig createConnectionConfig(HttpClientSettings settings) { ConnectionConfig.Builder builder = ConnectionConfig.custom(); PropertyMapper map = PropertyMapper.get(); map.from(settings::connectTimeout) .as(Duration::toMillis) .to((timeout) -> builder.setConnectTimeout(timeout, TimeUnit.MILLISECONDS)); map.from(settings::readTimeout) .asInt(Duration::toMillis) .to((timeout) -> builder.setSocketTimeout(timeout, TimeUnit.MILLISECONDS)); this.connectionConfigCustomizer.accept(builder); return builder.build(); } private RequestConfig createDefaultRequestConfig() { RequestConfig.Builder builder = RequestConfig.custom(); this.defaultRequestConfigCustomizer.accept(builder); return builder.build(); } /** * Factory that can be used to optionally create a {@link TlsSocketStrategy} given an * {@link SslBundle}. * * @since 4.0.0 */ public
HttpComponentsHttpClientBuilder
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/tofix/ObjectIdWithUnwrapping1298Test.java
{ "start": 1401, "end": 3070 }
class ____ { public Long id; public final String name; public Child(@JsonProperty("name") String name) { this.name = name; this.id = ObjectIdWithUnwrapping1298Test.nextId++; } } @JacksonTestFailureExpected @Test void objectIdWithRepeatedChild() throws Exception { ObjectMapper mapper = new ObjectMapper(JsonFactory.builder() .disable(StreamWriteFeature.AUTO_CLOSE_CONTENT).build()); // to keep output faithful to original, prevent auto-closing... // Equivalent to Spring _embedded for Bean w/ List property ListOfParents parents = new ListOfParents(); //Bean with Relationship Parent parent1 = new Parent(); Child child1 = new Child("Child1"); parent1.child = child1; parents.addParent(parent1); // serialize parent1 and parent2 String json = mapper .writerWithDefaultPrettyPrinter() .writeValueAsString(parents); assertNotNull(json); // System.out.println("This works: " + json); // Add parent3 to create ObjectId reference // Bean w/ repeated relationship from parent1, should generate ObjectId Parent parent3 = new Parent(); parent3.child = child1; parents.addParent(parent3); StringWriter sw = new StringWriter(); try { mapper // .writerWithDefaultPrettyPrinter() .writeValue(sw, parents); } catch (Exception e) { fail("Failed with " + e.getClass().getName() + ", output so far: " + sw); } } }
Child
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/json/JsonValueWriterTests.java
{ "start": 1510, "end": 9620 }
class ____ { @Test void writeNameAndValueWhenNameIsNull() { assertThat(doWrite((writer) -> writer.write(null, "test"))).isEqualTo(quoted("test")); } @Test void writeNameAndValueWhenNameIsNotNull() { assertThat(doWrite((writer) -> { writer.start(Series.OBJECT); writer.write("name", "value"); writer.end(Series.OBJECT); })).isEqualTo(""" {"name":"value"}"""); } @Test void writeWhenNull() { assertThat(write(null)).isEqualTo("null"); } @Test void writeWhenWritableJson() { JsonWriter<String> writer = (instance, out) -> out.append(""" {"test":"%s"}""".formatted(instance)); assertThat(write(writer.write("hello"))).isEqualTo(""" {"test":"hello"}"""); } @Test void writeWhenStringArray() { assertThat(write(new String[] { "a", "b", "c" })).isEqualTo(""" ["a","b","c"]"""); } @Test void writeWhenNumberArray() { assertThat(write(new int[] { 1, 2, 3 })).isEqualTo("[1,2,3]"); assertThat(write(new double[] { 1.0, 2.0, 3.0 })).isEqualTo("[1.0,2.0,3.0]"); } @Test void writeWhenBooleanArray() { assertThat(write(new boolean[] { true, false, true })).isEqualTo("[true,false,true]"); } @Test void writeWhenArrayWithNullElements() { assertThat(write(new Object[] { null, null })).isEqualTo("[null,null]"); } @Test void writeWhenArrayWithMixedElementTypes() { assertThat(write(new Object[] { "a", "b", "c", 1, 2, true, null })).isEqualTo(""" ["a","b","c",1,2,true,null]"""); } @Test void writeWhenCollection() { assertThat(write(List.of("a", "b", "c"))).isEqualTo(""" ["a","b","c"]"""); assertThat(write(new LinkedHashSet<>(List.of("a", "b", "c")))).isEqualTo(""" ["a","b","c"]"""); } @Test void writeWhenMap() { Map<String, String> map = new LinkedHashMap<>(); map.put("a", "A"); map.put("b", "B"); assertThat(write(map)).isEqualTo(""" {"a":"A","b":"B"}"""); } @Test void writeWhenMapWithNumericalKeys() { Map<Integer, String> map = new LinkedHashMap<>(); map.put(1, "A"); map.put(2, "B"); assertThat(write(map)).isEqualTo(""" {"1":"A","2":"B"}"""); } @Test void writeWhenMapWithMixedValueTypes() { Map<Object, Object> map = new LinkedHashMap<>(); map.put("a", 1); map.put("b", 2.0); map.put("c", true); map.put("d", "d"); map.put("e", null); assertThat(write(map)).isEqualTo(""" {"a":1,"b":2.0,"c":true,"d":"d","e":null}"""); } @Test void writeWhenNumber() { assertThat(write((byte) 123)).isEqualTo("123"); assertThat(write(123)).isEqualTo("123"); assertThat(write(123L)).isEqualTo("123"); assertThat(write(2.0)).isEqualTo("2.0"); assertThat(write(2.0f)).isEqualTo("2.0"); assertThat(write(Byte.valueOf((byte) 123))).isEqualTo("123"); assertThat(write(Integer.valueOf(123))).isEqualTo("123"); assertThat(write(Long.valueOf(123L))).isEqualTo("123"); assertThat(write(Double.valueOf(2.0))).isEqualTo("2.0"); assertThat(write(Float.valueOf(2.0f))).isEqualTo("2.0"); } @Test void writeWhenBoolean() { assertThat(write(true)).isEqualTo("true"); assertThat(write(Boolean.TRUE)).isEqualTo("true"); assertThat(write(false)).isEqualTo("false"); assertThat(write(Boolean.FALSE)).isEqualTo("false"); } @Test void writeWhenString() { assertThat(write("test")).isEqualTo(quoted("test")); } @Test void writeWhenStringRequiringEscape() { assertThat(write("\"")).isEqualTo(quoted("\\\"")); assertThat(write("\\")).isEqualTo(quoted("\\\\")); assertThat(write("\b")).isEqualTo(quoted("\\b")); assertThat(write("\f")).isEqualTo(quoted("\\f")); assertThat(write("\n")).isEqualTo(quoted("\\n")); assertThat(write("\r")).isEqualTo(quoted("\\r")); assertThat(write("\t")).isEqualTo(quoted("\\t")); assertThat(write("\u0000\u001F")).isEqualTo(quoted("\\u0000\\u001F")); } @Test void shouldNotEscapeForwardSlash() { assertThat(write("/")).isEqualTo(quoted("/")); } @Test void writeObject() { Map<String, String> map = Map.of("a", "A"); String actual = doWrite((valueWriter) -> valueWriter.writeObject(map::forEach)); assertThat(actual).isEqualTo(""" {"a":"A"}"""); } @Test void writePairs() { String actual = doWrite((valueWriter) -> { valueWriter.start(Series.OBJECT); valueWriter.writePairs(Map.of("a", "A")::forEach); valueWriter.writePairs(Map.of("b", "B")::forEach); valueWriter.end(Series.OBJECT); }); assertThat(actual).isEqualTo(""" {"a":"A","b":"B"}"""); } @Test void writePairsWhenDuplicateThrowsException() { assertThatIllegalStateException().isThrownBy(() -> doWrite((valueWriter) -> { valueWriter.start(Series.OBJECT); valueWriter.writePairs(Map.of("a", "A")::forEach); valueWriter.writePairs(Map.of("a", "B")::forEach); valueWriter.end(Series.OBJECT); })).withMessage("The name 'a' has already been written"); } @Test void writeArray() { List<String> list = List.of("a", "b", "c"); String actual = doWrite((valueWriter) -> valueWriter.writeArray(list::forEach)); assertThat(actual).isEqualTo(""" ["a","b","c"]"""); } @Test void writeElements() { String actual = doWrite((valueWriter) -> { valueWriter.start(Series.ARRAY); valueWriter.writeElements(List.of("a", "b")::forEach); valueWriter.writeElements(List.of("c", "d")::forEach); valueWriter.end(Series.ARRAY); }); assertThat(actual).isEqualTo(""" ["a","b","c","d"]"""); } @Test void startAndEndWithNull() { String actual = doWrite((valueWriter) -> { valueWriter.start(null); valueWriter.write("test"); valueWriter.end(null); }); assertThat(actual).isEqualTo(quoted("test")); } @Test void endWhenNotStartedThrowsException() { doWrite((valueWriter) -> assertThatExceptionOfType(NoSuchElementException.class) .isThrownBy(() -> valueWriter.end(Series.ARRAY))); } @Test // gh-44502 void writeJavaNioPathWhenSingleElementShouldBeSerializedAsString() { assertThat(doWrite((valueWriter) -> valueWriter.write(Path.of("a")))).isEqualTo(quoted("a")); } @Test // gh-44502 @EnabledOnOs(OS.WINDOWS) void writeJavaNioPathShouldBeSerializedAsStringOnWindows() { assertThat(doWrite((valueWriter) -> valueWriter.write(Path.of("a/b/c")))).isEqualTo(quoted("a\\\\b\\\\c")); } @Test // gh-44502 @DisabledOnOs(OS.WINDOWS) void writeJavaNioPathShouldBeSerializedAsString() { assertThat(doWrite((valueWriter) -> valueWriter.write(Path.of("a/b/c")))).isEqualTo(quoted("a/b/c")); } @Test void illegalStateExceptionShouldBeThrownWhenCollectionExceededNestingDepth() { JsonValueWriter writer = new JsonValueWriter(new StringBuilder(), 128); List<Object> list = new ArrayList<>(); list.add(list); assertThatIllegalStateException().isThrownBy(() -> writer.write(list)) .withMessageStartingWith( "JSON nesting depth (129) exceeds maximum depth of 128 (current path: [0][0][0][0][0][0][0][0][0][0][0][0]"); } @Test void illegalStateExceptionShouldBeThrownWhenMapExceededNestingDepth() { JsonValueWriter writer = new JsonValueWriter(new StringBuilder(), 128); Map<String, Object> map = new LinkedHashMap<>(); map.put("foo", Map.of("bar", map)); assertThatIllegalStateException().isThrownBy(() -> writer.write(map)) .withMessageStartingWith( "JSON nesting depth (129) exceeds maximum depth of 128 (current path: foo.bar.foo.bar.foo.bar.foo"); } @Test void illegalStateExceptionShouldBeThrownWhenIterableExceededNestingDepth() { JsonValueWriter writer = new JsonValueWriter(new StringBuilder(), 128); List<Object> list = new ArrayList<>(); list.add(list); assertThatIllegalStateException().isThrownBy(() -> writer.write((Iterable<Object>) list::iterator)) .withMessageStartingWith( "JSON nesting depth (129) exceeds maximum depth of 128 (current path: [0][0][0][0][0][0][0][0][0][0][0][0]"); } private <V> String write(@Nullable V value) { return doWrite((valueWriter) -> valueWriter.write(value)); } private String doWrite(Consumer<JsonValueWriter> action) { StringBuilder out = new StringBuilder(); action.accept(new JsonValueWriter(out)); return out.toString(); } private String quoted(String string) { return "\"" + string + "\""; } }
JsonValueWriterTests
java
spring-projects__spring-security
access/src/main/java/org/springframework/security/access/method/AbstractFallbackMethodSecurityMetadataSource.java
{ "start": 2663, "end": 3366 }
class ____ null, the method will be unchanged. Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass); // First try is the method in the target class. Collection<ConfigAttribute> attr = findAttributes(specificMethod, targetClass); if (attr != null) { return attr; } // Second try is the config attribute on the target class. attr = findAttributes(specificMethod.getDeclaringClass()); if (attr != null) { return attr; } if (specificMethod != method || targetClass == null) { // Fallback is to look at the original method. attr = findAttributes(method, method.getDeclaringClass()); if (attr != null) { return attr; } // Last fallback is the
is
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/json/JobIDSerializer.java
{ "start": 1250, "end": 1631 }
class ____ extends StdSerializer<JobID> { private static final long serialVersionUID = -6598593519161574611L; protected JobIDSerializer() { super(JobID.class); } @Override public void serialize(JobID value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeString(value.toString()); } }
JobIDSerializer
java
apache__camel
components/camel-cyberark-vault/src/generated/java/org/apache/camel/component/cyberark/vault/CyberArkVaultEndpointUriFactory.java
{ "start": 524, "end": 2699 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":label"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(13); props.add("account"); props.add("apiKey"); props.add("authToken"); props.add("certificatePath"); props.add("conjurClient"); props.add("label"); props.add("lazyStartProducer"); props.add("operation"); props.add("password"); props.add("secretId"); props.add("url"); props.add("username"); props.add("verifySsl"); PROPERTY_NAMES = Collections.unmodifiableSet(props); Set<String> secretProps = new HashSet<>(4); secretProps.add("apiKey"); secretProps.add("authToken"); secretProps.add("password"); secretProps.add("username"); SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps); MULTI_VALUE_PREFIXES = Collections.emptyMap(); } @Override public boolean isEnabled(String scheme) { return "cyberark-vault".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "label", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
CyberArkVaultEndpointUriFactory
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/results/graph/Fetchable.java
{ "start": 717, "end": 3051 }
interface ____ extends ModelPart { /** * The name of the fetchable. This is the part's "local name". * * @see #getNavigableRole() * @see NavigableRole#getLocalName() */ String getFetchableName(); /** * The key that identifies this {@linkplain Fetchable} within a {@link FetchableContainer}. * If this {@linkplain Fetchable} is part of {@link FetchableContainer#visitFetchables(IndexedConsumer, EntityMappingType)}, * the values is guaranteed to be between 0 (inclusive) and {@link FetchableContainer#getNumberOfFetchableKeys()} (exclusive). * Other {@linkplain Fetchable} objects may have a special negative value. * <p> * The main intent of this key is to index e.g. {@link Fetch} objects in an array. */ int getFetchableKey(); /** * The configured fetch timing and style */ FetchOptions getMappedFetchOptions(); /** * Check whether this Fetchable is considered a circular fetch. * * @param fetchablePath The overall path within the graph * * @return The Fetch representing the circularity; {@code null} indicates the fetch is not circular */ default Fetch resolveCircularFetch( NavigablePath fetchablePath, FetchParent fetchParent, FetchTiming fetchTiming, DomainResultCreationState creationState) { return null; } /** * Generates a Fetch of this fetchable * * @param fetchParent The parent of the Fetch we are generating * @param fetchablePath The overall path within the graph * @param fetchTiming The requested fetch timing */ Fetch generateFetch( FetchParent fetchParent, NavigablePath fetchablePath, FetchTiming fetchTiming, boolean selected, String resultVariable, DomainResultCreationState creationState); /** * Should this Fetchable affect the fetch depth? E.g., composites * would generally not increment the fetch depth. * * @see org.hibernate.cfg.AvailableSettings#MAX_FETCH_DEPTH */ default boolean incrementFetchDepth(){ return false; } default AttributeMapping asAttributeMapping() { return null; } default boolean isSelectable() { final AttributeMapping attributeMapping = asAttributeMapping(); if ( attributeMapping != null && attributeMapping.getAttributeMetadata() != null ) { return attributeMapping.getAttributeMetadata().isSelectable(); } else { return true; } } }
Fetchable
java
apache__flink
flink-python/src/main/java/org/apache/flink/streaming/api/utils/PythonTypeUtils.java
{ "start": 43237, "end": 44005 }
class ____ extends DataConverter<Integer, Long> { private static final long serialVersionUID = 1L; public static final IntDataConverter INSTANCE = new IntDataConverter(); @Override public Integer toInternal(Long value) { if (value == null) { return null; } return value.intValue(); } @Override public Long toExternal(Integer value) { if (value == null) { return null; } return value.longValue(); } } /** * Python Float will be converted to Double in PemJa, so we need FloatDataConverter to convert * Java Double to internal Float. */ public static final
IntDataConverter
java
netty__netty
codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttReasonCodes.java
{ "start": 8862, "end": 9368 }
enum ____ only correct values VALUES[unsignedByte] = code; // [java/index-out-of-bounds] } } private final byte byteValue; PubRel(byte byteValue) { this.byteValue = byteValue; } /** * @return the value number corresponding to the constant. * */ public byte byteValue() { return byteValue; } /** * @param b the number to decode. * @return the
contains
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ThreadLocalUsageTest.java
{ "start": 2437, "end": 2563 }
interface ____ {}") .addSourceLines( "Test.java", """ @Singleton
Singleton
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/domain/sample/IdClassExampleDepartment.java
{ "start": 792, "end": 1820 }
class ____ { private String name; @Id private long departmentId; public String getName() { return name; } public void setName(String name) { this.name = name; } public long getDepartmentId() { return departmentId; } public void setDepartmentId(long departmentId) { this.departmentId = departmentId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (departmentId ^ (departmentId >>> 32)); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; IdClassExampleDepartment other = (IdClassExampleDepartment) obj; if (departmentId != other.departmentId) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
IdClassExampleDepartment
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/runc/RuncContainerExecutorConfig.java
{ "start": 1615, "end": 5199 }
class ____ { final private String version; final private String runAsUser; final private String username; final private String containerId; final private String applicationId; final private String pidFile; final private String containerScriptPath; final private String containerCredentialsPath; final private int https; final private String keystorePath; final private String truststorePath; final private List<String> localDirs; final private List<String> logDirs; final private List<OCILayer> layers; final private int reapLayerKeepCount; final private OCIRuntimeConfig ociRuntimeConfig; public String getVersion() { return version; } public String getRunAsUser() { return runAsUser; } public String getUsername() { return username; } public String getContainerId() { return containerId; } public String getApplicationId() { return applicationId; } public String getPidFile() { return pidFile; } public String getContainerScriptPath() { return containerScriptPath; } public String getContainerCredentialsPath() { return containerCredentialsPath; } public int getHttps() { return https; } public String getKeystorePath() { return keystorePath; } public String getTruststorePath() { return truststorePath; } public List<String> getLocalDirs() { return localDirs; } public List<String> getLogDirs() { return logDirs; } public List<OCILayer> getLayers() { return layers; } public int getReapLayerKeepCount() { return reapLayerKeepCount; } public OCIRuntimeConfig getOciRuntimeConfig() { return ociRuntimeConfig; } public RuncContainerExecutorConfig() { this(null, null, null, null, null, null, null, null, 0, null, null, null, null, null, 0, null); } public RuncContainerExecutorConfig(String runAsUser, String username, String containerId, String applicationId, String pidFile, String containerScriptPath, String containerCredentialsPath, int https, String keystorePath, String truststorePath, List<String> localDirs, List<String> logDirs, List<OCILayer> layers, int reapLayerKeepCount, OCIRuntimeConfig ociRuntimeConfig) { this("0.1", runAsUser, username, containerId, applicationId, pidFile, containerScriptPath, containerCredentialsPath, https, keystorePath, truststorePath, localDirs, logDirs, layers, reapLayerKeepCount, ociRuntimeConfig); } public RuncContainerExecutorConfig(String version, String runAsUser, String username, String containerId, String applicationId, String pidFile, String containerScriptPath, String containerCredentialsPath, int https, String keystorePath, String truststorePath, List<String> localDirs, List<String> logDirs, List<OCILayer> layers, int reapLayerKeepCount, OCIRuntimeConfig ociRuntimeConfig) { this.version = version; this.runAsUser = runAsUser; this.username = username; this.containerId = containerId; this.applicationId = applicationId; this.pidFile = pidFile; this.containerScriptPath = containerScriptPath; this.containerCredentialsPath = containerCredentialsPath; this.https = https; this.keystorePath = keystorePath; this.truststorePath = truststorePath; this.localDirs = localDirs; this.logDirs = logDirs; this.layers = layers; this.reapLayerKeepCount = reapLayerKeepCount; this.ociRuntimeConfig = ociRuntimeConfig; } /** * This
RuncContainerExecutorConfig
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/io/Readable.java
{ "start": 1166, "end": 3041 }
interface ____ extends Named { /** * Represent this Readable as an input stream. * * @return The input stream * @throws IOException if an I/O exception occurs */ @NonNull InputStream asInputStream() throws IOException; /** * Does the underlying readable resource exist. * * @return True if it does */ boolean exists(); /** * Obtain a {@link Reader} for this readable using {@link StandardCharsets#UTF_8}. * * @return The reader * @throws IOException if an I/O error occurs */ default Reader asReader() throws IOException { return asReader(StandardCharsets.UTF_8); } /** * Obtain a {@link Reader} for this readable. * * @param charset The charset to use * @return The reader * @throws IOException if an I/O error occurs */ default Reader asReader(Charset charset) throws IOException { ArgumentUtils.requireNonNull("charset", charset); return new InputStreamReader(asInputStream(), charset); } /** * Create a {@link Readable} for the given URL. * * @param url The URL * @return The readable. */ static @NonNull Readable of(@NonNull URL url) { return new UrlReadable(url); } /** * Create a {@link Readable} for the given file. * * @param file The file * @return The readable. */ static @NonNull Readable of(@NonNull File file) { ArgumentUtils.requireNonNull("file", file); return new FileReadable(file); } /** * Create a {@link Readable} for the given path. * * @param path The path * @return The readable. */ static @NonNull Readable of(@NonNull Path path) { ArgumentUtils.requireNonNull("path", path); return new FileReadable(path.toFile()); } }
Readable
java
elastic__elasticsearch
x-pack/plugin/rollup/src/main/java/org/elasticsearch/xpack/rollup/action/RollupIndexCaps.java
{ "start": 3070, "end": 4058 }
class ____ { public List<RollupJobConfig> jobs; // Ignore unknown fields because there could be unrelated doc types private static final ConstructingObjectParser<DocParser, Void> DOC_PARSER = new ConstructingObjectParser<>( "_rollup_doc_parser", true, a -> { List<RollupJobConfig> j = new ArrayList<>(); for (Object o : (List) a[0]) { if (o instanceof RollupJobConfig) { j.add((RollupJobConfig) o); } } return new DocParser(j); } ); static { DOC_PARSER.declareField(constructorArg(), MetaParser.META_PARSER::apply, META_FIELD, ObjectParser.ValueType.OBJECT); } DocParser(List<RollupJobConfig> jobs) { this.jobs = jobs; } } /** * Parser for `_meta` portion of mapping metadata */ private static
DocParser
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringEnrichExpressionTest.java
{ "start": 1050, "end": 1314 }
class ____ extends EnrichExpressionTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/enrichExpressionTest.xml"); } }
SpringEnrichExpressionTest
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/extension/duplicated/impl/DuplicatedWithoutOverriddenExt2.java
{ "start": 954, "end": 1136 }
class ____ implements DuplicatedWithoutOverriddenExt { @Override public String echo() { return "DuplicatedWithoutOverriddenExt2"; } }
DuplicatedWithoutOverriddenExt2
java
spring-projects__spring-security
oauth2/oauth2-core/src/main/java/org/springframework/security/oauth2/core/authorization/OAuth2AuthorizationManagers.java
{ "start": 1156, "end": 3584 }
class ____ { private OAuth2AuthorizationManagers() { } /** * Create an {@link AuthorizationManager} that requires an {@link Authentication} to * have a {@code SCOPE_scope} authority. * * <p> * For example, if you call {@code hasScope("read")}, then this will require that each * authentication have a {@link org.springframework.security.core.GrantedAuthority} * whose value is {@code SCOPE_read}. * * <p> * This would equivalent to calling * {@code AuthorityAuthorizationManager#hasAuthority("SCOPE_read")}. * @param scope the scope value to require * @param <T> the secure object * @return an {@link AuthorizationManager} that requires a {@code "SCOPE_scope"} * authority */ public static <T> AuthorizationManager<T> hasScope(String scope) { assertScope(scope); return AuthorityAuthorizationManager.hasAuthority("SCOPE_" + scope); } /** * Create an {@link AuthorizationManager} that requires an {@link Authentication} to * have at least one authority among {@code SCOPE_scope1}, {@code SCOPE_scope2}, ... * {@code SCOPE_scopeN}. * * <p> * For example, if you call {@code hasAnyScope("read", "write")}, then this will * require that each authentication have at least a * {@link org.springframework.security.core.GrantedAuthority} whose value is either * {@code SCOPE_read} or {@code SCOPE_write}. * * <p> * This would equivalent to calling * {@code AuthorityAuthorizationManager#hasAnyAuthority("SCOPE_read", "SCOPE_write")}. * @param scopes the scope values to allow * @param <T> the secure object * @return an {@link AuthorizationManager} that requires at least one authority among * {@code "SCOPE_scope1"}, {@code SCOPE_scope2}, ... {@code SCOPE_scopeN}. * */ public static <T> AuthorizationManager<T> hasAnyScope(String... scopes) { String[] mappedScopes = new String[scopes.length]; for (int i = 0; i < scopes.length; i++) { assertScope(scopes[i]); mappedScopes[i] = "SCOPE_" + scopes[i]; } return AuthorityAuthorizationManager.hasAnyAuthority(mappedScopes); } private static void assertScope(String scope) { Assert.isTrue(!scope.startsWith("SCOPE_"), () -> scope + " should not start with SCOPE_ since SCOPE_" + " is automatically prepended when using hasScope and hasAnyScope. Consider using " + " AuthorityAuthorizationManager#hasAuthority or #hasAnyAuthority instead."); } }
OAuth2AuthorizationManagers
java
google__dagger
javatests/dagger/hilt/android/processor/internal/GeneratorsTest.java
{ "start": 1046, "end": 1450 }
class ____ { private static final Joiner JOINER = Joiner.on("\n"); @Test public void copyConstructorParametersCopiesExternalNullables() { Source baseActivity = HiltCompilerTests.javaSource( "test.BaseActivity", "package test;", "", "import androidx.fragment.app.FragmentActivity;", "", "public abstract
GeneratorsTest
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/aot/generate/ValueCodeGeneratorTests.java
{ "start": 10158, "end": 10601 }
class ____ { @Test void generateWhenStringList() { List<String> list = List.of("a", "b", "c"); assertThat(resolve(generateCode(list))).hasImport(List.class) .hasValueCode("List.of(\"a\", \"b\", \"c\")"); } @Test void generateWhenEmptyList() { List<String> list = List.of(); assertThat(resolve(generateCode(list))).hasImport(Collections.class) .hasValueCode("Collections.emptyList()"); } } @Nested
ListTests
java
apache__hadoop
hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/StreamInputFormat.java
{ "start": 1332, "end": 3062 }
class ____ extends KeyValueTextInputFormat { @SuppressWarnings("unchecked") public RecordReader<Text, Text> getRecordReader(final InputSplit genericSplit, JobConf job, Reporter reporter) throws IOException { String c = job.get("stream.recordreader.class"); if (c == null || c.indexOf("LineRecordReader") >= 0) { return super.getRecordReader(genericSplit, job, reporter); } // handling non-standard record reader (likely StreamXmlRecordReader) FileSplit split = (FileSplit) genericSplit; LOG.info("getRecordReader start.....split=" + split); reporter.setStatus(split.toString()); // Open the file and seek to the start of the split FileSystem fs = split.getPath().getFileSystem(job); FSDataInputStream in = fs.open(split.getPath()); // Factory dispatch based on available params.. Class readerClass; { readerClass = StreamUtil.goodClassOrNull(job, c, null); if (readerClass == null) { throw new RuntimeException("Class not found: " + c); } } Constructor ctor; try { ctor = readerClass.getConstructor(new Class[] { FSDataInputStream.class, FileSplit.class, Reporter.class, JobConf.class, FileSystem.class }); } catch (NoSuchMethodException nsm) { throw new RuntimeException(nsm); } RecordReader<Text, Text> reader; try { reader = (RecordReader<Text, Text>) ctor.newInstance(new Object[] { in, split, reporter, job, fs }); } catch (Exception nsm) { throw new RuntimeException(nsm); } return reader; } }
StreamInputFormat
java
quarkusio__quarkus
integration-tests/grpc-hibernate/src/main/java/com/example/grpc/hibernate/Item.java
{ "start": 177, "end": 435 }
class ____ { @Id @GeneratedValue public Long id; public String text; @Override public String toString() { return "Item{" + "id=" + id + ", text='" + text + '\'' + '}'; } }
Item
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/SuperCallToObjectMethodTest.java
{ "start": 1621, "end": 2211 }
class ____ extends Exception { int i; @Override public boolean equals(Object obj) { if (obj instanceof Foo) { return i == ((Foo) obj).i; } // BUG: Diagnostic contains: return super.equals(obj); } } """) .doTest(); } @Test public void negativeOtherSupertypeWithEquals() { helper() .addSourceLines( "Foo.java", """ import java.util.AbstractSet; abstract
Foo
java
spring-projects__spring-security
crypto/src/test/java/org/springframework/security/crypto/password/Md4PasswordEncoderTests.java
{ "start": 857, "end": 2227 }
class ____ extends AbstractPasswordEncoderValidationTests { @BeforeEach void setup() { setEncoder(new Md4PasswordEncoder()); } @Test public void matchesWhenEncodedPasswordNullThenFalse() { assertThat(getEncoder().matches("raw", null)).isFalse(); } @Test public void matchesWhenEncodedPasswordEmptyThenFalse() { assertThat(getEncoder().matches("raw", "")).isFalse(); } @Test public void testEncodeUnsaltedPassword() { Md4PasswordEncoder md4 = getEncoder(); md4.setEncodeHashAsBase64(true); assertThat(md4.matches("ww_uni123", "8zobtq72iAt0W6KNqavGwg==")).isTrue(); } @Test public void testEncodeSaltedPassword() { Md4PasswordEncoder md4 = getEncoder(); md4.setEncodeHashAsBase64(true); assertThat(md4.matches("ww_uni123", "{Alan K Stewart}ZplT6P5Kv6Rlu6W4FIoYNA==")).isTrue(); } @Test public void testNonAsciiPasswordHasCorrectHash() { assertThat(getEncoder().matches("\u4F60\u597d", "a7f1196539fd1f85f754ffd185b16e6e")).isTrue(); } @Test public void testEncodedMatches() { String rawPassword = "password"; String encodedPassword = getEncoder().encode(rawPassword); assertThat(getEncoder().matches(rawPassword, encodedPassword)).isTrue(); } @Test public void javadocWhenHasSaltThenMatches() { assertThat(getEncoder().matches("password", "{thisissalt}6cc7924dad12ade79dfb99e424f25260")); } }
Md4PasswordEncoderTests
java
apache__dubbo
dubbo-plugin/dubbo-qos/src/test/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClassesTest.java
{ "start": 1113, "end": 2875 }
class ____ { @Test void test() { FrameworkModel frameworkModel = new FrameworkModel(); SerializeSecurityManager ssm = frameworkModel.getBeanFactory().getBean(SerializeSecurityManager.class); SerializeWarnedClasses serializeWarnedClasses = new SerializeWarnedClasses(frameworkModel); CommandContext commandContext1 = Mockito.mock(CommandContext.class); Mockito.when(commandContext1.isHttp()).thenReturn(false); CommandContext commandContext2 = Mockito.mock(CommandContext.class); Mockito.when(commandContext2.isHttp()).thenReturn(true); Assertions.assertFalse( serializeWarnedClasses.execute(commandContext1, null).contains("Test1234")); Assertions.assertFalse( serializeWarnedClasses.execute(commandContext2, null).contains("Test1234")); ssm.getWarnedClasses().add("Test1234"); Assertions.assertTrue( serializeWarnedClasses.execute(commandContext1, null).contains("Test1234")); Assertions.assertTrue( serializeWarnedClasses.execute(commandContext2, null).contains("Test1234")); Assertions.assertFalse( serializeWarnedClasses.execute(commandContext1, null).contains("Test4321")); Assertions.assertFalse( serializeWarnedClasses.execute(commandContext2, null).contains("Test4321")); ssm.getWarnedClasses().add("Test4321"); Assertions.assertTrue( serializeWarnedClasses.execute(commandContext1, null).contains("Test4321")); Assertions.assertTrue( serializeWarnedClasses.execute(commandContext2, null).contains("Test4321")); frameworkModel.destroy(); } }
SerializeWarnedClassesTest
java
spring-projects__spring-framework
spring-jms/src/test/java/org/springframework/jms/support/destination/SimpleDestinationResolverTests.java
{ "start": 1204, "end": 3646 }
class ____ { private static final String DESTINATION_NAME = "foo"; private final SimpleDestinationResolver resolver = new SimpleDestinationResolver(); @Test void resolveWithPubSubTopicSession() throws Exception { Topic expectedDestination1 = new StubTopic(); Topic expectedDestination2 = new StubTopic(); TopicSession session = mock(); given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination1); testResolveDestination(session, expectedDestination1, true); given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination2); testResolveDestination(session, expectedDestination1, true); } @Test void resolveWithPubSubVanillaSession() throws Exception { Topic expectedDestination1 = new StubTopic(); Topic expectedDestination2 = new StubTopic(); Session session = mock(); given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination1); testResolveDestination(session, expectedDestination1, true); given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination2); testResolveDestination(session, expectedDestination1, true); } @Test void resolveWithPointToPointQueueSession() throws Exception { Queue expectedDestination1 = new StubQueue(); Queue expectedDestination2 = new StubQueue(); QueueSession session = mock(); given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination1); testResolveDestination(session, expectedDestination1, false); given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination2); testResolveDestination(session, expectedDestination1, false); } @Test void resolveWithPointToPointVanillaSession() throws Exception { Queue expectedDestination1 = new StubQueue(); Queue expectedDestination2 = new StubQueue(); Session session = mock(); given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination1); testResolveDestination(session, expectedDestination1, false); given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination2); testResolveDestination(session, expectedDestination1, false); } private void testResolveDestination(Session session, Destination expected, boolean isPubSub) throws JMSException { Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, isPubSub); assertThat(destination).isNotNull(); assertThat(destination).isSameAs(expected); } }
SimpleDestinationResolverTests
java
spring-projects__spring-boot
module/spring-boot-restclient/src/main/java/org/springframework/boot/restclient/RestTemplateBuilder.java
{ "start": 13655, "end": 33641 }
class ____ should be used with the * {@link RestTemplate}. * @param requestFactoryType the request factory type to use * @return a new builder instance * @see ClientHttpRequestFactoryBuilder#of(Class) * @see #requestFactoryBuilder(ClientHttpRequestFactoryBuilder) */ public RestTemplateBuilder requestFactory(Class<? extends ClientHttpRequestFactory> requestFactoryType) { Assert.notNull(requestFactoryType, "'requestFactoryType' must not be null"); return requestFactoryBuilder(ClientHttpRequestFactoryBuilder.of(requestFactoryType)); } /** * Set the {@code Supplier} of {@link ClientHttpRequestFactory} that should be called * each time we {@link #build()} a new {@link RestTemplate} instance. * @param requestFactorySupplier the supplier for the request factory * @return a new builder instance * @see ClientHttpRequestFactoryBuilder#of(Supplier) * @see #requestFactoryBuilder(ClientHttpRequestFactoryBuilder) */ public RestTemplateBuilder requestFactory(Supplier<ClientHttpRequestFactory> requestFactorySupplier) { Assert.notNull(requestFactorySupplier, "'requestFactorySupplier' must not be null"); return requestFactoryBuilder(ClientHttpRequestFactoryBuilder.of(requestFactorySupplier)); } /** * Set the {@link ClientHttpRequestFactoryBuilder} that should be used each time we * {@link #build()} a new {@link RestTemplate} instance. * @param requestFactoryBuilder the {@link ClientHttpRequestFactoryBuilder} to use * @return a new builder instance * @see ClientHttpRequestFactoryBuilder */ public RestTemplateBuilder requestFactoryBuilder(ClientHttpRequestFactoryBuilder<?> requestFactoryBuilder) { Assert.notNull(requestFactoryBuilder, "'requestFactoryBuilder' must not be null"); return new RestTemplateBuilder(this.clientSettings, this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, this.requestCustomizers); } /** * Set the {@link UriTemplateHandler} that should be used with the * {@link RestTemplate}. * @param uriTemplateHandler the URI template handler to use * @return a new builder instance */ public RestTemplateBuilder uriTemplateHandler(UriTemplateHandler uriTemplateHandler) { Assert.notNull(uriTemplateHandler, "'uriTemplateHandler' must not be null"); return new RestTemplateBuilder(this.clientSettings, this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, this.requestCustomizers); } /** * Set the {@link ResponseErrorHandler} that should be used with the * {@link RestTemplate}. * @param errorHandler the error handler to use * @return a new builder instance */ public RestTemplateBuilder errorHandler(ResponseErrorHandler errorHandler) { Assert.notNull(errorHandler, "'errorHandler' must not be null"); return new RestTemplateBuilder(this.clientSettings, this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, this.requestCustomizers); } /** * Add HTTP Basic Authentication to requests with the given username/password pair, * unless a custom Authorization header has been set before. * @param username the user name * @param password the password * @return a new builder instance * @see #basicAuthentication(String, String, Charset) */ public RestTemplateBuilder basicAuthentication(String username, String password) { return basicAuthentication(username, password, null); } /** * Add HTTP Basic Authentication to requests with the given username/password pair, * unless a custom Authorization header has been set before. * @param username the user name * @param password the password * @param charset the charset to use * @return a new builder instance */ public RestTemplateBuilder basicAuthentication(String username, String password, @Nullable Charset charset) { return new RestTemplateBuilder(this.clientSettings, this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, new BasicAuthentication(username, password, charset), this.defaultHeaders, this.customizers, this.requestCustomizers); } /** * Add a default header that will be set if not already present on the outgoing * {@link ClientHttpRequest}. * @param name the name of the header * @param values the header values * @return a new builder instance */ public RestTemplateBuilder defaultHeader(String name, String... values) { Assert.notNull(name, "'name' must not be null"); Assert.notNull(values, "'values' must not be null"); return new RestTemplateBuilder(this.clientSettings, this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, append(this.defaultHeaders, name, values), this.customizers, this.requestCustomizers); } /** * Sets the {@link HttpClientSettings}. This will replace any previously set * {@link #connectTimeout(Duration) connectTimeout}, {@link #readTimeout(Duration) * readTimeout} and {@link #sslBundle(SslBundle) sslBundle} values. * @param clientSettings the client settings * @return a new builder instance */ public RestTemplateBuilder clientSettings(HttpClientSettings clientSettings) { Assert.notNull(clientSettings, "'clientSettings' must not be null"); return new RestTemplateBuilder(clientSettings, this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, this.requestCustomizers); } /** * Update the {@link HttpClientSettings} using the given customizer. * @param clientSettingsCustomizer a {@link UnaryOperator} to update client factory * settings * @return a new builder instance */ public RestTemplateBuilder clientSettings(UnaryOperator<HttpClientSettings> clientSettingsCustomizer) { Assert.notNull(clientSettingsCustomizer, "'clientSettingsCustomizer' must not be null"); return new RestTemplateBuilder(clientSettingsCustomizer.apply(this.clientSettings), this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, this.requestCustomizers); } /** * Sets the connection timeout on the underlying {@link ClientHttpRequestFactory}. * @param connectTimeout the connection timeout * @return a new builder instance. */ public RestTemplateBuilder connectTimeout(Duration connectTimeout) { return new RestTemplateBuilder(this.clientSettings.withConnectTimeout(connectTimeout), this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, this.requestCustomizers); } /** * Sets the read timeout on the underlying {@link ClientHttpRequestFactory}. * @param readTimeout the read timeout * @return a new builder instance. */ public RestTemplateBuilder readTimeout(Duration readTimeout) { return new RestTemplateBuilder(this.clientSettings.withReadTimeout(readTimeout), this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, this.requestCustomizers); } /** * Sets the redirect strategy on the underlying {@link ClientHttpRequestFactory}. * @param redirects the redirect strategy * @return a new builder instance. */ public RestTemplateBuilder redirects(HttpRedirects redirects) { return new RestTemplateBuilder(this.clientSettings.withRedirects(redirects), this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, this.requestCustomizers); } /** * Sets the SSL bundle on the underlying {@link ClientHttpRequestFactory}. * @param sslBundle the SSL bundle * @return a new builder instance */ public RestTemplateBuilder sslBundle(SslBundle sslBundle) { return new RestTemplateBuilder(this.clientSettings.withSslBundle(sslBundle), this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, this.requestCustomizers); } /** * Set the {@link RestTemplateCustomizer RestTemplateCustomizers} that should be * applied to the {@link RestTemplate}. Customizers are applied in the order that they * were added after builder configuration has been applied. Setting this value will * replace any previously configured customizers. * @param customizers the customizers to set * @return a new builder instance * @see #additionalCustomizers(RestTemplateCustomizer...) */ public RestTemplateBuilder customizers(RestTemplateCustomizer... customizers) { Assert.notNull(customizers, "'customizers' must not be null"); return customizers(Arrays.asList(customizers)); } /** * Set the {@link RestTemplateCustomizer RestTemplateCustomizers} that should be * applied to the {@link RestTemplate}. Customizers are applied in the order that they * were added after builder configuration has been applied. Setting this value will * replace any previously configured customizers. * @param customizers the customizers to set * @return a new builder instance * @see #additionalCustomizers(RestTemplateCustomizer...) */ public RestTemplateBuilder customizers(Collection<? extends RestTemplateCustomizer> customizers) { Assert.notNull(customizers, "'customizers' must not be null"); return new RestTemplateBuilder(this.clientSettings, this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, copiedSetOf(customizers), this.requestCustomizers); } /** * Add {@link RestTemplateCustomizer RestTemplateCustomizers} that should be applied * to the {@link RestTemplate}. Customizers are applied in the order that they were * added after builder configuration has been applied. * @param customizers the customizers to add * @return a new builder instance * @see #customizers(RestTemplateCustomizer...) */ public RestTemplateBuilder additionalCustomizers(RestTemplateCustomizer... customizers) { Assert.notNull(customizers, "'customizers' must not be null"); return additionalCustomizers(Arrays.asList(customizers)); } /** * Add {@link RestTemplateCustomizer RestTemplateCustomizers} that should be applied * to the {@link RestTemplate}. Customizers are applied in the order that they were * added after builder configuration has been applied. * @param customizers the customizers to add * @return a new builder instance * @see #customizers(RestTemplateCustomizer...) */ public RestTemplateBuilder additionalCustomizers(Collection<? extends RestTemplateCustomizer> customizers) { Assert.notNull(customizers, "'customizers' must not be null"); return new RestTemplateBuilder(this.clientSettings, this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, append(this.customizers, customizers), this.requestCustomizers); } /** * Set the {@link RestTemplateRequestCustomizer RestTemplateRequestCustomizers} that * should be applied to the {@link ClientHttpRequest}. Customizers are applied in the * order that they were added. Setting this value will replace any previously * configured request customizers. * @param requestCustomizers the request customizers to set * @return a new builder instance * @see #additionalRequestCustomizers(RestTemplateRequestCustomizer...) */ public RestTemplateBuilder requestCustomizers(RestTemplateRequestCustomizer<?>... requestCustomizers) { Assert.notNull(requestCustomizers, "'requestCustomizers' must not be null"); return requestCustomizers(Arrays.asList(requestCustomizers)); } /** * Set the {@link RestTemplateRequestCustomizer RestTemplateRequestCustomizers} that * should be applied to the {@link ClientHttpRequest}. Customizers are applied in the * order that they were added. Setting this value will replace any previously * configured request customizers. * @param requestCustomizers the request customizers to set * @return a new builder instance * @see #additionalRequestCustomizers(RestTemplateRequestCustomizer...) */ public RestTemplateBuilder requestCustomizers( Collection<? extends RestTemplateRequestCustomizer<?>> requestCustomizers) { Assert.notNull(requestCustomizers, "'requestCustomizers' must not be null"); return new RestTemplateBuilder(this.clientSettings, this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, copiedSetOf(requestCustomizers)); } /** * Add the {@link RestTemplateRequestCustomizer RestTemplateRequestCustomizers} that * should be applied to the {@link ClientHttpRequest}. Customizers are applied in the * order that they were added. * @param requestCustomizers the request customizers to add * @return a new builder instance * @see #requestCustomizers(RestTemplateRequestCustomizer...) */ public RestTemplateBuilder additionalRequestCustomizers(RestTemplateRequestCustomizer<?>... requestCustomizers) { Assert.notNull(requestCustomizers, "'requestCustomizers' must not be null"); return additionalRequestCustomizers(Arrays.asList(requestCustomizers)); } /** * Add the {@link RestTemplateRequestCustomizer RestTemplateRequestCustomizers} that * should be applied to the {@link ClientHttpRequest}. Customizers are applied in the * order that they were added. * @param requestCustomizers the request customizers to add * @return a new builder instance * @see #requestCustomizers(Collection) */ public RestTemplateBuilder additionalRequestCustomizers( Collection<? extends RestTemplateRequestCustomizer<?>> requestCustomizers) { Assert.notNull(requestCustomizers, "'requestCustomizers' must not be null"); return new RestTemplateBuilder(this.clientSettings, this.detectRequestFactory, this.rootUri, this.messageConverters, this.interceptors, this.requestFactoryBuilder, this.uriTemplateHandler, this.errorHandler, this.basicAuthentication, this.defaultHeaders, this.customizers, append(this.requestCustomizers, requestCustomizers)); } /** * Build a new {@link RestTemplate} instance and configure it using this builder. * @return a configured {@link RestTemplate} instance. * @see #build(Class) * @see #configure(RestTemplate) */ public RestTemplate build() { return configure(new RestTemplate()); } /** * Build a new {@link RestTemplate} instance of the specified type and configure it * using this builder. * @param <T> the type of rest template * @param restTemplateClass the template type to create * @return a configured {@link RestTemplate} instance. * @see RestTemplateBuilder#build() * @see #configure(RestTemplate) */ public <T extends RestTemplate> T build(Class<T> restTemplateClass) { return configure(BeanUtils.instantiateClass(restTemplateClass)); } /** * Configure the provided {@link RestTemplate} instance using this builder. * @param <T> the type of rest template * @param restTemplate the {@link RestTemplate} to configure * @return the rest template instance * @see RestTemplateBuilder#build() * @see RestTemplateBuilder#build(Class) */ public <T extends RestTemplate> T configure(T restTemplate) { ClientHttpRequestFactory requestFactory = buildRequestFactory(); if (requestFactory != null) { restTemplate.setRequestFactory(requestFactory); } addClientHttpRequestInitializer(restTemplate); if (!CollectionUtils.isEmpty(this.messageConverters)) { restTemplate.setMessageConverters(new ArrayList<>(this.messageConverters)); } if (this.uriTemplateHandler != null) { restTemplate.setUriTemplateHandler(this.uriTemplateHandler); } if (this.errorHandler != null) { restTemplate.setErrorHandler(this.errorHandler); } if (this.rootUri != null) { RootUriBuilderFactory.applyTo(restTemplate, this.rootUri); } restTemplate.getInterceptors().addAll(this.interceptors); if (!CollectionUtils.isEmpty(this.customizers)) { for (RestTemplateCustomizer customizer : this.customizers) { customizer.customize(restTemplate); } } return restTemplate; } /** * Build a new {@link ClientHttpRequestFactory} instance using the settings of this * builder. * @return a {@link ClientHttpRequestFactory} or {@code null} */ public @Nullable ClientHttpRequestFactory buildRequestFactory() { ClientHttpRequestFactoryBuilder<?> requestFactoryBuilder = requestFactoryBuilder(); return (requestFactoryBuilder != null) ? requestFactoryBuilder.build(this.clientSettings) : null; } /** * Return a {@link ClientHttpRequestFactoryBuilder} instance using the settings of * this builder. * @return a {@link ClientHttpRequestFactoryBuilder} or {@code null} */ public @Nullable ClientHttpRequestFactoryBuilder<?> requestFactoryBuilder() { if (this.requestFactoryBuilder != null) { return this.requestFactoryBuilder; } if (this.detectRequestFactory) { return ClientHttpRequestFactoryBuilder.detect(); } return null; } private void addClientHttpRequestInitializer(RestTemplate restTemplate) { if (this.basicAuthentication == null && this.defaultHeaders.isEmpty() && this.requestCustomizers.isEmpty()) { return; } restTemplate.getClientHttpRequestInitializers() .add(new RestTemplateBuilderClientHttpRequestInitializer(this.basicAuthentication, this.defaultHeaders, this.requestCustomizers)); } @SuppressWarnings("unchecked") private <T> Set<T> copiedSetOf(T... items) { return copiedSetOf(Arrays.asList(items)); } private <T> Set<T> copiedSetOf(Iterable<? extends T> collection) { LinkedHashSet<T> set = new LinkedHashSet<>(); collection.forEach(set::add); return Collections.unmodifiableSet(set); } private static <T> List<T> copiedListOf(T[] items) { return Collections.unmodifiableList(Arrays.asList(Arrays.copyOf(items, items.length))); } private static <T> Set<T> append(@Nullable Collection<? extends T> collection, @Nullable Collection<? extends T> additions) { Set<T> result = new LinkedHashSet<>((collection != null) ? collection : Collections.emptySet()); if (additions != null) { result.addAll(additions); } return Collections.unmodifiableSet(result); } private static <K, V> Map<K, List<V>> append(@Nullable Map<K, List<V>> map, K key, V @Nullable [] values) { Map<K, List<V>> result = new LinkedHashMap<>((map != null) ? map : Collections.emptyMap()); if (values != null) { result.put(key, copiedListOf(values)); } return Collections.unmodifiableMap(result); } }
that
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/savedrequest/Enumerator.java
{ "start": 1214, "end": 1362 }
class ____<T> implements Enumeration<T> { /** * The <code>Iterator</code> over which the <code>Enumeration</code> represented by * this
Enumerator
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/MessageParametersTest.java
{ "start": 1164, "end": 2340 }
class ____ { @Test void testResolveUrl() { String genericUrl = "/jobs/:jobid/state"; TestMessageParameters parameters = new TestMessageParameters(); JobID pathJobID = new JobID(); JobID queryJobID = new JobID(); parameters.pathParameter.resolve(pathJobID); parameters.queryParameter.resolve(Collections.singletonList(queryJobID)); String resolvedUrl = MessageParameters.resolveUrl(genericUrl, parameters); assertThat("/jobs/" + pathJobID + "/state?jobid=" + queryJobID).isEqualTo(resolvedUrl); } @Test void testUnresolvedParameters() { String genericUrl = "/jobs/:jobid/state"; TestMessageParameters parameters = new TestMessageParameters(); assertThatThrownBy(() -> MessageParameters.resolveUrl(genericUrl, parameters)) .isInstanceOf(IllegalStateException.class); JobID jobID = new JobID(); parameters.pathParameter.resolve(jobID); String resolvedUrl = MessageParameters.resolveUrl(genericUrl, parameters); assertThat(resolvedUrl).isEqualTo("/jobs/" + jobID + "/state"); } private static
MessageParametersTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ForEachIterableTest.java
{ "start": 4085, "end": 4628 }
class ____ { abstract void doSomething(Object element); void iteratorWhile(Iterable<?> list) { for (Object element : list) { doSomething(element); } } } """) .doTest(); } @Test public void empty() { BugCheckerRefactoringTestHelper.newInstance(ForEachIterable.class, getClass()) .addInputLines( "in/Test.java", """ import java.util.Iterator; abstract
Test
java
spring-projects__spring-security
oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/web/AuthenticatedPrincipalOAuth2AuthorizedClientRepositoryTests.java
{ "start": 1604, "end": 6174 }
class ____ { private String registrationId = "registrationId"; private String principalName = "principalName"; private OAuth2AuthorizedClientService authorizedClientService; private OAuth2AuthorizedClientRepository anonymousAuthorizedClientRepository; private AuthenticatedPrincipalOAuth2AuthorizedClientRepository authorizedClientRepository; private MockHttpServletRequest request; private MockHttpServletResponse response; @BeforeEach public void setup() { this.authorizedClientService = mock(OAuth2AuthorizedClientService.class); this.anonymousAuthorizedClientRepository = mock(OAuth2AuthorizedClientRepository.class); this.authorizedClientRepository = new AuthenticatedPrincipalOAuth2AuthorizedClientRepository( this.authorizedClientService); this.authorizedClientRepository .setAnonymousAuthorizedClientRepository(this.anonymousAuthorizedClientRepository); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); } @Test public void constructorWhenAuthorizedClientServiceIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(null)); } @Test public void setAuthorizedClientRepositoryWhenAuthorizedClientRepositoryIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.authorizedClientRepository.setAnonymousAuthorizedClientRepository(null)); } @Test public void loadAuthorizedClientWhenAuthenticatedPrincipalThenLoadFromService() { Authentication authentication = this.createAuthenticatedPrincipal(); this.authorizedClientRepository.loadAuthorizedClient(this.registrationId, authentication, this.request); verify(this.authorizedClientService).loadAuthorizedClient(this.registrationId, this.principalName); } @Test public void loadAuthorizedClientWhenAnonymousPrincipalThenLoadFromAnonymousRepository() { Authentication authentication = this.createAnonymousPrincipal(); this.authorizedClientRepository.loadAuthorizedClient(this.registrationId, authentication, this.request); verify(this.anonymousAuthorizedClientRepository).loadAuthorizedClient(this.registrationId, authentication, this.request); } @Test public void saveAuthorizedClientWhenAuthenticatedPrincipalThenSaveToService() { Authentication authentication = this.createAuthenticatedPrincipal(); OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class); this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authentication, this.request, this.response); verify(this.authorizedClientService).saveAuthorizedClient(authorizedClient, authentication); } @Test public void saveAuthorizedClientWhenAnonymousPrincipalThenSaveToAnonymousRepository() { Authentication authentication = this.createAnonymousPrincipal(); OAuth2AuthorizedClient authorizedClient = mock(OAuth2AuthorizedClient.class); this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authentication, this.request, this.response); verify(this.anonymousAuthorizedClientRepository).saveAuthorizedClient(authorizedClient, authentication, this.request, this.response); } @Test public void removeAuthorizedClientWhenAuthenticatedPrincipalThenRemoveFromService() { Authentication authentication = this.createAuthenticatedPrincipal(); this.authorizedClientRepository.removeAuthorizedClient(this.registrationId, authentication, this.request, this.response); verify(this.authorizedClientService).removeAuthorizedClient(this.registrationId, this.principalName); } @Test public void removeAuthorizedClientWhenAnonymousPrincipalThenRemoveFromAnonymousRepository() { Authentication authentication = this.createAnonymousPrincipal(); this.authorizedClientRepository.removeAuthorizedClient(this.registrationId, authentication, this.request, this.response); verify(this.anonymousAuthorizedClientRepository).removeAuthorizedClient(this.registrationId, authentication, this.request, this.response); } private Authentication createAuthenticatedPrincipal() { TestingAuthenticationToken authentication = new TestingAuthenticationToken(this.principalName, "password"); authentication.setAuthenticated(true); return authentication; } private Authentication createAnonymousPrincipal() { return new AnonymousAuthenticationToken("key-1234", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); } }
AuthenticatedPrincipalOAuth2AuthorizedClientRepositoryTests
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/store/StoreOp.java
{ "start": 904, "end": 1087 }
interface ____ store activity. * Used by for FileSystem based operation. * * @param <W> write to be done to * @param <R> read to be done from * @param <M> manager used */ public
for
java
dropwizard__dropwizard
dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ParamValidatorUnwrapperTest.java
{ "start": 643, "end": 2699 }
class ____ { @NotNull(payload = Unwrapping.Skip.class) @Min(3) IntParam inter = new IntParam("4"); @NotNull(payload = Unwrapping.Skip.class) @NotEmpty @Length(max = 3) public NonEmptyStringParam name = new NonEmptyStringParam("a"); } private final Validator validator = Validators.newValidator(); @Test void succeedsWithAllGoodData() { final Example example = new Example(); final Set<ConstraintViolation<Example>> validate = validator.validate(example); assertThat(validate).isEmpty(); } @Test void failsWithInvalidIntParam() { final Example example = new Example(); example.inter = new IntParam("2"); final Set<ConstraintViolation<Example>> validate = validator.validate(example); assertThat(validate).hasSize(1); } @SuppressWarnings("NullAway") @Test void failsWithNullIntParam() { final Example example = new Example(); example.inter = null; final Set<ConstraintViolation<Example>> validate = validator.validate(example); assertThat(validate).hasSize(1); } @SuppressWarnings("NullAway") @Test void failsWithNullNonEmptyStringParam() { final Example example = new Example(); example.name = null; final Set<ConstraintViolation<Example>> validate = validator.validate(example); assertThat(validate).hasSize(1); } @Test void failsWithInvalidNonEmptyStringParam() { final Example example = new Example(); example.name = new NonEmptyStringParam("hello"); final Set<ConstraintViolation<Example>> validate = validator.validate(example); assertThat(validate).hasSize(1); } @Test void failsWithEmptyNonEmptyStringParam() { final Example example = new Example(); example.name = new NonEmptyStringParam(""); final Set<ConstraintViolation<Example>> validate = validator.validate(example); assertThat(validate).hasSize(1); } }
Example
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/api/connector/source/lib/InputFormatSource.java
{ "start": 5653, "end": 7388 }
class ____<OUT> implements SplitEnumerator<SourceSplit, Void> { private final InputFormat<OUT, InputSplit> format; private final SplitEnumeratorContext<SourceSplit> context; private Queue<SourceSplit> remainingSplits; public InputFormatSplitEnumerator( InputFormat<OUT, InputSplit> format, SplitEnumeratorContext<SourceSplit> context) { this.format = format; this.context = context; } @Override public void start() { try { remainingSplits = Arrays.stream(format.createInputSplits(context.currentParallelism())) .map(InputSplitWrapperSourceSplit::new) .collect(Collectors.toCollection(LinkedList::new)); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void handleSplitRequest(int subtaskId, @Nullable String requesterHostname) { final SourceSplit nextSplit = remainingSplits.poll(); if (nextSplit != null) { context.assignSplit(nextSplit, subtaskId); } else { context.signalNoMoreSplits(subtaskId); } } @Override public void addSplitsBack(List<SourceSplit> splits, int subtaskId) { remainingSplits.addAll(splits); } @Override public void addReader(int subtaskId) {} @Override public Void snapshotState(long checkpointId) { return null; } @Override public void close() {} } private static
InputFormatSplitEnumerator
java
google__dagger
dagger-runtime/main/java/dagger/multibindings/LongKey.java
{ "start": 1422, "end": 1460 }
interface ____ { long value(); }
LongKey
java
apache__camel
components/camel-smooks/src/main/java/org/apache/camel/component/smooks/SmooksEndpoint.java
{ "start": 1631, "end": 3863 }
class ____ extends DefaultEndpoint { @UriPath(description = "Path to the Smooks configuration file") @Metadata(required = true, supportFileReference = true) private String smooksConfig; @UriParam(description = "File path to place the generated HTML execution report. The report is a useful tool in the developer’s arsenal for diagnosing issues or comprehending a transformation. Do not set in production since this is a major performance drain") private String reportPath; @UriParam(description = "Allow execution context to be set from the " + SmooksConstants.SMOOKS_EXECUTION_CONTEXT + " header", label = "advanced", defaultValue = "false") private Boolean allowExecutionContextFromHeader = false; private final SmooksProcessor smooksProcessor; public SmooksEndpoint(String endpointUri, Component component, SmooksProcessor processor) { super(endpointUri, component); this.smooksProcessor = processor; } @Override public Producer createProducer() { return new SmooksProducer(this, smooksProcessor); } @Override public Consumer createConsumer(Processor processor) { throw new IllegalArgumentException("Consumer is not supported"); } @Override protected void doStart() throws Exception { super.doStart(); ServiceHelper.startService(smooksProcessor); } @Override protected void doStop() throws Exception { super.doStop(); ServiceHelper.stopService(smooksProcessor); } public String getSmooksConfig() { return smooksConfig; } public void setSmooksConfig(String smooksConfig) { this.smooksConfig = smooksConfig; } public String getReportPath() { return reportPath; } public void setReportPath(String reportPath) { this.reportPath = reportPath; } public Boolean getAllowExecutionContextFromHeader() { return allowExecutionContextFromHeader; } public void setAllowExecutionContextFromHeader(Boolean allowExecutionContextFromHeader) { this.allowExecutionContextFromHeader = allowExecutionContextFromHeader; } }
SmooksEndpoint
java
spring-projects__spring-framework
spring-jms/src/test/java/org/springframework/jms/annotation/AbstractJmsAnnotationDrivenTests.java
{ "start": 10576, "end": 10828 }
class ____ { @JmsListeners({ @JmsListener(id = "first", destination = "myQueue"), @JmsListener(id = "second", destination = "anotherQueue", concurrency = "2-10") }) public void repeatableHandle(String msg) { } } static
JmsListenersBean
java
quarkusio__quarkus
extensions/amazon-lambda/deployment/src/test/java/io/quarkus/amazon/lambda/deployment/RequestHandlerJandexUtilTest.java
{ "start": 21494, "end": 21688 }
class ____ implements DefaultMethodInterface { // Uses the default implementation from interface } // Concrete method overrides default method public static
DefaultMethodHandler
java
quarkusio__quarkus
extensions/spring-data-jpa/deployment/src/main/java/io/quarkus/spring/data/deployment/MethodNameParser.java
{ "start": 32619, "end": 34212 }
class ____ is annotated with `@Id`. * * @param entityClass the `ClassInfo` object representing the entity class. * @return the `FieldInfo` of the first field annotated with `@Id`. * @throws NoSuchElementException if no field with the `@Id` annotation is found. */ private FieldInfo getIdFieldInfo(ClassInfo entityClass) { return entityClass.fields().stream() .filter(fieldInfo -> fieldInfo.hasAnnotation(DotName.createSimple(Id.class.getName()))).findFirst().get(); } private List<ClassInfo> getSuperClassInfos(IndexView indexView, ClassInfo entityClass) { List<ClassInfo> mappedSuperClassInfoElements = new ArrayList<>(3); Type superClassType = entityClass.superClassType(); while (superClassType != null && !superClassType.name().equals(DotNames.OBJECT)) { ClassInfo superClass = indexView.getClassByName(superClassType.name()); if (superClass.declaredAnnotation(DotNames.JPA_MAPPED_SUPERCLASS) != null) { mappedSuperClassInfoElements.add(superClass); } else if (superClass.declaredAnnotation(DotNames.JPA_INHERITANCE) != null) { mappedSuperClassInfoElements.add(superClass); } superClassType = superClass.superClassType(); } return mappedSuperClassInfoElements; } private boolean isHibernateProvidedBasicType(DotName dotName) { return DotNames.HIBERNATE_PROVIDED_BASIC_TYPES.contains(dotName); } // Tries to get the parent (name) of a field that is typed, e.g.: //
that