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
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/TypeFilterUtils.java
{ "start": 1731, "end": 4866 }
class ____ { /** * Create {@linkplain TypeFilter type filters} from the supplied * {@link AnnotationAttributes}, such as those sourced from * {@link ComponentScan#includeFilters()} or {@link ComponentScan#excludeFilters()}. * <p>Each {@link TypeFilter} will be instantiated using an appropriate * constructor, with {@code BeanClassLoaderAware}, {@code BeanFactoryAware}, * {@code EnvironmentAware}, and {@code ResourceLoaderAware} contracts * invoked if they are implemented by the type filter. * @param filterAttributes {@code AnnotationAttributes} for a * {@link ComponentScan.Filter @Filter} declaration * @param environment the {@code Environment} to make available to filters * @param resourceLoader the {@code ResourceLoader} to make available to filters * @param registry the {@code BeanDefinitionRegistry} to make available to filters * as a {@link org.springframework.beans.factory.BeanFactory} if applicable * @return a list of instantiated and configured type filters * @see TypeFilter * @see AnnotationTypeFilter * @see AssignableTypeFilter * @see AspectJTypeFilter * @see RegexPatternTypeFilter * @see org.springframework.beans.factory.BeanClassLoaderAware * @see org.springframework.beans.factory.BeanFactoryAware * @see org.springframework.context.EnvironmentAware * @see org.springframework.context.ResourceLoaderAware */ public static List<TypeFilter> createTypeFiltersFor(AnnotationAttributes filterAttributes, Environment environment, ResourceLoader resourceLoader, BeanDefinitionRegistry registry) { List<TypeFilter> typeFilters = new ArrayList<>(); FilterType filterType = filterAttributes.getEnum("type"); for (Class<?> filterClass : filterAttributes.getClassArray("classes")) { switch (filterType) { case ANNOTATION -> { Assert.isAssignable(Annotation.class, filterClass, "@ComponentScan ANNOTATION type filter requires an annotation type"); @SuppressWarnings("unchecked") Class<Annotation> annotationType = (Class<Annotation>) filterClass; typeFilters.add(new AnnotationTypeFilter(annotationType)); } case ASSIGNABLE_TYPE -> typeFilters.add(new AssignableTypeFilter(filterClass)); case CUSTOM -> { Assert.isAssignable(TypeFilter.class, filterClass, "@ComponentScan CUSTOM type filter requires a TypeFilter implementation"); TypeFilter filter = ParserStrategyUtils.instantiateClass(filterClass, TypeFilter.class, environment, resourceLoader, registry); typeFilters.add(filter); } default -> throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType); } } for (String expression : filterAttributes.getStringArray("pattern")) { switch (filterType) { case ASPECTJ -> typeFilters.add(new AspectJTypeFilter(expression, resourceLoader.getClassLoader())); case REGEX -> typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression))); default -> throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType); } } return typeFilters; } }
TypeFilterUtils
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadLockingTest.java
{ "start": 15179, "end": 15750 }
class ____ { @EmbeddedId private EntityWithAggregateId.Key key; @NaturalId private String data; public EntityWithAggregateId() { } public EntityWithAggregateId(EntityWithAggregateId.Key key, String data) { this.key = key; this.data = data; } public EntityWithAggregateId.Key getKey() { return key; } public void setKey(EntityWithAggregateId.Key key) { this.key = key; } public String getData() { return data; } public void setData(String data) { this.data = data; } @Embeddable public static
EntityWithAggregateId
java
spring-projects__spring-boot
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscovererTests.java
{ "start": 20303, "end": 20459 }
class ____ extends AbstractFilteredEndpoint { @ReadOperation @Nullable Object getAll() { return null; } } static
SpecializedSuperclassTestEndpoint
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/ProtobufWrapperLegacy.java
{ "start": 2054, "end": 4493 }
class ____ not an unshaded protobuf message %s", message.getClass()); this.message = (com.google.protobuf.Message) message; } public com.google.protobuf.Message getMessage() { return message; } @Override public void writeTo(ResponseBuffer out) throws IOException { int length = message.getSerializedSize(); length += com.google.protobuf.CodedOutputStream. computeUInt32SizeNoTag(length); out.ensureCapacity(length); message.writeDelimitedTo(out); } @SuppressWarnings("unchecked") @Override protected <T> T readFrom(ByteBuffer bb) throws IOException { // using the parser with a byte[]-backed coded input stream is the // most efficient way to deserialize a protobuf. it has a direct // path to the PB ctor that doesn't create multi-layered streams // that internally buffer. com.google.protobuf.CodedInputStream cis = com.google.protobuf.CodedInputStream.newInstance( bb.array(), bb.position() + bb.arrayOffset(), bb.remaining()); try { cis.pushLimit(cis.readRawVarint32()); message = message.getParserForType().parseFrom(cis); cis.checkLastTagWas(0); } finally { // advance over the bytes read. bb.position(bb.position() + cis.getTotalBytesRead()); } return (T) message; } /** * Has protobuf been looked for and is known as absent? * Saves a check on every message. */ private static final AtomicBoolean PROTOBUF_KNOWN_NOT_FOUND = new AtomicBoolean(false); /** * Is a message an unshaded protobuf message? * @param payload payload * @return true if protobuf.jar is on the classpath and the payload is a Message */ public static boolean isUnshadedProtobufMessage(Object payload) { if (PROTOBUF_KNOWN_NOT_FOUND.get()) { // protobuf is known to be absent. fail fast without examining // jars or generating exceptions. return false; } // load the protobuf message class. // if it does not load, then the payload is guaranteed not to be // an unshaded protobuf message // this relies on classloader caching for performance try { Class<?> protobufMessageClazz = Class.forName("com.google.protobuf.Message"); return protobufMessageClazz.isAssignableFrom(payload.getClass()); } catch (ClassNotFoundException e) { PROTOBUF_KNOWN_NOT_FOUND.set(true); return false; } } }
is
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/openai/response/OpenAiChatCompletionResponseEntity.java
{ "start": 945, "end": 4383 }
class ____ { /** * Parses the OpenAI chat completion response. * For a request like: * * <pre> * <code> * { * "inputs": ["Please summarize this text: some text", "Answer the following question: Question"] * } * </code> * </pre> * * The response would look like: * * <pre> * <code> * { * "id": "chatcmpl-123", * "object": "chat.completion", * "created": 1677652288, * "model": "gpt-3.5-turbo-0613", * "system_fingerprint": "fp_44709d6fcb", * "choices": [ * { * "index": 0, * "message": { * "role": "assistant", * "content": "\n\nHello there, how may I assist you today?", * }, * "logprobs": null, * "finish_reason": "stop" * } * ], * "usage": { * "prompt_tokens": 9, * "completion_tokens": 12, * "total_tokens": 21 * } * } * </code> * </pre> */ public static ChatCompletionResults fromResponse(Request request, HttpResult response) throws IOException { return fromResponse(response.body()); } public static ChatCompletionResults fromResponse(byte[] response) throws IOException { try (var p = XContentFactory.xContent(XContentType.JSON).createParser(XContentParserConfiguration.EMPTY, response)) { return CompletionResult.PARSER.apply(p, null).toChatCompletionResults(); } } public record CompletionResult(List<Choice> choices) { @SuppressWarnings("unchecked") public static final ConstructingObjectParser<CompletionResult, Void> PARSER = new ConstructingObjectParser<>( CompletionResult.class.getSimpleName(), true, args -> new CompletionResult((List<Choice>) args[0]) ); static { PARSER.declareObjectArray(constructorArg(), Choice.PARSER::apply, new ParseField("choices")); } public ChatCompletionResults toChatCompletionResults() { return new ChatCompletionResults( choices.stream().map(choice -> new ChatCompletionResults.Result(choice.message.content)).toList() ); } } public record Choice(Message message) { public static final ConstructingObjectParser<Choice, Void> PARSER = new ConstructingObjectParser<>( Choice.class.getSimpleName(), true, args -> new Choice((Message) args[0]) ); static { PARSER.declareObject(constructorArg(), Message.PARSER::apply, new ParseField("message")); } } public record Message(String content) { public static final ConstructingObjectParser<Message, Void> PARSER = new ConstructingObjectParser<>( Message.class.getSimpleName(), true, args -> new Message((String) args[0]) ); static { PARSER.declareString(constructorArg(), new ParseField("content")); } } }
OpenAiChatCompletionResponseEntity
java
resilience4j__resilience4j
resilience4j-spring/src/test/java/io/github/resilience4j/CircuitBreakerDummyService.java
{ "start": 314, "end": 3399 }
class ____ implements TestDummyService { @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "recovery") public String sync() { return syncError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "recovery") public String syncSuccess() { return "ok"; } @Override public CompletionStage<String> asyncThreadPool() { // no-op return null; } @Override public CompletionStage<String> asyncThreadPoolSuccess() { // no-op return null; } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "completionStageRecovery") public CompletionStage<String> async() { return asyncError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "fluxRecovery") public Flux<String> flux() { return fluxError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "monoRecovery") public Mono<String> mono(String parameter) { return monoError(parameter); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "observableRecovery") public Observable<String> observable() { return observableError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "singleRecovery") public Single<String> single() { return singleError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "completableRecovery") public Completable completable() { return completableError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "maybeRecovery") public Maybe<String> maybe() { return maybeError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "flowableRecovery") public Flowable<String> flowable() { return flowableError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "rx3ObservableRecovery") public io.reactivex.rxjava3.core.Observable<String> rx3Observable() { return rx3ObservableError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "rx3SingleRecovery") public io.reactivex.rxjava3.core.Single<String> rx3Single() { return rx3SingleError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "rx3CompletableRecovery") public io.reactivex.rxjava3.core.Completable rx3Completable() { return rx3CompletableError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "rx3MaybeRecovery") public io.reactivex.rxjava3.core.Maybe<String> rx3Maybe() { return rx3MaybeError(); } @Override @CircuitBreaker(name = BACKEND, fallbackMethod = "rx3FlowableRecovery") public io.reactivex.rxjava3.core.Flowable<String> rx3Flowable() { return rx3FlowableError(); } @Override @CircuitBreaker(name = "#root.args[0]", fallbackMethod = "#{'recovery'}") public String spelSync(String backend) { return syncError(); } }
CircuitBreakerDummyService
java
apache__thrift
lib/java/src/main/java/org/apache/thrift/transport/TSaslTransport.java
{ "start": 1512, "end": 1890 }
class ____ extends TEndpointTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TSaslTransport.class); protected static final int DEFAULT_MAX_LENGTH = 0x7FFFFFFF; protected static final int MECHANISM_NAME_BYTES = 1; protected static final int STATUS_BYTES = 1; protected static final int PAYLOAD_LENGTH_BYTES = 4; protected static
TSaslTransport
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/http/server/reactive/PersonService.java
{ "start": 747, "end": 855 }
class ____ { public Person findByName(String name) { return new Person(name); } }
PersonService
java
google__guava
android/guava/src/com/google/common/collect/AbstractMapBasedMultimap.java
{ "start": 15067, "end": 18987 }
class ____ implements Iterator<V> { final Iterator<V> delegateIterator; final Collection<V> originalDelegate = delegate; WrappedIterator() { delegateIterator = iteratorOrListIterator(delegate); } WrappedIterator(Iterator<V> delegateIterator) { this.delegateIterator = delegateIterator; } /** * If the delegate changed since the iterator was created, the iterator is no longer valid. */ void validateIterator() { refreshIfEmpty(); if (delegate != originalDelegate) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { validateIterator(); return delegateIterator.hasNext(); } @Override @ParametricNullness public V next() { validateIterator(); return delegateIterator.next(); } @Override public void remove() { delegateIterator.remove(); totalSize--; removeIfEmpty(); } Iterator<V> getDelegateIterator() { validateIterator(); return delegateIterator; } } @Override public boolean add(@ParametricNullness V value) { refreshIfEmpty(); boolean wasEmpty = delegate.isEmpty(); boolean changed = delegate.add(value); if (changed) { totalSize++; if (wasEmpty) { addToMap(); } } return changed; } @Nullable WrappedCollection getAncestor() { return ancestor; } // The following methods are provided for better performance. @Override public boolean addAll(Collection<? extends V> collection) { if (collection.isEmpty()) { return false; } int oldSize = size(); // calls refreshIfEmpty boolean changed = delegate.addAll(collection); if (changed) { int newSize = delegate.size(); totalSize += newSize - oldSize; if (oldSize == 0) { addToMap(); } } return changed; } @Override public boolean contains(@Nullable Object o) { refreshIfEmpty(); return delegate.contains(o); } @Override public boolean containsAll(Collection<?> c) { refreshIfEmpty(); return delegate.containsAll(c); } @Override public void clear() { int oldSize = size(); // calls refreshIfEmpty if (oldSize == 0) { return; } delegate.clear(); totalSize -= oldSize; removeIfEmpty(); // maybe shouldn't be removed if this is a sublist } @Override public boolean remove(@Nullable Object o) { refreshIfEmpty(); boolean changed = delegate.remove(o); if (changed) { totalSize--; removeIfEmpty(); } return changed; } @Override public boolean removeAll(Collection<?> c) { if (c.isEmpty()) { return false; } int oldSize = size(); // calls refreshIfEmpty boolean changed = delegate.removeAll(c); if (changed) { int newSize = delegate.size(); totalSize += newSize - oldSize; removeIfEmpty(); } return changed; } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); int oldSize = size(); // calls refreshIfEmpty boolean changed = delegate.retainAll(c); if (changed) { int newSize = delegate.size(); totalSize += newSize - oldSize; removeIfEmpty(); } return changed; } } private static <E extends @Nullable Object> Iterator<E> iteratorOrListIterator( Collection<E> collection) { return (collection instanceof List) ? ((List<E>) collection).listIterator() : collection.iterator(); } /** Set decorator that stays in sync with the multimap values for a key. */ @WeakOuter final
WrappedIterator
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/metadata/ComposableIndexTemplateMetadata.java
{ "start": 1316, "end": 1465 }
class ____ a custom {@link Metadata.ProjectCustom} implementation that * stores a map of ids to {@link ComposableIndexTemplate} templates. */ public
is
java
grpc__grpc-java
alts/src/main/java/io/grpc/alts/internal/AltsFraming.java
{ "start": 6948, "end": 6989 }
class ____ read a frame. * * <p>This
to
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/inference/nlp/tokenizers/BertJapaneseTokenizer.java
{ "start": 532, "end": 1616 }
class ____ extends BertTokenizer { protected BertJapaneseTokenizer( List<String> originalVocab, SortedMap<String, Integer> vocab, boolean doLowerCase, boolean doTokenizeCjKChars, boolean doStripAccents, boolean withSpecialTokens, int maxSequenceLength, Set<String> neverSplit ) { super(originalVocab, vocab, doLowerCase, doTokenizeCjKChars, doStripAccents, withSpecialTokens, maxSequenceLength, neverSplit); } @Override protected WordPieceAnalyzer createWordPieceAnalyzer( List<String> vocabulary, List<String> neverSplit, boolean doLowerCase, boolean doTokenizeCjKChars, boolean doStripAccents, String unknownToken ) { return new JapaneseWordPieceAnalyzer(vocabulary, new ArrayList<>(neverSplit), doLowerCase, doStripAccents, unknownToken); } public static Builder builder(List<String> vocab, Tokenization tokenization) { return new JapaneseBuilder(vocab, tokenization); } public static
BertJapaneseTokenizer
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompConversionException.java
{ "start": 881, "end": 1103 }
class ____ extends NestedRuntimeException { public StompConversionException(String msg, Throwable cause) { super(msg, cause); } public StompConversionException(String msg) { super(msg); } }
StompConversionException
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/internal/OpenSamlOperations.java
{ "start": 2610, "end": 5444 }
class ____ { private final String id; private final Issuer issuer; private final String algorithm; private final byte[] signature; private final byte[] content; RedirectParameters(Map<String, String> parameters, String parametersQuery, RequestAbstractType request) { this.id = request.getID(); this.issuer = request.getIssuer(); this.algorithm = parameters.get(Saml2ParameterNames.SIG_ALG); if (parameters.get(Saml2ParameterNames.SIGNATURE) != null) { this.signature = Saml2Utils.samlDecode(parameters.get(Saml2ParameterNames.SIGNATURE)); } else { this.signature = null; } Map<String, String> queryParams = UriComponentsBuilder.newInstance() .query(parametersQuery) .build(true) .getQueryParams() .toSingleValueMap(); String relayState = parameters.get(Saml2ParameterNames.RELAY_STATE); this.content = getContent(Saml2ParameterNames.SAML_REQUEST, relayState, queryParams); } RedirectParameters(Map<String, String> parameters, String parametersQuery, StatusResponseType response) { this.id = response.getID(); this.issuer = response.getIssuer(); this.algorithm = parameters.get(Saml2ParameterNames.SIG_ALG); if (parameters.get(Saml2ParameterNames.SIGNATURE) != null) { this.signature = Saml2Utils.samlDecode(parameters.get(Saml2ParameterNames.SIGNATURE)); } else { this.signature = null; } Map<String, String> queryParams = UriComponentsBuilder.newInstance() .query(parametersQuery) .build(true) .getQueryParams() .toSingleValueMap(); String relayState = parameters.get(Saml2ParameterNames.RELAY_STATE); this.content = getContent(Saml2ParameterNames.SAML_RESPONSE, relayState, queryParams); } static byte[] getContent(String samlObject, String relayState, final Map<String, String> queryParams) { if (Objects.nonNull(relayState)) { return String .format("%s=%s&%s=%s&%s=%s", samlObject, queryParams.get(samlObject), Saml2ParameterNames.RELAY_STATE, queryParams.get(Saml2ParameterNames.RELAY_STATE), Saml2ParameterNames.SIG_ALG, queryParams.get(Saml2ParameterNames.SIG_ALG)) .getBytes(StandardCharsets.UTF_8); } else { return String .format("%s=%s&%s=%s", samlObject, queryParams.get(samlObject), Saml2ParameterNames.SIG_ALG, queryParams.get(Saml2ParameterNames.SIG_ALG)) .getBytes(StandardCharsets.UTF_8); } } String getId() { return this.id; } Issuer getIssuer() { return this.issuer; } byte[] getContent() { return this.content; } String getAlgorithm() { return this.algorithm; } byte[] getSignature() { return this.signature; } boolean hasSignature() { return this.signature != null; } } }
RedirectParameters
java
apache__camel
components/camel-netty/src/main/java/org/apache/camel/component/netty/codec/DatagramPacketDecoder.java
{ "start": 1177, "end": 1660 }
class ____ extends MessageToMessageDecoder<DatagramPacket> { @Override protected void decode(ChannelHandlerContext ctx, DatagramPacket msg, List<Object> out) throws Exception { // decode the DatagramPackage to AddressedEnvelope DefaultAddressedEnvelope<Object, InetSocketAddress> addressEvelop = new DefaultAddressedEnvelope<>(msg.content().retain(), msg.recipient(), msg.sender()); out.add(addressEvelop); } }
DatagramPacketDecoder
java
grpc__grpc-java
api/src/main/java/io/grpc/LoadBalancer.java
{ "start": 2508, "end": 5482 }
interface ____ called from a Synchronization Context, * meaning they are serialized, thus the balancer implementation doesn't need to worry about * synchronization among them. {@link io.grpc.LoadBalancer.Helper#getSynchronizationContext} * allows implementations to schedule tasks to be run in the same Synchronization Context, with or * without a delay, thus those tasks don't need to worry about synchronizing with the balancer * methods. * * <p>However, the actual running thread may be the network thread, thus the following rules must be * followed to prevent blocking or even dead-locking in a network: * * <ol> * * <li><strong>Never block in the Synchronization Context</strong>. The callback methods must * return quickly. Examples or work that must be avoided: CPU-intensive calculation, waiting on * synchronization primitives, blocking I/O, blocking RPCs, etc.</li> * * <li><strong>Avoid calling into other components with lock held</strong>. The Synchronization * Context may be under a lock, e.g., the transport lock of OkHttp. If your LoadBalancer holds a * lock in a callback method (e.g., {@link #handleResolvedAddresses handleResolvedAddresses()}) * while calling into another method that also involves locks, be cautious of deadlock. Generally * you wouldn't need any locking in the LoadBalancer if you follow the canonical implementation * pattern below.</li> * * </ol> * * <h3>The canonical implementation pattern</h3> * * <p>A {@link LoadBalancer} keeps states like the latest addresses from NameResolver, the * Subchannel(s) and their latest connectivity states. These states are mutated within the * Synchronization Context, * * <p>A typical {@link SubchannelPicker SubchannelPicker} holds a snapshot of these states. It may * have its own states, e.g., a picker from a round-robin load-balancer may keep a pointer to the * next Subchannel, which are typically mutated by multiple threads. The picker should only mutate * its own state, and should not mutate or re-acquire the states of the LoadBalancer. This way the * picker only needs to synchronize its own states, which is typically trivial to implement. * * <p>When the LoadBalancer states changes, e.g., Subchannels has become or stopped being READY, and * we want subsequent RPCs to use the latest list of READY Subchannels, LoadBalancer would create a * new picker, which holds a snapshot of the latest Subchannel list. Refer to the javadoc of {@link * io.grpc.LoadBalancer.SubchannelStateListener#onSubchannelState onSubchannelState()} how to do * this properly. * * <p>No synchronization should be necessary between LoadBalancer and its pickers if you follow * the pattern above. It may be possible to implement in a different way, but that would usually * result in more complicated threading. * * @since 1.2.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/1771") @NotThreadSafe public abstract
are
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/arm-java/org/apache/hadoop/ipc/protobuf/TestProtosLegacy.java
{ "start": 217678, "end": 224756 }
class ____ extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2OrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_AddRequestProto2_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_AddRequestProto2_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2.class, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2.Builder.class); } // Construct using org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); params_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_AddRequestProto2_descriptor; } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2 getDefaultInstanceForType() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2.getDefaultInstance(); } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2 build() { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2 result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2 buildPartial() { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2 result = new org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2(this); int from_bitField0_ = bitField0_; if (((bitField0_ & 0x00000001) == 0x00000001)) { params_ = java.util.Collections.unmodifiableList(params_); bitField0_ = (bitField0_ & ~0x00000001); } result.params_ = params_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2) { return mergeFrom((org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2 other) { if (other == org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2.getDefaultInstance()) return this; if (!other.params_.isEmpty()) { if (params_.isEmpty()) { params_ = other.params_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureParamsIsMutable(); params_.addAll(other.params_); } onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2 parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.AddRequestProto2) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // repeated int32 params = 1; private java.util.List<java.lang.Integer> params_ = java.util.Collections.emptyList(); private void ensureParamsIsMutable() { if (!((bitField0_ & 0x00000001) == 0x00000001)) { params_ = new java.util.ArrayList<java.lang.Integer>(params_); bitField0_ |= 0x00000001; } } /** * <code>repeated int32 params = 1;</code> */ public java.util.List<java.lang.Integer> getParamsList() { return java.util.Collections.unmodifiableList(params_); } /** * <code>repeated int32 params = 1;</code> */ public int getParamsCount() { return params_.size(); } /** * <code>repeated int32 params = 1;</code> */ public int getParams(int index) { return params_.get(index); } /** * <code>repeated int32 params = 1;</code> */ public Builder setParams( int index, int value) { ensureParamsIsMutable(); params_.set(index, value); onChanged(); return this; } /** * <code>repeated int32 params = 1;</code> */ public Builder addParams(int value) { ensureParamsIsMutable(); params_.add(value); onChanged(); return this; } /** * <code>repeated int32 params = 1;</code> */ public Builder addAllParams( java.lang.Iterable<? extends java.lang.Integer> values) { ensureParamsIsMutable(); super.addAll(values, params_); onChanged(); return this; } /** * <code>repeated int32 params = 1;</code> */ public Builder clearParams() { params_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } // @@protoc_insertion_point(builder_scope:hadoop.common.AddRequestProto2) } static { defaultInstance = new AddRequestProto2(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:hadoop.common.AddRequestProto2) } public
Builder
java
google__dagger
javatests/dagger/internal/codegen/AssistedFactoryErrorsTest.java
{ "start": 8688, "end": 9028 }
class ____ {", " @AssistedInject Foo(@Assisted int i) {}", "}"); Source fooFactory = CompilerTests.javaSource( "test.FooFactory", "package test;", "", "import dagger.assisted.AssistedFactory;", "", "@AssistedFactory", "
Foo
java
elastic__elasticsearch
test/external-modules/die-with-dignity/src/javaRestTest/java/org/elasticsearch/qa/die_with_dignity/DieWithDignityIT.java
{ "start": 1321, "end": 6115 }
class ____ extends ESRestTestCase { @ClassRule public static ElasticsearchCluster cluster = ElasticsearchCluster.local() .distribution(DistributionType.INTEG_TEST) .module("test-die-with-dignity") .setting("xpack.security.enabled", "false") .jvmArg("-Ddie.with.dignity.test=true") .jvmArg("-XX:-ExitOnOutOfMemoryError") .build(); @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } public void testDieWithDignity() throws Exception { final long pid = getElasticsearchPid(); assertJvmArgs(pid, containsString("-Ddie.with.dignity.test=true")); expectThrows(IOException.class, () -> client().performRequest(new Request("GET", "/_die_with_dignity"))); // the Elasticsearch process should die assertBusy(() -> assertJvmArgs(pid, not(containsString("-Ddie.with.dignity.test=true")))); // parse the logs and ensure that Elasticsearch died with the expected cause boolean fatalError = false; boolean fatalErrorInThreadExiting = false; for (String line : readLines(cluster.getNodeLog(0, LogType.SERVER_JSON))) { if (containsAll(line, ".*ERROR.*", ".*ExceptionsHelper.*", ".*fatal error.*")) { fatalError = true; } else if (containsAll( line, ".*ERROR.*", ".*ElasticsearchUncaughtExceptionHandler.*", ".*fatal error in thread \\[elasticsearch-error-rethrower\\], exiting.*", ".*java.lang.OutOfMemoryError: Requested array size exceeds VM limit.*" )) { fatalErrorInThreadExiting = true; } } assertTrue(fatalError); assertTrue(fatalErrorInThreadExiting); } private Process startJcmd(long pid) throws IOException { final String jcmdPath = PathUtils.get(System.getProperty("java.home"), "bin/jcmd").toString(); return new ProcessBuilder().command(jcmdPath, Long.toString(pid), "VM.command_line").redirectErrorStream(true).start(); } private void assertJvmArgs(long pid, Matcher<String> matcher) throws IOException, InterruptedException { Process jcmdProcess = startJcmd(pid); if (Constants.WINDOWS) { // jcmd on windows appears to have a subtle bug where if the process being connected to // dies while jcmd is running, it can hang indefinitely. Here we detect this case by // waiting a fixed amount of time, and then killing/retrying the process boolean exited = jcmdProcess.waitFor(10, TimeUnit.SECONDS); if (exited == false) { logger.warn("jcmd hung, killing process and retrying"); jcmdProcess.destroyForcibly(); jcmdProcess = startJcmd(pid); } } List<String> outputLines = readLines(jcmdProcess.getInputStream()); String jvmArgs = null; try { for (String line : outputLines) { if (line.startsWith("jvm_args")) { jvmArgs = line; break; } } assertThat(jvmArgs, matcher); } catch (AssertionError ae) { logger.error("Failed matcher for jvm pid " + pid); logger.error("jcmd output: " + String.join("\n", outputLines)); throw ae; } } private long getElasticsearchPid() throws IOException { Response response = client().performRequest(new Request("GET", "/_nodes/process")); @SuppressWarnings("unchecked") var nodesInfo = (Map<String, Object>) entityAsMap(response).get("nodes"); @SuppressWarnings("unchecked") var nodeInfo = (Map<String, Object>) nodesInfo.values().iterator().next(); @SuppressWarnings("unchecked") var processInfo = (Map<String, Object>) nodeInfo.get("process"); Object stringPid = processInfo.get("id"); return Long.parseLong(stringPid.toString()); } private List<String> readLines(InputStream is) throws IOException { try (BufferedReader in = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { return in.lines().toList(); } } private boolean containsAll(String line, String... subStrings) { for (String subString : subStrings) { if (line.matches(subString) == false) { return false; } } return true; } @Override protected boolean preserveClusterUponCompletion() { // as the cluster is dead its state can not be wiped successfully so we have to bypass wiping the cluster return true; } }
DieWithDignityIT
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/rest/RestSecuritiesDefinition.java
{ "start": 1458, "end": 5060 }
class ____ { @XmlTransient private RestDefinition rest; @XmlElements({ @XmlElement(name = "apiKey", type = ApiKeyDefinition.class), @XmlElement(name = "basicAuth", type = BasicAuthDefinition.class), @XmlElement(name = "bearerToken", type = BearerTokenDefinition.class), @XmlElement(name = "oauth2", type = OAuth2Definition.class), @XmlElement(name = "openIdConnect", type = OpenIdConnectDefinition.class), @XmlElement(name = "mutualTLS", type = MutualTLSDefinition.class) }) private List<RestSecurityDefinition> securityDefinitions = new ArrayList<>(); public RestSecuritiesDefinition() { } public RestSecuritiesDefinition(RestDefinition rest) { this.rest = rest; } public List<RestSecurityDefinition> getSecurityDefinitions() { return securityDefinitions; } /** * Security definitions */ public void setSecurityDefinitions(List<RestSecurityDefinition> securityDefinitions) { this.securityDefinitions = securityDefinitions; } public ApiKeyDefinition apiKey(String key) { return apiKey(key, null); } public ApiKeyDefinition apiKey(String key, String description) { ApiKeyDefinition auth = new ApiKeyDefinition(rest); auth.setKey(key); auth.setDescription(description); securityDefinitions.add(auth); return auth; } public RestSecuritiesDefinition basicAuth(String key) { return basicAuth(key, null); } public RestSecuritiesDefinition basicAuth(String key, String description) { BasicAuthDefinition auth = new BasicAuthDefinition(rest); securityDefinitions.add(auth); auth.setKey(key); auth.setDescription(description); return this; } public RestSecuritiesDefinition bearerToken(String key, String bearerFormat) { return bearerToken(key, null, bearerFormat); } public RestSecuritiesDefinition bearerToken(String key, String description, String bearerFormat) { BearerTokenDefinition auth = new BearerTokenDefinition(rest); securityDefinitions.add(auth); auth.setKey(key); auth.setDescription(description); auth.setFormat(bearerFormat); return this; } public RestSecuritiesDefinition mutualTLS(String key) { return mutualTLS(key, null); } public RestSecuritiesDefinition mutualTLS(String key, String description) { MutualTLSDefinition auth = new MutualTLSDefinition(rest); securityDefinitions.add(auth); auth.setKey(key); auth.setDescription(description); return this; } public RestSecuritiesDefinition openIdConnect(String key, String url) { return openIdConnect(key, null, url); } public RestSecuritiesDefinition openIdConnect(String key, String description, String url) { OpenIdConnectDefinition auth = new OpenIdConnectDefinition(rest); securityDefinitions.add(auth); auth.setKey(key); auth.setDescription(description); auth.setUrl(url); return this; } public OAuth2Definition oauth2(String key) { return oauth2(key, null); } public OAuth2Definition oauth2(String key, String description) { OAuth2Definition auth = new OAuth2Definition(rest); auth.setKey(key); auth.setDescription(description); securityDefinitions.add(auth); return auth; } public RestDefinition end() { return rest; } }
RestSecuritiesDefinition
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/NodeFencer.java
{ "start": 1716, "end": 2186 }
class ____ must implement the {@link FenceMethod} interface. * The fencing methods that ship with Hadoop may also be referred to * by shortened names:<br> * <ul> * <li><code>shell(/path/to/some/script.sh args...)</code> (see {@link ShellCommandFencer}) * <li><code>sshfence(...)</code> (see {@link SshFenceByTcpPort}) * <li><code>powershell(...)</code> (see {@link PowerShellFencer}) * </ul> */ @InterfaceAudience.Private @InterfaceStability.Evolving public
provided
java
apache__maven
compat/maven-model-builder/src/main/java/org/apache/maven/model/building/DefaultModelBuilder.java
{ "start": 4394, "end": 16658 }
class ____ implements ModelBuilder { @Inject private ModelProcessor modelProcessor; @Inject private ModelValidator modelValidator; @Inject private ModelNormalizer modelNormalizer; @Inject private ModelInterpolator modelInterpolator; @Inject private ModelPathTranslator modelPathTranslator; @Inject private ModelUrlNormalizer modelUrlNormalizer; @Inject private SuperPomProvider superPomProvider; @Inject private InheritanceAssembler inheritanceAssembler; @Inject private ProfileSelector profileSelector; @Inject private ProfileInjector profileInjector; @Inject private PluginManagementInjector pluginManagementInjector; @Inject private DependencyManagementInjector dependencyManagementInjector; @Inject private DependencyManagementImporter dependencyManagementImporter; @Inject @Nullable private LifecycleBindingsInjector lifecycleBindingsInjector; @Inject private PluginConfigurationExpander pluginConfigurationExpander; @Inject private ReportConfigurationExpander reportConfigurationExpander; @Inject private ReportingConverter reportingConverter; @Inject private ProfileActivationFilePathInterpolator profileActivationFilePathInterpolator; public DefaultModelBuilder setModelProcessor(ModelProcessor modelProcessor) { this.modelProcessor = modelProcessor; return this; } public DefaultModelBuilder setModelValidator(ModelValidator modelValidator) { this.modelValidator = modelValidator; return this; } public DefaultModelBuilder setModelNormalizer(ModelNormalizer modelNormalizer) { this.modelNormalizer = modelNormalizer; return this; } public DefaultModelBuilder setModelInterpolator(ModelInterpolator modelInterpolator) { this.modelInterpolator = modelInterpolator; return this; } public DefaultModelBuilder setModelPathTranslator(ModelPathTranslator modelPathTranslator) { this.modelPathTranslator = modelPathTranslator; return this; } public DefaultModelBuilder setModelUrlNormalizer(ModelUrlNormalizer modelUrlNormalizer) { this.modelUrlNormalizer = modelUrlNormalizer; return this; } public DefaultModelBuilder setSuperPomProvider(SuperPomProvider superPomProvider) { this.superPomProvider = superPomProvider; return this; } public DefaultModelBuilder setProfileSelector(ProfileSelector profileSelector) { this.profileSelector = profileSelector; return this; } public DefaultModelBuilder setProfileInjector(ProfileInjector profileInjector) { this.profileInjector = profileInjector; return this; } public DefaultModelBuilder setInheritanceAssembler(InheritanceAssembler inheritanceAssembler) { this.inheritanceAssembler = inheritanceAssembler; return this; } public DefaultModelBuilder setDependencyManagementImporter(DependencyManagementImporter depMgmtImporter) { this.dependencyManagementImporter = depMgmtImporter; return this; } public DefaultModelBuilder setDependencyManagementInjector(DependencyManagementInjector depMgmtInjector) { this.dependencyManagementInjector = depMgmtInjector; return this; } public DefaultModelBuilder setLifecycleBindingsInjector(LifecycleBindingsInjector lifecycleBindingsInjector) { this.lifecycleBindingsInjector = lifecycleBindingsInjector; return this; } public DefaultModelBuilder setPluginConfigurationExpander(PluginConfigurationExpander pluginConfigurationExpander) { this.pluginConfigurationExpander = pluginConfigurationExpander; return this; } public DefaultModelBuilder setPluginManagementInjector(PluginManagementInjector pluginManagementInjector) { this.pluginManagementInjector = pluginManagementInjector; return this; } public DefaultModelBuilder setReportConfigurationExpander(ReportConfigurationExpander reportConfigurationExpander) { this.reportConfigurationExpander = reportConfigurationExpander; return this; } public DefaultModelBuilder setReportingConverter(ReportingConverter reportingConverter) { this.reportingConverter = reportingConverter; return this; } public DefaultModelBuilder setProfileActivationFilePathInterpolator( ProfileActivationFilePathInterpolator profileActivationFilePathInterpolator) { this.profileActivationFilePathInterpolator = profileActivationFilePathInterpolator; return this; } @SuppressWarnings("checkstyle:methodlength") @Override public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException { return build(request, new LinkedHashSet<>()); } @SuppressWarnings("checkstyle:methodlength") protected ModelBuildingResult build(ModelBuildingRequest request, Collection<String> importIds) throws ModelBuildingException { // phase 1 DefaultModelBuildingResult result = new DefaultModelBuildingResult(); DefaultModelProblemCollector problems = new DefaultModelProblemCollector(result); // read and validate raw model Model inputModel = request.getRawModel(); if (inputModel == null) { inputModel = readModel(request.getModelSource(), request.getPomFile(), request, problems); } // profile activation DefaultProfileActivationContext profileActivationContext = getProfileActivationContext(request, inputModel); problems.setSource("(external profiles)"); List<Profile> activeExternalProfiles = profileSelector.getActiveProfiles(request.getProfiles(), profileActivationContext, problems); result.setActiveExternalProfiles(activeExternalProfiles); if (!activeExternalProfiles.isEmpty()) { Properties profileProps = new Properties(); for (Profile profile : activeExternalProfiles) { profileProps.putAll(profile.getProperties()); } profileProps.putAll(profileActivationContext.getUserProperties()); profileActivationContext.setUserProperties(profileProps); } problems.setRootModel(inputModel); ModelData resultData = new ModelData(request.getModelSource(), inputModel); ModelData superData = new ModelData(null, getSuperModel()); Collection<String> parentIds = new LinkedHashSet<>(); List<ModelData> lineage = new ArrayList<>(); for (ModelData currentData = resultData; currentData != null; ) { lineage.add(currentData); Model rawModel = currentData.getModel(); currentData.setRawModel(rawModel); Model tmpModel = rawModel.clone(); currentData.setModel(tmpModel); problems.setSource(tmpModel); // model normalization modelNormalizer.mergeDuplicates(tmpModel, request, problems); profileActivationContext.setProjectProperties(tmpModel.getProperties()); List<Profile> interpolatedProfiles = getInterpolatedProfiles(rawModel, profileActivationContext, problems); tmpModel.setProfiles(interpolatedProfiles); List<Profile> activePomProfiles = profileSelector.getActiveProfiles(tmpModel.getProfiles(), profileActivationContext, problems); List<Profile> rawProfiles = new ArrayList<>(); for (Profile activePomProfile : activePomProfiles) { rawProfiles.add(rawModel.getProfiles().get(interpolatedProfiles.indexOf(activePomProfile))); } currentData.setActiveProfiles(rawProfiles); // profile injection for (Profile activeProfile : activePomProfiles) { profileInjector.injectProfile(tmpModel, activeProfile, request, problems); } if (currentData == resultData) { for (Profile activeProfile : activeExternalProfiles) { profileInjector.injectProfile(tmpModel, activeProfile, request, problems); } } if (currentData == superData) { break; } configureResolver(request.getModelResolver(), tmpModel, problems); ModelData parentData = readParent(tmpModel, currentData.getSource(), request, problems); if (parentData == null) { currentData = superData; } else if (currentData == resultData) { // First iteration - add initial id after version resolution. currentData.setGroupId( currentData.getRawModel().getGroupId() == null ? parentData.getGroupId() : currentData.getRawModel().getGroupId()); currentData.setVersion( currentData.getRawModel().getVersion() == null ? parentData.getVersion() : currentData.getRawModel().getVersion()); currentData.setArtifactId(currentData.getRawModel().getArtifactId()); parentIds.add(currentData.getId()); // Reset - only needed for 'getId'. currentData.setGroupId(null); currentData.setArtifactId(null); currentData.setVersion(null); currentData = parentData; } else if (!parentIds.add(parentData.getId())) { StringBuilder message = new StringBuilder("The parents form a cycle: "); for (String modelId : parentIds) { message.append(modelId); message.append(" -> "); } message.append(parentData.getId()); problems.add(new ModelProblemCollectorRequest(ModelProblem.Severity.FATAL, ModelProblem.Version.BASE) .setMessage(message.toString())); throw problems.newModelBuildingException(); } else { currentData = parentData; } } problems.setSource(inputModel); checkPluginVersions(lineage, request, problems); // inheritance assembly assembleInheritance(lineage, request, problems); Model resultModel = resultData.getModel(); problems.setSource(resultModel); problems.setRootModel(resultModel); // model interpolation resultModel = interpolateModel(resultModel, request, problems); resultData.setModel(resultModel); if (resultModel.getParent() != null) { final ModelData parentData = lineage.get(1); if (parentData.getVersion() == null || parentData.getVersion().contains("${")) { final Model interpolatedParent = interpolateModel(parentData.getModel(), request, problems); // parentData.setModel( interpolatedParent ); parentData.setVersion(interpolatedParent.getVersion()); } } // url normalization modelUrlNormalizer.normalize(resultModel, request); // Now the fully interpolated model is available: reconfigure the resolver configureResolver(request.getModelResolver(), resultModel, problems, true); resultData.setGroupId(resultModel.getGroupId()); resultData.setArtifactId(resultModel.getArtifactId()); resultData.setVersion(resultModel.getVersion()); result.setEffectiveModel(resultModel); for (ModelData currentData : lineage) { String modelId = (currentData != superData) ? currentData.getId() : ""; result.addModelId(modelId); result.setActivePomProfiles(modelId, currentData.getActiveProfiles()); result.setRawModel(modelId, currentData.getRawModel()); } if (!request.isTwoPhaseBuilding()) { build(request, result, importIds); } return result; } @FunctionalInterface private
DefaultModelBuilder
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/util/AsmUtil.java
{ "start": 1332, "end": 4125 }
class ____ { public static final int ASM_API_VERSION = Opcodes.ASM9; public static final List<org.objectweb.asm.Type> PRIMITIVES = asList( VOID_TYPE, BOOLEAN_TYPE, CHAR_TYPE, BYTE_TYPE, SHORT_TYPE, INT_TYPE, FLOAT_TYPE, LONG_TYPE, DOUBLE_TYPE); public static final List<org.objectweb.asm.Type> WRAPPERS = asList( getType(Void.class), getType(Boolean.class), getType(Character.class), getType(Byte.class), getType(Short.class), getType(Integer.class), getType(Float.class), getType(Long.class), getType(Double.class)); public static final Map<org.objectweb.asm.Type, org.objectweb.asm.Type> WRAPPER_TO_PRIMITIVE = new HashMap<>(); public static final Map<Character, String> PRIMITIVE_DESCRIPTOR_TO_PRIMITIVE_CLASS_LITERAL; static { for (int i = 0; i < AsmUtil.PRIMITIVES.size(); i++) { AsmUtil.WRAPPER_TO_PRIMITIVE.put(AsmUtil.WRAPPERS.get(i), AsmUtil.PRIMITIVES.get(i)); } PRIMITIVE_DESCRIPTOR_TO_PRIMITIVE_CLASS_LITERAL = Map.of( 'Z', "boolean", 'B', "byte", 'C', "char", 'D', "double", 'F', "float", 'I', "int", 'J', "long", 'S', "short"); } public static org.objectweb.asm.Type autobox(org.objectweb.asm.Type primitive) { return WRAPPERS.get(primitive.getSort()); } /** * @deprecated use {@link MethodInfo#genericSignatureIfRequired()} */ @Deprecated(since = "3.1", forRemoval = true) public static String getSignatureIfRequired(MethodInfo method) { return method.genericSignatureIfRequired(); } /** * @deprecated use {@link MethodInfo#genericSignatureIfRequired(Function)} */ @Deprecated(since = "3.1", forRemoval = true) public static String getSignatureIfRequired(MethodInfo method, Function<String, String> typeArgMapper) { if (!method.requiresGenericSignature()) { return null; } return getSignature(method, typeArgMapper); } private static boolean hasThrowsSignature(MethodInfo method) { // JVMS 16, chapter 4.7.9.1. Signatures: // // If the throws clause of a method or constructor declaration does not involve type variables, // then a compiler may treat the declaration as having no throws clause for the purpose of // emitting a method signature. // also, no need to check if an exception type is of kind PARAMETERIZED_TYPE, because // // JLS 16, chapter 8.1.2. Generic Classes and Type Parameters: // // It is a compile-time error if a generic
AsmUtil
java
google__guava
android/guava-tests/test/com/google/common/reflect/InvokableTest.java
{ "start": 24491, "end": 25120 }
class ____ { AnonymousClassInConstructor() { int i = 1; String s = "hello world"; Class<?> anonymous = new Runnable() { @Override public void run() { System.out.println(s + i); } }.getClass(); Constructor<?> constructor = anonymous.getDeclaredConstructors()[0]; assertEquals(0, Invokable.from(constructor).getParameters().size()); } } public void testLocalClassInInstanceInitializer() { LocalClassInInstanceInitializer unused = new LocalClassInInstanceInitializer(); } private static
AnonymousClassInConstructor
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/TableEnvironment.java
{ "start": 20051, "end": 20520 }
class ____ a catalog function in the given path. * * <p>Compared to system functions with a globally defined name, catalog functions are always * (implicitly or explicitly) identified by a catalog and database. * * <p>There must not be another function (temporary or permanent) registered under the same * path. * * @param path The path under which the function will be registered. See also the {@link * TableEnvironment}
as
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/license/ClusterStateLicenseServiceTests.java
{ "start": 2802, "end": 17640 }
class ____ extends ESTestCase { // must use member mock for generic @Mock private ClusterStateTaskExecutor.TaskContext<StartBasicClusterTask> taskContext; private AutoCloseable closeable; @Before public void init() { closeable = MockitoAnnotations.openMocks(this); } @After public void releaseMocks() throws Exception { closeable.close(); } public void testLogExpirationWarning() { long time = LocalDate.of(2018, 11, 15).atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli(); final boolean expired = randomBoolean(); final ClusterStateLicenseService service = new ClusterStateLicenseService( Settings.EMPTY, mock(ThreadPool.class), mockDefaultClusterService(), mock(Clock.class), mock(XPackLicenseState.class) ); final String message = service.buildExpirationMessage(time, expired).toString(); if (expired) { assertThat(message, startsWith("LICENSE [EXPIRED] ON [THURSDAY, NOVEMBER 15, 2018].\n")); } else { assertThat(message, startsWith("License [will expire] on [Thursday, November 15, 2018].\n")); } } /** * Tests loading a license when {@link LicenseSettings#ALLOWED_LICENSE_TYPES_SETTING} is on its default value (all license types) */ public void testRegisterLicenseWithoutTypeRestrictions() throws Exception { assertRegisterValidLicense( Settings.EMPTY, randomValueOtherThan(License.LicenseType.BASIC, () -> randomFrom(License.LicenseType.values())) ); } /** * Tests loading a license when {@link LicenseSettings#ALLOWED_LICENSE_TYPES_SETTING} is set, * and the uploaded license type matches */ public void testSuccessfullyRegisterLicenseMatchingTypeRestrictions() throws Exception { final List<License.LicenseType> allowed = randomSubsetOf( randomIntBetween(1, LicenseSettings.ALLOWABLE_UPLOAD_TYPES.size() - 1), LicenseSettings.ALLOWABLE_UPLOAD_TYPES ); final List<String> allowedNames = allowed.stream().map(License.LicenseType::getTypeName).toList(); final Settings settings = Settings.builder().putList("xpack.license.upload.types", allowedNames).build(); assertRegisterValidLicense(settings, randomFrom(allowed)); } /** * Tests loading a license when {@link LicenseSettings#ALLOWED_LICENSE_TYPES_SETTING} is set, * and the uploaded license type does not match */ public void testFailToRegisterLicenseNotMatchingTypeRestrictions() throws Exception { final List<License.LicenseType> allowed = randomSubsetOf( randomIntBetween(1, LicenseSettings.ALLOWABLE_UPLOAD_TYPES.size() - 2), LicenseSettings.ALLOWABLE_UPLOAD_TYPES ); final List<String> allowedNames = allowed.stream().map(License.LicenseType::getTypeName).toList(); final Settings settings = Settings.builder().putList("xpack.license.upload.types", allowedNames).build(); final License.LicenseType notAllowed = randomValueOtherThanMany( test -> allowed.contains(test), () -> randomFrom(LicenseSettings.ALLOWABLE_UPLOAD_TYPES) ); assertRegisterDisallowedLicenseType(settings, notAllowed); } /** * Tests that the license overrides from {@link LicenseOverrides} are applied when an override is present for a license's ID. */ public void testLicenseExpiryDateOverride() throws IOException { UUID licenseId = UUID.fromString("12345678-abcd-0000-0000-000000000000"); // Special test UUID License.LicenseType type = randomFrom(License.LicenseType.values()); License testLicense = buildLicense(licenseId, type, TimeValue.timeValueDays(randomIntBetween(1, 100)).millis()); assertThat(LicenseUtils.getExpiryDate(testLicense), equalTo(new Date(42000L).getTime())); } /** * Tests that a license with an overridden expiry date that's in the past is expired. */ public void testLicenseWithOverridenExpiryInPastIsExpired() throws IOException { UUID licenseId = UUID.fromString("12345678-abcd-0000-0000-000000000000"); // Special test UUID License.LicenseType type = randomFrom(LicenseSettings.ALLOWABLE_UPLOAD_TYPES); License testLicense = sign(buildLicense(licenseId, type, TimeValue.timeValueDays(randomIntBetween(1, 100)).millis())); tryRegisterLicense(Settings.EMPTY, testLicense, future -> { PutLicenseResponse response = future.actionGet(); assertThat(response.status(), equalTo(LicensesStatus.EXPIRED)); }); } public void testStartBasicStartsNewLicenseIfFieldsDifferent() throws Exception { final Settings settings = Settings.builder() .put("path.home", createTempDir()) .put(DISCOVERY_TYPE_SETTING.getKey(), SINGLE_NODE_DISCOVERY_TYPE) // So we skip TLS checks .build(); final ClusterService clusterService = mockDefaultClusterService(); @SuppressWarnings("unchecked") final var taskQueue = (MasterServiceTaskQueue<ClusterStateTaskListener>) mock(MasterServiceTaskQueue.class); Mockito.when(clusterService.createTaskQueue(eq("license-service-start-basic"), any(), any())).thenReturn(taskQueue); final Clock clock = randomBoolean() ? Clock.systemUTC() : Clock.systemDefaultZone(); final var taskExecutorCaptor = ArgumentCaptor.forClass(StartBasicClusterTask.Executor.class); final ClusterStateLicenseService service = new ClusterStateLicenseService( settings, mock(ThreadPool.class), clusterService, clock, mock(XPackLicenseState.class) ); verify(clusterService).createTaskQueue(eq("license-service-start-basic"), any(), taskExecutorCaptor.capture()); final Consumer<PlainActionFuture<PostStartBasicResponse>> assertion = future -> { PostStartBasicResponse response = future.actionGet(); assertThat(response.getStatus(), equalTo(PostStartBasicResponse.Status.GENERATED_BASIC)); }; final PlainActionFuture<PostStartBasicResponse> future = new PlainActionFuture<>(); service.startBasicLicense(new PostStartBasicRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT), future); if (future.isDone()) { // If validation failed, the future might be done without calling the updater task. assertion.accept(future); } else { final var taskCaptor = ArgumentCaptor.forClass(StartBasicClusterTask.class); @SuppressWarnings("unchecked") final ArgumentCaptor<Runnable> listenerCaptor = ArgumentCaptor.forClass(Runnable.class); verify(taskQueue).submitTask(any(), taskCaptor.capture(), any()); doNothing().when(taskContext).success(listenerCaptor.capture()); when(taskContext.getTask()).thenReturn(taskCaptor.getValue()); int maxNodes = randomValueOtherThan( LicenseSettings.SELF_GENERATED_LICENSE_MAX_NODES, () -> randomIntBetween(1, LicenseSettings.SELF_GENERATED_LICENSE_MAX_NODES) ); License oldLicense = sign(buildLicense(License.LicenseType.BASIC, TimeValue.timeValueDays(randomIntBetween(1, 100)), maxNodes)); ClusterState oldState = ClusterState.EMPTY_STATE.copyAndUpdateMetadata( m -> m.putCustom(LicensesMetadata.TYPE, new LicensesMetadata(oldLicense, null)) ); ClusterState updatedState = taskExecutorCaptor.getValue() .execute(new ClusterStateTaskExecutor.BatchExecutionContext<>(oldState, List.of(taskContext), () -> null)); // Pass updated state to listener to trigger onResponse call to wrapped `future` listenerCaptor.getValue().run(); assertion.accept(future); } } private ClusterService mockDefaultClusterService() { final ClusterState clusterState = mock(ClusterState.class); Mockito.when(clusterState.metadata()).thenReturn(Metadata.EMPTY_METADATA); Mockito.when(clusterState.getClusterName()).thenReturn(ClusterName.DEFAULT); final ClusterService clusterService = mock(ClusterService.class); Mockito.when(clusterService.state()).thenReturn(clusterState); Mockito.when(clusterService.getClusterName()).thenReturn(ClusterName.DEFAULT); return clusterService; } private void assertRegisterValidLicense(Settings baseSettings, License.LicenseType licenseType) throws IOException { tryRegisterLicense(baseSettings, licenseType, future -> assertThat(future.actionGet().status(), equalTo(LicensesStatus.VALID))); } private void assertRegisterDisallowedLicenseType(Settings baseSettings, License.LicenseType licenseType) throws IOException { tryRegisterLicense(baseSettings, licenseType, future -> { final IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, future::actionGet); assertThat( exception, TestMatchers.throwableWithMessage( "Registering [" + licenseType.getTypeName() + "] licenses is not allowed on " + "this cluster" ) ); }); } private void tryRegisterLicense( Settings baseSettings, License.LicenseType licenseType, Consumer<PlainActionFuture<PutLicenseResponse>> assertion ) throws IOException { tryRegisterLicense(baseSettings, sign(buildLicense(licenseType, TimeValue.timeValueDays(randomLongBetween(1, 1000)))), assertion); } private void tryRegisterLicense(Settings baseSettings, License license, Consumer<PlainActionFuture<PutLicenseResponse>> assertion) throws IOException { final Settings settings = Settings.builder() .put(baseSettings) .put("path.home", createTempDir()) .put(DISCOVERY_TYPE_SETTING.getKey(), SINGLE_NODE_DISCOVERY_TYPE) // So we skip TLS checks .build(); final ClusterService clusterService = mockDefaultClusterService(); final Clock clock = randomBoolean() ? Clock.systemUTC() : Clock.systemDefaultZone(); final XPackLicenseState licenseState = mock(XPackLicenseState.class); final ThreadPool threadPool = mock(ThreadPool.class); final ClusterStateLicenseService service = new ClusterStateLicenseService( settings, threadPool, clusterService, clock, licenseState ); final PutLicenseRequest request = new PutLicenseRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT); request.license(toSpec(license), XContentType.JSON); final PlainActionFuture<PutLicenseResponse> future = new PlainActionFuture<>(); service.registerLicense(request, future); if (future.isDone()) { // If validation failed, the future might be done without calling the updater task. assertion.accept(future); } else { ArgumentCaptor<ClusterStateUpdateTask> taskCaptor = ArgumentCaptor.forClass(ClusterStateUpdateTask.class); verify(clusterService, times(1)).submitUnbatchedStateUpdateTask(any(), taskCaptor.capture()); final ClusterStateUpdateTask task = taskCaptor.getValue(); assertThat(task, instanceOf(AckedClusterStateUpdateTask.class)); ((AckedClusterStateUpdateTask) task).onAllNodesAcked(); assertion.accept(future); } } private BytesReference toSpec(License license) throws IOException { XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON); builder.startObject(); builder.startObject("license"); license.toInnerXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); builder.endObject(); builder.flush(); return BytesReference.bytes(builder); } private License sign(License license) throws IOException { final Path publicKey = getDataPath("/public.key"); final Path privateKey = getDataPath("/private.key"); final LicenseSigner signer = new LicenseSigner(privateKey, publicKey); return signer.sign(license); } private License buildLicense(License.LicenseType type, TimeValue expires, int maxNodes) { return buildLicense(new UUID(randomLong(), randomLong()), type, expires.millis()); } private License buildLicense(License.LicenseType type, TimeValue expires) { return buildLicense(new UUID(randomLong(), randomLong()), type, expires.millis()); } private License buildLicense(UUID licenseId, License.LicenseType type, long expires) { int maxNodes = type == License.LicenseType.ENTERPRISE ? -1 : randomIntBetween(1, 500); return buildLicense(licenseId, type, expires, maxNodes); } private License buildLicense(UUID licenseId, License.LicenseType type, long expires, int maxNodes) { assert (type == License.LicenseType.ENTERPRISE && maxNodes != -1) == false : "enterprise license must have unlimited nodes"; return License.builder() .uid(licenseId.toString()) .type(type) .expiryDate(System.currentTimeMillis() + expires) .issuer(randomAlphaOfLengthBetween(5, 60)) .issuedTo(randomAlphaOfLengthBetween(5, 60)) .issueDate(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(randomLongBetween(1, 5000))) .maxNodes(maxNodes) .maxResourceUnits(type == License.LicenseType.ENTERPRISE ? randomIntBetween(10, 500) : -1) .signature(null) .build(); } private void assertExpiryWarning(long adjustment, String msg) { long now = System.currentTimeMillis(); long expiration = now + adjustment; String warning = LicenseUtils.getExpiryWarning(expiration, now); if (msg == null) { assertThat(warning, is(nullValue())); } else { assertThat(warning, Matchers.containsString(msg)); } } public void testNoExpiryWarning() { assertExpiryWarning(LICENSE_EXPIRATION_WARNING_PERIOD.getMillis(), null); } public void testExpiryWarningSoon() { assertExpiryWarning(LICENSE_EXPIRATION_WARNING_PERIOD.getMillis() - 1, "Your license will expire in [6] days"); } public void testExpiryWarningToday() { assertExpiryWarning(1, "Your license expires today"); } public void testExpiryWarningExpired() { assertExpiryWarning(0, "Your license expired on"); } }
ClusterStateLicenseServiceTests
java
elastic__elasticsearch
x-pack/plugin/ccr/src/main/java/org/elasticsearch/xpack/ccr/action/ShardFollowTaskCleaner.java
{ "start": 1524, "end": 5619 }
class ____ implements ClusterStateListener { private static final Logger logger = LogManager.getLogger(ShardFollowTaskCleaner.class); private final ThreadPool threadPool; private final Client client; /** * Tasks that are currently being completed. */ private final Set<ShardFollowTask> completing = Collections.synchronizedSet(new HashSet<>()); public ShardFollowTaskCleaner(final ClusterService clusterService, final ThreadPool threadPool, final Client client) { this.threadPool = threadPool; this.client = client; if (DiscoveryNode.isMasterNode(clusterService.getSettings())) { clusterService.addListener(this); } } @Override public void clusterChanged(final ClusterChangedEvent event) { if (event.state().blocks().hasGlobalBlock(GatewayService.STATE_NOT_RECOVERED_BLOCK)) { return; } if (event.localNodeMaster() == false) { return; } final Metadata metadata = event.state().metadata(); final PersistentTasksCustomMetadata persistentTasksMetadata = metadata.getProject().custom(PersistentTasksCustomMetadata.TYPE); final Metadata previousMetadata = event.previousState().metadata(); if (metadata.getProject().indices() == event.previousState().getMetadata().getProject().indices() && persistentTasksMetadata == previousMetadata.getProject().custom(PersistentTasksCustomMetadata.TYPE) && event.previousState().nodes().isLocalNodeElectedMaster() && event.blocksChanged() == false) { // nothing of relevance changed return; } if (persistentTasksMetadata == null) { return; } for (PersistentTasksCustomMetadata.PersistentTask<?> persistentTask : persistentTasksMetadata.tasks()) { if (ShardFollowTask.NAME.equals(persistentTask.getTaskName()) == false) { // this task is not a shard follow task continue; } ShardFollowTask shardFollowTask = (ShardFollowTask) persistentTask.getParams(); Index followerIndex = shardFollowTask.getFollowShardId().getIndex(); if (metadata.getProject().index(followerIndex) != null) { // the index exists, do not clean this persistent task continue; } if (completing.add(shardFollowTask) == false) { // already completing this task continue; } threadPool.generic().execute(ActionRunnable.wrap(ActionListener.runBefore(new ActionListener<PersistentTaskResponse>() { @Override public void onResponse(PersistentTaskResponse persistentTaskResponse) { logger.debug("task [{}] cleaned up", persistentTask.getId()); } @Override public void onFailure(Exception e) { logger.warn(() -> "failed to clean up task [" + persistentTask.getId() + "]", e); } }, () -> completing.remove(shardFollowTask)), listener -> { /* * We are executing under the system context, on behalf of the user to clean up the shard follow task after the follower * index was deleted. This is why the system role includes the privilege for persistent task completion. */ assert threadPool.getThreadContext().isSystemContext(); client.execute( CompletionPersistentTaskAction.INSTANCE, new CompletionPersistentTaskAction.Request( MasterNodeRequest.INFINITE_MASTER_NODE_TIMEOUT, persistentTask.getId(), persistentTask.getAllocationId(), new IndexNotFoundException(followerIndex), null ), listener ); })); } } }
ShardFollowTaskCleaner
java
spring-projects__spring-boot
module/spring-boot-webmvc/src/main/java/org/springframework/boot/webmvc/autoconfigure/WebMvcRegistrations.java
{ "start": 1816, "end": 2786 }
interface ____ { /** * Return the custom {@link RequestMappingHandlerMapping} that should be used and * processed by the MVC configuration. * @return the custom {@link RequestMappingHandlerMapping} instance */ default @Nullable RequestMappingHandlerMapping getRequestMappingHandlerMapping() { return null; } /** * Return the custom {@link RequestMappingHandlerAdapter} that should be used and * processed by the MVC configuration. * @return the custom {@link RequestMappingHandlerAdapter} instance */ default @Nullable RequestMappingHandlerAdapter getRequestMappingHandlerAdapter() { return null; } /** * Return the custom {@link ExceptionHandlerExceptionResolver} that should be used and * processed by the MVC configuration. * @return the custom {@link ExceptionHandlerExceptionResolver} instance */ default @Nullable ExceptionHandlerExceptionResolver getExceptionHandlerExceptionResolver() { return null; } }
WebMvcRegistrations
java
apache__camel
components/camel-mail/src/test/java/org/apache/camel/component/mail/AuthenticatorTest.java
{ "start": 1588, "end": 5349 }
class ____ extends CamelTestSupport { private static final MailboxUser james3 = Mailbox.getOrCreateUser("james3", "secret"); private static final MailboxUser james4 = Mailbox.getOrCreateUser("james4", "secret"); /** * Checks that the authenticator does dynamically return passwords for the smtp endpoint. */ @Test public void testSendAndReceiveMails() throws Exception { Mailbox.clearAll(); // first expect correct result because smtp authenticator does not return wrong password callAndCheck("mock:result"); // second expect exception because smtp authenticator does return wrong password callAndCheck("mock:exception"); // third expect correct result because smtp authenticator does not return wrong password callAndCheck("mock:result"); } private String callAndCheck(String endpoint) throws MessagingException, InterruptedException { MockEndpoint resultEndpoint = getMockEndpoint(endpoint); resultEndpoint.expectedMinimumMessageCount(1); //resultEndpoint.setResultWaitTime(60000); String body = "hello world!"; execute(james3.getEmail(), body); resultEndpoint.assertIsSatisfied(); Exchange exchange = resultEndpoint.getReceivedExchanges().get(0); String text = exchange.getIn().getBody(String.class); assertEquals(body, text, "mail body"); return body; } private void execute(String mailAddress, String body) throws MessagingException { Session session = Mailbox.getSmtpSession(); MimeMessage message = new MimeMessage(session); populateMimeMessageBody(message, body); message.setRecipients(Message.RecipientType.TO, mailAddress); Transport.send(message, james3.getLogin(), james3.getPassword()); } protected void populateMimeMessageBody(MimeMessage message, String body) throws MessagingException { MimeBodyPart plainPart = new MimeBodyPart(); plainPart.setText(body); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setText("<html><body>" + body + "</body></html>"); Multipart alt = new MimeMultipart("alternative"); alt.addBodyPart(plainPart); alt.addBodyPart(htmlPart); Multipart mixed = new MimeMultipart("mixed"); MimeBodyPart wrap = new MimeBodyPart(); wrap.setContent(alt); mixed.addBodyPart(wrap); mixed.addBodyPart(plainPart); mixed.addBodyPart(htmlPart); mixed.addBodyPart(plainPart); mixed.addBodyPart(htmlPart); message.setContent(mixed); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { getContext().getRegistry().bind("authPop3", new MyAuthenticator("pop3")); getContext().getRegistry().bind("authSmtp", new MyAuthenticator("smtp")); getContext().getRegistry().bind("authImap", new MyAuthenticator("imap")); onException(MessagingException.class).handled(true).to("mock:exception"); from("pop3://localhost:" + Mailbox.getPort(Protocol.pop3) + "?initialDelay=100&delay=100&authenticator=#authPop3").removeHeader("to") .to("smtp://localhost:" + Mailbox.getPort(Protocol.smtp) + "?authenticator=#authSmtp&to=james4@localhost"); from("imap://localhost:" + Mailbox.getPort(Protocol.imap) + "?initialDelay=200&delay=100&authenticator=#authImap").convertBodyTo(String.class) .to("mock:result"); } }; } public static
AuthenticatorTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/api/protocolrecords/impl/pb/TestPBLocalizerRPC.java
{ "start": 1948, "end": 3643 }
class ____ implements LocalizationProtocol { private final InetSocketAddress locAddr; private Server server; LocalizerService(InetSocketAddress locAddr) { this.locAddr = locAddr; } public void start() { Configuration conf = new Configuration(); YarnRPC rpc = YarnRPC.create(conf); server = rpc.getServer( LocalizationProtocol.class, this, locAddr, conf, null, 1); server.start(); } public void stop() { if (server != null) { server.stop(); } } @Override public LocalizerHeartbeatResponse heartbeat(LocalizerStatus status) { return dieHBResponse(); } } static LocalizerHeartbeatResponse dieHBResponse() { LocalizerHeartbeatResponse response = recordFactory.newRecordInstance(LocalizerHeartbeatResponse.class); response.setLocalizerAction(LocalizerAction.DIE); return response; } @Test public void testLocalizerRPC() throws Exception { InetSocketAddress locAddr = new InetSocketAddress("0.0.0.0", 8040); LocalizerService server = new LocalizerService(locAddr); try { server.start(); Configuration conf = new Configuration(); YarnRPC rpc = YarnRPC.create(conf); LocalizationProtocol client = (LocalizationProtocol) rpc.getProxy(LocalizationProtocol.class, locAddr, conf); LocalizerStatus status = recordFactory.newRecordInstance(LocalizerStatus.class); status.setLocalizerId("localizer0"); LocalizerHeartbeatResponse response = client.heartbeat(status); assertEquals(dieHBResponse(), response); } finally { server.stop(); } assertTrue(true); } }
LocalizerService
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/provider/ProxyIdAccessor.java
{ "start": 869, "end": 1451 }
interface ____ { /** * Returns whether the {@link ProxyIdAccessor} should be used for the given entity. Will inspect the entity to see * whether it is a proxy so that lenient id lookup can be used. * * @param entity must not be {@literal null}. * @return */ boolean shouldUseAccessorFor(Object entity); /** * Returns the identifier of the given entity by leniently inspecting it for the identifier value. * * @param entity must not be {@literal null}. * @return can be {@literal null}. */ @Nullable Object getIdentifierFrom(Object entity); }
ProxyIdAccessor
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/datastreams/TimeSeriesFeatureSetUsage.java
{ "start": 2615, "end": 15651 }
class ____ extends XPackFeatureUsage { private static final TransportVersion TIME_SERIES_TELEMETRY = TransportVersion.fromName("time_series_telemetry"); private static final TransportVersion ADD_DOWNSAMPLING_METHOD_TELEMETRY = TransportVersion.fromName("add_downsample_method_telemetry"); private final long timeSeriesDataStreamCount; private final long timeSeriesIndexCount; private final DownsamplingUsage downsamplingUsage; public TimeSeriesFeatureSetUsage(StreamInput input) throws IOException { super(input); this.timeSeriesDataStreamCount = input.readVLong(); if (timeSeriesDataStreamCount == 0) { timeSeriesIndexCount = 0; downsamplingUsage = null; } else { this.timeSeriesIndexCount = input.readVLong(); this.downsamplingUsage = input.readOptionalWriteable(DownsamplingUsage::read); } } /** * Helper constructor that only requires DLM stats. This can be used when elasticsearch is running in * data-stream-lifecycle-only mode. In this mode ILM is not supported, which entails there will be no stats either. */ public TimeSeriesFeatureSetUsage( long timeSeriesDataStreamCount, long timeSeriesIndexCount, DownsamplingFeatureStats dlmDownsamplingStats, Map<String, Long> indexCountPerInterval ) { this(timeSeriesDataStreamCount, timeSeriesIndexCount, null, null, dlmDownsamplingStats, indexCountPerInterval); } public TimeSeriesFeatureSetUsage( long timeSeriesDataStreamCount, long timeSeriesIndexCount, DownsamplingFeatureStats ilmDownsamplingStats, IlmPolicyStats ilmPolicyStats, DownsamplingFeatureStats dlmDownsamplingStats, Map<String, Long> indexCountPerInterval ) { super(XPackField.TIME_SERIES_DATA_STREAMS, true, true); this.timeSeriesDataStreamCount = timeSeriesDataStreamCount; if (timeSeriesDataStreamCount == 0) { this.timeSeriesIndexCount = 0; this.downsamplingUsage = null; } else { this.timeSeriesIndexCount = timeSeriesIndexCount; this.downsamplingUsage = new DownsamplingUsage( ilmDownsamplingStats, ilmPolicyStats, dlmDownsamplingStats, indexCountPerInterval ); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVLong(timeSeriesDataStreamCount); if (timeSeriesDataStreamCount > 0) { out.writeVLong(timeSeriesIndexCount); out.writeOptionalWriteable(downsamplingUsage); } } @Override public TransportVersion getMinimalSupportedVersion() { return TIME_SERIES_TELEMETRY; } public long getTimeSeriesDataStreamCount() { return timeSeriesDataStreamCount; } public long getTimeSeriesIndexCount() { return timeSeriesIndexCount; } public DownsamplingUsage getDownsamplingUsage() { return downsamplingUsage; } @Override protected void innerXContent(XContentBuilder builder, Params params) throws IOException { super.innerXContent(builder, params); builder.field("data_stream_count", timeSeriesDataStreamCount); if (timeSeriesDataStreamCount > 0) { builder.field("index_count", timeSeriesIndexCount); } if (downsamplingUsage != null) { builder.field("downsampling", downsamplingUsage); } } @Override public String toString() { return Strings.toString(this); } @Override public int hashCode() { return Objects.hash(timeSeriesDataStreamCount, timeSeriesIndexCount, downsamplingUsage); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj.getClass() != getClass()) { return false; } TimeSeriesFeatureSetUsage other = (TimeSeriesFeatureSetUsage) obj; return timeSeriesDataStreamCount == other.timeSeriesDataStreamCount && timeSeriesIndexCount == other.timeSeriesIndexCount && Objects.equals(downsamplingUsage, other.downsamplingUsage); } public record DownsamplingUsage( DownsamplingFeatureStats ilmDownsamplingStats, IlmPolicyStats ilmPolicyStats, DownsamplingFeatureStats dlmDownsamplingStats, Map<String, Long> indexCountPerInterval ) implements Writeable, ToXContentObject { public static DownsamplingUsage read(StreamInput in) throws IOException { DownsamplingFeatureStats ilmDownsamplingStats = in.readOptionalWriteable(DownsamplingFeatureStats::read); IlmPolicyStats ilmPolicyStats = ilmDownsamplingStats != null ? IlmPolicyStats.read(in) : null; DownsamplingFeatureStats dlmDownsamplingStats = DownsamplingFeatureStats.read(in); Map<String, Long> indexCountPerInterval = in.readImmutableMap(StreamInput::readString, StreamInput::readVLong); return new DownsamplingUsage(ilmDownsamplingStats, ilmPolicyStats, dlmDownsamplingStats, indexCountPerInterval); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalWriteable(ilmDownsamplingStats); if (ilmDownsamplingStats != null) { ilmPolicyStats.writeTo(out); } dlmDownsamplingStats.writeTo(out); out.writeMap(indexCountPerInterval, StreamOutput::writeString, StreamOutput::writeVLong); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); if (indexCountPerInterval != null && indexCountPerInterval.isEmpty() == false) { builder.startObject("index_count_per_interval"); for (Map.Entry<String, Long> entry : indexCountPerInterval.entrySet()) { builder.field(entry.getKey(), entry.getValue()); } builder.endObject(); } if (ilmDownsamplingStats != null) { builder.startObject("ilm"); ilmDownsamplingStats.toXContent(builder, params); ilmPolicyStats.toXContent(builder, params); builder.endObject(); } if (dlmDownsamplingStats != null) { builder.startObject("dlm"); dlmDownsamplingStats.toXContent(builder, params); builder.endObject(); } return builder.endObject(); } } public record DownsamplingFeatureStats( long dataStreamsCount, long indexCount, long minRounds, double averageRounds, long maxRounds, long aggregateSamplingMethod, long lastValueSamplingMethod, long undefinedSamplingMethod ) implements Writeable, ToXContentFragment { static final DownsamplingFeatureStats EMPTY = new DownsamplingFeatureStats(0, 0, 0, 0.0, 0, 0, 0, 0); public static DownsamplingFeatureStats read(StreamInput in) throws IOException { long dataStreamsCount = in.readVLong(); if (dataStreamsCount == 0) { return EMPTY; } else { return new DownsamplingFeatureStats( dataStreamsCount, in.readVLong(), in.readVLong(), in.readDouble(), in.readVLong(), in.getTransportVersion().supports(ADD_DOWNSAMPLING_METHOD_TELEMETRY) ? in.readVLong() : 0, in.getTransportVersion().supports(ADD_DOWNSAMPLING_METHOD_TELEMETRY) ? in.readVLong() : 0, in.getTransportVersion().supports(ADD_DOWNSAMPLING_METHOD_TELEMETRY) ? in.readVLong() : 0 ); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(this.dataStreamsCount); if (this.dataStreamsCount != 0) { out.writeVLong(this.indexCount); out.writeVLong(this.minRounds); out.writeDouble(this.averageRounds); out.writeVLong(this.maxRounds); if (out.getTransportVersion().supports(ADD_DOWNSAMPLING_METHOD_TELEMETRY)) { out.writeVLong(this.aggregateSamplingMethod); out.writeVLong(this.lastValueSamplingMethod); out.writeVLong(this.undefinedSamplingMethod); } } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("downsampled_data_stream_count", dataStreamsCount); if (dataStreamsCount > 0) { builder.field("downsampled_index_count", indexCount); builder.startObject("rounds_per_data_stream"); builder.field("min", minRounds); builder.field("average", averageRounds); builder.field("max", maxRounds); builder.endObject(); builder.startObject("sampling_method"); builder.field("aggregate", aggregateSamplingMethod); builder.field("last_value", lastValueSamplingMethod); builder.field("undefined", undefinedSamplingMethod); builder.endObject(); } return builder; } } /** * Calculates statistics specific to the ILM policies in use * @param downsamplingPhases the phases used for downsampling * @param forceMergeExplicitlyEnabledCounter the policies that have force merge explicitly enabled * @param forceMergeExplicitlyDisabledCounter the policies that have force merge implicitly enabled * @param forceMergeDefaultCounter the policies that have not specified force merge * @param downsampledForceMergeNeededCounter the policies that could potentially skip the force merge in downsampling */ public record IlmPolicyStats( Map<String, Long> downsamplingPhases, long forceMergeExplicitlyEnabledCounter, long forceMergeExplicitlyDisabledCounter, long forceMergeDefaultCounter, long downsampledForceMergeNeededCounter ) implements Writeable, ToXContentFragment { public static final IlmPolicyStats EMPTY = new IlmPolicyStats(Map.of(), 0L, 0L, 0L, 0L); static IlmPolicyStats read(StreamInput in) throws IOException { Map<String, Long> downsamplingPhases = in.readImmutableMap(StreamInput::readString, StreamInput::readVLong); long forceMergeExplicitlyEnabledCounter = 0; long forceMergeExplicitlyDisabledCounter = 0; long forceMergeDefaultCounter = 0; long downsampledForceMergeNeededCounter = 0; if (in.getTransportVersion().supports(DownsampleAction.ILM_FORCE_MERGE_IN_DOWNSAMPLING)) { forceMergeExplicitlyEnabledCounter = in.readVLong(); forceMergeExplicitlyDisabledCounter = in.readVLong(); forceMergeDefaultCounter = in.readVLong(); downsampledForceMergeNeededCounter = in.readVLong(); } return new IlmPolicyStats( downsamplingPhases, forceMergeExplicitlyEnabledCounter, forceMergeExplicitlyDisabledCounter, forceMergeDefaultCounter, downsampledForceMergeNeededCounter ); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeMap(downsamplingPhases, StreamOutput::writeString, StreamOutput::writeVLong); if (out.getTransportVersion().supports(DownsampleAction.ILM_FORCE_MERGE_IN_DOWNSAMPLING)) { out.writeVLong(forceMergeExplicitlyEnabledCounter); out.writeVLong(forceMergeExplicitlyDisabledCounter); out.writeVLong(forceMergeDefaultCounter); out.writeVLong(downsampledForceMergeNeededCounter); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("phases_in_use", downsamplingPhases); builder.startObject("force_merge"); builder.field("explicitly_enabled_count", forceMergeExplicitlyEnabledCounter); builder.field("explicitly_disabled_count", forceMergeExplicitlyDisabledCounter); builder.field("undefined_count", forceMergeDefaultCounter); builder.field("undefined_force_merge_needed_count", downsampledForceMergeNeededCounter); builder.endObject(); return null; } } }
TimeSeriesFeatureSetUsage
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/job/impl/TaskAttemptImpl.java
{ "start": 103356, "end": 104930 }
class ____ implements SingleArcTransition<TaskAttemptImpl, TaskAttemptEvent> { @SuppressWarnings("unchecked") @Override public void transition(TaskAttemptImpl taskAttempt, TaskAttemptEvent event) { TaskAttemptStatusUpdateEvent statusEvent = ((TaskAttemptStatusUpdateEvent)event); AtomicReference<TaskAttemptStatus> taskAttemptStatusRef = statusEvent.getTaskAttemptStatusRef(); TaskAttemptStatus newReportedStatus = taskAttemptStatusRef.getAndSet(null); // Now switch the information in the reportedStatus taskAttempt.reportedStatus = newReportedStatus; taskAttempt.reportedStatus.taskState = taskAttempt.getState(); // send event to speculator about the reported status taskAttempt.eventHandler.handle (new SpeculatorEvent (taskAttempt.reportedStatus, taskAttempt.clock.getTime())); taskAttempt.updateProgressSplits(); //if fetch failures are present, send the fetch failure event to job //this only will happen in reduce attempt type if (taskAttempt.reportedStatus.fetchFailedMaps != null && taskAttempt.reportedStatus.fetchFailedMaps.size() > 0) { String hostname = taskAttempt.container == null ? "UNKNOWN" : taskAttempt.container.getNodeId().getHost(); taskAttempt.eventHandler.handle(new JobTaskAttemptFetchFailureEvent( taskAttempt.attemptId, taskAttempt.reportedStatus.fetchFailedMaps, hostname)); } } } private static
StatusUpdater
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2101/Issue2101Mapper.java
{ "start": 354, "end": 1009 }
interface ____ { Issue2101Mapper INSTANCE = Mappers.getMapper( Issue2101Mapper.class ); @Mapping(target = "value1", source = "codeValue1") @Mapping(target = "value2", source = "codeValue2") Source map(Target target); @InheritInverseConfiguration @Mapping(target = "codeValue1.code", constant = "c1") @Mapping(target = "codeValue1.value", source = "value1") @Mapping(target = "codeValue2.code", constant = "c2") @Mapping(target = "codeValue2.value", source = "value2") Target map(Source source); default String mapFrom( CodeValuePair cv ) { return cv.code; } //CHECKSTYLE:OFF
Issue2101Mapper
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/InterceptorBindings.java
{ "start": 232, "end": 2764 }
class ____ { private final Set<String> allInterceptorBindings; private final Map<Class<? extends Annotation>, Set<Annotation>> transitiveInterceptorBindings; InterceptorBindings(Set<String> interceptorBindings, Map<Class<? extends Annotation>, Set<Annotation>> transitiveInterceptorBindings) { this.allInterceptorBindings = interceptorBindings; this.transitiveInterceptorBindings = transitiveInterceptorBindings; } boolean isRegistered(Class<? extends Annotation> annotationType) { return allInterceptorBindings.contains(annotationType.getName()); } Set<Annotation> getTransitive(Class<? extends Annotation> interceptorBinding) { return transitiveInterceptorBindings.get(interceptorBinding); } void verify(Annotation[] interceptorBindings) { if (interceptorBindings.length == 0) { return; } if (interceptorBindings.length == 1) { verifyInterceptorBinding(interceptorBindings[0].annotationType()); } else { Map<Class<? extends Annotation>, Integer> timesQualifierWasSeen = new HashMap<>(); for (Annotation interceptorBinding : interceptorBindings) { verifyInterceptorBinding(interceptorBinding.annotationType()); timesQualifierWasSeen.compute(interceptorBinding.annotationType(), TimesSeenBiFunction.INSTANCE); } checkInterceptorBindingsForDuplicates(timesQualifierWasSeen); } } // in various cases, specification requires to check interceptor bindings for duplicates and throw IAE private static void checkInterceptorBindingsForDuplicates(Map<Class<? extends Annotation>, Integer> timesSeen) { timesSeen.forEach(InterceptorBindings::checkInterceptorBindingsForDuplicates); } private static void checkInterceptorBindingsForDuplicates(Class<? extends Annotation> annClass, Integer timesSeen) { if (timesSeen > 1 && !annClass.isAnnotationPresent(Repeatable.class)) { throw new IllegalArgumentException("Interceptor binding " + annClass + " was used repeatedly but is not @Repeatable"); } } private void verifyInterceptorBinding(Class<? extends Annotation> annotationType) { if (!allInterceptorBindings.contains(annotationType.getName())) { throw new IllegalArgumentException("Annotation is not a registered interceptor binding: " + annotationType); } } private static
InterceptorBindings
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnClassTests.java
{ "start": 3425, "end": 3629 }
class ____ { @Bean String foo() { return "foo"; } } @Configuration(proxyBeanMethods = false) @ImportResource("org/springframework/boot/autoconfigure/condition/foo.xml") static
FooConfiguration
java
quarkusio__quarkus
extensions/devui/runtime/src/main/java/io/quarkus/devui/runtime/build/BuildMetricsDevUIController.java
{ "start": 791, "end": 8614 }
class ____ { private static final Logger LOG = Logger.getLogger(BuildMetricsDevUIController.class.getName()); private static final BuildMetricsDevUIController INSTANCE = new BuildMetricsDevUIController(); public static BuildMetricsDevUIController get() { return INSTANCE; } private Path buildMetricsPath; private volatile Map<String, Object> buildStepsMetrics; private BuildMetricsDevUIController() { } void setBuildMetricsPath(Path buildMetricsPath) { this.buildMetricsPath = buildMetricsPath; // Reread the data after reload this.buildStepsMetrics = null; } Map<String, Object> getBuildStepsMetrics() { if (buildStepsMetrics != null) { return buildStepsMetrics; } synchronized (this) { if (buildStepsMetrics != null) { return buildStepsMetrics; } buildStepsMetrics = prepareBuildStepsMetrics(); return buildStepsMetrics; } } public Map<String, Object> prepareBuildStepsMetrics() { Map<String, Object> metrics = new HashMap<>(); Map<String, JsonObject> stepIdToRecord = new HashMap<>(); Map<Integer, JsonObject> recordIdToRecord = new HashMap<>(); Map<String, List<JsonObject>> threadToRecords = new HashMap<>(); long buildDuration = 0; LocalTime buildStarted = null; if (Files.isReadable(buildMetricsPath)) { try { JsonObject data = new JsonObject(Files.readString(buildMetricsPath)); buildDuration = data.getLong("duration"); buildStarted = LocalDateTime .parse(data.getString("started"), DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalTime(); JsonArray records = data.getJsonArray("records"); for (Object record : records) { JsonObject recordObj = (JsonObject) record; recordObj.put("encodedStepId", URLEncoder.encode(recordObj.getString("stepId"), StandardCharsets.UTF_8.toString())); String thread = recordObj.getString("thread"); stepIdToRecord.put(recordObj.getString("stepId"), recordObj); recordIdToRecord.put(recordObj.getInteger("id"), recordObj); List<JsonObject> steps = threadToRecords.get(thread); if (steps == null) { steps = new ArrayList<>(); threadToRecords.put(thread, steps); } steps.add(recordObj); } metrics.put("records", records); metrics.put("items", data.getJsonArray("items")); metrics.put("itemsCount", data.getInteger("itemsCount")); metrics.put("duration", buildDuration); } catch (IOException e) { LOG.error(e); } } // Build dependency graphs Map<String, JsonObject> dependencyGraphs = new HashMap<>(); for (Map.Entry<String, JsonObject> e : stepIdToRecord.entrySet()) { dependencyGraphs.put(e.getKey(), buildDependencyGraph(e.getValue(), stepIdToRecord, recordIdToRecord).toJson()); } metrics.put("dependencyGraphs", dependencyGraphs); // Time slots long slotDuration = Math.max(10, buildDuration / 100); List<Long> slots = new ArrayList<>(); long currentSlot = slotDuration; while (currentSlot < buildDuration) { slots.add(currentSlot); currentSlot += slotDuration; } if (currentSlot != buildDuration) { slots.add(buildDuration); } metrics.put("slots", slots); Map<String, List<List<String>>> threadToSlotRecords = new HashMap<>(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS"); for (Map.Entry<String, List<JsonObject>> entry : threadToRecords.entrySet()) { String thread = entry.getKey(); List<JsonObject> records = entry.getValue(); List<List<String>> threadSlots = new ArrayList<>(); for (Long slot : slots) { List<String> slotRecords = new ArrayList<>(); for (JsonObject record : records) { LocalTime started = LocalTime.parse(record.getString("started"), formatter); long startAt = Duration.between(buildStarted, started).toMillis(); if (startAt < slot && (slot - slotDuration) < (startAt + record.getLong("duration"))) { slotRecords.add(record.getString("stepId")); } } threadSlots.add(slotRecords); } threadToSlotRecords.put(thread, threadSlots); } metrics.put("threadSlotRecords", threadToSlotRecords); return metrics; } DependencyGraph buildDependencyGraph(JsonObject step, Map<String, JsonObject> stepIdToRecord, Map<Integer, JsonObject> recordIdToRecord) { Set<Node> nodes = new HashSet<>(); Set<Link> links = new HashSet<>(); addNodesDependents(step, nodes, links, step, stepIdToRecord, recordIdToRecord); addNodeDependencies(step, nodes, links, step, stepIdToRecord, recordIdToRecord); return new DependencyGraph(nodes, links); } void addNodesDependents(JsonObject root, Set<Node> nodes, Set<Link> links, JsonObject record, Map<String, JsonObject> stepIdToRecord, Map<Integer, JsonObject> recordIdToRecord) { String stepId = record.getString("stepId"); nodes.add(new Node(stepId, record.getString("encodedStepId"))); for (Object dependentRecordId : record.getJsonArray("dependents")) { int recordId = (int) dependentRecordId; if (recordId != record.getInteger("id")) { JsonObject dependentRecord = recordIdToRecord.get(recordId); String dependentStepId = dependentRecord.getString("stepId"); links.add(Link.dependent(root.equals(record), dependentStepId, stepId)); nodes.add(new Node(dependentStepId, dependentRecord.getString("encodedStepId"))); // NOTE: we do not fetch transient dependencies yet because the UI is not ready to show so many nodes // if (added) { // addNodesDependents(root, nodes, links, dependentRecord, stepIdToRecord, recordIdToRecord); // } } } } void addNodeDependencies(JsonObject root, Set<Node> nodes, Set<Link> links, JsonObject record, Map<String, JsonObject> stepIdToRecord, Map<Integer, JsonObject> recordIdToRecord) { for (Map.Entry<String, JsonObject> entry : stepIdToRecord.entrySet()) { for (Object dependentRecordId : entry.getValue().getJsonArray("dependents")) { int recordId = (int) dependentRecordId; if (record.getInteger("id") == recordId) { links.add(Link.dependency(root.equals(record), record.getString("stepId"), entry.getValue().getString("stepId"))); nodes.add(new Node(entry.getValue().getString("stepId"), entry.getValue().getString("encodedStepId"))); // NOTE: we do not fetch transient dependencies yet because the UI is not ready to show so many nodes // if (added) { // addNodeDependencies(root, nodes, links, entry.getValue(), stepIdToRecord, recordIdToRecord); // } } } } } public static
BuildMetricsDevUIController
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DatasetComponentBuilderFactory.java
{ "start": 1395, "end": 1877 }
interface ____ { /** * Dataset (camel-dataset) * Provide data for load and soak testing of your Camel application. * * Category: core,testing * Since: 1.3 * Maven coordinates: org.apache.camel:camel-dataset * * @return the dsl builder */ static DatasetComponentBuilder dataset() { return new DatasetComponentBuilderImpl(); } /** * Builder for the Dataset component. */
DatasetComponentBuilderFactory
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/project/artifact/ProjectArtifactsCache.java
{ "start": 1585, "end": 1736 }
interface ____ extends Set<Artifact> { DependencyResolutionResult getResult(); } /** * CacheRecord */
ArtifactsSetWithResult
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/deftyping/DefaultWithBaseType1093Test.java
{ "start": 702, "end": 1794 }
class ____ { public int x, y; protected Point1093() { } protected Point1093(int _x, int _y) { x = _x; y = _y; } } // [databind#1093] @Test public void testWithDefaultTyping() throws Exception { ObjectMapper m = JsonMapper.builder() .activateDefaultTyping(NoCheckSubTypeValidator.instance, DefaultTyping.JAVA_LANG_OBJECT) .build(); final Point1093 input = new Point1093(28, 12); _testWithDefaultTyping(input, m.readerFor(Object.class), m.writer().forType(Object.class)); _testWithDefaultTyping(input, m.readerFor(Object.class), m.writerFor(Object.class)); } private void _testWithDefaultTyping(Point1093 input, ObjectReader r, ObjectWriter w) throws Exception { String json = w.writeValueAsString(input); Point1093 result = (Point1093) r.readValue(json); assertEquals(input.x, result.x); assertEquals(input.y, result.y); } }
Point1093
java
apache__flink
flink-state-backends/flink-statebackend-forst/src/main/java/org/apache/flink/state/forst/ForStStateBackend.java
{ "start": 40692, "end": 40946 }
class ____, then we can see the following exception: // "java.lang.UnsatisfiedLinkError: Native Library // /path/to/temp/dir/librocksdbjni-linux64.so // already loaded in another
loaders
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/subpackage/ClassWithStaticInnerTestCases.java
{ "start": 678, "end": 744 }
class ____ { @Test void test2() { } } }
ShouldNotBeDiscovered
java
processing__processing4
app/src/processing/app/tools/ThemeSelector.java
{ "start": 14610, "end": 16871 }
class ____ extends JPanel { static final int OUTSET = 5; static final int OUTLINE = 3; static final int DIM = 80; static final int BETWEEN = 25; static final int EACH = DIM + BETWEEN; static final int MARGIN = OUTSET + (OUTLINE + 1) / 2; static final int SIZE = MARGIN*2 + DIM*4 + BETWEEN*3; ColorfulPanel() { addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { handleMouse(e); } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { handleMouse(e); } }); setOpaque(false); } private void handleMouse(MouseEvent e) { int col = constrain((e.getX() - MARGIN) / EACH); int colEx = constrain((e.getX() - MARGIN) % EACH); int row = constrain((e.getY() - MARGIN) / EACH); int rowEx = constrain((e.getY() - MARGIN) % EACH); if (colEx < DIM && rowEx < DIM) { int index = row * 4 + col; if (index < currentSet.count && index != currentIndex) { setCurrentIndex(index); repaint(); } } } private int constrain(int value) { return Math.max(0, Math.min(value, 3)); } @Override public void paintComponent(Graphics g) { for (int i = 0; i < currentSet.count; i++) { int col = i % 4; int row = i / 4; int x = MARGIN + col*EACH; int y = MARGIN + row*EACH; g.drawImage(currentSet.images[i], x, y, DIM, DIM, null); } Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(OUTLINE)); g2.setColor(Color.GRAY); if (currentIndex != -1) { int col = currentIndex % 4; int row = currentIndex / 4; g2.drawRect(MARGIN + EACH * col - OUTSET, MARGIN + EACH * row - OUTSET, DIM + OUTSET * 2, DIM + OUTSET * 2); } } @Override public Dimension getPreferredSize() { return new Dimension(SIZE, SIZE); } public Dimension getMinimumSize() { return getPreferredSize(); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } } }
ColorfulPanel
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/DubboConfigBeanInitializerTest.java
{ "start": 2676, "end": 4165 }
class ____ { @BeforeAll public static void beforeAll() { DubboBootstrap.reset(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Autowired private FooService fooService; @Autowired private ApplicationContext applicationContext; @Test void test() { Assertions.assertNotNull(fooService, "fooService is null"); Assertions.assertNotNull(fooService.helloService, "ooService.helloService is null"); // expect fooService is registered before dubbo config bean List<String> beanNames = Arrays.asList(applicationContext.getBeanDefinitionNames()); int fooServiceIndex = beanNames.indexOf("fooService"); int applicationConfigIndex = beanNames.indexOf("dubbo-demo-application"); int registryConfigIndex = beanNames.indexOf("my-registry"); int configInitializerIndex = beanNames.indexOf(DubboConfigBeanInitializer.BEAN_NAME); Assertions.assertTrue(fooServiceIndex < applicationConfigIndex); Assertions.assertTrue(fooServiceIndex < registryConfigIndex); Assertions.assertTrue(fooServiceIndex < configInitializerIndex); } @Configuration // Import BusinessConfig first, make sure FooService bean is register early, // expect dubbo config beans are initialized before FooService bean @Import({BusinessConfig.class, ConsumerConfig.class, ProviderConfiguration.class}) static
DubboConfigBeanInitializerTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/AlterPartitionReassignmentsResponse.java
{ "start": 1127, "end": 2553 }
class ____ extends AbstractResponse { private final AlterPartitionReassignmentsResponseData data; public AlterPartitionReassignmentsResponse(AlterPartitionReassignmentsResponseData data) { super(ApiKeys.ALTER_PARTITION_REASSIGNMENTS); this.data = data; } public static AlterPartitionReassignmentsResponse parse(Readable readable, short version) { return new AlterPartitionReassignmentsResponse( new AlterPartitionReassignmentsResponseData(readable, version)); } @Override public AlterPartitionReassignmentsResponseData data() { return data; } @Override public boolean shouldClientThrottle(short version) { return true; } @Override public int throttleTimeMs() { return data.throttleTimeMs(); } @Override public void maybeSetThrottleTimeMs(int throttleTimeMs) { data.setThrottleTimeMs(throttleTimeMs); } @Override public Map<Errors, Integer> errorCounts() { Map<Errors, Integer> counts = new EnumMap<>(Errors.class); updateErrorCounts(counts, Errors.forCode(data.errorCode())); data.responses().forEach(topicResponse -> topicResponse.partitions().forEach(partitionResponse -> updateErrorCounts(counts, Errors.forCode(partitionResponse.errorCode())) )); return counts; } }
AlterPartitionReassignmentsResponse
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/util/NativeTypes.java
{ "start": 7698, "end": 8121 }
class ____ implements LiteralAnalyzer { @Override public void validate(String s) { if ( !( "true".equals( s ) || "false".equals( s ) ) ) { throw new IllegalArgumentException("only 'true' or 'false' are supported"); } } @Override public Class<?> getLiteral() { return boolean.class; } } private static
BooleanAnalyzer
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/tvf/unslicing/UnsliceAssigners.java
{ "start": 2177, "end": 3115 }
class ____ { /** * Creates a session window {@link UnsliceAssigner} that assigns elements to windows based on * the timestamp. * * @param rowtimeIndex The index of rowtime field in the input row, {@code -1} if based on * processing time. * @param shiftTimeZone The shift timezone of the window, if the proctime or rowtime type is * TIMESTAMP_LTZ, the shift timezone is the timezone user configured in TableConfig, other * cases the timezone is UTC which means never shift when assigning windows. * @param gap The session timeout, i.e. the time gap between sessions */ public static SessionUnsliceAssigner session( int rowtimeIndex, ZoneId shiftTimeZone, Duration gap) { return new SessionUnsliceAssigner(rowtimeIndex, shiftTimeZone, gap.toMillis()); } /** The {@link UnsliceAssigner} for session windows. */ public static
UnsliceAssigners
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiersTest.java
{ "start": 6136, "end": 6286 }
interface ____ { default void foo() { Private.logger.atInfo().log(); } public static final
Test
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/hive/stmt/HiveCreateTableStatement.java
{ "start": 1077, "end": 5123 }
class ____ extends SQLCreateTableStatement { protected List<SQLExpr> skewedBy = new ArrayList<SQLExpr>(); protected List<SQLExpr> skewedByOn = new ArrayList<SQLExpr>(); protected boolean skewedByStoreAsDirectories; protected Map<String, SQLObject> serdeProperties = new LinkedHashMap<String, SQLObject>(); protected boolean likeQuery; // for DLA protected List<SQLAssignItem> mappedBy = new ArrayList<SQLAssignItem>(1); protected SQLExpr intoBuckets; protected SQLExpr using; private boolean lbracketUse; private boolean rbracketUse; public HiveCreateTableStatement() { this.dbType = DbType.hive; } public HiveCreateTableStatement(DbType dbType) { this.dbType = dbType; } public boolean isLbracketUse() { return lbracketUse; } public void setLbracketUse(boolean lbracketUse) { this.lbracketUse = lbracketUse; } public boolean isRbracketUse() { return rbracketUse; } public void setRbracketUse(boolean rbracketUse) { this.rbracketUse = rbracketUse; } protected void accept0(SQLASTVisitor v) { if (v.visit(this)) { acceptChild(v); } v.endVisit(this); } protected void acceptChild(SQLASTVisitor v) { super.acceptChild(v); acceptChild(v, skewedBy); acceptChild(v, skewedByOn); for (SQLObject item : serdeProperties.values()) { acceptChild(v, item); } acceptChild(v, intoBuckets); } public void cloneTo(HiveCreateTableStatement x) { super.cloneTo(x); for (SQLExpr item : skewedBy) { x.addSkewedBy(item.clone()); } for (SQLExpr item : skewedByOn) { x.addSkewedByOn(item.clone()); } for (Map.Entry<String, SQLObject> entry : serdeProperties.entrySet()) { SQLObject entryValue = entry.getValue().clone(); entryValue.setParent(x); x.serdeProperties.put(entry.getKey(), entryValue); } x.setLikeQuery(this.likeQuery); if (mappedBy != null) { for (SQLAssignItem item : mappedBy) { SQLAssignItem item2 = item.clone(); item2.setParent(this); x.mappedBy.add(item2); } } if (intoBuckets != null) { x.intoBuckets = intoBuckets.clone(); } if (using != null) { x.setUsing(using.clone()); } } public HiveCreateTableStatement clone() { HiveCreateTableStatement x = new HiveCreateTableStatement(); cloneTo(x); return x; } public List<SQLExpr> getSkewedBy() { return skewedBy; } public void addSkewedBy(SQLExpr item) { item.setParent(this); this.skewedBy.add(item); } public List<SQLExpr> getSkewedByOn() { return skewedByOn; } public void addSkewedByOn(SQLExpr item) { item.setParent(this); this.skewedByOn.add(item); } public void setSkewedByStoreAsDirectories(boolean skewedByStoreAsDirectories) { this.skewedByStoreAsDirectories = skewedByStoreAsDirectories; } public boolean isSkewedByStoreAsDirectories() { return skewedByStoreAsDirectories; } public Map<String, SQLObject> getSerdeProperties() { return serdeProperties; } public boolean isLikeQuery() { return likeQuery; } public void setLikeQuery(boolean likeQuery) { this.likeQuery = likeQuery; } public List<SQLAssignItem> getMappedBy() { return mappedBy; } public SQLExpr getIntoBuckets() { return intoBuckets; } public void setIntoBuckets(SQLExpr intoBuckets) { this.intoBuckets = intoBuckets; } public SQLExpr getUsing() { return using; } public void setUsing(SQLExpr x) { if (x != null) { x.setParent(this); } this.using = x; } }
HiveCreateTableStatement
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/BeforeAndAfterTestExecutionCallbackTests.java
{ "start": 12689, "end": 13103 }
class ____ { @BeforeEach void beforeEach() { callSequence.add("beforeEachMethod"); throw new EnigmaException("@BeforeEach"); } @Test void test() { callSequence.add("test"); } @AfterEach void afterEach() { callSequence.add("afterEachMethod"); } } @SuppressWarnings("JUnitMalformedDeclaration") @ExtendWith(FooTestExecutionCallbacks.class) static
ExceptionInBeforeEachMethodTestCase
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/util/BigArraysTests.java
{ "start": 27589, "end": 28031 }
class ____ { final BigArrays bigArrays; final Function<Long, BigArray> arrayAllocator; final Function<Long, Long> ramEstimator; BigArraysHelper(BigArrays bigArrays, Function<Long, BigArray> arrayAllocator, Function<Long, Long> ramEstimator) { this.bigArrays = bigArrays; this.arrayAllocator = arrayAllocator; this.ramEstimator = ramEstimator; } } }
BigArraysHelper
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/xslt/XsltIncludeRelativeNestedTest.java
{ "start": 1042, "end": 1780 }
class ____ extends ContextTestSupport { @Test public void testXsltIncludeRelativeNested() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("file:src/test/data/?fileName=staff.xml&noop=true&initialDelay=0&delay=10") .to("xslt:org/apache/camel/component/xslt/staff_include_relative_nested.xsl") .to("log:foo").to("mock:result"); } }; } }
XsltIncludeRelativeNestedTest
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/type/classreading/ClassMetadataReadingVisitorMemberClassTests.java
{ "start": 928, "end": 1330 }
class ____ extends AbstractClassMetadataMemberClassTests { @Override public ClassMetadata getClassMetadataFor(Class<?> clazz) { try { MetadataReader reader = new SimpleMetadataReaderFactory().getMetadataReader(clazz.getName()); return reader.getAnnotationMetadata(); } catch (IOException ex) { throw new IllegalStateException(ex); } } }
ClassMetadataReadingVisitorMemberClassTests
java
apache__flink
flink-python/src/main/java/org/apache/flink/streaming/api/operators/python/process/AbstractExternalOneInputPythonFunctionOperator.java
{ "start": 7468, "end": 8278 }
class ____ { /** Reusable row for element data. */ private final Row reusableRunnerInput; public RunnerInputHandler() { this.reusableRunnerInput = new Row(3); } public Row buildRunnerInputData(long timestamp, long watermark, Object elementData) { reusableRunnerInput.setField(0, timestamp); reusableRunnerInput.setField(1, watermark); reusableRunnerInput.setField(2, elementData); return reusableRunnerInput; } public static TypeInformation<Row> getRunnerInputTypeInfo( TypeInformation<?> elementDataTypeInfo) { // structure: [timestamp, watermark, data] return Types.ROW(Types.LONG, Types.LONG, elementDataTypeInfo); } } }
RunnerInputHandler
java
square__retrofit
retrofit/src/main/java/retrofit2/Retrofit.java
{ "start": 6745, "end": 8466 }
interface ____ creation guarded by parameter safety. public <T> T create(final Class<T> service) { validateServiceInterface(service); return (T) Proxy.newProxyInstance( service.getClassLoader(), new Class<?>[] {service}, new InvocationHandler() { private final Object[] emptyArgs = new Object[0]; @Override public @Nullable Object invoke(Object proxy, Method method, @Nullable Object[] args) throws Throwable { // If the method is a method from Object then defer to normal invocation. if (method.getDeclaringClass() == Object.class) { return method.invoke(this, args); } args = args != null ? args : emptyArgs; Reflection reflection = Platform.reflection; return reflection.isDefaultMethod(method) ? reflection.invokeDefaultMethod(method, service, proxy, args) : loadServiceMethod(service, method).invoke(proxy, args); } }); } private void validateServiceInterface(Class<?> service) { if (!service.isInterface()) { throw new IllegalArgumentException("API declarations must be interfaces."); } Deque<Class<?>> check = new ArrayDeque<>(1); check.add(service); while (!check.isEmpty()) { Class<?> candidate = check.removeFirst(); if (candidate.getTypeParameters().length != 0) { StringBuilder message = new StringBuilder("Type parameters are unsupported on ").append(candidate.getName()); if (candidate != service) { message.append(" which is an
proxy
java
elastic__elasticsearch
x-pack/plugin/enrich/src/main/java/org/elasticsearch/xpack/enrich/action/EnrichCoordinatorStatsAction.java
{ "start": 3180, "end": 4297 }
class ____ extends BaseNodeResponse { private final EnrichStatsAction.Response.CacheStats cacheStats; private final CoordinatorStats coordinatorStats; NodeResponse(DiscoveryNode node, EnrichStatsAction.Response.CacheStats cacheStats, CoordinatorStats coordinatorStats) { super(node); this.cacheStats = cacheStats; this.coordinatorStats = coordinatorStats; } NodeResponse(StreamInput in) throws IOException { super(in); this.cacheStats = new EnrichStatsAction.Response.CacheStats(in); this.coordinatorStats = new CoordinatorStats(in); } public CoordinatorStats getCoordinatorStats() { return coordinatorStats; } public EnrichStatsAction.Response.CacheStats getCacheStats() { return cacheStats; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); cacheStats.writeTo(out); coordinatorStats.writeTo(out); } } public static
NodeResponse
java
google__dagger
javatests/dagger/hilt/processor/internal/originatingelement/OriginatingElementProcessorTest.java
{ "start": 1528, "end": 2066 }
class ____ {}", "}"); hiltCompiler(outer1, outer2) .compile( subject -> { subject.hasErrorCount(1); subject.hasErrorContaining( "@OriginatingElement should only be used to annotate top-level types, but found: " + "test.Outer2.Inner"); }); } @Test public void originatingElementValueWithInnerClass_fails() { Source outer1 = HiltCompilerTests.javaSource( "test.Outer1", "package test;", "", "
Inner
java
apache__camel
components/camel-spring-parent/camel-spring/src/main/java/org/apache/camel/spring/spi/CamelBeanPostProcessor.java
{ "start": 1965, "end": 10427 }
class ____ implements org.apache.camel.spi.CamelBeanPostProcessor, CamelContextAware, BeanPostProcessor, ApplicationContextAware, Ordered { private static final Logger LOG = LoggerFactory.getLogger(CamelBeanPostProcessor.class); private final Set<String> prototypeBeans = new LinkedHashSet<>(); private CamelContext camelContext; private ApplicationContext applicationContext; private String camelId; private boolean bindToRegistrySupported; private Predicate<BindToRegistry> lazyBeanStrategy; // must use a delegate, as we cannot extend DefaultCamelBeanPostProcessor, as this will cause the // XSD schema generator to include the DefaultCamelBeanPostProcessor as a type, which we do not want to private final DefaultCamelBeanPostProcessor delegate = new DefaultCamelBeanPostProcessor() { @Override public CamelContext getOrLookupCamelContext() { CamelContext answer = CamelBeanPostProcessor.this.camelContext; if (answer == null) { if (camelId != null) { LOG.trace("Looking up CamelContext by id: {} from Spring ApplicationContext: {}", camelId, applicationContext); answer = applicationContext.getBean(camelId, CamelContext.class); } else { // lookup by type and grab the single CamelContext if exists LOG.trace("Looking up CamelContext by type from Spring ApplicationContext: {}", applicationContext); Map<String, CamelContext> contexts = applicationContext.getBeansOfType(CamelContext.class); if (contexts.size() == 1) { answer = contexts.values().iterator().next(); } } if (answer != null) { // we found a camel context CamelBeanPostProcessor.this.camelContext = answer; } } return answer; } @Override public void setCamelContext(CamelContext camelContext) { super.setCamelContext(camelContext); if (camelPostProcessorHelper != null) { camelPostProcessorHelper.setCamelContext(camelContext); } } @Override public boolean canPostProcessBean(Object bean, String beanName) { if (bean == null) { return false; } return super.canPostProcessBean(bean, beanName); } @Override protected boolean bindToRegistrySupported() { // do not support @BindToRegistry as spring and spring-boot has its own set of annotations for this return false; } @Override public CamelPostProcessorHelper getPostProcessorHelper() { // lets lazily create the post processor if (camelPostProcessorHelper == null) { camelPostProcessorHelper = new CamelPostProcessorHelper(camelContext) { @Override public CamelContext getCamelContext() { CamelContext answer = CamelBeanPostProcessor.this.camelContext; if (answer == null) { // lets lazily lookup the camel context here // as doing this will cause this context to be started immediately // breaking the lifecycle ordering of different camel contexts // so we only want to do this on demand answer = delegate.getOrLookupCamelContext(); } return answer; } @Override protected RuntimeException createProxyInstantiationRuntimeException( Class<?> type, Endpoint endpoint, Exception e) { return new BeanInstantiationException( type, "Could not instantiate proxy of type " + type.getName() + " on endpoint " + endpoint, e); } @Override protected boolean isSingleton(Object bean, String beanName) { // no application context has been injected which means the bean // has not been enlisted in Spring application context if (applicationContext == null || beanName == null) { return super.isSingleton(bean, beanName); } else { return applicationContext.isSingleton(beanName); } } @Override protected void startService(Service service, CamelContext context, Object bean, String beanName) throws Exception { if (isSingleton(bean, beanName)) { getCamelContext().addService(service); } else { // only start service and do not add it to CamelContext ServiceHelper.startService(service); if (prototypeBeans.add(beanName)) { // do not spam the log with WARN so do this only once per bean name CamelBeanPostProcessor.LOG .warn("The bean with id [{}] is prototype scoped and cannot stop the injected " + " service when bean is destroyed: {}. You may want to stop the service " + "manually from the bean.", beanName, service); } } } }; } return camelPostProcessorHelper; } }; public CamelBeanPostProcessor() { } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { try { return delegate.postProcessBeforeInitialization(bean, beanName); } catch (BeansException e) { throw e; // do not wrap already beans exceptions } catch (Exception e) { throw new BeanCreationException("Error post processing bean: " + beanName, e); } } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { try { return delegate.postProcessAfterInitialization(bean, beanName); } catch (Exception e) { // do not wrap already beans exceptions if (e instanceof BeansException) { throw (BeansException) e; } throw new BeanCreationException("Error post processing bean: " + beanName, e); } } @Override public int getOrder() { return LOWEST_PRECEDENCE; } // Properties // ------------------------------------------------------------------------- @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public CamelContext getCamelContext() { return camelContext; } public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; this.delegate.setCamelContext(camelContext); } public String getCamelId() { return camelId; } public void setCamelId(String camelId) { this.camelId = camelId; } public boolean isBindToRegistrySupported() { return bindToRegistrySupported; } public void setBindToRegistrySupported(boolean bindToRegistrySupported) { this.bindToRegistrySupported = bindToRegistrySupported; } @Override public void setEnabled(boolean enabled) { delegate.setEnabled(enabled); } @Override public boolean isEnabled() { return delegate.isEnabled(); } @Override public void setLazyBeanStrategy(Predicate<BindToRegistry> strategy) { this.lazyBeanStrategy = strategy; } @Override public Predicate<BindToRegistry> getLazyBeanStrategy() { return lazyBeanStrategy; } }
CamelBeanPostProcessor
java
quarkusio__quarkus
docs/src/test/java/io/quarkus/docs/vale/LocalValeLintTest.java
{ "start": 546, "end": 3745 }
class ____ { @Test @EnabledIfSystemProperty(named = "vale", matches = ".*", disabledReason = "Requires a container runtime. Specifiy -Dvale to enable.") public void testAsciidocFiles() throws Exception { Path srcDir = Path.of("").resolve("src/main/asciidoc"); Path targetDir = Path.of("").resolve("target"); Path valeDir = ChangedFiles.getPath("vale.dir", ".vale"); Path gitDir = ChangedFiles.getPath("git.dir", "../.git"); Path configFile = Path.of(System.getProperty("vale.config", ".vale.ini")); YamlMetadataGenerator metadataGenerator = new YamlMetadataGenerator() .setSrcDir(srcDir) .setTargetDir(targetDir); ValeAsciidocLint linter = new ValeAsciidocLint() .setValeAlertLevel(System.getProperty("valeLevel")) .setValeImageName(System.getProperty("vale.image")) .setValeConfig(configFile) .setValeDir(valeDir) .setSrcDir(srcDir) .setTargetDir(targetDir); String valeFileFilter = System.getProperty("vale"); if ("git".equals(valeFileFilter)) { Path baseDir = gitDir.getParent().toAbsolutePath().normalize(); Path docsDir = baseDir.relativize(srcDir.toAbsolutePath()); Collection<String> files = ChangedFiles.getChangedFiles(gitDir, docsDir); if (files.isEmpty()) { return; // EXIT EARLY } metadataGenerator.setFileList(files); linter.setFileList(files); } else { metadataGenerator.setFileFilterPattern(valeFileFilter); linter.setFileFilterPattern(valeFileFilter); } // Generate YAML: doc requirements Index index = metadataGenerator.generateIndex(); Map<String, FileMessages> messages = index.messagesByFile(); // Find Vale errors Map<String, ChecksBySeverity> lintResults = linter.lintFiles(); // Write vale.yaml linter.resultsToYaml(lintResults, messages); boolean hasErrors = false; StringBuilder sb = new StringBuilder("\n"); for (String fileName : lintResults.keySet()) { sb.append(fileName).append(": ").append("\n"); FileMessages fm = messages.get(fileName); if (fm != null) { sb.append("\n metadata\n"); hasErrors |= fm.listAll(sb); } ChecksBySeverity lErrors = lintResults.get(fileName); if (lErrors != null) { hasErrors = true; // always fail in this purposeful case lErrors.checksBySeverity.entrySet().forEach(e -> { sb.append("\n ").append(e.getKey()).append("\n"); e.getValue().forEach(c -> sb.append(" ").append(c).append("\n")); }); } sb.append("\n"); } String result = sb.toString().trim(); System.err.println(result); if (hasErrors) { throw new LintException("target/vale.yaml"); } else { System.out.println("🥳 OK"); } } }
LocalValeLintTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/benckmark/wall/WallBenchmarkTest.java
{ "start": 798, "end": 1591 }
class ____ extends TestCase { WallProvider provider = new OracleWallProvider(); public static final int COUNT = 1000 * 1000; public void test_0() throws Exception { String sql = "SELECT t1.department_id, t2.*\n" + "FROM hr_info t1, TABLE(t1.people) t2\n" + "WHERE t2.department_id = t1.department_id;"; for (int i = 0; i < 10; ++i) { provider.clearCache(); long startMillis = System.currentTimeMillis(); perf(sql); long millis = System.currentTimeMillis() - startMillis; System.out.println("millis : " + millis); } } public void perf(String sql) { for (int i = 0; i < COUNT; ++i) { provider.check(sql); } } }
WallBenchmarkTest
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/checkpointing/RegionFailoverITCase.java
{ "start": 15906, "end": 17749 }
class ____ extends RichMapFunction<Tuple2<Integer, Integer>, Tuple2<Integer, Integer>> { private final int restartTimes; private ValueState<Integer> valueState; @Override public void open(OpenContext openContext) throws Exception { super.open(openContext); valueState = getRuntimeContext() .getState(new ValueStateDescriptor<>("value", Integer.class)); } FailingMapperFunction(int restartTimes) { this.restartTimes = restartTimes; } @Override public Tuple2<Integer, Integer> map(Tuple2<Integer, Integer> input) throws Exception { int indexOfThisSubtask = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(); if (input.f1 > FAIL_BASE * (jobFailedCnt.get() + 1)) { // we would let region-0 to failover first if (jobFailedCnt.get() < 1 && indexOfThisSubtask == 0) { jobFailedCnt.incrementAndGet(); throw new TestException(); } // then let last region to failover if (jobFailedCnt.get() < restartTimes && indexOfThisSubtask == NUM_OF_REGIONS - 1) { jobFailedCnt.incrementAndGet(); throw new TestException(); } } // take input (1, 2) and (1, 3) for example, we would finally emit (1, 5) out with the // usage of keyed state. Integer value = valueState.value(); if (value == null) { valueState.update(input.f1); return input; } else { return Tuple2.of(input.f0, value + input.f1); } } } private static
FailingMapperFunction
java
apache__camel
core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ManagedRuntimeEndpointRegistryMBean.java
{ "start": 1045, "end": 2260 }
interface ____ extends ManagedServiceMBean { @ManagedOperation(description = "Clears the registry") void clear(); @ManagedOperation(description = "Reset the statistic counters") void reset(); @ManagedAttribute(description = "Whether gathering runtime usage is enabled or not") boolean isEnabled(); @ManagedAttribute(description = "Whether gathering runtime usage is enabled or not") void setEnabled(boolean enabled); @ManagedAttribute(description = "Maximum number of endpoints to keep in the cache per route") int getLimit(); @ManagedAttribute(description = "Number of endpoints currently in the registry") int getSize(); @ManagedOperation(description = "Gets all the endpoint urls captured during runtime that are in-use") List<String> getAllEndpoints(boolean includeInputs); @ManagedOperation(description = "Gets all the endpoint urls captured during runtime that are in-use for the given route") List<String> getEndpointsPerRoute(String routeId, boolean includeInputs); @ManagedOperation(description = "Lists statistics about all the endpoints in the registry") TabularData endpointStatistics(); }
ManagedRuntimeEndpointRegistryMBean
java
google__guava
android/guava-tests/benchmark/com/google/common/collect/MinMaxPriorityQueueBenchmark.java
{ "start": 3595, "end": 4135 }
class ____ implements Function<Integer, BigInteger> { @Override public BigInteger apply(Integer from) { BigInteger v = BigInteger.valueOf(from); // Math.sin is very slow for values outside 4*pi // Need to take absolute value to avoid inverting the value. for (double i = 0; i < 100; i += 20) { v = v.add( v.multiply( BigInteger.valueOf(((Double) Math.abs(Math.sin(i) * 10.0)).longValue()))); } return v; } } public
ExpensiveComputation
java
apache__camel
components/camel-language/src/generated/java/org/apache/camel/component/language/LanguageComponentConfigurer.java
{ "start": 735, "end": 3021 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { LanguageComponent target = (LanguageComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "allowtemplatefromheader": case "allowTemplateFromHeader": target.setAllowTemplateFromHeader(property(camelContext, boolean.class, value)); return true; case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "contentcache": case "contentCache": target.setContentCache(property(camelContext, boolean.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "allowtemplatefromheader": case "allowTemplateFromHeader": return boolean.class; case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "contentcache": case "contentCache": return boolean.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { LanguageComponent target = (LanguageComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "allowtemplatefromheader": case "allowTemplateFromHeader": return target.isAllowTemplateFromHeader(); case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "contentcache": case "contentCache": return target.isContentCache(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); default: return null; } } }
LanguageComponentConfigurer
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/body/ConsumeQueueData.java
{ "start": 863, "end": 2563 }
class ____ { private long physicOffset; private int physicSize; private long tagsCode; private String extendDataJson; private String bitMap; private boolean eval; private String msg; public long getPhysicOffset() { return physicOffset; } public void setPhysicOffset(long physicOffset) { this.physicOffset = physicOffset; } public int getPhysicSize() { return physicSize; } public void setPhysicSize(int physicSize) { this.physicSize = physicSize; } public long getTagsCode() { return tagsCode; } public void setTagsCode(long tagsCode) { this.tagsCode = tagsCode; } public String getExtendDataJson() { return extendDataJson; } public void setExtendDataJson(String extendDataJson) { this.extendDataJson = extendDataJson; } public String getBitMap() { return bitMap; } public void setBitMap(String bitMap) { this.bitMap = bitMap; } public boolean isEval() { return eval; } public void setEval(boolean eval) { this.eval = eval; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public String toString() { return "ConsumeQueueData{" + "physicOffset=" + physicOffset + ", physicSize=" + physicSize + ", tagsCode=" + tagsCode + ", extendDataJson='" + extendDataJson + '\'' + ", bitMap='" + bitMap + '\'' + ", eval=" + eval + ", msg='" + msg + '\'' + '}'; } }
ConsumeQueueData
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/function/array/ArrayLengthTest.java
{ "start": 1451, "end": 4375 }
class ____ { @BeforeEach public void prepareData(SessionFactoryScope scope) { scope.inTransaction( em -> { em.persist( new EntityWithArrays( 1L, new String[]{} ) ); em.persist( new EntityWithArrays( 2L, new String[]{ "abc", null, "def" } ) ); em.persist( new EntityWithArrays( 3L, null ) ); } ); } @AfterEach public void cleanup(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testLengthZero(SessionFactoryScope scope) { scope.inSession( em -> { //tag::hql-array-length-example[] List<EntityWithArrays> results = em.createQuery( "from EntityWithArrays e where array_length(e.theArray) = 0", EntityWithArrays.class ) .getResultList(); //end::hql-array-length-example[] assertEquals( 1, results.size() ); assertEquals( 1L, results.get( 0 ).getId() ); } ); } @Test public void testLengthThree(SessionFactoryScope scope) { scope.inSession( em -> { List<EntityWithArrays> results = em.createQuery( "from EntityWithArrays e where array_length(e.theArray) = 3", EntityWithArrays.class ) .getResultList(); assertEquals( 1, results.size() ); assertEquals( 2L, results.get( 0 ).getId() ); } ); } @Test public void testLengthNull(SessionFactoryScope scope) { scope.inSession( em -> { List<EntityWithArrays> results = em.createQuery( "from EntityWithArrays e where array_length(e.theArray) is null", EntityWithArrays.class ) .getResultList(); assertEquals( 1, results.size() ); assertEquals( 3L, results.get( 0 ).getId() ); } ); } @Test public void testNodeBuilderArray(SessionFactoryScope scope) { scope.inSession( em -> { final NodeBuilder cb = (NodeBuilder) em.getCriteriaBuilder(); final JpaCriteriaQuery<Tuple> cq = cb.createTupleQuery(); final JpaRoot<EntityWithArrays> root = cq.from( EntityWithArrays.class ); cq.multiselect( root.get( "id" ), cb.arrayLength( root.get( "theArray" ) ) ); em.createQuery( cq ).getResultList(); } ); } @Test public void testNodeBuilderCollection(SessionFactoryScope scope) { scope.inSession( em -> { final NodeBuilder cb = (NodeBuilder) em.getCriteriaBuilder(); final JpaCriteriaQuery<Tuple> cq = cb.createTupleQuery(); final JpaRoot<EntityWithArrays> root = cq.from( EntityWithArrays.class ); cq.multiselect( root.get( "id" ), cb.collectionLength( root.get( "theCollection" ) ) ); em.createQuery( cq ).getResultList(); } ); } @Test public void testLengthThreeHql(SessionFactoryScope scope) { scope.inSession( em -> { //tag::hql-array-length-hql-example[] List<EntityWithArrays> results = em.createQuery( "from EntityWithArrays e where length(e.theArray) = 3", EntityWithArrays.class ) .getResultList(); //end::hql-array-length-hql-example[] assertEquals( 1, results.size() ); assertEquals( 2L, results.get( 0 ).getId() ); } ); } }
ArrayLengthTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-csi/src/main/java/org/apache/hadoop/yarn/csi/translator/NodeUnpublishVolumeRequestProtoTranslator.java
{ "start": 1229, "end": 1933 }
class ____<A, B> implements ProtoTranslator<NodeUnpublishVolumeRequest, Csi.NodeUnpublishVolumeRequest> { @Override public Csi.NodeUnpublishVolumeRequest convertTo( NodeUnpublishVolumeRequest messageA) throws YarnException { return Csi.NodeUnpublishVolumeRequest.newBuilder() .setVolumeId(messageA.getVolumeId()) .setTargetPath(messageA.getTargetPath()) .build(); } @Override public NodeUnpublishVolumeRequest convertFrom( Csi.NodeUnpublishVolumeRequest messageB) throws YarnException { return NodeUnpublishVolumeRequest .newInstance(messageB.getVolumeId(), messageB.getTargetPath()); } }
NodeUnpublishVolumeRequestProtoTranslator
java
spring-projects__spring-boot
module/spring-boot-jersey/src/test/java/org/springframework/boot/jersey/autoconfigure/actuate/endpoint/web/JerseyEndpointIntegrationTests.java
{ "start": 6511, "end": 6819 }
class ____ { @Bean TestControllerEndpoint testControllerEndpoint() { return new TestControllerEndpoint(); } @Bean TestRestControllerEndpoint testRestControllerEndpoint() { return new TestRestControllerEndpoint(); } } @Configuration(proxyBeanMethods = false) static
EndpointsConfiguration
java
dropwizard__dropwizard
dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/SubResourcesTest.java
{ "start": 7400, "end": 8441 }
class ____ { private final DogDAO dogDAO; private final PersonDAO personDAO; DogResource(DogDAO dogDAO, PersonDAO personDAO) { this.dogDAO = dogDAO; this.personDAO = personDAO; } @GET // Intentionally no `@UnitOfWork` public List<Dog> findAll(@PathParam("ownerName") String ownerName) { return dogDAO.findByOwner(ownerName); } @GET @Path("{dogName}") @UnitOfWork(readOnly = true) public Optional<Dog> find(@PathParam("ownerName") String ownerName, @PathParam("dogName") String dogName) { return dogDAO.findByOwnerAndName(ownerName, dogName); } @POST @UnitOfWork public Dog create(@PathParam("ownerName") String ownerName, Dog dog) { dog.setOwner(personDAO.findByName(ownerName).orElseThrow(() -> new WebApplicationException(404))); return dogDAO.persist(dog); } } public static
DogResource
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/impl/TestMetricsConfig.java
{ "start": 1249, "end": 5340 }
class ____ { static final Logger LOG = LoggerFactory.getLogger(TestMetricsConfig.class); /** * Common use cases * @throws Exception */ @Test public void testCommon() throws Exception { String filename = getTestFilename("test-metrics2"); new ConfigBuilder() .add("*.foo", "default foo") .add("p1.*.bar", "p1 default bar") .add("p1.t1.*.bar", "p1.t1 default bar") .add("p1.t1.i1.name", "p1.t1.i1.name") .add("p1.t1.42.bar", "p1.t1.42.bar") .add("p1.t2.i1.foo", "p1.t2.i1.foo") .add("p2.*.foo", "p2 default foo") .save(filename); MetricsConfig mc = MetricsConfig.create("p1", filename); LOG.debug("mc:"+ mc); Configuration expected = new ConfigBuilder() .add("*.bar", "p1 default bar") .add("t1.*.bar", "p1.t1 default bar") .add("t1.i1.name", "p1.t1.i1.name") .add("t1.42.bar", "p1.t1.42.bar") .add("t2.i1.foo", "p1.t2.i1.foo") .config; assertEq(expected, mc); testInstances(mc); } private void testInstances(MetricsConfig c) throws Exception { Map<String, MetricsConfig> map = c.getInstanceConfigs("t1"); Map<String, MetricsConfig> map2 = c.getInstanceConfigs("t2"); assertEquals(2, map.size(), "number of t1 instances"); assertEquals(1, map2.size(), "number of t2 instances"); assertTrue(map.containsKey("i1"), "contains t1 instance i1"); assertTrue(map.containsKey("42"), "contains t1 instance 42"); assertTrue(map2.containsKey("i1"), "contains t2 instance i1"); MetricsConfig t1i1 = map.get("i1"); MetricsConfig t1i42 = map.get("42"); MetricsConfig t2i1 = map2.get("i1"); LOG.debug("--- t1 instance i1:"+ t1i1); LOG.debug("--- t1 instance 42:"+ t1i42); LOG.debug("--- t2 instance i1:"+ t2i1); Configuration t1expected1 = new ConfigBuilder() .add("name", "p1.t1.i1.name").config; Configuration t1expected42 = new ConfigBuilder() .add("bar", "p1.t1.42.bar").config; Configuration t2expected1 = new ConfigBuilder() .add("foo", "p1.t2.i1.foo").config; assertEq(t1expected1, t1i1); assertEq(t1expected42, t1i42); assertEq(t2expected1, t2i1); LOG.debug("asserting foo == default foo"); // Check default lookups assertEquals("default foo", t1i1.getString("foo"), "value of foo in t1 instance i1"); assertEquals("p1.t1 default bar", t1i1.getString("bar"), "value of bar in t1 instance i1"); assertEquals("default foo", t1i42.getString("foo"), "value of foo in t1 instance 42"); assertEquals("p1.t2.i1.foo", t2i1.getString("foo"), "value of foo in t2 instance i1"); assertEquals("p1 default bar", t2i1.getString("bar"), "value of bar in t2 instance i1"); } /** * Should not throw if missing config files */ @Test public void testMissingFiles() { MetricsConfig config = MetricsConfig.create("JobTracker", "non-existent.properties"); assertTrue(config.isEmpty()); } /** * Test the config file load order * @throws Exception */ @Test public void testLoadFirst() throws Exception { String filename = getTestFilename("hadoop-metrics2-p1"); new ConfigBuilder().add("p1.foo", "p1foo").save(filename); MetricsConfig mc = MetricsConfig.create("p1"); MetricsConfig mc2 = MetricsConfig.create("p1", "na1", "na2", filename); Configuration expected = new ConfigBuilder().add("foo", "p1foo").config; assertEq(expected, mc); assertEq(expected, mc2); } /** * Test the config value separated by delimiter */ @Test public void testDelimiterConf() { String filename = getTestFilename("test-metrics2-delimiter"); new ConfigBuilder().add("p1.foo", "p1foo1,p1foo2,p1foo3").save(filename); MetricsConfig mc = MetricsConfig.create("p1", filename); Configuration expected = new ConfigBuilder() .add("foo", "p1foo1") .add("foo", "p1foo2") .add("foo", "p1foo3") .config; assertEq(expected, mc); } /** * Return a test filename in the
TestMetricsConfig
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/errors/WorkerErrantRecordReporter.java
{ "start": 7503, "end": 7633 }
class ____ aggregate producer futures and abstract away the record metadata from the * Connect user. */ public static
to
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/impl/LocationAwareLogEventFactory.java
{ "start": 1119, "end": 1428 }
interface ____ { LogEvent createEvent( String loggerName, Marker marker, String fqcn, StackTraceElement location, Level level, Message data, List<Property> properties, Throwable t); }
LocationAwareLogEventFactory
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/amazonbedrock/embeddings/AmazonBedrockEmbeddingsModelTests.java
{ "start": 984, "end": 6708 }
class ____ extends ESTestCase { public void testCreateModel_withTaskSettingsOverride() throws IOException { var baseTaskSettings = AmazonBedrockEmbeddingsTaskSettingsTests.randomTaskSettings(); var baseModel = createModel("id", "region", "model", AmazonBedrockProvider.AMAZONTITAN, "accesskey", "secretkey", baseTaskSettings); var overrideTaskSettings = AmazonBedrockEmbeddingsTaskSettingsTests.mutateTaskSettings(baseTaskSettings); var overrideTaskSettingsMap = AmazonBedrockEmbeddingsTaskSettingsTests.toMap(overrideTaskSettings); var overriddenModel = AmazonBedrockEmbeddingsModel.of(baseModel, overrideTaskSettingsMap); assertThat(overriddenModel.getTaskSettings(), equalTo(overrideTaskSettings)); assertThat(overriddenModel.getTaskSettings(), not(equalTo(baseTaskSettings))); } // model creation only - no tests to define, but we want to have the public createModel // method available public static AmazonBedrockEmbeddingsModel createModel( String inferenceId, String region, String model, AmazonBedrockProvider provider, String accessKey, String secretKey ) { return createModel( inferenceId, region, model, provider, accessKey, secretKey, AmazonBedrockEmbeddingsTaskSettingsTests.emptyTaskSettings() ); } public static AmazonBedrockEmbeddingsModel createModel( String inferenceId, String region, String model, AmazonBedrockProvider provider, String accessKey, String secretKey, AmazonBedrockEmbeddingsTaskSettings taskSettings ) { return createModel( inferenceId, region, model, provider, null, false, null, null, new RateLimitSettings(240), accessKey, secretKey, taskSettings ); } public static AmazonBedrockEmbeddingsModel createModel( String inferenceId, String region, String model, AmazonBedrockProvider provider, ChunkingSettings chunkingSettings, String accessKey, String secretKey ) { return createModel( inferenceId, region, model, provider, null, false, null, null, new RateLimitSettings(240), chunkingSettings, accessKey, secretKey ); } public static AmazonBedrockEmbeddingsModel createModel( String inferenceId, String region, String model, AmazonBedrockProvider provider, @Nullable Integer dimensions, boolean dimensionsSetByUser, @Nullable Integer maxTokens, @Nullable SimilarityMeasure similarity, RateLimitSettings rateLimitSettings, ChunkingSettings chunkingSettings, String accessKey, String secretKey ) { return new AmazonBedrockEmbeddingsModel( inferenceId, TaskType.TEXT_EMBEDDING, "amazonbedrock", new AmazonBedrockEmbeddingsServiceSettings( region, model, provider, dimensions, dimensionsSetByUser, maxTokens, similarity, rateLimitSettings ), AmazonBedrockEmbeddingsTaskSettingsTests.emptyTaskSettings(), chunkingSettings, new AwsSecretSettings(new SecureString(accessKey), new SecureString(secretKey)) ); } public static AmazonBedrockEmbeddingsModel createModel( String inferenceId, String region, String model, AmazonBedrockProvider provider, @Nullable Integer dimensions, boolean dimensionsSetByUser, @Nullable Integer maxTokens, @Nullable SimilarityMeasure similarity, RateLimitSettings rateLimitSettings, String accessKey, String secretKey ) { return createModel( inferenceId, region, model, provider, dimensions, dimensionsSetByUser, maxTokens, similarity, rateLimitSettings, accessKey, secretKey, AmazonBedrockEmbeddingsTaskSettingsTests.emptyTaskSettings() ); } public static AmazonBedrockEmbeddingsModel createModel( String inferenceId, String region, String model, AmazonBedrockProvider provider, @Nullable Integer dimensions, boolean dimensionsSetByUser, @Nullable Integer maxTokens, @Nullable SimilarityMeasure similarity, RateLimitSettings rateLimitSettings, String accessKey, String secretKey, AmazonBedrockEmbeddingsTaskSettings taskSettings ) { return new AmazonBedrockEmbeddingsModel( inferenceId, TaskType.TEXT_EMBEDDING, "amazonbedrock", new AmazonBedrockEmbeddingsServiceSettings( region, model, provider, dimensions, dimensionsSetByUser, maxTokens, similarity, rateLimitSettings ), taskSettings, null, new AwsSecretSettings(new SecureString(accessKey), new SecureString(secretKey)) ); } }
AmazonBedrockEmbeddingsModelTests
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/categorization/MlStandardTokenizerTests.java
{ "start": 599, "end": 12912 }
class ____ extends ESTestCase { public void testTokenizeNoPaths() throws IOException { String testData = "one .-_two **stars**in**their**eyes** three@-_ sand.-_wich 4four @five5 a1b2c3 42 www.elastic.co"; try (Tokenizer tokenizer = new MlStandardTokenizer()) { tokenizer.setReader(new StringReader(testData)); tokenizer.reset(); CharTermAttribute term = tokenizer.addAttribute(CharTermAttribute.class); OffsetAttribute offset = tokenizer.addAttribute(OffsetAttribute.class); assertTrue(tokenizer.incrementToken()); assertEquals("one", term.toString()); assertEquals(0, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("two", term.toString()); assertEquals(7, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("stars", term.toString()); assertEquals(13, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("in", term.toString()); assertEquals(20, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("their", term.toString()); assertEquals(24, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("eyes", term.toString()); assertEquals(31, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("three", term.toString()); assertEquals(38, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("sand.-_wich", term.toString()); assertEquals(47, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("five5", term.toString()); assertEquals(66, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("www.elastic.co", term.toString()); assertEquals(82, offset.startOffset()); assertFalse(tokenizer.incrementToken()); tokenizer.end(); assertEquals(testData.length(), offset.endOffset()); } } public void testTokenizeWithUnixPath() throws IOException { String testData = "Apr 27 21:04:05 Davids-MacBook-Pro com.apple.xpc.launchd[1] (com.apple.xpc.launchd.domain.pid.mdmclient.320): " + "Failed to bootstrap path: path = /usr/libexec/mdmclient, error = 108: Invalid path\n"; try (Tokenizer tokenizer = new MlStandardTokenizer()) { tokenizer.setReader(new StringReader(testData)); tokenizer.reset(); CharTermAttribute term = tokenizer.addAttribute(CharTermAttribute.class); OffsetAttribute offset = tokenizer.addAttribute(OffsetAttribute.class); assertTrue(tokenizer.incrementToken()); assertEquals("Apr", term.toString()); assertEquals(0, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("Davids-MacBook-Pro", term.toString()); assertEquals(16, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("com.apple.xpc.launchd", term.toString()); assertEquals(35, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("com.apple.xpc.launchd.domain.pid.mdmclient.320", term.toString()); assertEquals(61, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("Failed", term.toString()); assertEquals(110, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("to", term.toString()); assertEquals(117, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("bootstrap", term.toString()); assertEquals(120, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("path", term.toString()); assertEquals(130, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("path", term.toString()); assertEquals(136, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("/usr/libexec/mdmclient", term.toString()); assertEquals(143, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("error", term.toString()); assertEquals(167, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("Invalid", term.toString()); assertEquals(180, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("path", term.toString()); assertEquals(188, offset.startOffset()); assertFalse(tokenizer.incrementToken()); tokenizer.end(); assertEquals(testData.length(), offset.endOffset()); } } public void testTokenizeWithWindowsPaths() throws IOException { String testData = "05/05/2021 C:\\Windows\\System something:else \\\\myserver\\share\\folder \\ at_end\\ \\no\\drive\\specified " + "at_end_with_colon:\\"; try (Tokenizer tokenizer = new MlStandardTokenizer()) { tokenizer.setReader(new StringReader(testData)); tokenizer.reset(); CharTermAttribute term = tokenizer.addAttribute(CharTermAttribute.class); OffsetAttribute offset = tokenizer.addAttribute(OffsetAttribute.class); assertTrue(tokenizer.incrementToken()); assertEquals("C:\\Windows\\System", term.toString()); assertEquals(11, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("something", term.toString()); assertEquals(29, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("else", term.toString()); assertEquals(39, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("\\\\myserver\\share\\folder", term.toString()); assertEquals(44, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("at_end", term.toString()); assertEquals(70, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("\\no\\drive\\specified", term.toString()); assertEquals(78, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("at_end_with_colon", term.toString()); assertEquals(98, offset.startOffset()); assertFalse(tokenizer.incrementToken()); tokenizer.end(); assertEquals(testData.length(), offset.endOffset()); } } public void testTokenizeWithUrl() throws IOException { String testData = """ 10.8.0.12 - - [29/Nov/2020:21:34:55 +0000] "POST /intake/v2/events HTTP/1.1" 202 0 "-" \ "elasticapm-dotnet/1.5.1 System.Net.Http/4.6.28208.02 .NET_Core/2.2.8" 27821 0.002 [default-apm-apm-server-8200] [] \ 10.8.1.19:8200 0 0.001 202 f961c776ff732f5c8337530aa22c7216 """; try (Tokenizer tokenizer = new MlStandardTokenizer()) { tokenizer.setReader(new StringReader(testData)); tokenizer.reset(); CharTermAttribute term = tokenizer.addAttribute(CharTermAttribute.class); OffsetAttribute offset = tokenizer.addAttribute(OffsetAttribute.class); assertTrue(tokenizer.incrementToken()); assertEquals("POST", term.toString()); assertEquals(44, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("/intake/v2/events", term.toString()); assertEquals(49, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("HTTP/1.1", term.toString()); assertEquals(67, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("elasticapm-dotnet/1.5.1", term.toString()); assertEquals(88, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("System.Net.Http/4.6.28208.02", term.toString()); assertEquals(112, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("NET_Core/2.2.8", term.toString()); assertEquals(142, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("default-apm-apm-server-8200", term.toString()); assertEquals(171, offset.startOffset()); assertFalse(tokenizer.incrementToken()); tokenizer.end(); assertEquals(testData.length(), offset.endOffset()); } } public void testTokenizeWithPurelyNumericAtToken() throws IOException { String testData = "[1231529792] INFO proxy <12309105041220090733@192.168.123.123> - +++++++++++++++ CREATING ProxyCore ++++++++++++++++"; try (Tokenizer tokenizer = new MlStandardTokenizer()) { tokenizer.setReader(new StringReader(testData)); tokenizer.reset(); CharTermAttribute term = tokenizer.addAttribute(CharTermAttribute.class); OffsetAttribute offset = tokenizer.addAttribute(OffsetAttribute.class); assertTrue(tokenizer.incrementToken()); assertEquals("INFO", term.toString()); assertEquals(13, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("proxy", term.toString()); assertEquals(19, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("CREATING", term.toString()); assertEquals(82, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("ProxyCore", term.toString()); assertEquals(91, offset.startOffset()); assertFalse(tokenizer.incrementToken()); tokenizer.end(); assertEquals(testData.length(), offset.endOffset()); } } public void testTokenizeWithEmailAddress() throws IOException { String testData = "[1234662464] INFO session <a.n.other@elastic.co> - -----------------"; try (Tokenizer tokenizer = new MlStandardTokenizer()) { tokenizer.setReader(new StringReader(testData)); tokenizer.reset(); CharTermAttribute term = tokenizer.addAttribute(CharTermAttribute.class); OffsetAttribute offset = tokenizer.addAttribute(OffsetAttribute.class); assertTrue(tokenizer.incrementToken()); assertEquals("INFO", term.toString()); assertEquals(13, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("session", term.toString()); assertEquals(19, offset.startOffset()); assertTrue(tokenizer.incrementToken()); assertEquals("a.n.other@elastic.co", term.toString()); assertEquals(28, offset.startOffset()); assertFalse(tokenizer.incrementToken()); tokenizer.end(); assertEquals(testData.length(), offset.endOffset()); } } public void testTokenize_emptyString() throws IOException { String testData = ""; try (Tokenizer tokenizer = new MlStandardTokenizer()) { tokenizer.setReader(new StringReader(testData)); tokenizer.reset(); CharTermAttribute term = tokenizer.addAttribute(CharTermAttribute.class); OffsetAttribute offset = tokenizer.addAttribute(OffsetAttribute.class); assertFalse(tokenizer.incrementToken()); assertEquals("", term.toString()); tokenizer.end(); assertEquals(testData.length(), offset.endOffset()); } } }
MlStandardTokenizerTests
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/string/ToLowerTests.java
{ "start": 1453, "end": 4759 }
class ____ extends AbstractConfigurationFunctionTestCase { public ToLowerTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) { this.testCase = testCaseSupplier.get(); } @ParametersFactory public static Iterable<Object[]> parameters() { List<TestCaseSupplier> suppliers = new ArrayList<>(); suppliers(suppliers, "keyword ascii", DataType.KEYWORD, () -> randomAlphaOfLengthBetween(1, 10)); suppliers(suppliers, "keyword unicode", DataType.KEYWORD, () -> randomUnicodeOfLengthBetween(1, 10)); suppliers(suppliers, "text ascii", DataType.TEXT, () -> randomAlphaOfLengthBetween(1, 10)); suppliers(suppliers, "text unicode", DataType.TEXT, () -> randomUnicodeOfLengthBetween(1, 10)); return parameterSuppliersFromTypedDataWithDefaultChecks(true, suppliers); } public void testRandomLocale() { String testString = randomAlphaOfLength(10); Configuration cfg = ConfigurationTestUtils.randomConfiguration(); ToLower func = new ToLower(Source.EMPTY, Literal.keyword(Source.EMPTY, testString), cfg); assertThat(BytesRefs.toBytesRef(testString.toLowerCase(cfg.locale())), equalTo(func.fold(FoldContext.small()))); } @Override protected Expression buildWithConfiguration(Source source, List<Expression> args, Configuration configuration) { return new ToLower(source, args.get(0), configuration); } private static void suppliers(List<TestCaseSupplier> suppliers, String name, DataType type, Supplier<String> valueSupplier) { suppliers.add(new TestCaseSupplier(name, List.of(type), () -> { List<TestCaseSupplier.TypedData> values = new ArrayList<>(); String expectedToString = "ChangeCaseEvaluator[val=Attribute[channel=0], locale=en_US, caseType=LOWER]"; String value = valueSupplier.get(); values.add(new TestCaseSupplier.TypedData(new BytesRef(value), type, "0")); String expectedValue = value.toLowerCase(EsqlTestUtils.TEST_CFG.locale()); return new TestCaseSupplier.TestCase(values, expectedToString, type, equalTo(new BytesRef(expectedValue))).withConfiguration( TestCaseSupplier.TEST_SOURCE, configurationForLocale(Locale.US) ); })); suppliers.add(new TestCaseSupplier(name + " mv", List.of(type), () -> { List<TestCaseSupplier.TypedData> values = new ArrayList<>(); String expectedToString = "ChangeCaseEvaluator[val=Attribute[channel=0], locale=en_US, caseType=LOWER]"; List<String> strings = randomList(2, 10, valueSupplier); values.add(new TestCaseSupplier.TypedData(strings.stream().map(BytesRef::new).toList(), type, "0")); List<BytesRef> expectedValue = strings.stream().map(s -> new BytesRef(s.toLowerCase(EsqlTestUtils.TEST_CFG.locale()))).toList(); return new TestCaseSupplier.TestCase(values, expectedToString, type, equalTo(expectedValue)).withConfiguration( TestCaseSupplier.TEST_SOURCE, configurationForLocale(Locale.US) ); })); } @Override protected void extraBlockTests(Page in, Block out) { assertIsOrdIfInIsOrd(in, out); } }
ToLowerTests
java
apache__camel
components/camel-test/camel-test-spring-junit5/src/test/java/org/apache/camel/test/issues/AdviceWithOnExceptionTransactedTest.java
{ "start": 1539, "end": 2963 }
class ____ extends CamelSpringTestSupport { @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/test/issues/AdviceWithOnExceptionTransacted.xml"); } @Override public boolean isUseAdviceWith() { return true; } @Override protected void bindToRegistry(Registry registry) throws Exception { registry.bind("tx", new PlatformTransactionManager() { @Override public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { return null; } @Override public void commit(TransactionStatus status) throws TransactionException { } @Override public void rollback(TransactionStatus status) throws TransactionException { } }); } @Test public void testAddFirstWithOnException() throws Exception { AdviceWith.adviceWith(context, "advice-with-on-exception-transacted-test-route", a -> a.weaveAddFirst().transform(constant("Bye World"))); context.start(); getMockEndpoint("mock:result").expectedBodiesReceived("Bye World"); template.sendBody("direct:start", "Hello World"); MockEndpoint.assertIsSatisfied(context); } }
AdviceWithOnExceptionTransactedTest
java
alibaba__nacos
api/src/test/java/com/alibaba/nacos/api/config/remote/response/ConfigQueryResponseTest.java
{ "start": 988, "end": 3842 }
class ____ extends BasedConfigResponseTest { ConfigQueryResponse configQueryResponse; @BeforeEach void before() { configQueryResponse = ConfigQueryResponse.buildSuccessResponse("success"); configQueryResponse.setContentType("text"); configQueryResponse.setEncryptedDataKey("encryptedKey"); configQueryResponse.setLastModified(1111111L); configQueryResponse.setMd5(MD5); configQueryResponse.setTag(TAG); requestId = injectResponseUuId(configQueryResponse); } @Override @Test public void testSerializeSuccessResponse() throws JsonProcessingException { String json = mapper.writeValueAsString(configQueryResponse); assertTrue(json.contains("\"success\":" + Boolean.TRUE)); assertTrue(json.contains("\"requestId\":\"" + requestId)); assertTrue(json.contains("\"resultCode\":" + ResponseCode.SUCCESS.getCode())); assertTrue(json.contains("\"md5\":\"" + MD5 + "\"")); assertTrue(json.contains("\"errorCode\":0")); assertTrue(json.contains("\"content\":\"success\"")); assertTrue(json.contains("\"contentType\":\"text\"")); assertTrue(json.contains("\"lastModified\":1111111")); } @Override @Test public void testSerializeFailResponse() throws JsonProcessingException { ConfigQueryResponse configQueryResponse = ConfigQueryResponse.buildFailResponse(500, "Fail"); String json = mapper.writeValueAsString(configQueryResponse); assertTrue(json.contains("\"resultCode\":" + ResponseCode.FAIL.getCode())); assertTrue(json.contains("\"errorCode\":500")); assertTrue(json.contains("\"message\":\"Fail\"")); assertTrue(json.contains("\"success\":false")); } @Override @Test public void testDeserialize() throws JsonProcessingException { String json = "{\"resultCode\":200,\"errorCode\":0,\"requestId\":\"2239753e-e682-441c-83cf-fb8129ca68a4\"," + "\"content\":\"success\",\"encryptedDataKey\":\"encryptedKey\",\"contentType\":\"text\",\"md5\":\"test_MD5\"," + "\"lastModified\":1111111,\"tag\":\"tag\",\"beta\":false,\"success\":true}\n"; ConfigQueryResponse actual = mapper.readValue(json, ConfigQueryResponse.class); assertTrue(actual.isSuccess()); assertEquals(ResponseCode.SUCCESS.getCode(), actual.getResultCode()); assertEquals("success", actual.getContent()); assertEquals("text", actual.getContentType()); assertEquals("2239753e-e682-441c-83cf-fb8129ca68a4", actual.getRequestId()); assertEquals(MD5, actual.getMd5()); assertEquals(TAG, actual.getTag()); assertEquals("text", actual.getContentType()); assertEquals(1111111L, actual.getLastModified()); } }
ConfigQueryResponseTest
java
quarkusio__quarkus
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/validatorfactory/ValidatorFactoryFromValidationTest.java
{ "start": 529, "end": 1192 }
class ____ { @Inject ValidatorFactory validatorFactoryFromInjection; @RegisterExtension static final QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(() -> ShrinkWrap .create(JavaArchive.class)); @Test public void testValidatorFactoryManuallyCreatedIsManagedByQuarkus() { ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); // we need to unwrap here as we have a small wrapper around the manually created one assertThat(validatorFactoryFromInjection).isSameAs(validatorFactory.unwrap(HibernateValidatorFactory.class)); } }
ValidatorFactoryFromValidationTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/DurationGetTemporalUnitTest.java
{ "start": 3546, "end": 4108 }
class ____ {", " private static final TemporalUnit SECONDS = DAYS;", // This really should be flagged, but isn't :( " private static final long seconds = Duration.ZERO.get(SECONDS);", "}") .doTest(); } @Test public void durationGetWithCustomTemporalUnit() { helper .addSourceLines( "TestClass.java", "import java.time.Duration;", "import java.time.temporal.Temporal;", "import java.time.temporal.TemporalUnit;", "public
TestClass
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/metadata/IndexReshardingMetadata.java
{ "start": 3839, "end": 6944 }
class ____ * the persistent state required to recover correctly, always maintaining the invariant that only the source shard * accepts indexing and search requests for the target prior to handoff, and only the target shard accepts them afterward. * * The state we preserve is: * * The old and new shard counts for a resize operation, so that we can always identify which shards are sources * and which are targets during resharding. For example, old:2 new:6 implies that shard 1 is the source shard for * shards 3 and 5, and shard 2 is the source for shards 4 and 6. * * For each source shard, its current source state, which is either `SOURCE` or `DONE`. * - If a source shard may still contain data for any target shard then it is in state `SOURCE`. * - When all targets for a source have moved to `SPLIT` (see below), then the source deletes all documents from * its store that are now the responsibility of the target shards and transitions to `DONE`. * This isn't strictly required to be persistent for correctness, but it can save time on recovery * by allowing a DONE shard to skip interrogating targets and repeating cleanup. * * For each target shard, its current target state, which is one of `CLONE`, `HANDOFF`, `SPLIT`, or `DONE`. * - If the target has not yet copied all data from the source shard, then it is in `CLONE`. * - It moves to `HANDOFF` when it has copied all of its data from the source to indicate that it is now ready to * receive indexing actions, and starts RUNNING. After this point, the source may no longer contain the entire contents * of the target and must not index documents belonging to the target. But since search shards can't start up until * their corresponding index shards are active, search requests would fail if they routed to the target shard immediately * after handoff. So at HANDOFF, the source shards continue to service searches, but block refresh since they cannot * be guaranteed to have seen documents indexed after HANDOFF. * - When the target shard's corresponding search replica has started running, the target requests that the source filter * search results belonging to the target, and moves the target shard's state to `SPLIT`. The target's search replica * likewise filters documents not belonging to the target, which may be present due to the target bootstrapping by copying * the source's lucene files. * - Upon entering `SPLIT`, the target starts deleting all documents from its lucene store that do not belong to it. When that * is complete, it moves to `DONE` and removes filters for other shards, which are no longer necessary. * * Note that each target shard's split operates independently and all may happen concurrently. * * When all source shards have transitioned to `DONE`, the resize is complete and this metadata may be removed from cluster state. * We only allow at most a single resharding operation to be in flight for an index, so removing this metadata is a prerequisite * to beginning another resharding operation. */ public
holds
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/mapper/TextFieldTypeTests.java
{ "start": 2678, "end": 20545 }
class ____ extends FieldTypeTestCase { private static TextFieldType createFieldType() { return new TextFieldType("field", randomBoolean(), false); } public void testIsAggregatableDependsOnFieldData() { TextFieldType ft = createFieldType(); assertFalse(ft.isAggregatable()); ft.setFielddata(true); assertTrue(ft.isAggregatable()); } public void testTermQuery() { MappedFieldType ft = createFieldType(); assertEquals(new TermQuery(new Term("field", "foo")), ft.termQuery("foo", null)); assertEquals(AutomatonQueries.caseInsensitiveTermQuery(new Term("field", "fOo")), ft.termQueryCaseInsensitive("fOo", null)); MappedFieldType unsearchable = new TextFieldType("field", false, false, Collections.emptyMap()); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> unsearchable.termQuery("bar", null)); assertEquals("Cannot search on field [field] since it is not indexed.", e.getMessage()); } public void testTermsQuery() { MappedFieldType ft = createFieldType(); List<BytesRef> terms = new ArrayList<>(); terms.add(new BytesRef("foo")); terms.add(new BytesRef("bar")); assertEquals(new TermInSetQuery("field", terms), ft.termsQuery(Arrays.asList("foo", "bar"), null)); MappedFieldType unsearchable = new TextFieldType("field", false, false, Collections.emptyMap()); IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> unsearchable.termsQuery(Arrays.asList("foo", "bar"), null) ); assertEquals("Cannot search on field [field] since it is not indexed.", e.getMessage()); } public void testRangeQuery() { MappedFieldType ft = createFieldType(); assertEquals( new TermRangeQuery("field", BytesRefs.toBytesRef("foo"), BytesRefs.toBytesRef("bar"), true, false), ft.rangeQuery("foo", "bar", true, false, null, null, null, MOCK_CONTEXT) ); ElasticsearchException ee = expectThrows( ElasticsearchException.class, () -> ft.rangeQuery("foo", "bar", true, false, null, null, null, MOCK_CONTEXT_DISALLOW_EXPENSIVE) ); assertEquals( "[range] queries on [text] or [keyword] fields cannot be executed when " + "'search.allow_expensive_queries' is set to false.", ee.getMessage() ); } public void testRegexpQuery() { MappedFieldType ft = createFieldType(); assertEquals(new RegexpQuery(new Term("field", "foo.*")), ft.regexpQuery("foo.*", 0, 0, 10, null, MOCK_CONTEXT)); MappedFieldType unsearchable = new TextFieldType("field", false, false, Collections.emptyMap()); IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> unsearchable.regexpQuery("foo.*", 0, 0, 10, null, MOCK_CONTEXT) ); assertEquals("Cannot search on field [field] since it is not indexed.", e.getMessage()); ElasticsearchException ee = expectThrows( ElasticsearchException.class, () -> ft.regexpQuery("foo.*", randomInt(10), 0, randomInt(10) + 1, null, MOCK_CONTEXT_DISALLOW_EXPENSIVE) ); assertEquals("[regexp] queries cannot be executed when 'search.allow_expensive_queries' is set to false.", ee.getMessage()); } public void testFuzzyQuery() { MappedFieldType ft = createFieldType(); assertEquals( new FuzzyQuery(new Term("field", "foo"), 2, 1, 50, true), ft.fuzzyQuery("foo", Fuzziness.fromEdits(2), 1, 50, true, MOCK_CONTEXT) ); MappedFieldType unsearchable = new TextFieldType("field", false, false, Collections.emptyMap()); IllegalArgumentException e = expectThrows( IllegalArgumentException.class, () -> unsearchable.fuzzyQuery("foo", Fuzziness.fromEdits(2), 1, 50, true, MOCK_CONTEXT) ); assertEquals("Cannot search on field [field] since it is not indexed.", e.getMessage()); ElasticsearchException ee = expectThrows( ElasticsearchException.class, () -> ft.fuzzyQuery( "foo", Fuzziness.AUTO, randomInt(10) + 1, randomInt(10) + 1, randomBoolean(), MOCK_CONTEXT_DISALLOW_EXPENSIVE ) ); assertEquals("[fuzzy] queries cannot be executed when 'search.allow_expensive_queries' is set to false.", ee.getMessage()); assertEquals( new FuzzyQuery(new Term("field", "foo"), 2, 1, 50, true, MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE), ft.fuzzyQuery("foo", Fuzziness.fromEdits(2), 1, 50, true, MOCK_CONTEXT, MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE) ); } public void testIndexPrefixes() { TextFieldType ft = createFieldType(); ft.setIndexPrefixes(2, 10); Query q = ft.prefixQuery("goin", randomBoolean() ? null : CONSTANT_SCORE_BLENDED_REWRITE, false, randomMockContext()); assertEquals(new ConstantScoreQuery(new TermQuery(new Term("field._index_prefix", "goin"))), q); q = ft.prefixQuery("internationalisatio", randomBoolean() ? null : CONSTANT_SCORE_BLENDED_REWRITE, false, MOCK_CONTEXT); assertEquals(new PrefixQuery(new Term("field", "internationalisatio")), q); q = ft.prefixQuery("Internationalisatio", randomBoolean() ? null : CONSTANT_SCORE_BLENDED_REWRITE, true, MOCK_CONTEXT); assertEquals(AutomatonQueries.caseInsensitivePrefixQuery(new Term("field", "Internationalisatio")), q); ElasticsearchException ee = expectThrows( ElasticsearchException.class, () -> ft.prefixQuery("internationalisatio", null, false, MOCK_CONTEXT_DISALLOW_EXPENSIVE) ); assertEquals( "[prefix] queries cannot be executed when 'search.allow_expensive_queries' is set to false. " + "For optimised prefix queries on text fields please enable [index_prefixes].", ee.getMessage() ); q = ft.prefixQuery("g", randomBoolean() ? null : CONSTANT_SCORE_BLENDED_REWRITE, false, randomMockContext()); Automaton automaton = Operations.concatenate(Arrays.asList(Automata.makeChar('g'), Automata.makeAnyChar())); Query expected = new ConstantScoreQuery( new BooleanQuery.Builder().add(new AutomatonQuery(new Term("field._index_prefix", "g*"), automaton), BooleanClause.Occur.SHOULD) .add(new TermQuery(new Term("field", "g")), BooleanClause.Occur.SHOULD) .build() ); assertThat(q, equalTo(expected)); } public void testFetchSourceValue() throws IOException { TextFieldType fieldType = createFieldType(); assertEquals(List.of("value"), fetchSourceValue(fieldType, "value")); assertEquals(List.of("42"), fetchSourceValue(fieldType, 42L)); assertEquals(List.of("true"), fetchSourceValue(fieldType, true)); } public void testWildcardQuery() { TextFieldType ft = createFieldType(); // case sensitive AutomatonQuery actual = (AutomatonQuery) ft.wildcardQuery("*Butterflies*", null, false, MOCK_CONTEXT); AutomatonQuery expected = new WildcardQuery(new Term("field", new BytesRef("*Butterflies*"))); assertEquals(expected, actual); assertFalse(new CharacterRunAutomaton(actual.getAutomaton()).run("some butterflies somewhere")); // case insensitive actual = (AutomatonQuery) ft.wildcardQuery("*Butterflies*", null, true, MOCK_CONTEXT); expected = AutomatonQueries.caseInsensitiveWildcardQuery(new Term("field", new BytesRef("*Butterflies*"))); assertEquals(expected, actual); assertTrue(new CharacterRunAutomaton(actual.getAutomaton()).run("some butterflies somewhere")); assertTrue(new CharacterRunAutomaton(actual.getAutomaton()).run("some Butterflies somewhere")); ElasticsearchException ee = expectThrows( ElasticsearchException.class, () -> ft.wildcardQuery("valu*", null, MOCK_CONTEXT_DISALLOW_EXPENSIVE) ); assertEquals("[wildcard] queries cannot be executed when 'search.allow_expensive_queries' is set to false.", ee.getMessage()); } /** * we use this e.g. in query string query parser to normalize terms on text fields */ public void testNormalizedWildcardQuery() { TextFieldType ft = createFieldType(); AutomatonQuery actual = (AutomatonQuery) ft.normalizedWildcardQuery("*Butterflies*", null, MOCK_CONTEXT); AutomatonQuery expected = new WildcardQuery(new Term("field", new BytesRef("*butterflies*"))); assertEquals(expected, actual); assertTrue(new CharacterRunAutomaton(actual.getAutomaton()).run("some butterflies somewhere")); assertFalse(new CharacterRunAutomaton(actual.getAutomaton()).run("some Butterflies somewhere")); ElasticsearchException ee = expectThrows( ElasticsearchException.class, () -> ft.wildcardQuery("valu*", null, MOCK_CONTEXT_DISALLOW_EXPENSIVE) ); assertEquals("[wildcard] queries cannot be executed when 'search.allow_expensive_queries' is set to false.", ee.getMessage()); } public void testTermIntervals() throws IOException { TextFieldType ft = createFieldType(); IntervalsSource termIntervals = ft.termIntervals(new BytesRef("foo"), MOCK_CONTEXT); assertEquals(Intervals.term(new BytesRef("foo")), termIntervals); } public void testPrefixIntervals() throws IOException { TextFieldType ft = createFieldType(); IntervalsSource prefixIntervals = ft.prefixIntervals(new BytesRef("foo"), MOCK_CONTEXT); assertEquals(Intervals.prefix(new BytesRef("foo"), IndexSearcher.getMaxClauseCount()), prefixIntervals); } public void testWildcardIntervals() { TextFieldType ft = createFieldType(); IntervalsSource wildcardIntervals = ft.wildcardIntervals(new BytesRef("foo"), MOCK_CONTEXT); assertEquals(Intervals.wildcard(new BytesRef("foo"), IndexSearcher.getMaxClauseCount()), wildcardIntervals); } public void testRegexpIntervals() { TextFieldType ft = createFieldType(); IntervalsSource regexpIntervals = ft.regexpIntervals(new BytesRef("foo"), MOCK_CONTEXT); assertEquals(Intervals.regexp(new BytesRef("foo"), IndexSearcher.getMaxClauseCount()), regexpIntervals); } public void testFuzzyIntervals() { TextFieldType ft = createFieldType(); IntervalsSource fuzzyIntervals = ft.fuzzyIntervals("foo", 1, 2, true, MOCK_CONTEXT); FuzzyQuery fq = new FuzzyQuery(new Term("field", "foo"), 1, 2, 128, true); IntervalsSource expectedIntervals = Intervals.multiterm(fq.getAutomata(), IndexSearcher.getMaxClauseCount(), "foo"); assertEquals(expectedIntervals, fuzzyIntervals); } public void testPrefixIntervalsWithIndexedPrefixes() { TextFieldType ft = createFieldType(); ft.setIndexPrefixes(1, 4); IntervalsSource prefixIntervals = ft.prefixIntervals(new BytesRef("foo"), MOCK_CONTEXT); assertEquals(Intervals.fixField("field._index_prefix", Intervals.term(new BytesRef("foo"))), prefixIntervals); } public void testWildcardIntervalsWithIndexedPrefixes() { TextFieldType ft = createFieldType(); ft.setIndexPrefixes(1, 4); IntervalsSource wildcardIntervals = ft.wildcardIntervals(new BytesRef("foo"), MOCK_CONTEXT); assertEquals(Intervals.wildcard(new BytesRef("foo"), IndexSearcher.getMaxClauseCount()), wildcardIntervals); } public void testRangeIntervals() { TextFieldType ft = createFieldType(); IntervalsSource rangeIntervals = ft.rangeIntervals(new BytesRef("foo"), new BytesRef("foo1"), true, true, MOCK_CONTEXT); assertEquals( Intervals.range(new BytesRef("foo"), new BytesRef("foo1"), true, true, IndexSearcher.getMaxClauseCount()), rangeIntervals ); } public void testBlockLoaderUsesSyntheticSourceDelegateWhenIgnoreAboveIsNotSet() { // given KeywordFieldMapper.KeywordFieldType syntheticSourceDelegate = new KeywordFieldMapper.KeywordFieldType( "child", true, true, Collections.emptyMap() ); TextFieldType ft = new TextFieldType( "parent", true, false, new TextSearchInfo(TextFieldMapper.Defaults.FIELD_TYPE, null, Lucene.STANDARD_ANALYZER, Lucene.STANDARD_ANALYZER), true, false, syntheticSourceDelegate, Collections.singletonMap("potato", "tomato"), false, false ); // when BlockLoader blockLoader = ft.blockLoader(mock(MappedFieldType.BlockLoaderContext.class)); // then // verify that we delegate block loading to the synthetic source delegate assertTrue(blockLoader instanceof BlockLoader.Delegating); assertThat(((BlockLoader.Delegating) blockLoader).delegatingTo(), equalTo("child")); } public void testBlockLoaderDoesNotUseSyntheticSourceDelegateWhenIgnoreAboveIsSet() { // given Settings settings = Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()) .put(IndexSettings.MODE.getKey(), IndexMode.STANDARD) .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1) .build(); IndexSettings indexSettings = new IndexSettings(IndexMetadata.builder("index").settings(settings).build(), settings); MappingParserContext mappingParserContext = mock(MappingParserContext.class); doReturn(settings).when(mappingParserContext).getSettings(); doReturn(indexSettings).when(mappingParserContext).getIndexSettings(); doReturn(mock(ScriptCompiler.class)).when(mappingParserContext).scriptCompiler(); doReturn(true).when(mappingParserContext).isWithinMultiField(); KeywordFieldMapper.Builder builder = new KeywordFieldMapper.Builder("child", mappingParserContext); builder.ignoreAbove(123); KeywordFieldMapper.KeywordFieldType syntheticSourceDelegate = new KeywordFieldMapper.KeywordFieldType( "child", IndexType.terms(true, true), new TextSearchInfo(mock(FieldType.class), null, mock(NamedAnalyzer.class), mock(NamedAnalyzer.class)), mock(NamedAnalyzer.class), builder, true ); TextFieldType ft = new TextFieldType( "parent", true, false, new TextSearchInfo(TextFieldMapper.Defaults.FIELD_TYPE, null, Lucene.STANDARD_ANALYZER, Lucene.STANDARD_ANALYZER), true, false, syntheticSourceDelegate, Collections.singletonMap("potato", "tomato"), false, false ); // when var context = mock(MappedFieldType.BlockLoaderContext.class); when(context.indexSettings()).thenReturn(indexSettings); BlockLoader blockLoader = ft.blockLoader(context); // then // verify that we don't delegate anything assertFalse(blockLoader instanceof BlockLoader.Delegating); } public void testBlockLoaderDoesNotUseSyntheticSourceDelegateWhenIgnoreAboveIsSetAtIndexLevel() { // given Settings settings = Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()) .put(IndexSettings.MODE.getKey(), IndexMode.STANDARD) .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1) .put(IndexSettings.IGNORE_ABOVE_SETTING.getKey(), 123) .build(); IndexSettings indexSettings = new IndexSettings(IndexMetadata.builder("index").settings(settings).build(), settings); MappingParserContext mappingParserContext = mock(MappingParserContext.class); doReturn(settings).when(mappingParserContext).getSettings(); doReturn(indexSettings).when(mappingParserContext).getIndexSettings(); doReturn(mock(ScriptCompiler.class)).when(mappingParserContext).scriptCompiler(); doReturn(true).when(mappingParserContext).isWithinMultiField(); KeywordFieldMapper.Builder builder = new KeywordFieldMapper.Builder("child", mappingParserContext); KeywordFieldMapper.KeywordFieldType syntheticSourceDelegate = new KeywordFieldMapper.KeywordFieldType( "child", IndexType.terms(true, true), new TextSearchInfo(mock(FieldType.class), null, mock(NamedAnalyzer.class), mock(NamedAnalyzer.class)), mock(NamedAnalyzer.class), builder, true ); TextFieldType ft = new TextFieldType( "parent", true, false, new TextSearchInfo(TextFieldMapper.Defaults.FIELD_TYPE, null, Lucene.STANDARD_ANALYZER, Lucene.STANDARD_ANALYZER), true, false, syntheticSourceDelegate, Collections.singletonMap("potato", "tomato"), false, false ); // when var context = mock(MappedFieldType.BlockLoaderContext.class); when(context.indexSettings()).thenReturn(indexSettings); BlockLoader blockLoader = ft.blockLoader(context); // then // verify that we don't delegate anything assertFalse(blockLoader instanceof BlockLoader.Delegating); } }
TextFieldTypeTests
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/processor/PopReviveService.java
{ "start": 37488, "end": 38014 }
class ____ { HashMap<String, PopCheckPoint> map = new HashMap<>(); ArrayList<PopCheckPoint> sortList; long oldOffset; long endTime; long newOffset; ArrayList<PopCheckPoint> genSortList() { if (sortList != null) { return sortList; } sortList = new ArrayList<>(map.values()); sortList.sort((o1, o2) -> (int) (o1.getReviveOffset() - o2.getReviveOffset())); return sortList; } } }
ConsumeReviveObj
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/conversion/BigDecimalToBigIntegerConversion.java
{ "start": 647, "end": 1247 }
class ____ extends SimpleConversion { @Override public String getToExpression(ConversionContext conversionContext) { return "<SOURCE>.toBigInteger()"; } @Override public String getFromExpression(ConversionContext conversionContext) { return "new " + bigDecimal( conversionContext ) + "( <SOURCE> )"; } @Override protected Set<Type> getFromConversionImportTypes(ConversionContext conversionContext) { return asSet( conversionContext.getTypeFactory().getType( BigDecimal.class ) ); } }
BigDecimalToBigIntegerConversion
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/util/GenericFieldInfoTest.java
{ "start": 731, "end": 786 }
class ____ <T> extends A1<T> { } public static
A2
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/writeAsArray/WriteAsArray_Object.java
{ "start": 318, "end": 927 }
class ____ extends TestCase { public void test_0() throws Exception { A a = new A(); a.setId(123); a.setName("wenshao"); VO vo = new VO(); vo.setA(a); String text = JSON.toJSONString(vo, SerializerFeature.BeanToArray); Assert.assertEquals("[[123,\"wenshao\"]]", text); VO vo2 = JSON.parseObject(text, VO.class, Feature.SupportArrayToBean); Assert.assertEquals(vo.getA().getId(), vo2.getA().getId()); Assert.assertEquals(vo.getA().getName(), vo2.getA().getName()); } private static
WriteAsArray_Object
java
quarkusio__quarkus
extensions/liquibase/liquibase/deployment/src/test/java/io/quarkus/liquibase/test/LiquibaseExtensionConfigDefaultDataSourceTest.java
{ "start": 358, "end": 1350 }
class ____ { @Inject LiquibaseFactory liquibase; @Inject LiquibaseExtensionConfigFixture fixture; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClass(LiquibaseExtensionConfigFixture.class) .addAsResource("db/xml/changeLog.xml") .addAsResource("db/xml/create-tables.xml") .addAsResource("db/xml/create-views.xml") .addAsResource("db/xml/test/test.xml") .addAsResource("config-for-default-datasource.properties", "application.properties")); @Test @DisplayName("Reads liquibase configuration for default datasource correctly") public void testLiquibaseConfigInjection() { fixture.assertAllConfigurationSettings(liquibase.getConfiguration(), ""); assertFalse(fixture.migrateAtStart("")); } }
LiquibaseExtensionConfigDefaultDataSourceTest
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AuditWorkUnit.java
{ "start": 401, "end": 1360 }
interface ____ extends WorkUnitMergeVisitor, WorkUnitMergeDispatcher { Object getEntityId(); String getEntityName(); boolean containsWork(); boolean isPerformed(); /** * Perform this work unit in the given session. * * @param session Session, in which the work unit should be performed. * @param revisionData The current revision data, which will be used to populate the work unit with the correct * revision relation. */ void perform(SharedSessionContractImplementor session, Object revisionData); void undo(SharedSessionContractImplementor session); /** * @param revisionData The current revision data, which will be used to populate the work unit with the correct * revision relation. * * @return Generates data that should be saved when performing this work unit. */ Map<String, Object> generateData(Object revisionData); /** * @return Performed modification type. */ RevisionType getRevisionType(); }
AuditWorkUnit
java
apache__camel
dsl/camel-kamelet-main/src/test/java/org/apache/camel/main/MavenDependencyResolverTest.java
{ "start": 1340, "end": 4333 }
class ____ { public static final Logger LOG = LoggerFactory.getLogger(MavenDependencyResolverTest.class); @Test public void testDownload() throws Exception { List<String> deps = List.of("org.apache.camel:camel-core:3.17.0"); try (MavenDependencyDownloader downloader = new MavenDependencyDownloader()) { // build() creates own DIRegistry and configures the resolver/aether stuff through // org.apache.camel:camel-tooling-maven downloader.build(); List<MavenArtifact> answer = downloader.resolveDependenciesViaAether(deps, null, true, false); Assertions.assertNotNull(answer); assertTrue(answer.size() > 15); for (MavenArtifact ma : answer) { LOG.info("Artifact (transitive): {}", ma); } answer = downloader.resolveDependenciesViaAether(deps, null, false, false); Assertions.assertNotNull(answer); assertEquals(1, answer.size()); for (MavenArtifact ma : answer) { LOG.info("Artifact (non-transitive): {}", ma); } } } @Test public void testGeneratePluginUsesCorrectTransitiveDependencies() throws Exception { List<String> deps = List.of("org.apache.camel:camel-jbang-plugin-generate:4.8.0"); Predicate<MavenArtifact> artifactFilter = mavenArtifact -> "jackson-datatype-guava" .equals(mavenArtifact.getGav().getArtifactId()); try (MavenDependencyDownloader downloader = new MavenDependencyDownloader()) { downloader.build(); List<MavenArtifact> answer = downloader.resolveDependenciesViaAether(deps, null, true, false); Assertions.assertNotNull(answer); Assertions.assertTrue(answer.stream().anyMatch(artifactFilter), "check jackson-datatype-guava is present in transitive dependencies"); //jackson version from Camel 4.8.0 parent should be 2.17.2 String expectedVersion = "2.17.2"; Assertions.assertNotEquals(expectedVersion, answer.stream().filter(artifactFilter) .findFirst().get().getGav().getVersion(), "check jackson-datatype-guava version without parent"); //resolve the dependencies with parent answer = downloader.resolveDependenciesViaAether("org.apache.camel:camel-jbang-parent:4.8.0", deps, null, true, false); Assertions.assertNotNull(answer); Assertions.assertTrue(answer.stream().anyMatch(artifactFilter), "check jackson-datatype-guava is present in transitive dependencies"); Assertions.assertEquals(expectedVersion, answer.stream().filter(artifactFilter) .findFirst().get().getGav().getVersion(), "check jackson-datatype-guava version with parent"); } } }
MavenDependencyResolverTest
java
apache__maven
its/core-it-suite/src/test/resources/mng-3724/maven-mng3724-plugin/src/main/java/jar/AbstractMng2734Mojo.java
{ "start": 906, "end": 1232 }
class ____ extends AbstractMojo { /** * Location of the file. * @parameter expression="${project.build.directory}/generated/src/main/java" * @required */ private File generatorTargetDir; protected final File getGeneratorTargetDir() { return generatorTargetDir; } }
AbstractMng2734Mojo
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/aot/hint/BindingReflectionHintsRegistrarTests.java
{ "start": 15614, "end": 15703 }
class ____ { public Set<SampleClassB> getB() { return null; } } static
SampleClassA
java
google__dagger
dagger-runtime/main/java/dagger/internal/SetBuilder.java
{ "start": 872, "end": 1046 }
class ____ returns a {@link Set}. Used in component implementations where a set * must be created in one fluent statement for inlined request fulfillments. */ public final
that
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/CancelableCompletionStageTest.java
{ "start": 979, "end": 2366 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot(jar -> jar.addClasses(Resource.class)); @BeforeEach void setUp() { Resource.COUNT.set(0); } @Inject Vertx vertx; @TestHTTPResource URL url; @Test public void testNormal() { when().get("test") .then() .statusCode(200) .body(equalTo("Hello, world")); } @Test public void testCancel() { WebClient client = WebClient.create(vertx); client.get(url.getPort(), url.getHost(), "/test").send(); try { // make sure we did make the proper request await().atMost(Duration.ofSeconds(2)).untilAtomic(Resource.COUNT, equalTo(1)); // this will effectively cancel the request client.close(); // make sure we wait until the request could have completed Thread.sleep(7_000); // if the count did not increase, it means that Uni was cancelled assertEquals(1, Resource.COUNT.get()); } catch (InterruptedException ignored) { } finally { try { client.close(); } catch (Exception ignored) { } } } @Path("test") public static
CancelableCompletionStageTest
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/context/request/NativeWebRequest.java
{ "start": 1014, "end": 2055 }
interface ____ extends WebRequest { /** * Return the underlying native request object. * @see jakarta.servlet.http.HttpServletRequest */ Object getNativeRequest(); /** * Return the underlying native response object, if any. * @see jakarta.servlet.http.HttpServletResponse */ @Nullable Object getNativeResponse(); /** * Return the underlying native request object, if available. * @param requiredType the desired type of request object * @return the matching request object, or {@code null} if none * of that type is available * @see jakarta.servlet.http.HttpServletRequest */ <T> @Nullable T getNativeRequest(@Nullable Class<T> requiredType); /** * Return the underlying native response object, if available. * @param requiredType the desired type of response object * @return the matching response object, or {@code null} if none * of that type is available * @see jakarta.servlet.http.HttpServletResponse */ <T> @Nullable T getNativeResponse(@Nullable Class<T> requiredType); }
NativeWebRequest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/KeyGroupsStateHandle.java
{ "start": 1292, "end": 7006 }
class ____ implements StreamStateHandle, KeyedStateHandle { private static final long serialVersionUID = -8070326169926626355L; /** Range of key-groups with their respective offsets in the stream state */ private final KeyGroupRangeOffsets groupRangeOffsets; /** Inner stream handle to the actual states of the key-groups in the range */ private final StreamStateHandle stateHandle; private final StateHandleID stateHandleId; /** * @param groupRangeOffsets range of key-group ids that in the state of this handle * @param streamStateHandle handle to the actual state of the key-groups */ public KeyGroupsStateHandle( KeyGroupRangeOffsets groupRangeOffsets, StreamStateHandle streamStateHandle) { this(groupRangeOffsets, streamStateHandle, new StateHandleID(UUID.randomUUID().toString())); } private KeyGroupsStateHandle( KeyGroupRangeOffsets groupRangeOffsets, StreamStateHandle streamStateHandle, StateHandleID stateHandleId) { Preconditions.checkNotNull(groupRangeOffsets); Preconditions.checkNotNull(streamStateHandle); Preconditions.checkNotNull(stateHandleId); this.groupRangeOffsets = groupRangeOffsets; this.stateHandle = streamStateHandle; this.stateHandleId = stateHandleId; } public static KeyGroupsStateHandle restore( KeyGroupRangeOffsets groupRangeOffsets, StreamStateHandle streamStateHandle, StateHandleID stateHandleId) { return new KeyGroupsStateHandle(groupRangeOffsets, streamStateHandle, stateHandleId); } /** * @return the internal key-group range to offsets metadata */ public KeyGroupRangeOffsets getGroupRangeOffsets() { return groupRangeOffsets; } /** * @return The handle to the actual states */ public StreamStateHandle getDelegateStateHandle() { return stateHandle; } /** * @param keyGroupId the id of a key-group. the id must be contained in the range of this * handle. * @return offset to the position of data for the provided key-group in the stream referenced by * this state handle */ public long getOffsetForKeyGroup(int keyGroupId) { return groupRangeOffsets.getKeyGroupOffset(keyGroupId); } /** * @param keyGroupRange a key group range to intersect. * @return key-group state over a range that is the intersection between this handle's key-group * range and the provided key-group range. */ @Override public KeyGroupsStateHandle getIntersection(KeyGroupRange keyGroupRange) { KeyGroupRangeOffsets offsets = groupRangeOffsets.getIntersection(keyGroupRange); if (offsets.getKeyGroupRange().getNumberOfKeyGroups() <= 0) { return null; } return new KeyGroupsStateHandle(offsets, stateHandle, stateHandleId); } @Override public StateHandleID getStateHandleId() { return stateHandleId; } @Override public PhysicalStateHandleID getStreamStateHandleID() { return stateHandle.getStreamStateHandleID(); } @Override public KeyGroupRange getKeyGroupRange() { return groupRangeOffsets.getKeyGroupRange(); } @Override public void registerSharedStates(SharedStateRegistry stateRegistry, long checkpointID) { // No shared states } @Override public void discardState() throws Exception { stateHandle.discardState(); } @Override public long getStateSize() { return stateHandle.getStateSize(); } @Override public void collectSizeStats(StateObjectSizeStatsCollector collector) { // TODO: for now this ignores that only some key groups might be accessed when reading the // state, so this only reports the upper bound. We could introduce // #collectSizeStats(StateObjectSizeStatsCollector, KeyGroupRange) in KeyedStateHandle // that computes which groups where actually touched and computes the size, depending on // the exact state handle type, from either the offsets (e.g. here) or for the full size // (e.g. remote incremental) when we restore from managed/raw keyed state. stateHandle.collectSizeStats(collector); } @Override public long getCheckpointedSize() { return getStateSize(); } @Override public FSDataInputStream openInputStream() throws IOException { return stateHandle.openInputStream(); } @Override public Optional<byte[]> asBytesIfInMemory() { return stateHandle.asBytesIfInMemory(); } @Override public Optional<org.apache.flink.core.fs.Path> maybeGetPath() { return stateHandle.maybeGetPath(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof KeyGroupsStateHandle)) { return false; } KeyGroupsStateHandle that = (KeyGroupsStateHandle) o; if (!groupRangeOffsets.equals(that.groupRangeOffsets)) { return false; } return stateHandle.equals(that.stateHandle); } @Override public int hashCode() { int result = groupRangeOffsets.hashCode(); result = 31 * result + stateHandle.hashCode(); return result; } @Override public String toString() { return "KeyGroupsStateHandle{" + "groupRangeOffsets=" + groupRangeOffsets + ", stateHandle=" + stateHandle + '}'; } }
KeyGroupsStateHandle
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ErroneousThreadPoolConstructorCheckerTest.java
{ "start": 11933, "end": 12564 }
class ____ { private static final int CORE_SIZE = 10; private static final int MAX_SIZE = 20; public void createThreadPool() { new ThreadPoolExecutor(CORE_SIZE, CORE_SIZE, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); } } """) .doTest(); } @Test public void erroneousThreadPoolConstructor_staticConstantsForPoolSize_refactorUsingSecondFix() { refactoringHelper .setFixChooser(FixChoosers.SECOND) .addInputLines( "Test.java", """ import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit;
Test
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/AbstractAsyncThreadContextTestBase.java
{ "start": 3193, "end": 4089 }
enum ____ { ALL_ASYNC, MIXED, BOTH_ALL_ASYNC_AND_MIXED; void initSelector() { final ContextSelector selector; if (this == ALL_ASYNC || this == BOTH_ALL_ASYNC_AND_MIXED) { selector = new AsyncLoggerContextSelector(); } else { selector = new ClassLoaderContextSelector(); } LogManager.setFactory(new Log4jContextFactory(selector)); } void initConfigFile() { // NOTICE: PLEASE DON'T REFACTOR: keep "file" local variable for confirmation in debugger. final String file = this == ALL_ASYNC // ? "AsyncLoggerThreadContextTest.xml" // : "AsyncLoggerConfigThreadContextTest.xml"; props.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, file); } } protected
Mode
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java
{ "start": 1031, "end": 1516 }
class ____ MockMvc builder implementations, providing the capability to * create a {@link MockMvc} instance. * * <p>{@link org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder}, * which derives from this class, provides a concrete {@code build} method, * and delegates to abstract methods to obtain a {@link WebApplicationContext}. * * @author Rossen Stoyanchev * @author Rob Winch * @author Stephane Nicoll * @author Sam Brannen * @since 3.2 */ public abstract
for
java
alibaba__druid
core/src/test/java/com/alibaba/druid/sql/dialect/starrocks/visitor/StarRocksOutputVisitorTest.java
{ "start": 515, "end": 5614 }
class ____ extends TestCase { public void testStarRocksOutputVisitor() { String message = "output error"; String origin = "CREATE TABLE IF NOT EXISTS `detailDemo` (\n" + "\t`recruit_date` DATE NOT NULL COMMENT 'YYYY-MM-DD',\n" + "\t`region_num` TINYINT COMMENT 'range [-128, 127]',\n" + "\t`num_plate` SMALLINT COMMENT 'range [-32768, 32767] ',\n" + "\t`tel` INT COMMENT 'range [-2147483648, 2147483647]',\n" + "\t`id` BIGINT COMMENT 'range [-2^63 + 1 ~ 2^63 - 1]',\n" + "\t`password` LARGEINT COMMENT 'range [-2^127 + 1 ~ 2^127 - 1]',\n" + "\t`name` CHAR(20) NOT NULL COMMENT 'range char(m),m in (1-255)',\n" + "\t`profile` VARCHAR(500) NOT NULL COMMENT 'upper limit value 1048576 bytes',\n" + "\t`hobby` STRING NOT NULL COMMENT 'upper limit value 65533 bytes',\n" + "\t`leave_time` DATETIME COMMENT 'YYYY-MM-DD HH:MM:SS',\n" + "\t`channel` FLOAT COMMENT '4 bytes',\n" + "\t`income` DOUBLE COMMENT '8 bytes',\n" + "\t`account` DECIMAL(12, 4) COMMENT '\"\"',\n" + "\t`ispass` BOOLEAN COMMENT 'true/false'\n" + ") ENGINE = OLAP\n" + "DUPLICATE KEY(`recruit_date`, `region_num`)\n" + "COMMENT 'xxxxx'\n" + "PARTITION BY RANGE(`recruit_date`)\n" + "(\n" + " PARTITION p202101 VALUES [(\"20210101\"),(\"20210201\")),\n" + " PARTITION p202102 VALUES [(\"20210201\"),(\"20210301\")),\n" + " PARTITION p202103 VALUES [(\"20210301\"),(MAXVALUE))\n" + ")\n" + "DISTRIBUTED BY HASH(`recruit_date`, `region_num`) BUCKETS 8\n" + "PROPERTIES (\n" + " \"storage_medium\" = \"[SSD|HDD]\",\n" + " \"dynamic_partition.enable\" = \"true|false\",\n" + " \"dynamic_partition.time_unit\" = \"DAY|WEEK|MONTH\",\n" + " \"dynamic_partition.start\" = \"${integer_value}\",\n" + " [\"storage_cooldown_time\" = \"yyyy-MM-dd HH:mm:ss\",]\n" + " [\"replication_num\" = \"3\"]\n" + ")"; String expected = "CREATE TABLE IF NOT EXISTS `detailDemo` ( `recruit_date` DATE NOT NULL COMMENT 'YYYY-MM-DD', `region_num` TINYINT COMMENT 'range [-128, 127]', `num_plate` SMALLINT COMMENT 'range [-32768, 32767] ', `tel` INT COMMENT 'range [-2147483648, 2147483647]', `id` BIGINT COMMENT 'range [-2^63 + 1 ~ 2^63 - 1]', `password` LARGEINT COMMENT 'range [-2^127 + 1 ~ 2^127 - 1]', `name` CHAR(20) NOT NULL COMMENT 'range char(m),m in (1-255)', `profile` VARCHAR(500) NOT NULL COMMENT 'upper limit value 1048576 bytes', `hobby` STRING NOT NULL COMMENT 'upper limit value 65533 bytes', `leave_time` DATETIME COMMENT 'YYYY-MM-DD HH:MM:SS', `channel` FLOAT COMMENT '4 bytes', `income` DOUBLE COMMENT '8 bytes', `account` DECIMAL(12, 4) COMMENT '\"\"', `ispass` BOOLEAN COMMENT 'true/false' ) ENGINE = OLAP DUPLICATE KEY (`recruit_date`, `region_num`) COMMENT 'xxxxx' PARTITION BY RANGE(`recruit_date`) ( PARTITION p202101 VALUES [(\"20210101\"),(\"20210201\")), PARTITION p202102 VALUES [(\"20210201\"),(\"20210301\")), PARTITION p202103 VALUES [(\"20210301\"),(MAXVALUE)) ) DISTRIBUTED BY HASH(`recruit_date`, `region_num`) BUCKETS 8 PROPERTIES ( \"storage_medium\" = \"[SSD|HDD]\", \"dynamic_partition.enable\" = \"true|false\", \"dynamic_partition.time_unit\" = \"DAY|WEEK|MONTH\", \"dynamic_partition.start\" = \"${integer_value}\", [\"storage_cooldown_time\" = \"yyyy-MM-dd HH:mm:ss\",] [\"replication_num\" = \"3\"] )"; SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(origin, DbType.starrocks); StringBuilder builder = new StringBuilder(); StarRocksOutputVisitor visitor = new StarRocksOutputVisitor(builder); visitor.setUppCase(false); visitor.setPrettyFormat(false); visitor.setParameterized(false); SQLStatement stmt = parser.parseStatement(); stmt.accept(visitor); String result = builder.toString(); Assert.assertEquals(message, expected, result); } public void testCreateResourceStmt() { StarRocksCreateResourceStatement stmt = new StarRocksCreateResourceStatement(); stmt.setExternal(true); stmt.setName(new SQLIdentifierExpr("spark")); stmt.addProperty(new SQLCharExpr("spark.master"), new SQLCharExpr("yarn")); String expected = "CREATE EXTERNAL RESOURCE spark\n" + "PROPERTIES (\n" + "\t'spark.master' = 'yarn'\n" + ")"; assertEquals(expected, stmt.toString()); } }
StarRocksOutputVisitorTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/tck2_2/caching/InheritedCacheableTest.java
{ "start": 4504, "end": 4870 }
class ____ extends Person { public String employeeCode; public String costCenter; public Employee() { } public Employee(String id, String name, String employeeCode, String costCenter) { super( id, name ); this.employeeCode = employeeCode; this.costCenter = costCenter; } } @Entity( name = "Customer" ) @Cacheable(false) public static
Employee
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableMap.java
{ "start": 999, "end": 1619 }
class ____<T, U> extends AbstractFlowableWithUpstream<T, U> { final Function<? super T, ? extends U> mapper; public FlowableMap(Flowable<T> source, Function<? super T, ? extends U> mapper) { super(source); this.mapper = mapper; } @Override protected void subscribeActual(Subscriber<? super U> s) { if (s instanceof ConditionalSubscriber) { source.subscribe(new MapConditionalSubscriber<T, U>((ConditionalSubscriber<? super U>)s, mapper)); } else { source.subscribe(new MapSubscriber<T, U>(s, mapper)); } } static final
FlowableMap