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 | netty__netty | resolver-dns/src/test/java/io/netty/resolver/dns/DnsNameResolverTest.java | {
"start": 102429,
"end": 102664
} | class ____ {
final List<InetSocketAddress> nameServers;
QueryRedirectedEvent(List<InetSocketAddress> nameServers) {
this.nameServers = nameServers;
}
}
private static final | QueryRedirectedEvent |
java | apache__flink | flink-state-backends/flink-statebackend-changelog/src/main/java/org/apache/flink/state/changelog/restore/ChangelogBackendRestoreOperation.java | {
"start": 2170,
"end": 2329
} | class ____ {
/** Builds base backend for {@link ChangelogKeyedStateBackend} from state. */
@FunctionalInterface
public | ChangelogBackendRestoreOperation |
java | junit-team__junit5 | junit-platform-commons/src/main/java/org/junit/platform/commons/support/ModifierSupport.java | {
"start": 4199,
"end": 4471
} | class ____ {@code abstract}
* @see java.lang.reflect.Modifier#isAbstract(int)
*/
public static boolean isAbstract(Class<?> clazz) {
return ReflectionUtils.isAbstract(clazz);
}
/**
* Determine if the supplied member is {@code abstract}.
*
* @param member the | is |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/support/replication/TransportBroadcastReplicationAction.java | {
"start": 2606,
"end": 6993
} | class ____<
Request extends BroadcastRequest<Request>,
Response extends BaseBroadcastResponse,
ShardRequest extends ReplicationRequest<ShardRequest>,
ShardResponse extends ReplicationResponse> extends HandledTransportAction<Request, Response> {
private final ActionType<ShardResponse> replicatedBroadcastShardAction;
private final ClusterService clusterService;
private final IndexNameExpressionResolver indexNameExpressionResolver;
private final NodeClient client;
private final Executor executor;
private final ProjectResolver projectResolver;
protected record ShardRecord(ShardId shardId, SplitShardCountSummary splitSummary) {}
public TransportBroadcastReplicationAction(
String name,
Writeable.Reader<Request> requestReader,
ClusterService clusterService,
TransportService transportService,
NodeClient client,
ActionFilters actionFilters,
IndexNameExpressionResolver indexNameExpressionResolver,
ActionType<ShardResponse> replicatedBroadcastShardAction,
Executor executor,
ProjectResolver projectResolver
) {
super(name, transportService, actionFilters, requestReader, EsExecutors.DIRECT_EXECUTOR_SERVICE);
this.client = client;
this.replicatedBroadcastShardAction = replicatedBroadcastShardAction;
this.clusterService = clusterService;
this.indexNameExpressionResolver = indexNameExpressionResolver;
this.executor = executor;
this.projectResolver = projectResolver;
}
@Override
protected void doExecute(Task task, Request request, ActionListener<Response> listener) {
executor.execute(ActionRunnable.wrap(listener, createAsyncAction(task, request)));
}
private CheckedConsumer<ActionListener<Response>, Exception> createAsyncAction(Task task, Request request) {
return new CheckedConsumer<ActionListener<Response>, Exception>() {
private int totalShardCopyCount;
private int successShardCopyCount;
private final List<DefaultShardOperationFailedException> allFailures = new ArrayList<>();
@Override
public void accept(ActionListener<Response> listener) {
assert totalShardCopyCount == 0 && successShardCopyCount == 0 && allFailures.isEmpty() : "shouldn't call this twice";
final ClusterState clusterState = clusterService.state();
final ProjectState projectState = projectResolver.getProjectState(clusterState);
final ProjectMetadata project = projectState.metadata();
final List<ShardRecord> shards = shards(request, projectState);
final Map<String, IndexMetadata> indexMetadataByName = project.indices();
try (var refs = new RefCountingRunnable(() -> finish(listener))) {
shards.forEach(shardRecord -> {
ShardId shardId = shardRecord.shardId();
SplitShardCountSummary shardCountSummary = shardRecord.splitSummary();
// NB This sends O(#shards) requests in a tight loop; TODO add some throttling here?
shardExecute(
task,
request,
shardId,
shardCountSummary,
ActionListener.releaseAfter(new ReplicationResponseActionListener(shardId, indexMetadataByName), refs.acquire())
);
});
}
}
private synchronized void addShardResponse(int numCopies, int successful, List<DefaultShardOperationFailedException> failures) {
totalShardCopyCount += numCopies;
successShardCopyCount += successful;
allFailures.addAll(failures);
}
void finish(ActionListener<Response> listener) {
// no need for synchronized here, the RefCountingRunnable guarantees that all the addShardResponse calls happen-before here
logger.trace("{}: got all shard responses", actionName);
listener.onResponse(newResponse(successShardCopyCount, allFailures.size(), totalShardCopyCount, allFailures));
}
| TransportBroadcastReplicationAction |
java | google__guava | android/guava/src/com/google/common/base/Optional.java | {
"start": 3663,
"end": 4260
} | class ____ possible.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained#optional">using {@code
* Optional}</a>.
*
* @param <T> the type of instance that can be contained. {@code Optional} is naturally covariant on
* this type, so it is safe to cast an {@code Optional<T>} to {@code Optional<S>} for any
* supertype {@code S} of {@code T}.
* @author Kurt Alfred Kluever
* @author Kevin Bourrillion
* @since 10.0
*/
@DoNotMock("Use Optional.of(value) or Optional.absent()")
@GwtCompatible
public abstract | whenever |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/common/state/ValueStateDescriptorTest.java | {
"start": 1429,
"end": 3921
} | class ____ {
@Test
void testHashCodeEquals() throws Exception {
final String name = "testName";
ValueStateDescriptor<String> original = new ValueStateDescriptor<>(name, String.class);
ValueStateDescriptor<String> same = new ValueStateDescriptor<>(name, String.class);
ValueStateDescriptor<String> sameBySerializer =
new ValueStateDescriptor<>(name, StringSerializer.INSTANCE);
// test that hashCode() works on state descriptors with initialized and uninitialized
// serializers
assertThat(same).hasSameHashCodeAs(original);
assertThat(sameBySerializer).hasSameHashCodeAs(original);
assertThat(same).isEqualTo(original);
assertThat(sameBySerializer).isEqualTo(original);
// equality with a clone
ValueStateDescriptor<String> clone = CommonTestUtils.createCopySerializable(original);
assertThat(clone).isEqualTo(original);
// equality with an initialized
clone.initializeSerializerUnlessSet(new ExecutionConfig());
assertThat(clone).isEqualTo(original);
original.initializeSerializerUnlessSet(new ExecutionConfig());
assertThat(same).isEqualTo(original);
}
@Test
void testVeryLargeDefaultValue() throws Exception {
// ensure that we correctly read very large data when deserializing the default value
TypeSerializer<String> serializer =
new KryoSerializer<>(String.class, new SerializerConfigImpl());
byte[] data = new byte[200000];
for (int i = 0; i < 200000; i++) {
data[i] = 65;
}
data[199000] = '\0';
String defaultValue = new String(data, ConfigConstants.DEFAULT_CHARSET);
ValueStateDescriptor<String> descr =
new ValueStateDescriptor<>("testName", serializer, defaultValue);
assertThat(descr.getName()).isEqualTo("testName");
assertThat(descr.getDefaultValue()).isEqualTo(defaultValue);
assertThat(descr.getSerializer()).isNotNull();
assertThat(descr.getSerializer()).isEqualTo(serializer);
ValueStateDescriptor<String> copy = CommonTestUtils.createCopySerializable(descr);
assertThat(copy.getName()).isEqualTo("testName");
assertThat(copy.getDefaultValue()).isEqualTo(defaultValue);
assertThat(copy.getSerializer()).isNotNull();
assertThat(copy.getSerializer()).isEqualTo(serializer);
}
}
| ValueStateDescriptorTest |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/Customizer.java | {
"start": 888,
"end": 1263
} | interface ____<T> {
/**
* Performs the customizations on the input argument.
* @param t the input argument
*/
void customize(T t);
/**
* Returns a {@link Customizer} that does not alter the input argument.
* @return a {@link Customizer} that does not alter the input argument.
*/
static <T> Customizer<T> withDefaults() {
return (t) -> {
};
}
}
| Customizer |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/savedrequest/RequestCacheAwareFilterTests.java | {
"start": 1147,
"end": 2973
} | class ____ {
@Test
public void doFilterWhenHttpSessionRequestCacheConfiguredThenSavedRequestRemovedAfterMatch() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/destination");
MockHttpServletResponse response = new MockHttpServletResponse();
RequestCache requestCache = mock(RequestCache.class);
RequestCacheAwareFilter filter = new RequestCacheAwareFilter(requestCache);
given(requestCache.getMatchingRequest(request, response)).willReturn(request);
filter.doFilter(request, response, new MockFilterChain());
verify(requestCache).getMatchingRequest(request, response);
}
@Test
public void doFilterWhenCookieRequestCacheConfiguredThenExpiredSavedRequestCookieSetAfterMatch() throws Exception {
CookieRequestCache cache = new CookieRequestCache();
RequestCacheAwareFilter filter = new RequestCacheAwareFilter(cache);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServerName("abc.com");
request.setRequestURI("/destination");
request.setScheme("https");
request.setServerPort(443);
request.setSecure(true);
String encodedRedirectUrl = Base64.getEncoder().encodeToString("https://abc.com/destination".getBytes());
Cookie savedRequest = new Cookie("REDIRECT_URI", encodedRedirectUrl);
savedRequest.setMaxAge(-1);
savedRequest.setSecure(request.isSecure());
savedRequest.setPath("/");
savedRequest.setHttpOnly(true);
request.setCookies(savedRequest);
MockHttpServletResponse response = new MockHttpServletResponse();
filter.doFilter(request, response, new MockFilterChain());
Cookie expiredCookie = response.getCookie("REDIRECT_URI");
assertThat(expiredCookie).isNotNull();
assertThat(expiredCookie.getValue()).isEmpty();
assertThat(expiredCookie.getMaxAge()).isZero();
}
}
| RequestCacheAwareFilterTests |
java | apache__flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/functions/timestamps/AscendingTimestampExtractor.java | {
"start": 4242,
"end": 4570
} | class ____ implements MonotonyViolationHandler {
private static final long serialVersionUID = 1L;
@Override
public void handleViolation(long elementTimestamp, long lastTimestamp) {}
}
/** Handler that fails the program when timestamp monotony is violated. */
public static final | IgnoringHandler |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/processor/internals/TaskMetadataImpl.java | {
"start": 1133,
"end": 3518
} | class ____ implements TaskMetadata {
private final TaskId taskId;
private final Set<TopicPartition> topicPartitions;
private final Map<TopicPartition, Long> committedOffsets;
private final Map<TopicPartition, Long> endOffsets;
private final Optional<Long> timeCurrentIdlingStarted;
public TaskMetadataImpl(final TaskId taskId,
final Set<TopicPartition> topicPartitions,
final Map<TopicPartition, Long> committedOffsets,
final Map<TopicPartition, Long> endOffsets,
final Optional<Long> timeCurrentIdlingStarted) {
this.taskId = taskId;
this.topicPartitions = Collections.unmodifiableSet(topicPartitions);
this.committedOffsets = Collections.unmodifiableMap(committedOffsets);
this.endOffsets = Collections.unmodifiableMap(endOffsets);
this.timeCurrentIdlingStarted = timeCurrentIdlingStarted;
}
@Override
public TaskId taskId() {
return taskId;
}
@Override
public Set<TopicPartition> topicPartitions() {
return topicPartitions;
}
@Override
public Map<TopicPartition, Long> committedOffsets() {
return committedOffsets;
}
@Override
public Map<TopicPartition, Long> endOffsets() {
return endOffsets;
}
@Override
public Optional<Long> timeCurrentIdlingStarted() {
return timeCurrentIdlingStarted;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TaskMetadataImpl that = (TaskMetadataImpl) o;
return Objects.equals(taskId, that.taskId) &&
Objects.equals(topicPartitions, that.topicPartitions);
}
@Override
public int hashCode() {
return Objects.hash(taskId, topicPartitions);
}
@Override
public String toString() {
return "TaskMetadata{" +
"taskId=" + taskId +
", topicPartitions=" + topicPartitions +
", committedOffsets=" + committedOffsets +
", endOffsets=" + endOffsets +
", timeCurrentIdlingStarted=" + timeCurrentIdlingStarted +
'}';
}
}
| TaskMetadataImpl |
java | apache__kafka | connect/runtime/src/test/java/org/apache/kafka/connect/util/RetryUtilTest.java | {
"start": 1776,
"end": 8598
} | class ____ {
private final Time mockTime = new MockTime(10);
private Callable<String> mockCallable;
private final Supplier<String> testMsg = () -> "Test";
@SuppressWarnings("unchecked")
@BeforeEach
public void setUp() throws Exception {
mockCallable = Mockito.mock(Callable.class);
}
@Test
public void testSuccess() throws Exception {
Mockito.when(mockCallable.call()).thenReturn("success");
assertEquals("success", RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(100), 1, mockTime));
Mockito.verify(mockCallable, Mockito.times(1)).call();
}
@Test
public void testExhaustingRetries() throws Exception {
Mockito.when(mockCallable.call()).thenThrow(new TimeoutException("timeout exception"));
ConnectException e = assertThrows(ConnectException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(50), 10, mockTime));
Mockito.verify(mockCallable, Mockito.atLeastOnce()).call();
assertTrue(e.getMessage().contains("Reason: timeout exception"));
}
@Test
public void retriesEventuallySucceed() throws Exception {
Mockito.when(mockCallable.call())
.thenThrow(new TimeoutException())
.thenThrow(new TimeoutException())
.thenThrow(new TimeoutException())
.thenReturn("success");
assertEquals("success", RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(100), 1, mockTime));
Mockito.verify(mockCallable, Mockito.times(4)).call();
}
@Test
public void failWithNonRetriableException() throws Exception {
Mockito.when(mockCallable.call())
.thenThrow(new TimeoutException("timeout"))
.thenThrow(new TimeoutException("timeout"))
.thenThrow(new TimeoutException("timeout"))
.thenThrow(new TimeoutException("timeout"))
.thenThrow(new TimeoutException("timeout"))
.thenThrow(new NullPointerException("Non retriable"));
NullPointerException e = assertThrows(NullPointerException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(100), 0, mockTime));
assertEquals("Non retriable", e.getMessage());
Mockito.verify(mockCallable, Mockito.times(6)).call();
}
@Test
public void noRetryAndSucceed() throws Exception {
Mockito.when(mockCallable.call()).thenReturn("success");
assertEquals("success", RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(0), 100, mockTime));
Mockito.verify(mockCallable, Mockito.times(1)).call();
}
@Test
public void noRetryAndFailed() throws Exception {
Mockito.when(mockCallable.call()).thenThrow(new TimeoutException("timeout exception"));
TimeoutException e = assertThrows(TimeoutException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(0), 100, mockTime));
Mockito.verify(mockCallable, Mockito.times(1)).call();
assertEquals("timeout exception", e.getMessage());
}
@Test
public void testNoBackoffTimeAndSucceed() throws Exception {
Mockito.when(mockCallable.call())
.thenThrow(new TimeoutException())
.thenThrow(new TimeoutException())
.thenThrow(new TimeoutException())
.thenReturn("success");
assertEquals("success", RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(100), 0, mockTime));
Mockito.verify(mockCallable, Mockito.times(4)).call();
}
@Test
public void testNoBackoffTimeAndFail() throws Exception {
Mockito.when(mockCallable.call()).thenThrow(new TimeoutException("timeout exception"));
ConnectException e = assertThrows(ConnectException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(80), 0, mockTime));
Mockito.verify(mockCallable, Mockito.atLeastOnce()).call();
assertTrue(e.getMessage().contains("Reason: timeout exception"));
}
@Test
public void testBackoffMoreThanTimeoutWillOnlyExecuteOnce() throws Exception {
Mockito.when(mockCallable.call()).thenThrow(new TimeoutException("timeout exception"));
assertThrows(TimeoutException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(50), 100, mockTime));
Mockito.verify(mockCallable, Mockito.times(1)).call();
}
@Test
public void testInvalidTimeDuration() throws Exception {
Mockito.when(mockCallable.call()).thenReturn("success");
assertEquals("success", RetryUtil.retryUntilTimeout(mockCallable, testMsg, null, 10, mockTime));
assertEquals("success", RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(-1), 10, mockTime));
Mockito.verify(mockCallable, Mockito.times(2)).call();
}
@Test
public void testInvalidRetryTimeout() throws Exception {
Mockito.when(mockCallable.call())
.thenThrow(new TimeoutException("timeout"))
.thenReturn("success");
assertEquals("success", RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(100), -1, mockTime));
Mockito.verify(mockCallable, Mockito.times(2)).call();
}
@Test
public void testSupplier() throws Exception {
Mockito.when(mockCallable.call()).thenThrow(new TimeoutException("timeout exception"));
ConnectException e = assertThrows(ConnectException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, null, Duration.ofMillis(100), 10, mockTime));
assertTrue(e.getMessage().startsWith("Fail to callable"));
e = assertThrows(ConnectException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, () -> null, Duration.ofMillis(100), 10, mockTime));
assertTrue(e.getMessage().startsWith("Fail to callable"));
e = assertThrows(ConnectException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, () -> "execute lambda", Duration.ofMillis(500), 10, mockTime));
assertTrue(e.getMessage().startsWith("Fail to execute lambda"));
Mockito.verify(mockCallable, Mockito.atLeast(3)).call();
}
@Test
public void testWakeupException() throws Exception {
Mockito.when(mockCallable.call()).thenThrow(new WakeupException());
assertThrows(ConnectException.class,
() -> RetryUtil.retryUntilTimeout(mockCallable, testMsg, Duration.ofMillis(50), 10, mockTime));
Mockito.verify(mockCallable, Mockito.atLeastOnce()).call();
}
}
| RetryUtilTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AS2EndpointBuilderFactory.java | {
"start": 75760,
"end": 109586
} | interface ____
extends
AS2EndpointConsumerBuilder,
AS2EndpointProducerBuilder {
default AdvancedAS2EndpointBuilder advanced() {
return (AdvancedAS2EndpointBuilder) this;
}
/**
* The value of the AS2From header of AS2 message.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param as2From the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder as2From(String as2From) {
doSetProperty("as2From", as2From);
return this;
}
/**
* The structure of AS2 Message. One of: PLAIN - No encryption, no
* signature, SIGNED - No encryption, signature, ENCRYPTED - Encryption,
* no signature, ENCRYPTED_SIGNED - Encryption, signature.
*
* The option is a:
* <code>org.apache.camel.component.as2.api.AS2MessageStructure</code>
* type.
*
* Group: common
*
* @param as2MessageStructure the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder as2MessageStructure(org.apache.camel.component.as2.api.AS2MessageStructure as2MessageStructure) {
doSetProperty("as2MessageStructure", as2MessageStructure);
return this;
}
/**
* The structure of AS2 Message. One of: PLAIN - No encryption, no
* signature, SIGNED - No encryption, signature, ENCRYPTED - Encryption,
* no signature, ENCRYPTED_SIGNED - Encryption, signature.
*
* The option will be converted to a
* <code>org.apache.camel.component.as2.api.AS2MessageStructure</code>
* type.
*
* Group: common
*
* @param as2MessageStructure the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder as2MessageStructure(String as2MessageStructure) {
doSetProperty("as2MessageStructure", as2MessageStructure);
return this;
}
/**
* The value of the AS2To header of AS2 message.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param as2To the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder as2To(String as2To) {
doSetProperty("as2To", as2To);
return this;
}
/**
* The version of the AS2 protocol.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: 1.1
* Group: common
*
* @param as2Version the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder as2Version(String as2Version) {
doSetProperty("as2Version", as2Version);
return this;
}
/**
* The port number of asynchronous MDN server.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: common
*
* @param asyncMdnPortNumber the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder asyncMdnPortNumber(Integer asyncMdnPortNumber) {
doSetProperty("asyncMdnPortNumber", asyncMdnPortNumber);
return this;
}
/**
* The port number of asynchronous MDN server.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Group: common
*
* @param asyncMdnPortNumber the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder asyncMdnPortNumber(String asyncMdnPortNumber) {
doSetProperty("asyncMdnPortNumber", asyncMdnPortNumber);
return this;
}
/**
* The name of the attached file.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param attachedFileName the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder attachedFileName(String attachedFileName) {
doSetProperty("attachedFileName", attachedFileName);
return this;
}
/**
* The Client Fully Qualified Domain Name (FQDN). Used in message ids
* sent by endpoint.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: camel.apache.org
* Group: common
*
* @param clientFqdn the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder clientFqdn(String clientFqdn) {
doSetProperty("clientFqdn", clientFqdn);
return this;
}
/**
* The algorithm used to compress EDI message.
*
* The option is a:
* <code>org.apache.camel.component.as2.api.AS2CompressionAlgorithm</code> type.
*
* Group: common
*
* @param compressionAlgorithm the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder compressionAlgorithm(org.apache.camel.component.as2.api.AS2CompressionAlgorithm compressionAlgorithm) {
doSetProperty("compressionAlgorithm", compressionAlgorithm);
return this;
}
/**
* The algorithm used to compress EDI message.
*
* The option will be converted to a
* <code>org.apache.camel.component.as2.api.AS2CompressionAlgorithm</code> type.
*
* Group: common
*
* @param compressionAlgorithm the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder compressionAlgorithm(String compressionAlgorithm) {
doSetProperty("compressionAlgorithm", compressionAlgorithm);
return this;
}
/**
* The value of the Disposition-Notification-To header. Assigning a
* value to this parameter requests a message disposition notification
* (MDN) for the AS2 message.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param dispositionNotificationTo the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder dispositionNotificationTo(String dispositionNotificationTo) {
doSetProperty("dispositionNotificationTo", dispositionNotificationTo);
return this;
}
/**
* The charset of the content type of EDI message.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: us-ascii
* Group: common
*
* @param ediMessageCharset the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder ediMessageCharset(String ediMessageCharset) {
doSetProperty("ediMessageCharset", ediMessageCharset);
return this;
}
/**
* The transfer encoding of EDI message.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param ediMessageTransferEncoding the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder ediMessageTransferEncoding(String ediMessageTransferEncoding) {
doSetProperty("ediMessageTransferEncoding", ediMessageTransferEncoding);
return this;
}
/**
* The content type of EDI message. One of application/edifact,
* application/edi-x12, application/edi-consent, application/xml.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param ediMessageType the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder ediMessageType(String ediMessageType) {
doSetProperty("ediMessageType", ediMessageType);
return this;
}
/**
* The value of the From header of AS2 message.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param from the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder from(String from) {
doSetProperty("from", from);
return this;
}
/**
* The maximum size of the connection pool for http connections (client
* only).
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Default: 5
* Group: common
*
* @param httpConnectionPoolSize the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder httpConnectionPoolSize(Integer httpConnectionPoolSize) {
doSetProperty("httpConnectionPoolSize", httpConnectionPoolSize);
return this;
}
/**
* The maximum size of the connection pool for http connections (client
* only).
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Default: 5
* Group: common
*
* @param httpConnectionPoolSize the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder httpConnectionPoolSize(String httpConnectionPoolSize) {
doSetProperty("httpConnectionPoolSize", httpConnectionPoolSize);
return this;
}
/**
* The time to live for connections in the connection pool (client
* only).
*
* The option is a: <code>java.time.Duration</code> type.
*
* Default: 15m
* Group: common
*
* @param httpConnectionPoolTtl the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder httpConnectionPoolTtl(java.time.Duration httpConnectionPoolTtl) {
doSetProperty("httpConnectionPoolTtl", httpConnectionPoolTtl);
return this;
}
/**
* The time to live for connections in the connection pool (client
* only).
*
* The option will be converted to a <code>java.time.Duration</code>
* type.
*
* Default: 15m
* Group: common
*
* @param httpConnectionPoolTtl the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder httpConnectionPoolTtl(String httpConnectionPoolTtl) {
doSetProperty("httpConnectionPoolTtl", httpConnectionPoolTtl);
return this;
}
/**
* The timeout of the http connection (client only).
*
* The option is a: <code>java.time.Duration</code> type.
*
* Default: 5s
* Group: common
*
* @param httpConnectionTimeout the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder httpConnectionTimeout(java.time.Duration httpConnectionTimeout) {
doSetProperty("httpConnectionTimeout", httpConnectionTimeout);
return this;
}
/**
* The timeout of the http connection (client only).
*
* The option will be converted to a <code>java.time.Duration</code>
* type.
*
* Default: 5s
* Group: common
*
* @param httpConnectionTimeout the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder httpConnectionTimeout(String httpConnectionTimeout) {
doSetProperty("httpConnectionTimeout", httpConnectionTimeout);
return this;
}
/**
* The timeout of the underlying http socket (client only).
*
* The option is a: <code>java.time.Duration</code> type.
*
* Default: 5s
* Group: common
*
* @param httpSocketTimeout the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder httpSocketTimeout(java.time.Duration httpSocketTimeout) {
doSetProperty("httpSocketTimeout", httpSocketTimeout);
return this;
}
/**
* The timeout of the underlying http socket (client only).
*
* The option will be converted to a <code>java.time.Duration</code>
* type.
*
* Default: 5s
* Group: common
*
* @param httpSocketTimeout the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder httpSocketTimeout(String httpSocketTimeout) {
doSetProperty("httpSocketTimeout", httpSocketTimeout);
return this;
}
/**
* Sets the name of a parameter to be passed in the exchange In Body.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param inBody the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder inBody(String inBody) {
doSetProperty("inBody", inBody);
return this;
}
/**
* The template used to format MDN message.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param mdnMessageTemplate the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder mdnMessageTemplate(String mdnMessageTemplate) {
doSetProperty("mdnMessageTemplate", mdnMessageTemplate);
return this;
}
/**
* The return URL that the message receiver should send an asynchronous
* MDN to. If not present the receipt is synchronous. (Client only).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param receiptDeliveryOption the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder receiptDeliveryOption(String receiptDeliveryOption) {
doSetProperty("receiptDeliveryOption", receiptDeliveryOption);
return this;
}
/**
* The request URI of EDI message.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: /
* Group: common
*
* @param requestUri the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder requestUri(String requestUri) {
doSetProperty("requestUri", requestUri);
return this;
}
/**
* The value included in the Server message header identifying the AS2
* Server.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: Camel AS2 Server Endpoint
* Group: common
*
* @param server the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder server(String server) {
doSetProperty("server", server);
return this;
}
/**
* The Server Fully Qualified Domain Name (FQDN). Used in message ids
* sent by endpoint.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: camel.apache.org
* Group: common
*
* @param serverFqdn the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder serverFqdn(String serverFqdn) {
doSetProperty("serverFqdn", serverFqdn);
return this;
}
/**
* The port number of server.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: common
*
* @param serverPortNumber the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder serverPortNumber(Integer serverPortNumber) {
doSetProperty("serverPortNumber", serverPortNumber);
return this;
}
/**
* The port number of server.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Group: common
*
* @param serverPortNumber the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder serverPortNumber(String serverPortNumber) {
doSetProperty("serverPortNumber", serverPortNumber);
return this;
}
/**
* The value of Subject header of AS2 message.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param subject the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder subject(String subject) {
doSetProperty("subject", subject);
return this;
}
/**
* The host name (IP or DNS name) of target host.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param targetHostname the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder targetHostname(String targetHostname) {
doSetProperty("targetHostname", targetHostname);
return this;
}
/**
* The port number of target host. -1 indicates the scheme default port.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Default: 80
* Group: common
*
* @param targetPortNumber the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder targetPortNumber(Integer targetPortNumber) {
doSetProperty("targetPortNumber", targetPortNumber);
return this;
}
/**
* The port number of target host. -1 indicates the scheme default port.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Default: 80
* Group: common
*
* @param targetPortNumber the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder targetPortNumber(String targetPortNumber) {
doSetProperty("targetPortNumber", targetPortNumber);
return this;
}
/**
* The value included in the User-Agent message header identifying the
* AS2 user agent.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: Camel AS2 Client Endpoint
* Group: common
*
* @param userAgent the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder userAgent(String userAgent) {
doSetProperty("userAgent", userAgent);
return this;
}
/**
* The access token that is used by the client for bearer
* authentication.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessToken the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder accessToken(String accessToken) {
doSetProperty("accessToken", accessToken);
return this;
}
/**
* The key used to encrypt the EDI message.
*
* The option is a: <code>java.security.PrivateKey</code> type.
*
* Group: security
*
* @param decryptingPrivateKey the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder decryptingPrivateKey(java.security.PrivateKey decryptingPrivateKey) {
doSetProperty("decryptingPrivateKey", decryptingPrivateKey);
return this;
}
/**
* The key used to encrypt the EDI message.
*
* The option will be converted to a
* <code>java.security.PrivateKey</code> type.
*
* Group: security
*
* @param decryptingPrivateKey the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder decryptingPrivateKey(String decryptingPrivateKey) {
doSetProperty("decryptingPrivateKey", decryptingPrivateKey);
return this;
}
/**
* The algorithm used to encrypt EDI message.
*
* The option is a:
* <code>org.apache.camel.component.as2.api.AS2EncryptionAlgorithm</code> type.
*
* Group: security
*
* @param encryptingAlgorithm the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder encryptingAlgorithm(org.apache.camel.component.as2.api.AS2EncryptionAlgorithm encryptingAlgorithm) {
doSetProperty("encryptingAlgorithm", encryptingAlgorithm);
return this;
}
/**
* The algorithm used to encrypt EDI message.
*
* The option will be converted to a
* <code>org.apache.camel.component.as2.api.AS2EncryptionAlgorithm</code> type.
*
* Group: security
*
* @param encryptingAlgorithm the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder encryptingAlgorithm(String encryptingAlgorithm) {
doSetProperty("encryptingAlgorithm", encryptingAlgorithm);
return this;
}
/**
* The chain of certificates used to encrypt EDI message.
*
* The option is a: <code>java.security.cert.Certificate[]</code> type.
*
* Group: security
*
* @param encryptingCertificateChain the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder encryptingCertificateChain(java.security.cert.Certificate[] encryptingCertificateChain) {
doSetProperty("encryptingCertificateChain", encryptingCertificateChain);
return this;
}
/**
* The chain of certificates used to encrypt EDI message.
*
* The option will be converted to a
* <code>java.security.cert.Certificate[]</code> type.
*
* Group: security
*
* @param encryptingCertificateChain the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder encryptingCertificateChain(String encryptingCertificateChain) {
doSetProperty("encryptingCertificateChain", encryptingCertificateChain);
return this;
}
/**
* Set hostname verifier for SSL session.
*
* The option is a: <code>javax.net.ssl.HostnameVerifier</code> type.
*
* Group: security
*
* @param hostnameVerifier the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder hostnameVerifier(javax.net.ssl.HostnameVerifier hostnameVerifier) {
doSetProperty("hostnameVerifier", hostnameVerifier);
return this;
}
/**
* Set hostname verifier for SSL session.
*
* The option will be converted to a
* <code>javax.net.ssl.HostnameVerifier</code> type.
*
* Group: security
*
* @param hostnameVerifier the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder hostnameVerifier(String hostnameVerifier) {
doSetProperty("hostnameVerifier", hostnameVerifier);
return this;
}
/**
* The access token that is used by the server when it sends an async
* MDN.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param mdnAccessToken the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder mdnAccessToken(String mdnAccessToken) {
doSetProperty("mdnAccessToken", mdnAccessToken);
return this;
}
/**
* The password that is used by the server for basic authentication when
* it sends an async MDN.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param mdnPassword the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder mdnPassword(String mdnPassword) {
doSetProperty("mdnPassword", mdnPassword);
return this;
}
/**
* The user-name that is used by the server for basic authentication
* when it sends an async MDN. If options for basic authentication and
* bearer authentication are both set then basic authentication takes
* precedence.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param mdnUserName the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder mdnUserName(String mdnUserName) {
doSetProperty("mdnUserName", mdnUserName);
return this;
}
/**
* The password that is used by the client for basic authentication.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param password the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder password(String password) {
doSetProperty("password", password);
return this;
}
/**
* The list of algorithms, in order of preference, requested to generate
* a message integrity check (MIC) returned in message disposition
* notification (MDN). Multiple algorithms can be separated by comma.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param signedReceiptMicAlgorithms the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder signedReceiptMicAlgorithms(String signedReceiptMicAlgorithms) {
doSetProperty("signedReceiptMicAlgorithms", signedReceiptMicAlgorithms);
return this;
}
/**
* The algorithm used to sign EDI message.
*
* The option is a:
* <code>org.apache.camel.component.as2.api.AS2SignatureAlgorithm</code>
* type.
*
* Group: security
*
* @param signingAlgorithm the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder signingAlgorithm(org.apache.camel.component.as2.api.AS2SignatureAlgorithm signingAlgorithm) {
doSetProperty("signingAlgorithm", signingAlgorithm);
return this;
}
/**
* The algorithm used to sign EDI message.
*
* The option will be converted to a
* <code>org.apache.camel.component.as2.api.AS2SignatureAlgorithm</code>
* type.
*
* Group: security
*
* @param signingAlgorithm the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder signingAlgorithm(String signingAlgorithm) {
doSetProperty("signingAlgorithm", signingAlgorithm);
return this;
}
/**
* The chain of certificates used to sign EDI message.
*
* The option is a: <code>java.security.cert.Certificate[]</code> type.
*
* Group: security
*
* @param signingCertificateChain the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder signingCertificateChain(java.security.cert.Certificate[] signingCertificateChain) {
doSetProperty("signingCertificateChain", signingCertificateChain);
return this;
}
/**
* The chain of certificates used to sign EDI message.
*
* The option will be converted to a
* <code>java.security.cert.Certificate[]</code> type.
*
* Group: security
*
* @param signingCertificateChain the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder signingCertificateChain(String signingCertificateChain) {
doSetProperty("signingCertificateChain", signingCertificateChain);
return this;
}
/**
* The key used to sign the EDI message.
*
* The option is a: <code>java.security.PrivateKey</code> type.
*
* Group: security
*
* @param signingPrivateKey the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder signingPrivateKey(java.security.PrivateKey signingPrivateKey) {
doSetProperty("signingPrivateKey", signingPrivateKey);
return this;
}
/**
* The key used to sign the EDI message.
*
* The option will be converted to a
* <code>java.security.PrivateKey</code> type.
*
* Group: security
*
* @param signingPrivateKey the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder signingPrivateKey(String signingPrivateKey) {
doSetProperty("signingPrivateKey", signingPrivateKey);
return this;
}
/**
* Set SSL context for connection to remote server.
*
* The option is a: <code>javax.net.ssl.SSLContext</code> type.
*
* Group: security
*
* @param sslContext the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder sslContext(javax.net.ssl.SSLContext sslContext) {
doSetProperty("sslContext", sslContext);
return this;
}
/**
* Set SSL context for connection to remote server.
*
* The option will be converted to a
* <code>javax.net.ssl.SSLContext</code> type.
*
* Group: security
*
* @param sslContext the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder sslContext(String sslContext) {
doSetProperty("sslContext", sslContext);
return this;
}
/**
* The user-name that is used by the client for basic authentication. If
* options for basic authentication and bearer authentication are both
* set then basic authentication takes precedence.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param userName the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder userName(String userName) {
doSetProperty("userName", userName);
return this;
}
/**
* Certificates to validate the message's signature against. If not
* supplied, validation will not take place. Server: validates the
* received message. Client: not yet implemented, should validate the
* MDN.
*
* The option is a: <code>java.security.cert.Certificate[]</code> type.
*
* Group: security
*
* @param validateSigningCertificateChain the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder validateSigningCertificateChain(java.security.cert.Certificate[] validateSigningCertificateChain) {
doSetProperty("validateSigningCertificateChain", validateSigningCertificateChain);
return this;
}
/**
* Certificates to validate the message's signature against. If not
* supplied, validation will not take place. Server: validates the
* received message. Client: not yet implemented, should validate the
* MDN.
*
* The option will be converted to a
* <code>java.security.cert.Certificate[]</code> type.
*
* Group: security
*
* @param validateSigningCertificateChain the value to set
* @return the dsl builder
*/
default AS2EndpointBuilder validateSigningCertificateChain(String validateSigningCertificateChain) {
doSetProperty("validateSigningCertificateChain", validateSigningCertificateChain);
return this;
}
}
/**
* Advanced builder for endpoint for the AS2 component.
*/
public | AS2EndpointBuilder |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelNoRedeliveryTest.java | {
"start": 2142,
"end": 2364
} | class ____ implements Processor {
@Override
public void process(Exchange exchange) {
counter.increment();
throw new IllegalArgumentException("Forced");
}
}
}
| MyFailProcessor |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embedded/many2one/Country.java | {
"start": 373,
"end": 788
} | class ____ implements Serializable {
private String iso2;
private String name;
public Country() {
}
public Country(String iso2, String name) {
this.iso2 = iso2;
this.name = name;
}
@Id
public String getIso2() {
return iso2;
}
public void setIso2(String iso2) {
this.iso2 = iso2;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| Country |
java | apache__logging-log4j2 | log4j-1.2-api/src/main/java/org/apache/log4j/MDC.java | {
"start": 1166,
"end": 2417
} | class ____ {
private static final ThreadLocal<Map<String, Object>> localMap = new InheritableThreadLocal<Map<String, Object>>() {
@Override
protected Map<String, Object> initialValue() {
return new HashMap<>();
}
@Override
protected Map<String, Object> childValue(final Map<String, Object> parentValue) {
return parentValue == null ? new HashMap<>() : new HashMap<>(parentValue);
}
};
private MDC() {}
public static void put(final String key, final String value) {
localMap.get().put(key, value);
ThreadContext.put(key, value);
}
public static void put(final String key, final Object value) {
localMap.get().put(key, value);
ThreadContext.put(key, value.toString());
}
public static Object get(final String key) {
return localMap.get().get(key);
}
public static void remove(final String key) {
localMap.get().remove(key);
ThreadContext.remove(key);
}
public static void clear() {
localMap.get().clear();
ThreadContext.clearMap();
}
public static Hashtable<String, Object> getContext() {
return new Hashtable<>(localMap.get());
}
}
| MDC |
java | spring-projects__spring-boot | documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/testing/springbootapplications/autoconfiguredspringrestdocs/withwebtestclient/MyWebTestClientBuilderCustomizerConfiguration.java | {
"start": 1104,
"end": 1320
} | class ____ {
@Bean
public WebTestClientBuilderCustomizer restDocumentation() {
return (builder) -> builder.entityExchangeResultConsumer(document("{method-name}"));
}
}
| MyWebTestClientBuilderCustomizerConfiguration |
java | google__guice | core/src/com/google/inject/matcher/Matchers.java | {
"start": 7493,
"end": 8530
} | class ____ extends AbstractMatcher<Object> implements Serializable {
private final Object value;
public IdenticalTo(Object value) {
this.value = checkNotNull(value, "value");
}
@Override
public boolean matches(Object other) {
return value == other;
}
@Override
public boolean equals(Object other) {
return other instanceof IdenticalTo && ((IdenticalTo) other).value == value;
}
@Override
public int hashCode() {
return 37 * System.identityHashCode(value);
}
@Override
public String toString() {
return "identicalTo(" + value + ")";
}
private static final long serialVersionUID = 0;
}
/**
* Returns a matcher which matches classes in the given package. Packages are specific to their
* classloader, so classes with the same package name may not have the same package at runtime.
*/
public static Matcher<Class> inPackage(final Package targetPackage) {
return new InPackage(targetPackage);
}
private static | IdenticalTo |
java | elastic__elasticsearch | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/action/TransportStartDataFrameAnalyticsActionTests.java | {
"start": 2514,
"end": 9107
} | class ____ extends ESTestCase {
private static final String JOB_ID = "data_frame_id";
// Cannot assign the node because upgrade mode is enabled
public void testGetAssignment_UpgradeModeIsEnabled() {
TaskExecutor executor = createTaskExecutor();
TaskParams params = new TaskParams(JOB_ID, MlConfigVersion.CURRENT, false);
ClusterState clusterState = ClusterState.builder(new ClusterName("_name"))
.metadata(Metadata.builder().putCustom(MlMetadata.TYPE, new MlMetadata.Builder().isUpgradeMode(true).build()))
.build();
Assignment assignment = executor.getAssignment(params, clusterState.nodes().getAllNodes(), clusterState, ProjectId.DEFAULT);
assertThat(assignment.getExecutorNode(), is(nullValue()));
assertThat(assignment.getExplanation(), is(equalTo("persistent task cannot be assigned while upgrade mode is enabled.")));
}
// Cannot assign the node because there are no existing nodes in the cluster state
public void testGetAssignment_NoNodes() {
TaskExecutor executor = createTaskExecutor();
TaskParams params = new TaskParams(JOB_ID, MlConfigVersion.CURRENT, false);
ClusterState clusterState = ClusterState.builder(new ClusterName("_name"))
.metadata(Metadata.builder().putCustom(MlMetadata.TYPE, new MlMetadata.Builder().build()))
.build();
Assignment assignment = executor.getAssignment(params, clusterState.nodes().getAllNodes(), clusterState, ProjectId.DEFAULT);
assertThat(assignment.getExecutorNode(), is(nullValue()));
assertThat(assignment.getExplanation(), is(emptyString()));
}
// Cannot assign the node because none of the existing nodes is an ML node
public void testGetAssignment_NoMlNodes() {
TaskExecutor executor = createTaskExecutor();
TaskParams params = new TaskParams(JOB_ID, MlConfigVersion.CURRENT, false);
ClusterState clusterState = ClusterState.builder(new ClusterName("_name"))
.metadata(Metadata.builder().putCustom(MlMetadata.TYPE, new MlMetadata.Builder().build()))
.nodes(
DiscoveryNodes.builder()
.add(createNode(0, false, Version.CURRENT, MlConfigVersion.CURRENT))
.add(createNode(1, false, Version.CURRENT, MlConfigVersion.CURRENT))
.add(createNode(2, false, Version.CURRENT, MlConfigVersion.CURRENT))
)
.build();
Assignment assignment = executor.getAssignment(params, clusterState.nodes().getAllNodes(), clusterState, ProjectId.DEFAULT);
assertThat(assignment.getExecutorNode(), is(nullValue()));
assertThat(
assignment.getExplanation(),
allOf(
containsString("Not opening job [data_frame_id] on node [_node_name0]. Reason: This node isn't a machine learning node."),
containsString("Not opening job [data_frame_id] on node [_node_name1]. Reason: This node isn't a machine learning node."),
containsString("Not opening job [data_frame_id] on node [_node_name2]. Reason: This node isn't a machine learning node.")
)
);
}
// The node can be assigned despite being newer than the job.
// In such a case destination index will be created from scratch so that its mappings are up-to-date.
public void testGetAssignment_MlNodeIsNewerThanTheMlJobButTheAssignmentSuceeds() {
TaskExecutor executor = createTaskExecutor();
TaskParams params = new TaskParams(JOB_ID, MlConfigVersion.V_7_9_0, false);
ClusterState clusterState = ClusterState.builder(new ClusterName("_name"))
.metadata(Metadata.builder().putCustom(MlMetadata.TYPE, new MlMetadata.Builder().build()))
.nodes(DiscoveryNodes.builder().add(createNode(0, true, Version.V_7_10_0, MlConfigVersion.V_7_10_0)))
.build();
Assignment assignment = executor.getAssignment(params, clusterState.nodes().getAllNodes(), clusterState, ProjectId.DEFAULT);
assertThat(assignment.getExecutorNode(), is(equalTo("_node_id0")));
assertThat(assignment.getExplanation(), is(emptyString()));
}
private static TaskExecutor createTaskExecutor() {
ClusterService clusterService = mock(ClusterService.class);
ClusterSettings clusterSettings = new ClusterSettings(
Settings.EMPTY,
Sets.newHashSet(
MachineLearning.CONCURRENT_JOB_ALLOCATIONS,
MachineLearning.MAX_MACHINE_MEMORY_PERCENT,
MachineLearningField.USE_AUTO_MACHINE_MEMORY_PERCENT,
MachineLearning.MAX_ML_NODE_SIZE,
MachineLearningField.MAX_LAZY_ML_NODES,
MachineLearning.MAX_OPEN_JOBS_PER_NODE
)
);
when(clusterService.getClusterSettings()).thenReturn(clusterSettings);
when(clusterService.threadPool()).thenReturn(mock(ThreadPool.class));
return new TaskExecutor(
Settings.EMPTY,
mock(Client.class),
clusterService,
mock(DataFrameAnalyticsManager.class),
mock(DataFrameAnalyticsAuditor.class),
mock(MlMemoryTracker.class),
TestIndexNameExpressionResolver.newInstance(),
mock(XPackLicenseState.class)
);
}
private static DiscoveryNode createNode(int i, boolean isMlNode, Version nodeVersion, MlConfigVersion mlConfigVersion) {
return DiscoveryNodeUtils.builder("_node_id" + i)
.name("_node_name" + i)
.address(new TransportAddress(InetAddress.getLoopbackAddress(), 9300 + i))
.attributes(
isMlNode
? Map.of(
"ml.machine_memory",
String.valueOf(ByteSizeValue.ofGb(1).getBytes()),
"ml.max_jvm_size",
String.valueOf(ByteSizeValue.ofMb(400).getBytes()),
MlConfigVersion.ML_CONFIG_VERSION_NODE_ATTR,
mlConfigVersion.toString()
)
: Map.of()
)
.roles(
isMlNode
? Set.of(DiscoveryNodeRole.MASTER_ROLE, DiscoveryNodeRole.DATA_ROLE, DiscoveryNodeRole.ML_ROLE)
: Set.of(DiscoveryNodeRole.MASTER_ROLE, DiscoveryNodeRole.DATA_ROLE)
)
.version(VersionInformation.inferVersions(nodeVersion))
.build();
}
}
| TransportStartDataFrameAnalyticsActionTests |
java | apache__rocketmq | proxy/src/test/java/org/apache/rocketmq/proxy/remoting/protocol/http2proxy/Http2ProtocolProxyHandlerTest.java | {
"start": 1292,
"end": 2214
} | class ____ {
private Http2ProtocolProxyHandler http2ProtocolProxyHandler;
@Mock
private Channel inboundChannel;
@Mock
private ChannelPipeline inboundPipeline;
@Mock
private Channel outboundChannel;
@Mock
private ChannelPipeline outboundPipeline;
@Before
public void setUp() throws Exception {
http2ProtocolProxyHandler = new Http2ProtocolProxyHandler();
}
@Test
public void configPipeline() {
when(inboundChannel.pipeline()).thenReturn(inboundPipeline);
when(inboundPipeline.addLast(any(HAProxyMessageForwarder.class))).thenReturn(inboundPipeline);
when(outboundChannel.pipeline()).thenReturn(outboundPipeline);
when(outboundPipeline.addFirst(any(HAProxyMessageEncoder.class))).thenReturn(outboundPipeline);
http2ProtocolProxyHandler.configPipeline(inboundChannel, outboundChannel);
}
} | Http2ProtocolProxyHandlerTest |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/ClientSecretAuthenticationProvider.java | {
"start": 2341,
"end": 7121
} | class ____ implements AuthenticationProvider {
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-3.2.1";
private final Log logger = LogFactory.getLog(getClass());
private final RegisteredClientRepository registeredClientRepository;
private final CodeVerifierAuthenticator codeVerifierAuthenticator;
private PasswordEncoder passwordEncoder;
/**
* Constructs a {@code ClientSecretAuthenticationProvider} using the provided
* parameters.
* @param registeredClientRepository the repository of registered clients
* @param authorizationService the authorization service
*/
public ClientSecretAuthenticationProvider(RegisteredClientRepository registeredClientRepository,
OAuth2AuthorizationService authorizationService) {
Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null");
Assert.notNull(authorizationService, "authorizationService cannot be null");
this.registeredClientRepository = registeredClientRepository;
this.codeVerifierAuthenticator = new CodeVerifierAuthenticator(authorizationService);
this.passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
/**
* Sets the {@link PasswordEncoder} used to validate the
* {@link RegisteredClient#getClientSecret() client secret}. If not set, the client
* secret will be compared using
* {@link PasswordEncoderFactories#createDelegatingPasswordEncoder()}.
* @param passwordEncoder the {@link PasswordEncoder} used to validate the client
* secret
*/
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.passwordEncoder = passwordEncoder;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2ClientAuthenticationToken clientAuthentication = (OAuth2ClientAuthenticationToken) authentication;
// @formatter:off
if (!ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(clientAuthentication.getClientAuthenticationMethod()) &&
!ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(clientAuthentication.getClientAuthenticationMethod())) {
return null;
}
// @formatter:on
String clientId = clientAuthentication.getPrincipal().toString();
RegisteredClient registeredClient = this.registeredClientRepository.findByClientId(clientId);
if (registeredClient == null) {
throwInvalidClient(OAuth2ParameterNames.CLIENT_ID);
}
if (this.logger.isTraceEnabled()) {
this.logger.trace("Retrieved registered client");
}
if (!registeredClient.getClientAuthenticationMethods()
.contains(clientAuthentication.getClientAuthenticationMethod())) {
throwInvalidClient("authentication_method");
}
if (clientAuthentication.getCredentials() == null) {
throwInvalidClient("credentials");
}
String clientSecret = clientAuthentication.getCredentials().toString();
if (!this.passwordEncoder.matches(clientSecret, registeredClient.getClientSecret())) {
if (this.logger.isDebugEnabled()) {
this.logger.debug(LogMessage.format(
"Invalid request: client_secret does not match" + " for registered client '%s'",
registeredClient.getId()));
}
throwInvalidClient(OAuth2ParameterNames.CLIENT_SECRET);
}
if (registeredClient.getClientSecretExpiresAt() != null
&& Instant.now().isAfter(registeredClient.getClientSecretExpiresAt())) {
throwInvalidClient("client_secret_expires_at");
}
if (this.passwordEncoder.upgradeEncoding(registeredClient.getClientSecret())) {
registeredClient = RegisteredClient.from(registeredClient)
.clientSecret(this.passwordEncoder.encode(clientSecret))
.build();
this.registeredClientRepository.save(registeredClient);
}
if (this.logger.isTraceEnabled()) {
this.logger.trace("Validated client authentication parameters");
}
// Validate the "code_verifier" parameter for the confidential client, if
// available
this.codeVerifierAuthenticator.authenticateIfAvailable(clientAuthentication, registeredClient);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Authenticated client secret");
}
return new OAuth2ClientAuthenticationToken(registeredClient,
clientAuthentication.getClientAuthenticationMethod(), clientAuthentication.getCredentials());
}
@Override
public boolean supports(Class<?> authentication) {
return OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication);
}
private static void throwInvalidClient(String parameterName) {
OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT,
"Client authentication failed: " + parameterName, ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
}
| ClientSecretAuthenticationProvider |
java | google__guava | android/guava-testlib/src/com/google/common/testing/CollectorTester.java | {
"start": 3218,
"end": 6916
} | enum ____ {
/** Get one accumulator and accumulate the elements into it sequentially. */
SEQUENTIAL {
@Override
final <T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object>
A result(Collector<T, A, R> collector, Iterable<T> inputs) {
A accum = collector.supplier().get();
for (T input : inputs) {
collector.accumulator().accept(accum, input);
}
return accum;
}
},
/** Get one accumulator for each element and merge the accumulators left-to-right. */
MERGE_LEFT_ASSOCIATIVE {
@Override
final <T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object>
A result(Collector<T, A, R> collector, Iterable<T> inputs) {
A accum = collector.supplier().get();
for (T input : inputs) {
A newAccum = collector.supplier().get();
collector.accumulator().accept(newAccum, input);
accum = collector.combiner().apply(accum, newAccum);
}
return accum;
}
},
/** Get one accumulator for each element and merge the accumulators right-to-left. */
MERGE_RIGHT_ASSOCIATIVE {
@Override
final <T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object>
A result(Collector<T, A, R> collector, Iterable<T> inputs) {
List<A> stack = new ArrayList<>();
for (T input : inputs) {
A newAccum = collector.supplier().get();
collector.accumulator().accept(newAccum, input);
push(stack, newAccum);
}
push(stack, collector.supplier().get());
while (stack.size() > 1) {
A right = pop(stack);
A left = pop(stack);
push(stack, collector.combiner().apply(left, right));
}
return pop(stack);
}
<E extends @Nullable Object> void push(List<E> stack, E value) {
stack.add(value);
}
<E extends @Nullable Object> E pop(List<E> stack) {
return stack.remove(stack.size() - 1);
}
};
abstract <T extends @Nullable Object, A extends @Nullable Object, R extends @Nullable Object>
A result(Collector<T, A, R> collector, Iterable<T> inputs);
}
/**
* Verifies that the specified expected result is always produced by collecting the specified
* inputs, regardless of how the elements are divided.
*/
@SafeVarargs
@CanIgnoreReturnValue
@SuppressWarnings("nullness") // TODO(cpovirk): Remove after we fix whatever the bug is.
public final CollectorTester<T, A, R> expectCollects(R expectedResult, T... inputs) {
List<T> list = Arrays.asList(inputs);
doExpectCollects(expectedResult, list);
if (collector.characteristics().contains(Collector.Characteristics.UNORDERED)) {
Collections.reverse(list);
doExpectCollects(expectedResult, list);
}
return this;
}
private void doExpectCollects(R expectedResult, List<T> inputs) {
for (CollectStrategy scheme : CollectStrategy.values()) {
A finalAccum = scheme.result(collector, inputs);
if (collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)) {
@SuppressWarnings("unchecked") // `R` and `A` match for an `IDENTITY_FINISH`
R result = (R) finalAccum;
assertEquivalent(expectedResult, result);
}
assertEquivalent(expectedResult, collector.finisher().apply(finalAccum));
}
}
private void assertEquivalent(R expected, R actual) {
assertTrue(
"Expected " + expected + " got " + actual + " modulo equivalence " + equivalence,
equivalence.test(expected, actual));
}
}
| CollectStrategy |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/resource/ResourceInjectionTest.java | {
"start": 1877,
"end": 2919
} | class ____ {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder()
.beanClasses(EEResourceField.class, JpaClient.class)
.resourceReferenceProviders(EntityManagerProvider.class, DummyProvider.class)
.resourceAnnotations(PersistenceContext.class, Dummy.class)
.injectionPointsTransformers(new InjectionPointsTransformer() {
@Override
public boolean appliesTo(org.jboss.jandex.Type requiredType) {
return requiredType.name().toString().equals(String.class.getName());
}
@Override
public void transform(TransformationContext transformationContext) {
if (transformationContext.getAllTargetAnnotations()
.stream()
.anyMatch(it -> it.name().toString().equals(Dummy.class.getName()))) {
// pretend that the injection point has an annotation whose | ResourceInjectionTest |
java | quarkusio__quarkus | extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/metrics/JvmMetricsTest.java | {
"start": 6193,
"end": 6350
} | class ____ {
@GET
@Path("/span")
public Response span() {
return Response.ok("hello").build();
}
}
}
| SpanResource |
java | google__error-prone | core/src/test/java/com/google/errorprone/refaster/UMethodTypeTest.java | {
"start": 962,
"end": 1691
} | class ____ {
@Test
public void equality() {
UType stringTy = UClassType.create("java.lang.String");
new EqualsTester()
.addEqualityGroup(UMethodType.create(stringTy, UPrimitiveType.INT))
.addEqualityGroup(UMethodType.create(stringTy, UPrimitiveType.INT, UPrimitiveType.INT))
.addEqualityGroup(UMethodType.create(UPrimitiveType.INT, UPrimitiveType.INT))
.addEqualityGroup(UMethodType.create(stringTy, stringTy))
.addEqualityGroup(UMethodType.create(stringTy))
.testEquals();
}
@Test
public void serialization() {
SerializableTester.reserializeAndAssert(
UMethodType.create(UClassType.create("java.lang.String"), UPrimitiveType.INT));
}
}
| UMethodTypeTest |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/api/parallel/ResourceLockAnnotationTests.java | {
"start": 20830,
"end": 20966
} | class ____ {
@Test
@ResourceLock(value = "d2", mode = ResourceAccessMode.READ)
void test() {
}
}
static | NestedClassTemplate |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/main/java/org/apache/camel/spring/xml/SpringErrorHandlerType.java | {
"start": 1551,
"end": 2188
} | class ____ represents the selected type.
*/
public Class<?> getTypeAsClass() {
switch (this) {
case DefaultErrorHandler:
return LegacyDefaultErrorHandlerBuilder.class;
case DeadLetterChannel:
return LegacyDeadLetterChannelBuilder.class;
case NoErrorHandler:
return LegacyNoErrorHandlerBuilder.class;
case TransactionErrorHandler:
return LegacyTransactionErrorHandlerBuilder.class;
default:
throw new IllegalArgumentException("Unknown error handler: " + this);
}
}
}
| which |
java | netty__netty | codec-http/src/main/java/io/netty/handler/codec/rtsp/RtspHeaders.java | {
"start": 913,
"end": 1088
} | class ____ {
/**
* @deprecated Use {@link RtspHeaderNames} instead.
*
* Standard RTSP header names.
*/
@Deprecated
public static final | RtspHeaders |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/IBMCOSEndpointBuilderFactory.java | {
"start": 54691,
"end": 58780
} | interface ____
extends
IBMCOSEndpointConsumerBuilder,
IBMCOSEndpointProducerBuilder {
default AdvancedIBMCOSEndpointBuilder advanced() {
return (AdvancedIBMCOSEndpointBuilder) this;
}
/**
* Automatically create the bucket if it doesn't exist.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param autoCreateBucket the value to set
* @return the dsl builder
*/
default IBMCOSEndpointBuilder autoCreateBucket(boolean autoCreateBucket) {
doSetProperty("autoCreateBucket", autoCreateBucket);
return this;
}
/**
* Automatically create the bucket if it doesn't exist.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param autoCreateBucket the value to set
* @return the dsl builder
*/
default IBMCOSEndpointBuilder autoCreateBucket(String autoCreateBucket) {
doSetProperty("autoCreateBucket", autoCreateBucket);
return this;
}
/**
* The delimiter to use for listing objects.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param delimiter the value to set
* @return the dsl builder
*/
default IBMCOSEndpointBuilder delimiter(String delimiter) {
doSetProperty("delimiter", delimiter);
return this;
}
/**
* IBM COS Endpoint URL (e.g.,
* https://s3.us-south.cloud-object-storage.appdomain.cloud).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param endpointUrl the value to set
* @return the dsl builder
*/
default IBMCOSEndpointBuilder endpointUrl(String endpointUrl) {
doSetProperty("endpointUrl", endpointUrl);
return this;
}
/**
* IBM COS Location/Region (e.g., us-south, eu-gb).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param location the value to set
* @return the dsl builder
*/
default IBMCOSEndpointBuilder location(String location) {
doSetProperty("location", location);
return this;
}
/**
* The prefix to use for listing objects.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param prefix the value to set
* @return the dsl builder
*/
default IBMCOSEndpointBuilder prefix(String prefix) {
doSetProperty("prefix", prefix);
return this;
}
/**
* IBM Cloud API Key for authentication.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param apiKey the value to set
* @return the dsl builder
*/
default IBMCOSEndpointBuilder apiKey(String apiKey) {
doSetProperty("apiKey", apiKey);
return this;
}
/**
* IBM COS Service Instance ID (CRN).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param serviceInstanceId the value to set
* @return the dsl builder
*/
default IBMCOSEndpointBuilder serviceInstanceId(String serviceInstanceId) {
doSetProperty("serviceInstanceId", serviceInstanceId);
return this;
}
}
/**
* Advanced builder for endpoint for the IBM Cloud Object Storage component.
*/
public | IBMCOSEndpointBuilder |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationMetadataLoader.java | {
"start": 1118,
"end": 2260
} | class ____ {
private static final String PATH = "META-INF/spring-autoconfigure-metadata.properties";
private AutoConfigurationMetadataLoader() {
}
static AutoConfigurationMetadata loadMetadata(ClassLoader classLoader) {
return loadMetadata(classLoader, PATH);
}
static AutoConfigurationMetadata loadMetadata(@Nullable ClassLoader classLoader, String path) {
try {
Enumeration<URL> urls = (classLoader != null) ? classLoader.getResources(path)
: ClassLoader.getSystemResources(path);
Properties properties = new Properties();
while (urls.hasMoreElements()) {
properties.putAll(PropertiesLoaderUtils.loadProperties(new UrlResource(urls.nextElement())));
}
return loadMetadata(properties);
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load @ConditionalOnClass location [" + path + "]", ex);
}
}
static AutoConfigurationMetadata loadMetadata(Properties properties) {
return new PropertiesAutoConfigurationMetadata(properties);
}
/**
* {@link AutoConfigurationMetadata} implementation backed by a properties file.
*/
private static | AutoConfigurationMetadataLoader |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/shell/TestAclCommands.java | {
"start": 2090,
"end": 8039
} | class ____ {
private String path;
private Configuration conf = null;
@BeforeEach
public void setup(@TempDir java.nio.file.Path testFolder) throws IOException {
conf = new Configuration();
path = testFolder.resolve("file").toFile().getPath();
}
@Test
public void testGetfaclValidations() throws Exception {
assertFalse(0 == runCommand(new String[] {"-getfacl"}), "getfacl should fail without path");
assertFalse(0 == runCommand(new String[] {"-getfacl", path, "extraArg"}),
"getfacl should fail with extra argument");
}
@Test
public void testSetfaclValidations() throws Exception {
assertFalse(0 == runCommand(new String[] {"-setfacl", path}),
"setfacl should fail without options");
assertFalse(0 == runCommand(new String[] {"-setfacl", "-R", path}),
"setfacl should fail without options -b, -k, -m, -x or --set");
assertFalse(0 == runCommand(new String[] {"-setfacl"}),
"setfacl should fail without path");
assertFalse(0 == runCommand(new String[] {"-setfacl", "-m", path}),
"setfacl should fail without aclSpec");
assertFalse(0 == runCommand(new String[] {"-setfacl", "-m", path}),
"setfacl should fail with conflicting options");
assertFalse(0 == runCommand(new String[] {"-setfacl", path, "extra"}),
"setfacl should fail with extra arguments");
assertFalse(0 == runCommand(new String[] {"-setfacl", "--set",
"default:user::rwx", path, "extra"}), "setfacl should fail with extra arguments");
assertFalse(0 == runCommand(new String[] {"-setfacl", "-x", "user:user1:rwx",
path}), "setfacl should fail with permissions for -x");
assertFalse(0 == runCommand(new String[] {"-setfacl", "-m", "", path}),
"setfacl should fail ACL spec missing");
}
@Test
public void testSetfaclValidationsWithoutPermissions() throws Exception {
List<AclEntry> parsedList = new ArrayList<AclEntry>();
try {
parsedList = AclEntry.parseAclSpec("user:user1:", true);
} catch (IllegalArgumentException e) {
}
assertTrue(parsedList.size() == 0);
assertFalse(0 == runCommand(new String[]{"-setfacl", "-m", "user:user1:",
"/path"}), "setfacl should fail with less arguments");
}
@Test
public void testMultipleAclSpecParsing() throws Exception {
List<AclEntry> parsedList = AclEntry.parseAclSpec(
"group::rwx,user:user1:rwx,user:user2:rw-,"
+ "group:group1:rw-,default:group:group1:rw-", true);
AclEntry basicAcl = new AclEntry.Builder().setType(AclEntryType.GROUP)
.setPermission(FsAction.ALL).build();
AclEntry user1Acl = new AclEntry.Builder().setType(AclEntryType.USER)
.setPermission(FsAction.ALL).setName("user1").build();
AclEntry user2Acl = new AclEntry.Builder().setType(AclEntryType.USER)
.setPermission(FsAction.READ_WRITE).setName("user2").build();
AclEntry group1Acl = new AclEntry.Builder().setType(AclEntryType.GROUP)
.setPermission(FsAction.READ_WRITE).setName("group1").build();
AclEntry defaultAcl = new AclEntry.Builder().setType(AclEntryType.GROUP)
.setPermission(FsAction.READ_WRITE).setName("group1")
.setScope(AclEntryScope.DEFAULT).build();
List<AclEntry> expectedList = new ArrayList<AclEntry>();
expectedList.add(basicAcl);
expectedList.add(user1Acl);
expectedList.add(user2Acl);
expectedList.add(group1Acl);
expectedList.add(defaultAcl);
assertEquals(expectedList, parsedList, "Parsed Acl not correct");
}
@Test
public void testMultipleAclSpecParsingWithoutPermissions() throws Exception {
List<AclEntry> parsedList = AclEntry.parseAclSpec(
"user::,user:user1:,group::,group:group1:,mask::,other::,"
+ "default:user:user1::,default:mask::", false);
AclEntry owner = new AclEntry.Builder().setType(AclEntryType.USER).build();
AclEntry namedUser = new AclEntry.Builder().setType(AclEntryType.USER)
.setName("user1").build();
AclEntry group = new AclEntry.Builder().setType(AclEntryType.GROUP).build();
AclEntry namedGroup = new AclEntry.Builder().setType(AclEntryType.GROUP)
.setName("group1").build();
AclEntry mask = new AclEntry.Builder().setType(AclEntryType.MASK).build();
AclEntry other = new AclEntry.Builder().setType(AclEntryType.OTHER).build();
AclEntry defaultUser = new AclEntry.Builder()
.setScope(AclEntryScope.DEFAULT).setType(AclEntryType.USER)
.setName("user1").build();
AclEntry defaultMask = new AclEntry.Builder()
.setScope(AclEntryScope.DEFAULT).setType(AclEntryType.MASK).build();
List<AclEntry> expectedList = new ArrayList<AclEntry>();
expectedList.add(owner);
expectedList.add(namedUser);
expectedList.add(group);
expectedList.add(namedGroup);
expectedList.add(mask);
expectedList.add(other);
expectedList.add(defaultUser);
expectedList.add(defaultMask);
assertEquals(expectedList, parsedList, "Parsed Acl not correct");
}
@Test
public void testLsNoRpcForGetAclStatus() throws Exception {
Configuration conf = new Configuration();
conf.set(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY, "stubfs:///");
conf.setClass("fs.stubfs.impl", StubFileSystem.class, FileSystem.class);
conf.setBoolean("stubfs.noRpcForGetAclStatus", true);
assertEquals(0, ToolRunner.run(conf, new FsShell(), new String[]{"-ls", "/"}),
"ls must succeed even if getAclStatus RPC does not exist.");
}
@Test
public void testLsAclsUnsupported() throws Exception {
Configuration conf = new Configuration();
conf.set(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY, "stubfs:///");
conf.setClass("fs.stubfs.impl", StubFileSystem.class, FileSystem.class);
assertEquals(0, ToolRunner.run(conf, new FsShell(), new String[]{"-ls", "/"}),
"ls must succeed even if FileSystem does not implement ACLs.");
}
public static | TestAclCommands |
java | google__guava | android/guava/src/com/google/common/base/Ticker.java | {
"start": 953,
"end": 1211
} | interface ____ only be used to measure elapsed time, not wall time.
*
* @author Kevin Bourrillion
* @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly
* source-compatible</a> since 9.0)
*/
@GwtCompatible
public abstract | can |
java | quarkusio__quarkus | test-framework/arquillian/src/test/java/io/quarkus/arquillian/test/SimpleWarTest.java | {
"start": 572,
"end": 1126
} | class ____ {
@Deployment
public static WebArchive createTestArchive() {
return ShrinkWrap.create(WebArchive.class)
.addAsLibrary(ShrinkWrap.create(JavaArchive.class).addClass(Foo.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"))
.addClass(SimpleClass.class);
}
@Inject
SimpleClass simple;
@Test
public void testRunner() {
assertNotNull(simple);
assertNotNull(simple.config);
assertNotNull(simple.foo);
}
}
| SimpleWarTest |
java | spring-projects__spring-framework | spring-messaging/src/main/java/org/springframework/messaging/rsocket/annotation/support/RSocketPayloadReturnValueHandler.java | {
"start": 1674,
"end": 3175
} | class ____ extends AbstractEncoderMethodReturnValueHandler {
/**
* Message header name that is expected to have an {@link java.util.concurrent.atomic.AtomicReference}
* which will receive the {@code Flux<Payload>} that represents the response.
*/
public static final String RESPONSE_HEADER = "rsocketResponse";
public RSocketPayloadReturnValueHandler(List<Encoder<?>> encoders, ReactiveAdapterRegistry registry) {
super(encoders, registry);
}
@Override
protected Mono<Void> handleEncodedContent(
Flux<DataBuffer> encodedContent, MethodParameter returnType, Message<?> message) {
AtomicReference<Flux<Payload>> responseRef = getResponseReference(message);
Assert.notNull(responseRef, "Missing '" + RESPONSE_HEADER + "'");
responseRef.set(encodedContent.map(PayloadUtils::createPayload));
return Mono.empty();
}
@Override
protected Mono<Void> handleNoContent(MethodParameter returnType, Message<?> message) {
AtomicReference<Flux<Payload>> responseRef = getResponseReference(message);
if (responseRef != null) {
responseRef.set(Flux.empty());
}
return Mono.empty();
}
@SuppressWarnings("unchecked")
private @Nullable AtomicReference<Flux<Payload>> getResponseReference(Message<?> message) {
Object headerValue = message.getHeaders().get(RESPONSE_HEADER);
Assert.state(headerValue == null || headerValue instanceof AtomicReference, "Expected AtomicReference");
return (AtomicReference<Flux<Payload>>) headerValue;
}
}
| RSocketPayloadReturnValueHandler |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/kstream/internals/KStreamKStreamJoin.java | {
"start": 4971,
"end": 17794
} | class ____ extends ContextualProcessor<K, VThis, K, VOut> {
private WindowStore<K, VOther> otherWindowStore;
private Sensor droppedRecordsSensor;
private Optional<KeyValueStore<TimestampedKeyAndJoinSide<K>, LeftOrRightValue<VLeft, VRight>>> outerJoinStore = Optional.empty();
private InternalProcessorContext<K, VOut> internalProcessorContext;
private TimeTracker sharedTimeTracker;
@Override
public void init(final ProcessorContext<K, VOut> context) {
super.init(context);
internalProcessorContext = (InternalProcessorContext<K, VOut>) context;
final StreamsMetricsImpl metrics = (StreamsMetricsImpl) context.metrics();
droppedRecordsSensor = droppedRecordsSensor(Thread.currentThread().getName(), context.taskId().toString(), metrics);
otherWindowStore = context.getStateStore(otherWindowStoreFactory.storeName());
sharedTimeTracker = sharedTimeTrackerSupplier.get(context.taskId());
if (enableSpuriousResultFix) {
outerJoinStore = outerJoinWindowStoreFactory.map(s -> context.getStateStore(s.storeName()));
sharedTimeTracker.setEmitInterval(
StreamsConfig.InternalConfig.getLong(
context.appConfigs(),
EMIT_INTERVAL_MS_KSTREAMS_OUTER_JOIN_SPURIOUS_RESULTS_FIX,
1000L
)
);
}
}
@Override
public void process(final Record<K, VThis> record) {
final long inputRecordTimestamp = record.timestamp();
sharedTimeTracker.advanceStreamTime(inputRecordTimestamp);
if (outer && record.key() == null && record.value() != null) {
context().forward(record.withValue(joiner.apply(record.key(), record.value(), null)));
return;
} else if (StreamStreamJoinUtil.skipRecord(record, LOG, droppedRecordsSensor, context())) {
return;
}
// Emit all non-joined records which window has closed
if (inputRecordTimestamp == sharedTimeTracker.streamTime) {
outerJoinStore.ifPresent(store -> emitNonJoinedOuterRecords(store, record));
}
final long timeFrom = Math.max(0L, inputRecordTimestamp - joinBeforeMs);
final long timeTo = Math.max(0L, inputRecordTimestamp + joinAfterMs);
try (final WindowStoreIterator<VOther> iter = otherWindowStore.fetch(record.key(), timeFrom, timeTo)) {
final boolean needOuterJoin = outer && !iter.hasNext();
iter.forEachRemaining(otherRecord -> emitInnerJoin(record, otherRecord, inputRecordTimestamp));
if (needOuterJoin) {
// The maxStreamTime contains the max time observed in both sides of the join.
// Having access to the time observed in the other join side fixes the following
// problem:
//
// Say we have a window size of 5 seconds
// 1. A non-joined record with time T10 is seen in the left-topic (maxLeftStreamTime: 10)
// The record is not processed yet, and is added to the outer-join store
// 2. A non-joined record with time T2 is seen in the right-topic (maxRightStreamTime: 2)
// The record is not processed yet, and is added to the outer-join store
// 3. A joined record with time T11 is seen in the left-topic (maxLeftStreamTime: 11)
// It is time to look at the expired records. T10 and T2 should be emitted, but
// because T2 was late, then it is not fetched by the window store, so it is not processed
//
// See KStreamKStreamLeftJoinTest.testLowerWindowBound() tests
//
// This condition below allows us to process the out-of-order records without the need
// to hold it in the temporary outer store
if (outerJoinStore.isEmpty() || timeTo < sharedTimeTracker.streamTime) {
context().forward(record.withValue(joiner.apply(record.key(), record.value(), null)));
} else {
sharedTimeTracker.updatedMinTime(inputRecordTimestamp);
putInOuterJoinStore(record);
}
}
}
}
protected abstract TimestampedKeyAndJoinSide<K> makeThisKey(final K key, final long inputRecordTimestamp);
protected abstract LeftOrRightValue<VLeft, VRight> makeThisValue(final VThis thisValue);
protected abstract TimestampedKeyAndJoinSide<K> makeOtherKey(final K key, final long timestamp);
protected abstract VThis thisValue(final LeftOrRightValue<? extends VLeft, ? extends VRight> leftOrRightValue);
protected abstract VOther otherValue(final LeftOrRightValue<? extends VLeft, ? extends VRight> leftOrRightValue);
private void emitNonJoinedOuterRecords(final KeyValueStore<TimestampedKeyAndJoinSide<K>, LeftOrRightValue<VLeft, VRight>> store,
final Record<K, VThis> record) {
// calling `store.all()` creates an iterator what is an expensive operation on RocksDB;
// to reduce runtime cost, we try to avoid paying those cost
// only try to emit left/outer join results if there _might_ be any result records
if (sharedTimeTracker.minTime + joinAfterMs + joinGraceMs >= sharedTimeTracker.streamTime) {
return;
}
// throttle the emit frequency to a (configurable) interval;
// we use processing time to decouple from data properties,
// as throttling is a non-functional performance optimization
if (internalProcessorContext.currentSystemTimeMs() < sharedTimeTracker.nextTimeToEmit) {
return;
}
// Ensure `nextTimeToEmit` is synced with `currentSystemTimeMs`, if we dont set it everytime,
// they can get out of sync during a clock drift
sharedTimeTracker.nextTimeToEmit = internalProcessorContext.currentSystemTimeMs();
sharedTimeTracker.advanceNextTimeToEmit();
// reset to MAX_VALUE in case the store is empty
sharedTimeTracker.minTime = Long.MAX_VALUE;
try (final KeyValueIterator<TimestampedKeyAndJoinSide<K>, LeftOrRightValue<VLeft, VRight>> it = store.all()) {
TimestampedKeyAndJoinSide<K> prevKey = null;
boolean outerJoinLeftWindowOpen = false;
boolean outerJoinRightWindowOpen = false;
while (it.hasNext()) {
final KeyValue<TimestampedKeyAndJoinSide<K>, LeftOrRightValue<VLeft, VRight>> nextKeyValue = it.next();
final TimestampedKeyAndJoinSide<K> timestampedKeyAndJoinSide = nextKeyValue.key;
sharedTimeTracker.minTime = timestampedKeyAndJoinSide.timestamp();
if (outerJoinLeftWindowOpen && outerJoinRightWindowOpen) {
// if windows are open for both joinSides we can break since there are no more candidates to emit
break;
}
// Continue with the next outer record if window for this joinSide has not closed yet
// There might be an outer record for the other joinSide which window has not closed yet
// We rely on the <timestamp><left/right-boolean><key> ordering of KeyValueIterator
if (isOuterJoinWindowOpen(timestampedKeyAndJoinSide)) {
if (timestampedKeyAndJoinSide.isLeftSide()) {
outerJoinLeftWindowOpen = true; // there are no more candidates to emit on left-outerJoin-side
} else {
outerJoinRightWindowOpen = true; // there are no more candidates to emit on right-outerJoin-side
}
// We continue with the next outer record
continue;
}
final LeftOrRightValue<VLeft, VRight> leftOrRightValue = nextKeyValue.value;
forwardNonJoinedOuterRecords(record, timestampedKeyAndJoinSide, leftOrRightValue);
if (prevKey != null && !prevKey.equals(timestampedKeyAndJoinSide)) {
// blind-delete the previous key from the outer window store now it is emitted;
// we do this because this delete would remove the whole list of values of the same key,
// and hence if we delete eagerly and then fail, we would miss emitting join results of the later
// values in the list.
// we do not use delete() calls since it would incur extra get()
store.put(prevKey, null);
}
prevKey = timestampedKeyAndJoinSide;
}
// at the end of the iteration, we need to delete the last key
if (prevKey != null) {
store.put(prevKey, null);
}
}
}
private void forwardNonJoinedOuterRecords(final Record<K, VThis> record,
final TimestampedKeyAndJoinSide<K> timestampedKeyAndJoinSide,
final LeftOrRightValue<VLeft, VRight> leftOrRightValue) {
final K key = timestampedKeyAndJoinSide.key();
final long timestamp = timestampedKeyAndJoinSide.timestamp();
final VThis thisValue = thisValue(leftOrRightValue);
final VOther otherValue = otherValue(leftOrRightValue);
final VOut nullJoinedValue = joiner.apply(key, thisValue, otherValue);
context().forward(
record.withKey(key).withValue(nullJoinedValue).withTimestamp(timestamp)
);
}
private boolean isOuterJoinWindowOpen(final TimestampedKeyAndJoinSide<K> timestampedKeyAndJoinSide) {
final long outerJoinLookBackTimeMs = getOuterJoinLookBackTimeMs(timestampedKeyAndJoinSide);
return sharedTimeTracker.minTime + outerJoinLookBackTimeMs + joinGraceMs >= sharedTimeTracker.streamTime;
}
private long getOuterJoinLookBackTimeMs(
final TimestampedKeyAndJoinSide<K> timestampedKeyAndJoinSide) {
// depending on the JoinSide we fill in the outerJoinLookBackTimeMs
if (timestampedKeyAndJoinSide.isLeftSide()) {
return windowsAfterMs; // On the left-JoinSide we look back in time
} else {
return windowsBeforeMs; // On the right-JoinSide we look forward in time
}
}
private void emitInnerJoin(final Record<K, VThis> thisRecord, final KeyValue<Long, VOther> otherRecord,
final long inputRecordTimestamp) {
outerJoinStore.ifPresent(store -> {
// use putIfAbsent to first read and see if there's any values for the key,
// if yes delete the key, otherwise do not issue a put;
// we may delete some values with the same key early but since we are going
// range over all values of the same key even after failure, since the other window-store
// is only cleaned up by stream time, so this is okay for at-least-once.
final TimestampedKeyAndJoinSide<K> otherKey = makeOtherKey(thisRecord.key(), otherRecord.key);
store.putIfAbsent(otherKey, null);
});
context().forward(
thisRecord.withValue(joiner.apply(thisRecord.key(), thisRecord.value(), otherRecord.value))
.withTimestamp(Math.max(inputRecordTimestamp, otherRecord.key)));
}
private void putInOuterJoinStore(final Record<K, VThis> thisRecord) {
outerJoinStore.ifPresent(store -> {
final TimestampedKeyAndJoinSide<K> thisKey = makeThisKey(thisRecord.key(), thisRecord.timestamp());
final LeftOrRightValue<VLeft, VRight> thisValue = makeThisValue(thisRecord.value());
store.put(thisKey, thisValue);
});
}
@Override
public void close() {
sharedTimeTrackerSupplier.remove(context().taskId());
}
}
}
| KStreamKStreamJoinProcessor |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/component/properties/MyErrorBean.java | {
"start": 869,
"end": 1099
} | class ____ {
private int counter;
public void doSomething(String body) {
counter++;
throw new IllegalArgumentException("Damn");
}
public int getCounter() {
return counter;
}
}
| MyErrorBean |
java | apache__camel | components/camel-spring-parent/camel-spring-redis/src/generated/java/org/apache/camel/component/redis/RedisEndpointUriFactory.java | {
"start": 515,
"end": 2546
} | class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":host:port";
private static final Set<String> PROPERTY_NAMES;
private static final Set<String> SECRET_PROPERTY_NAMES;
private static final Map<String, String> MULTI_VALUE_PREFIXES;
static {
Set<String> props = new HashSet<>(12);
props.add("bridgeErrorHandler");
props.add("channels");
props.add("command");
props.add("connectionFactory");
props.add("exceptionHandler");
props.add("exchangePattern");
props.add("host");
props.add("lazyStartProducer");
props.add("listenerContainer");
props.add("port");
props.add("redisTemplate");
props.add("serializer");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
SECRET_PROPERTY_NAMES = Collections.emptySet();
MULTI_VALUE_PREFIXES = Collections.emptyMap();
}
@Override
public boolean isEnabled(String scheme) {
return "spring-redis".equals(scheme);
}
@Override
public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException {
String syntax = scheme + BASE;
String uri = syntax;
Map<String, Object> copy = new HashMap<>(properties);
uri = buildPathParameter(syntax, uri, "host", null, true, copy);
uri = buildPathParameter(syntax, uri, "port", null, true, copy);
uri = buildQueryParameters(uri, copy, encode);
return uri;
}
@Override
public Set<String> propertyNames() {
return PROPERTY_NAMES;
}
@Override
public Set<String> secretPropertyNames() {
return SECRET_PROPERTY_NAMES;
}
@Override
public Map<String, String> multiValuePrefixes() {
return MULTI_VALUE_PREFIXES;
}
@Override
public boolean isLenientProperties() {
return false;
}
}
| RedisEndpointUriFactory |
java | grpc__grpc-java | benchmarks/src/generated/main/grpc/io/grpc/benchmarks/proto/WorkerServiceGrpc.java | {
"start": 10458,
"end": 12696
} | interface ____ {
/**
* <pre>
* Start server with specified workload.
* First request sent specifies the ServerConfig followed by ServerStatus
* response. After that, a "Mark" can be sent anytime to request the latest
* stats. Closing the stream will initiate shutdown of the test server
* and once the shutdown has finished, the OK status is sent to terminate
* this RPC.
* </pre>
*/
default io.grpc.stub.StreamObserver<io.grpc.benchmarks.proto.Control.ServerArgs> runServer(
io.grpc.stub.StreamObserver<io.grpc.benchmarks.proto.Control.ServerStatus> responseObserver) {
return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getRunServerMethod(), responseObserver);
}
/**
* <pre>
* Start client with specified workload.
* First request sent specifies the ClientConfig followed by ClientStatus
* response. After that, a "Mark" can be sent anytime to request the latest
* stats. Closing the stream will initiate shutdown of the test client
* and once the shutdown has finished, the OK status is sent to terminate
* this RPC.
* </pre>
*/
default io.grpc.stub.StreamObserver<io.grpc.benchmarks.proto.Control.ClientArgs> runClient(
io.grpc.stub.StreamObserver<io.grpc.benchmarks.proto.Control.ClientStatus> responseObserver) {
return io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall(getRunClientMethod(), responseObserver);
}
/**
* <pre>
* Just return the core count - unary call
* </pre>
*/
default void coreCount(io.grpc.benchmarks.proto.Control.CoreRequest request,
io.grpc.stub.StreamObserver<io.grpc.benchmarks.proto.Control.CoreResponse> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getCoreCountMethod(), responseObserver);
}
/**
* <pre>
* Quit this worker
* </pre>
*/
default void quitWorker(io.grpc.benchmarks.proto.Control.Void request,
io.grpc.stub.StreamObserver<io.grpc.benchmarks.proto.Control.Void> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getQuitWorkerMethod(), responseObserver);
}
}
/**
* Base | AsyncService |
java | apache__camel | components/camel-file-watch/src/generated/java/org/apache/camel/component/file/watch/FileWatchComponentConfigurer.java | {
"start": 737,
"end": 3945
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
FileWatchComponent target = (FileWatchComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "concurrentconsumers":
case "concurrentConsumers": target.setConcurrentConsumers(property(camelContext, int.class, value)); return true;
case "filehasher":
case "fileHasher": target.setFileHasher(property(camelContext, io.methvin.watcher.hashing.FileHasher.class, value)); return true;
case "pollthreads":
case "pollThreads": target.setPollThreads(property(camelContext, int.class, value)); return true;
case "queuesize":
case "queueSize": target.setQueueSize(property(camelContext, int.class, value)); return true;
case "usefilehashing":
case "useFileHashing": target.setUseFileHashing(property(camelContext, boolean.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "concurrentconsumers":
case "concurrentConsumers": return int.class;
case "filehasher":
case "fileHasher": return io.methvin.watcher.hashing.FileHasher.class;
case "pollthreads":
case "pollThreads": return int.class;
case "queuesize":
case "queueSize": return int.class;
case "usefilehashing":
case "useFileHashing": return boolean.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
FileWatchComponent target = (FileWatchComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "concurrentconsumers":
case "concurrentConsumers": return target.getConcurrentConsumers();
case "filehasher":
case "fileHasher": return target.getFileHasher();
case "pollthreads":
case "pollThreads": return target.getPollThreads();
case "queuesize":
case "queueSize": return target.getQueueSize();
case "usefilehashing":
case "useFileHashing": return target.isUseFileHashing();
default: return null;
}
}
}
| FileWatchComponentConfigurer |
java | spring-projects__spring-boot | integration-test/spring-boot-server-integration-tests/src/intTest/java/org/springframework/boot/context/embedded/EmbeddedServletContainerTest.java | {
"start": 1124,
"end": 1252
} | interface ____ {
String packaging();
Class<? extends AbstractApplicationLauncher>[] launchers();
}
| EmbeddedServletContainerTest |
java | apache__camel | components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/bean/MyBatisBeanSelectOneTest.java | {
"start": 1170,
"end": 2790
} | class ____ extends MyBatisTestSupport {
@Test
public void testSelectOne() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(Account.class);
template.sendBody("direct:start", 456);
MockEndpoint.assertIsSatisfied(context);
Account account = mock.getReceivedExchanges().get(0).getIn().getBody(Account.class);
assertEquals("Claus", account.getFirstName());
}
@Test
public void testSelectOneTwoTime() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(2);
mock.message(0).body().isInstanceOf(Account.class);
mock.message(1).body().isInstanceOf(Account.class);
template.sendBody("direct:start", 456);
template.sendBody("direct:start", 123);
MockEndpoint.assertIsSatisfied(context);
Account account = mock.getReceivedExchanges().get(0).getIn().getBody(Account.class);
assertEquals("Claus", account.getFirstName());
account = mock.getReceivedExchanges().get(1).getIn().getBody(Account.class);
assertEquals("James", account.getFirstName());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.to("mybatis-bean:AccountService:selectBeanAccountById")
.to("mock:result");
}
};
}
}
| MyBatisBeanSelectOneTest |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/ObjectPostProcessorTests.java | {
"start": 994,
"end": 1174
} | class ____ {
@Test
public void convertTypes() {
assertThatObject(PerformConversion.perform(new ArrayList<>())).isInstanceOf(LinkedList.class);
}
static | ObjectPostProcessorTests |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/EsqlBaseParser.java | {
"start": 16606,
"end": 18361
} | class ____ extends ParserRuleContext {
public QueryContext query() {
return getRuleContext(QueryContext.class,0);
}
public TerminalNode EOF() { return getToken(EsqlBaseParser.EOF, 0); }
@SuppressWarnings("this-escape")
public SingleStatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override public int getRuleIndex() { return RULE_singleStatement; }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).enterSingleStatement(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).exitSingleStatement(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof EsqlBaseParserVisitor ) return ((EsqlBaseParserVisitor<? extends T>)visitor).visitSingleStatement(this);
else return visitor.visitChildren(this);
}
}
public final SingleStatementContext singleStatement() throws RecognitionException {
SingleStatementContext _localctx = new SingleStatementContext(_ctx, getState());
enterRule(_localctx, 2, RULE_singleStatement);
try {
enterOuterAlt(_localctx, 1);
{
setState(205);
query(0);
setState(206);
match(EOF);
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
@SuppressWarnings("CheckReturnValue")
public static | SingleStatementContext |
java | elastic__elasticsearch | libs/logstash-bridge/src/main/java/org/elasticsearch/logstashbridge/plugins/IngestCommonPluginBridge.java | {
"start": 950,
"end": 5085
} | class ____ implements IngestPluginBridge {
public static final String APPEND_PROCESSOR_TYPE = org.elasticsearch.ingest.common.AppendProcessor.TYPE;
public static final String BYTES_PROCESSOR_TYPE = org.elasticsearch.ingest.common.BytesProcessor.TYPE;
public static final String COMMUNITY_ID_PROCESSOR_TYPE = org.elasticsearch.ingest.common.CommunityIdProcessor.TYPE;
public static final String CONVERT_PROCESSOR_TYPE = org.elasticsearch.ingest.common.ConvertProcessor.TYPE;
public static final String CSV_PROCESSOR_TYPE = org.elasticsearch.ingest.common.CsvProcessor.TYPE;
public static final String DATE_INDEX_NAME_PROCESSOR_TYPE = org.elasticsearch.ingest.common.DateIndexNameProcessor.TYPE;
public static final String DATE_PROCESSOR_TYPE = org.elasticsearch.ingest.common.DateProcessor.TYPE;
public static final String DISSECT_PROCESSOR_TYPE = org.elasticsearch.ingest.common.DissectProcessor.TYPE;
public static final String DROP_PROCESSOR_TYPE = org.elasticsearch.ingest.DropProcessor.TYPE;
public static final String FAIL_PROCESSOR_TYPE = org.elasticsearch.ingest.common.FailProcessor.TYPE;
public static final String FINGERPRINT_PROCESSOR_TYPE = org.elasticsearch.ingest.common.FingerprintProcessor.TYPE;
public static final String FOR_EACH_PROCESSOR_TYPE = org.elasticsearch.ingest.common.ForEachProcessor.TYPE;
public static final String GROK_PROCESSOR_TYPE = org.elasticsearch.ingest.common.GrokProcessor.TYPE;
public static final String GSUB_PROCESSOR_TYPE = org.elasticsearch.ingest.common.GsubProcessor.TYPE;
public static final String HTML_STRIP_PROCESSOR_TYPE = org.elasticsearch.ingest.common.HtmlStripProcessor.TYPE;
public static final String JOIN_PROCESSOR_TYPE = org.elasticsearch.ingest.common.JoinProcessor.TYPE;
public static final String JSON_PROCESSOR_TYPE = org.elasticsearch.ingest.common.JsonProcessor.TYPE;
public static final String KEY_VALUE_PROCESSOR_TYPE = org.elasticsearch.ingest.common.KeyValueProcessor.TYPE;
public static final String LOWERCASE_PROCESSOR_TYPE = org.elasticsearch.ingest.common.LowercaseProcessor.TYPE;
public static final String NETWORK_DIRECTION_PROCESSOR_TYPE = org.elasticsearch.ingest.common.NetworkDirectionProcessor.TYPE;
public static final String REGISTERED_DOMAIN_PROCESSOR_TYPE = org.elasticsearch.ingest.common.RegisteredDomainProcessor.TYPE;
public static final String RECOVER_FAILURE_DOCUMENT_PROCESSOR_TYPE = RecoverFailureDocumentProcessor.TYPE;
public static final String REMOVE_PROCESSOR_TYPE = org.elasticsearch.ingest.common.RemoveProcessor.TYPE;
public static final String RENAME_PROCESSOR_TYPE = org.elasticsearch.ingest.common.RenameProcessor.TYPE;
public static final String REROUTE_PROCESSOR_TYPE = org.elasticsearch.ingest.common.RerouteProcessor.TYPE;
public static final String SCRIPT_PROCESSOR_TYPE = org.elasticsearch.ingest.common.ScriptProcessor.TYPE;
public static final String SET_PROCESSOR_TYPE = org.elasticsearch.ingest.common.SetProcessor.TYPE;
public static final String SORT_PROCESSOR_TYPE = org.elasticsearch.ingest.common.SortProcessor.TYPE;
public static final String SPLIT_PROCESSOR_TYPE = org.elasticsearch.ingest.common.SplitProcessor.TYPE;
public static final String TRIM_PROCESSOR_TYPE = org.elasticsearch.ingest.common.TrimProcessor.TYPE;
public static final String URL_DECODE_PROCESSOR_TYPE = org.elasticsearch.ingest.common.URLDecodeProcessor.TYPE;
public static final String UPPERCASE_PROCESSOR_TYPE = org.elasticsearch.ingest.common.UppercaseProcessor.TYPE;
public static final String URI_PARTS_PROCESSOR_TYPE = org.elasticsearch.ingest.common.UriPartsProcessor.TYPE;
private final IngestCommonPlugin delegate;
public IngestCommonPluginBridge() {
delegate = new IngestCommonPlugin();
}
@Override
public Map<String, ProcessorFactoryBridge> getProcessors(final ProcessorParametersBridge parameters) {
return StableBridgeAPI.fromInternal(this.delegate.getProcessors(parameters.toInternal()), ProcessorFactoryBridge::fromInternal);
}
}
| IngestCommonPluginBridge |
java | google__guava | guava/src/com/google/common/base/Predicate.java | {
"start": 1195,
"end": 1600
} | interface ____ now a legacy type. Use {@code java.util.function.Predicate} (or the
* appropriate primitive specialization such as {@code IntPredicate}) instead whenever possible.
* Otherwise, at least reduce <i>explicit</i> dependencies on this type by using lambda expressions
* or method references instead of classes, leaving your code easier to migrate in the future.
*
* <p>The {@link Predicates} | is |
java | quarkusio__quarkus | extensions/panache/hibernate-orm-panache-common/runtime/src/main/java/io/quarkus/hibernate/orm/panache/common/NestedProjectedClass.java | {
"start": 228,
"end": 380
} | class ____ is used for query projection as a nest inside the projected class.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @ | that |
java | spring-projects__spring-boot | configuration-metadata/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/specific/InvalidDoubleRegistrationProperties.java | {
"start": 907,
"end": 1085
} | class ____ {
@TestConfigurationProperties("foo")
public Foo foo() {
return new Foo();
}
@TestConfigurationProperties("foo")
public static | InvalidDoubleRegistrationProperties |
java | quarkusio__quarkus | independent-projects/bootstrap/app-model/src/main/java/io/quarkus/maven/dependency/ArtifactDependency.java | {
"start": 153,
"end": 3485
} | class ____ extends GACTV implements Dependency, Serializable {
private static final long serialVersionUID = 5669341172899612719L;
@Deprecated(forRemoval = true)
public static Dependency of(String groupId, String artifactId, String version) {
return new ArtifactDependency(groupId, artifactId, null, ArtifactCoords.TYPE_JAR, version);
}
private final String scope;
private final int flags;
private final Collection<ArtifactKey> exclusions;
public ArtifactDependency(String groupId, String artifactId, String classifier, String type, String version) {
super(groupId, artifactId, classifier, type, version);
this.scope = SCOPE_COMPILE;
flags = 0;
this.exclusions = List.of();
}
public ArtifactDependency(String groupId, String artifactId, String classifier, String type, String version, String scope,
boolean optional) {
super(groupId, artifactId, classifier, type, version);
this.scope = scope;
flags = optional ? DependencyFlags.OPTIONAL : 0;
this.exclusions = List.of();
}
public ArtifactDependency(ArtifactCoords coords, int... flags) {
this(coords, SCOPE_COMPILE, flags);
}
public ArtifactDependency(ArtifactCoords coords, String scope, int... flags) {
super(coords.getGroupId(), coords.getArtifactId(), coords.getClassifier(), coords.getType(),
coords.getVersion());
this.scope = scope;
int allFlags = 0;
for (int f : flags) {
allFlags |= f;
}
this.flags = allFlags;
this.exclusions = List.of();
}
public ArtifactDependency(Dependency d) {
super(d.getGroupId(), d.getArtifactId(), d.getClassifier(), d.getType(), d.getVersion());
this.scope = d.getScope();
this.flags = d.getFlags();
this.exclusions = d.getExclusions();
}
public ArtifactDependency(AbstractDependencyBuilder<?, ?> builder) {
super(builder.getGroupId(), builder.getArtifactId(), builder.getClassifier(), builder.getType(), builder.getVersion());
this.scope = builder.getScope();
this.flags = builder.getFlags();
this.exclusions = builder.exclusions.isEmpty() ? builder.exclusions : List.copyOf(builder.exclusions);
}
@Override
public String getScope() {
return scope;
}
@Override
public int getFlags() {
return flags;
}
@Override
public Collection<ArtifactKey> getExclusions() {
return exclusions;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + Objects.hash(exclusions, flags, scope);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (!(obj instanceof ArtifactDependency))
return false;
ArtifactDependency other = (ArtifactDependency) obj;
return flags == other.flags && Objects.equals(scope, other.scope) && exclusions.equals(other.exclusions);
}
@Override
public String toString() {
return "[" + toGACTVString() + " " + scope + " " + flags + "]";
}
}
| ArtifactDependency |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-guava-tests/src/test/java/org/assertj/tests/guava/api/RangeSetAssert_contains_Test.java | {
"start": 1386,
"end": 3500
} | class ____ {
@Test
void should_fail_if_actual_is_null() {
// GIVEN
RangeSet<Integer> actual = null;
// WHEN
var error = expectAssertionError(() -> assertThat(actual).contains(1));
// THEN
then(error).hasMessage(actualIsNull());
}
@Test
void should_fail_if_values_is_null() {
// GIVEN
RangeSet<Integer> actual = ImmutableRangeSet.of();
Integer[] values = null;
// WHEN
Throwable thrown = catchThrowable(() -> assertThat(actual).contains(values));
// THEN
then(thrown).isInstanceOf(NullPointerException.class)
.hasMessage(shouldNotBeNull("values").create());
}
@Test
void should_fail_if_values_is_empty() {
// GIVEN
RangeSet<Integer> actual = ImmutableRangeSet.of(closed(0, 1));
Integer[] values = {};
// WHEN
Throwable thrown = catchThrowable(() -> assertThat(actual).contains(values));
// THEN
then(thrown).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Expecting values not to be empty");
}
@Test
void should_fail_if_actual_does_not_contain_values() {
// GIVEN
RangeSet<Integer> actual = ImmutableRangeSet.of(closed(0, 3));
Integer[] values = array(3, 4, 5);
// WHEN
var error = expectAssertionError(() -> assertThat(actual).contains(values));
// THEN
then(error).hasMessage(shouldContain(actual, values, array(4, 5)).create());
}
@Test
void should_pass_if_both_actual_and_values_are_empty() {
// GIVEN
RangeSet<Integer> actual = ImmutableRangeSet.of();
Integer[] values = {};
// WHEN/THEN
assertThat(actual).contains(values);
}
@Test
void should_pass_if_actual_contains_values() {
// GIVEN
RangeSet<Integer> actual = ImmutableRangeSet.of(closed(0, 10));
// WHEN/THEN
assertThat(actual).contains(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
@Test
void should_pass_if_actual_contains_duplicated_values() {
// GIVEN
RangeSet<Integer> actual = ImmutableRangeSet.of(closed(0, 10));
// WHEN/THEN
assertThat(actual).contains(1, 1, 5, 5, 10, 10);
}
}
| RangeSetAssert_contains_Test |
java | grpc__grpc-java | core/src/test/java/io/grpc/internal/ServerCallImplTest.java | {
"start": 2388,
"end": 16677
} | class ____ {
@Rule public final MockitoRule mocks = MockitoJUnit.rule();
@Mock private ServerStream stream;
@Mock private ServerCall.Listener<Long> callListener;
private final CallTracer serverCallTracer = CallTracer.getDefaultFactory().create();
private ServerCallImpl<Long, Long> call;
private Context.CancellableContext context;
private static final MethodDescriptor<Long, Long> UNARY_METHOD =
MethodDescriptor.<Long, Long>newBuilder()
.setType(MethodType.UNARY)
.setFullMethodName("service/method")
.setRequestMarshaller(new LongMarshaller())
.setResponseMarshaller(new LongMarshaller())
.build();
private static final MethodDescriptor<Long, Long> CLIENT_STREAMING_METHOD =
MethodDescriptor.<Long, Long>newBuilder()
.setType(MethodType.UNARY)
.setFullMethodName("service/method")
.setRequestMarshaller(new LongMarshaller())
.setResponseMarshaller(new LongMarshaller())
.build();
private final Metadata requestHeaders = new Metadata();
@Before
public void setUp() {
context = Context.ROOT.withCancellation();
call = new ServerCallImpl<>(stream, UNARY_METHOD, requestHeaders, context,
DecompressorRegistry.getDefaultInstance(), CompressorRegistry.getDefaultInstance(),
serverCallTracer, PerfMark.createTag());
}
@Test
public void callTracer_success() {
callTracer0(Status.OK);
}
@Test
public void callTracer_failure() {
callTracer0(Status.UNKNOWN);
}
private void callTracer0(Status status) {
CallTracer tracer = CallTracer.getDefaultFactory().create();
ServerStats.Builder beforeBuilder = new ServerStats.Builder();
tracer.updateBuilder(beforeBuilder);
ServerStats before = beforeBuilder.build();
assertEquals(0, before.callsStarted);
assertEquals(0, before.lastCallStartedNanos);
call = new ServerCallImpl<>(stream, UNARY_METHOD, requestHeaders, context,
DecompressorRegistry.getDefaultInstance(), CompressorRegistry.getDefaultInstance(),
tracer, PerfMark.createTag());
// required boilerplate
call.sendHeaders(new Metadata());
call.sendMessage(123L);
// end: required boilerplate
call.close(status, new Metadata());
ServerStats.Builder afterBuilder = new ServerStats.Builder();
tracer.updateBuilder(afterBuilder);
ServerStats after = afterBuilder.build();
assertEquals(1, after.callsStarted);
if (status.isOk()) {
assertEquals(1, after.callsSucceeded);
} else {
assertEquals(1, after.callsFailed);
}
}
@Test
public void request() {
call.request(10);
verify(stream).request(10);
}
@Test
public void setOnReadyThreshold() {
call.setOnReadyThreshold(10);
verify(stream).setOnReadyThreshold(10);
}
@Test
public void sendHeader_firstCall() {
Metadata headers = new Metadata();
call.sendHeaders(headers);
verify(stream).writeHeaders(headers, false);
}
@Test
public void sendHeader_contentLengthDiscarded() {
Metadata headers = new Metadata();
headers.put(CONTENT_LENGTH_KEY, "123");
call.sendHeaders(headers);
verify(stream).writeHeaders(headers, false);
assertNull(headers.get(CONTENT_LENGTH_KEY));
}
@Test
public void sendHeader_failsOnSecondCall() {
call.sendHeaders(new Metadata());
Metadata headers = new Metadata();
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> call.sendHeaders(headers));
assertThat(e).hasMessageThat().isEqualTo("sendHeaders has already been called");
}
@Test
public void sendHeader_failsOnClosed() {
call.close(Status.CANCELLED, new Metadata());
Metadata headers = new Metadata();
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> call.sendHeaders(headers));
assertThat(e).hasMessageThat().isEqualTo("call is closed");
}
@Test
public void sendMessage() {
call.sendHeaders(new Metadata());
call.sendMessage(1234L);
verify(stream).writeMessage(isA(InputStream.class));
}
@Test
public void sendMessage_failsOnClosed() {
call.sendHeaders(new Metadata());
call.close(Status.CANCELLED, new Metadata());
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> call.sendMessage(1234L));
assertThat(e).hasMessageThat().isEqualTo("call is closed");
}
@Test
public void sendMessage_failsIfheadersUnsent() {
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> call.sendMessage(1234L));
assertThat(e).hasMessageThat().isEqualTo("sendHeaders has not been called");
}
@Test
public void sendMessage_closesOnFailure() {
call.sendHeaders(new Metadata());
doThrow(new RuntimeException("bad")).when(stream).writeMessage(isA(InputStream.class));
call.sendMessage(1234L);
verify(stream).cancel(isA(Status.class));
}
@Test
public void sendMessage_serverSendsOne_closeOnSecondCall_unary() {
sendMessage_serverSendsOne_closeOnSecondCall(UNARY_METHOD);
}
@Test
public void sendMessage_serverSendsOne_closeOnSecondCall_clientStreaming() {
sendMessage_serverSendsOne_closeOnSecondCall(CLIENT_STREAMING_METHOD);
}
private void sendMessage_serverSendsOne_closeOnSecondCall(
MethodDescriptor<Long, Long> method) {
ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<>(
stream,
method,
requestHeaders,
context,
DecompressorRegistry.getDefaultInstance(),
CompressorRegistry.getDefaultInstance(),
serverCallTracer,
PerfMark.createTag());
serverCall.sendHeaders(new Metadata());
serverCall.sendMessage(1L);
verify(stream, times(1)).writeMessage(any(InputStream.class));
verify(stream, never()).close(any(Status.class), any(Metadata.class));
// trying to send a second message causes gRPC to close the underlying stream
serverCall.sendMessage(1L);
verify(stream, times(1)).writeMessage(any(InputStream.class));
ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
verify(stream, times(1)).cancel(statusCaptor.capture());
assertEquals(Status.Code.INTERNAL, statusCaptor.getValue().getCode());
assertEquals(ServerCallImpl.TOO_MANY_RESPONSES, statusCaptor.getValue().getDescription());
}
@Test
public void sendMessage_serverSendsOne_closeOnSecondCall_appRunToCompletion_unary() {
sendMessage_serverSendsOne_closeOnSecondCall_appRunToCompletion(UNARY_METHOD);
}
@Test
public void sendMessage_serverSendsOne_closeOnSecondCall_appRunToCompletion_clientStreaming() {
sendMessage_serverSendsOne_closeOnSecondCall_appRunToCompletion(CLIENT_STREAMING_METHOD);
}
private void sendMessage_serverSendsOne_closeOnSecondCall_appRunToCompletion(
MethodDescriptor<Long, Long> method) {
ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<>(
stream,
method,
requestHeaders,
context,
DecompressorRegistry.getDefaultInstance(),
CompressorRegistry.getDefaultInstance(),
serverCallTracer,
PerfMark.createTag());
serverCall.sendHeaders(new Metadata());
serverCall.sendMessage(1L);
serverCall.sendMessage(1L);
verify(stream, times(1)).writeMessage(any(InputStream.class));
verify(stream, times(1)).cancel(any(Status.class));
// App runs to completion but everything is ignored
serverCall.sendMessage(1L);
serverCall.close(Status.OK, new Metadata());
try {
serverCall.close(Status.OK, new Metadata());
fail("calling a second time should still cause an error");
} catch (IllegalStateException expected) {
// noop
}
}
@Test
public void serverSendsOne_okFailsOnMissingResponse_unary() {
serverSendsOne_okFailsOnMissingResponse(UNARY_METHOD);
}
@Test
public void serverSendsOne_okFailsOnMissingResponse_clientStreaming() {
serverSendsOne_okFailsOnMissingResponse(CLIENT_STREAMING_METHOD);
}
private void serverSendsOne_okFailsOnMissingResponse(
MethodDescriptor<Long, Long> method) {
ServerCallImpl<Long, Long> serverCall = new ServerCallImpl<>(
stream,
method,
requestHeaders,
context,
DecompressorRegistry.getDefaultInstance(),
CompressorRegistry.getDefaultInstance(),
serverCallTracer,
PerfMark.createTag());
serverCall.close(Status.OK, new Metadata());
ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
verify(stream, times(1)).cancel(statusCaptor.capture());
assertEquals(Status.Code.INTERNAL, statusCaptor.getValue().getCode());
assertEquals(ServerCallImpl.MISSING_RESPONSE, statusCaptor.getValue().getDescription());
}
@Test
public void serverSendsOne_canErrorWithoutResponse() {
final String description = "test description";
final Status status = Status.RESOURCE_EXHAUSTED.withDescription(description);
final Metadata metadata = new Metadata();
call.close(status, metadata);
verify(stream, times(1)).close(same(status), same(metadata));
}
@Test
public void isReady() {
when(stream.isReady()).thenReturn(true);
assertTrue(call.isReady());
call.close(Status.OK, new Metadata());
assertFalse(call.isReady());
}
@Test
public void getAuthority() {
when(stream.getAuthority()).thenReturn("fooapi.googleapis.com");
assertEquals("fooapi.googleapis.com", call.getAuthority());
verify(stream).getAuthority();
}
@Test
public void getNullAuthority() {
when(stream.getAuthority()).thenReturn(null);
assertNull(call.getAuthority());
verify(stream).getAuthority();
}
@Test
public void getSecurityLevel() {
Attributes attributes = Attributes.newBuilder()
.set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.INTEGRITY).build();
when(stream.getAttributes()).thenReturn(attributes);
assertEquals(SecurityLevel.INTEGRITY, call.getSecurityLevel());
verify(stream).getAttributes();
}
@Test
public void getNullSecurityLevel() {
when(stream.getAttributes()).thenReturn(null);
assertEquals(SecurityLevel.NONE, call.getSecurityLevel());
verify(stream).getAttributes();
}
@Test
public void setMessageCompression() {
call.setMessageCompression(true);
verify(stream).setMessageCompression(true);
}
@Test
public void streamListener_halfClosed() {
ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.halfClosed();
verify(callListener).onHalfClose();
}
@Test
public void streamListener_halfClosed_onlyOnce() {
ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.halfClosed();
// canceling the call should short circuit future halfClosed() calls.
streamListener.closed(Status.CANCELLED);
streamListener.halfClosed();
verify(callListener).onHalfClose();
}
@Test
public void streamListener_closedOk() {
ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.closed(Status.OK);
verify(callListener).onComplete();
assertTrue(context.isCancelled());
assertNull(context.cancellationCause());
// The call considers cancellation to be an exceptional situation so it should
// not be cancelled with an OK status.
assertFalse(call.isCancelled());
}
@Test
public void streamListener_closedCancelled() {
ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.closed(Status.CANCELLED);
verify(callListener).onCancel();
assertTrue(context.isCancelled());
assertNotNull(context.cancellationCause());
}
@Test
public void streamListener_onReady() {
ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.onReady();
verify(callListener).onReady();
}
@Test
public void streamListener_onReady_onlyOnce() {
ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.onReady();
// canceling the call should short circuit future halfClosed() calls.
streamListener.closed(Status.CANCELLED);
streamListener.onReady();
verify(callListener).onReady();
}
@Test
public void streamListener_messageRead() {
ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.messagesAvailable(new SingleMessageProducer(UNARY_METHOD.streamRequest(1234L)));
verify(callListener).onMessage(1234L);
}
@Test
public void streamListener_messageRead_onlyOnce() {
ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
streamListener.messagesAvailable(new SingleMessageProducer(UNARY_METHOD.streamRequest(1234L)));
// canceling the call should short circuit future halfClosed() calls.
streamListener.closed(Status.CANCELLED);
streamListener.messagesAvailable(new SingleMessageProducer(UNARY_METHOD.streamRequest(1234L)));
verify(callListener).onMessage(1234L);
}
@Test
public void streamListener_unexpectedRuntimeException() {
ServerStreamListenerImpl<Long> streamListener =
new ServerCallImpl.ServerStreamListenerImpl<>(call, callListener, context);
doThrow(new RuntimeException("unexpected exception"))
.when(callListener)
.onMessage(any(Long.class));
InputStream inputStream = UNARY_METHOD.streamRequest(1234L);
SingleMessageProducer producer = new SingleMessageProducer(inputStream);
RuntimeException e = assertThrows(RuntimeException.class,
() -> streamListener.messagesAvailable(producer));
assertThat(e).hasMessageThat().isEqualTo("unexpected exception");
}
private static | ServerCallImplTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/EncryptionAndCompressionFunctionsTest.java | {
"start": 969,
"end": 3758
} | class ____ extends TestCase {
public void test_0() throws Exception {
String sql = "INSERT INTO t VALUES (1,AES_ENCRYPT('text','password'))";
SQLStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> stmtList = parser.parseStatementList();
String text = output(stmtList);
assertEquals("INSERT INTO t\nVALUES (1, AES_ENCRYPT('text', 'password'));", text);
}
public void test_1() throws Exception {
String sql = "SELECT LENGTH(COMPRESS(REPEAT('a',1000)))";
SQLStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> stmtList = parser.parseStatementList();
String text = output(stmtList);
assertEquals("SELECT LENGTH(COMPRESS(REPEAT('a', 1000)));", text);
}
public void test_2() throws Exception {
String sql = "SELECT LENGTH(COMPRESS(REPEAT('a',16)))";
SQLStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> stmtList = parser.parseStatementList();
String text = output(stmtList);
assertEquals("SELECT LENGTH(COMPRESS(REPEAT('a', 16)));", text);
}
public void test_3() throws Exception {
String sql = "SELECT MD5('testing')";
SQLStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> stmtList = parser.parseStatementList();
String text = output(stmtList);
assertEquals("SELECT MD5('testing');", text);
}
public void test_4() throws Exception {
String sql = "SELECT SHA1('abc')";
SQLStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> stmtList = parser.parseStatementList();
String text = output(stmtList);
assertEquals("SELECT SHA1('abc');", text);
}
public void test_5() throws Exception {
String sql = "SELECT SHA2('abc')";
SQLStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> stmtList = parser.parseStatementList();
String text = output(stmtList);
assertEquals("SELECT SHA2('abc');", text);
}
public void test_6() throws Exception {
String sql = "SELECT PASSWORD('badpwd')";
SQLStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> stmtList = parser.parseStatementList();
String text = output(stmtList);
assertEquals("SELECT PASSWORD('badpwd');", text);
}
private String output(List<SQLStatement> stmtList) {
StringBuilder out = new StringBuilder();
for (SQLStatement stmt : stmtList) {
stmt.accept(new MySqlOutputVisitor(out));
out.append(";");
}
return out.toString();
}
}
| EncryptionAndCompressionFunctionsTest |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBeanByNameLookupTestClassScopedExtensionContextIntegrationTests.java | {
"start": 2028,
"end": 2945
} | class ____ {
@MockitoSpyBean("field1")
ExampleService field;
@MockitoSpyBean("field3")
ExampleService prototypeScoped;
@Test
void fieldHasOverride(ApplicationContext ctx) {
assertThat(ctx.getBean("field1"))
.isInstanceOf(ExampleService.class)
.satisfies(MockitoAssertions::assertIsSpy)
.isSameAs(field);
assertThat(field.greeting()).isEqualTo("bean1");
}
@Test
void fieldForPrototypeHasOverride(ConfigurableApplicationContext ctx) {
assertThat(ctx.getBean("field3"))
.isInstanceOf(ExampleService.class)
.satisfies(MockitoAssertions::assertIsSpy)
.isSameAs(prototypeScoped);
assertThat(ctx.getBeanFactory().getBeanDefinition("field3").isSingleton()).as("isSingleton").isTrue();
assertThat(prototypeScoped.greeting()).isEqualTo("bean3");
}
@Nested
@DisplayName("With @MockitoSpyBean in enclosing | MockitoSpyBeanByNameLookupTestClassScopedExtensionContextIntegrationTests |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8245BeforePhaseCliTest.java | {
"start": 1104,
"end": 4048
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify phase before:clean spits a warning and calls clean
*/
@Test
void testPhaseBeforeCleanAllWihConcurrentBuilder() throws Exception {
File testDir = extractResources("/mng-8245-before-after-phase-all");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setLogFileName("before-clean-concurrent.txt");
verifier.addCliArguments("-b", "concurrent", "before:clean");
verifier.execute();
verifier.verifyTextInLog("Illegal call to phase 'before:clean'. The main phase 'clean' will be used instead.");
verifier.verifyTextInLog("Hallo 'before:clean' phase.");
verifier.verifyTextInLog("Hallo 'after:clean' phase.");
}
/**
* Verify phase before:clean spits a warning and calls clean
*/
@Test
void testPhaseBeforeCleanAllWithLegacyBuilder() throws Exception {
File testDir = extractResources("/mng-8245-before-after-phase-all");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setLogFileName("before-clean-legacy.txt");
verifier.addCliArguments("before:clean");
verifier.execute();
verifier.verifyTextInLog("Illegal call to phase 'before:clean'. The main phase 'clean' will be used instead.");
verifier.verifyTextInLog("Hallo 'before:clean' phase.");
verifier.verifyTextInLog("Hallo 'after:clean' phase.");
}
/**
* Verify phase after:clean spits a warning and calls clean
*/
@Test
void testPhaseAfterCleanAllWihConcurrentBuilder() throws Exception {
File testDir = extractResources("/mng-8245-before-after-phase-all");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setLogFileName("after-clean-concurrent.txt");
verifier.addCliArguments("-b", "concurrent", "after:clean");
verifier.execute();
verifier.verifyTextInLog("Illegal call to phase 'after:clean'. The main phase 'clean' will be used instead.");
verifier.verifyTextInLog("Hallo 'before:clean' phase.");
verifier.verifyTextInLog("Hallo 'after:clean' phase.");
}
/**
* Verify phase after:clean spits a warning and calls clean
*/
@Test
void testPhaseAfterCleanAllWithLegacyBuilder() throws Exception {
File testDir = extractResources("/mng-8245-before-after-phase-all");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setLogFileName("after-clean-legacy.txt");
verifier.addCliArguments("after:clean");
verifier.execute();
verifier.verifyTextInLog("Illegal call to phase 'after:clean'. The main phase 'clean' will be used instead.");
verifier.verifyTextInLog("Hallo 'before:clean' phase.");
verifier.verifyTextInLog("Hallo 'after:clean' phase.");
}
}
| MavenITmng8245BeforePhaseCliTest |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/status/StatusLogger.java | {
"start": 6106,
"end": 9193
} | class ____ extends AbstractLogger {
private static final long serialVersionUID = 2L;
/**
* The name of the system property that enables debug mode in its presence.
* <p>
* This is a local clone of {@link Constants#LOG4J2_DEBUG}.
* The cloning is necessary to avoid cyclic initialization.
* </p>
*/
private static final String DEBUG_PROPERTY_NAME = "log4j2.debug";
/**
* The name of the system property that can be configured with the maximum number of events buffered.
* <p>
* Once the limit is reached, older entries will be removed as new entries are added.
* </p>
*/
public static final String MAX_STATUS_ENTRIES = "log4j2.status.entries";
/**
* The default fallback listener buffer capacity.
* <p>
* This constant is intended for tests.
* </p>
*
* @see #MAX_STATUS_ENTRIES
*/
static final int DEFAULT_FALLBACK_LISTENER_BUFFER_CAPACITY = 0;
/**
* The name of the system property that can be configured with the {@link Level} name to use as the fallback listener level.
* <p>
* The fallback listener is used when the listener registry is empty.
* The fallback listener will accept entries filtered by the level provided in this configuration.
* </p>
*
* @since 2.8
*/
public static final String DEFAULT_STATUS_LISTENER_LEVEL = "log4j2.StatusLogger.level";
/**
* The default fallback listener level.
* <p>
* This constant is intended for tests and indeed makes things awfully confusing given the {@link #DEFAULT_STATUS_LISTENER_LEVEL} property, which is actually intended to be a property <em>name</em>, not its <em>default value</em>.
* </p>
*/
static final Level DEFAULT_FALLBACK_LISTENER_LEVEL = Level.ERROR;
/**
* The name of the system property that can be configured with a {@link java.time.format.DateTimeFormatter} pattern that will be used while formatting the created {@link StatusData}.
* <p>
* When not provided, {@link Instant#toString()} will be used.
* </p>
*
* @see #STATUS_DATE_FORMAT_ZONE
* @since 2.11.0
*/
public static final String STATUS_DATE_FORMAT = "log4j2.StatusLogger.dateFormat";
/**
* The name of the system property that can be configured with a time-zone ID (e.g., {@code Europe/Amsterdam}, {@code UTC+01:00}) that will be used while formatting the created {@link StatusData}.
* <p>
* When not provided, {@link ZoneId#systemDefault()} will be used.
* </p>
*
* @see #STATUS_DATE_FORMAT
* @since 2.23.1
*/
static final String STATUS_DATE_FORMAT_ZONE = "log4j2.StatusLogger.dateFormatZone";
/**
* The name of the file to be searched in the classpath to read properties from.
*
* @since 2.23.0
*/
public static final String PROPERTIES_FILE_NAME = "log4j2.StatusLogger.properties";
/**
* Holder for user-provided {@link StatusLogger} configurations.
*
* @since 2.23.0
*/
public static final | StatusLogger |
java | elastic__elasticsearch | benchmarks/src/main/java/org/elasticsearch/benchmark/compute/operator/MultivalueDedupeBenchmark.java | {
"start": 1986,
"end": 7748
} | class ____ {
private static final BlockFactory blockFactory = BlockFactory.getInstance(
new NoopCircuitBreaker("noop"),
BigArrays.NON_RECYCLING_INSTANCE
);
@Param({ "BOOLEAN", "BYTES_REF", "DOUBLE", "INT", "LONG" })
private ElementType elementType;
@Param({ "3", "5", "10", "50", "100", "1000" })
private int size;
@Param({ "0", "2", "10", "100", "1000" })
private int repeats;
private Block block;
@Setup
public void setup() {
this.block = switch (elementType) {
case BOOLEAN -> {
BooleanBlock.Builder builder = blockFactory.newBooleanBlockBuilder(AggregatorBenchmark.BLOCK_LENGTH * (size + repeats));
for (int p = 0; p < AggregatorBenchmark.BLOCK_LENGTH; p++) {
List<Boolean> values = new ArrayList<>();
for (int i = 0; i < size; i++) {
values.add(i % 2 == 0);
}
for (int r = 0; r < repeats; r++) {
values.add(r < size ? r % 2 == 0 : false);
}
Randomness.shuffle(values);
builder.beginPositionEntry();
for (Boolean v : values) {
builder.appendBoolean(v);
}
builder.endPositionEntry();
}
yield builder.build();
}
case BYTES_REF -> {
BytesRefBlock.Builder builder = blockFactory.newBytesRefBlockBuilder(AggregatorBenchmark.BLOCK_LENGTH * (size + repeats));
for (int p = 0; p < AggregatorBenchmark.BLOCK_LENGTH; p++) {
List<BytesRef> values = new ArrayList<>();
for (int i = 0; i < size; i++) {
values.add(new BytesRef("SAFADFASDFSADFDAFS" + i));
}
for (int r = 0; r < repeats; r++) {
values.add(new BytesRef("SAFADFASDFSADFDAFS" + ((r < size ? r : 0))));
}
Randomness.shuffle(values);
builder.beginPositionEntry();
for (BytesRef v : values) {
builder.appendBytesRef(v);
}
builder.endPositionEntry();
}
yield builder.build();
}
case DOUBLE -> {
DoubleBlock.Builder builder = blockFactory.newDoubleBlockBuilder(AggregatorBenchmark.BLOCK_LENGTH * (size + repeats));
for (int p = 0; p < AggregatorBenchmark.BLOCK_LENGTH; p++) {
List<Double> values = new ArrayList<>();
for (int i = 0; i < size; i++) {
values.add((double) i);
}
for (int r = 0; r < repeats; r++) {
values.add(r < size ? (double) r : 0.0);
}
Randomness.shuffle(values);
builder.beginPositionEntry();
for (Double v : values) {
builder.appendDouble(v);
}
builder.endPositionEntry();
}
yield builder.build();
}
case INT -> {
IntBlock.Builder builder = blockFactory.newIntBlockBuilder(AggregatorBenchmark.BLOCK_LENGTH * (size + repeats));
for (int p = 0; p < AggregatorBenchmark.BLOCK_LENGTH; p++) {
List<Integer> values = new ArrayList<>();
for (int i = 0; i < size; i++) {
values.add(i);
}
for (int r = 0; r < repeats; r++) {
values.add(r < size ? r : 0);
}
Randomness.shuffle(values);
builder.beginPositionEntry();
for (Integer v : values) {
builder.appendInt(v);
}
builder.endPositionEntry();
}
yield builder.build();
}
case LONG -> {
LongBlock.Builder builder = blockFactory.newLongBlockBuilder(AggregatorBenchmark.BLOCK_LENGTH * (size + repeats));
for (int p = 0; p < AggregatorBenchmark.BLOCK_LENGTH; p++) {
List<Long> values = new ArrayList<>();
for (long i = 0; i < size; i++) {
values.add(i);
}
for (int r = 0; r < repeats; r++) {
values.add(r < size ? r : 0L);
}
Randomness.shuffle(values);
builder.beginPositionEntry();
for (Long v : values) {
builder.appendLong(v);
}
builder.endPositionEntry();
}
yield builder.build();
}
default -> throw new IllegalArgumentException();
};
}
@Benchmark
@OperationsPerInvocation(AggregatorBenchmark.BLOCK_LENGTH)
public void adaptive() {
MultivalueDedupe.dedupeToBlockAdaptive(block, blockFactory).close();
}
@Benchmark
@OperationsPerInvocation(AggregatorBenchmark.BLOCK_LENGTH)
public void copyAndSort() {
MultivalueDedupe.dedupeToBlockUsingCopyAndSort(block, blockFactory).close();
}
@Benchmark
@OperationsPerInvocation(AggregatorBenchmark.BLOCK_LENGTH)
public void copyMissing() {
MultivalueDedupe.dedupeToBlockUsingCopyMissing(block, blockFactory).close();
}
}
| MultivalueDedupeBenchmark |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/exc/TestExceptionHandlingWithJsonCreatorDeserialization.java | {
"start": 809,
"end": 1040
} | class ____ {
private Baz baz;
@JsonCreator
public Bar(@JsonProperty("baz") Baz baz) {
this.baz = baz;
}
public Baz getBaz() {
return baz;
}
}
static | Bar |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmcontainer/RMContainerImpl.java | {
"start": 20623,
"end": 21230
} | class ____ extends
BaseTransition {
@Override
public void transition(RMContainerImpl container, RMContainerEvent event) {
// Notify AllocationTagsManager
container.rmContext.getAllocationTagsManager().addContainer(
container.getNodeId(), container.getContainerId(),
container.getAllocationTags());
container.eventHandler.handle(
new RMAppAttemptEvent(container.appAttemptId,
RMAppAttemptEventType.CONTAINER_ALLOCATED));
publishNonAMContainerEventstoATS(container);
}
}
private static final | ContainerStartedTransition |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/collection/set/PersistentSetTest.java | {
"start": 1471,
"end": 13089
} | class ____ {
@Test
public void testWriteMethodDirtying(SessionFactoryScope scope) {
Parent parent = new Parent( "p1" );
Child child = new Child( "c1" );
parent.getChildren().add( child );
child.setParent( parent );
Child otherChild = new Child( "c2" );
scope.inTransaction(
session -> {
session.persist( parent );
session.flush();
// at this point, the set on parent has now been replaced with a PersistentSet...
PersistentSet children = (PersistentSet) parent.getChildren();
assertFalse( children.add( child ) );
assertFalse( children.isDirty() );
assertFalse( children.remove( otherChild ) );
assertFalse( children.isDirty() );
HashSet otherSet = new HashSet();
otherSet.add( child );
assertFalse( children.addAll( otherSet ) );
assertFalse( children.isDirty() );
assertFalse( children.retainAll( otherSet ) );
assertFalse( children.isDirty() );
otherSet = new HashSet();
otherSet.add( otherChild );
assertFalse( children.removeAll( otherSet ) );
assertFalse( children.isDirty() );
assertTrue( children.retainAll( otherSet ) );
assertTrue( children.isDirty() );
assertTrue( children.isEmpty() );
children.clear();
session.remove( child );
assertTrue( children.isDirty() );
session.flush();
children.clear();
assertFalse( children.isDirty() );
session.remove( parent );
}
);
}
@Test
public void testCollectionMerging(SessionFactoryScope scope) {
Parent p = new Parent( "p1" );
scope.inTransaction(
session -> {
Child child = new Child( "c1" );
p.getChildren().add( child );
child.setParent( p );
session.persist( p );
}
);
CollectionStatistics stats = scope.getSessionFactory().getStatistics()
.getCollectionStatistics( Parent.class.getName() + ".children" );
long recreateCount = stats.getRecreateCount();
long updateCount = stats.getUpdateCount();
Parent merged = (Parent) scope.fromTransaction(
session ->
session.merge( p )
);
assertEquals( 1, merged.getChildren().size() );
assertEquals( recreateCount, stats.getRecreateCount() );
assertEquals( updateCount, stats.getUpdateCount() );
scope.inTransaction(
session -> {
Parent parent = session.get( Parent.class, "p1" );
assertEquals( 1, parent.getChildren().size() );
session.remove( parent );
}
);
}
@Test
public void testCollectiondirtyChecking(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Parent parent = new Parent( "p1" );
Child child = new Child( "c1" );
parent.getChildren().add( child );
child.setParent( parent );
session.persist( parent );
}
);
CollectionStatistics stats = scope.getSessionFactory().getStatistics()
.getCollectionStatistics( Parent.class.getName() + ".children" );
long recreateCount = stats.getRecreateCount();
long updateCount = stats.getUpdateCount();
Parent parent = scope.fromTransaction(
session -> {
Parent p = session.get( Parent.class, "p1" );
assertEquals( 1, p.getChildren().size() );
return p;
}
);
assertEquals( 1, parent.getChildren().size() );
assertEquals( recreateCount, stats.getRecreateCount() );
assertEquals( updateCount, stats.getUpdateCount() );
scope.inTransaction(
session -> {
assertEquals( 1, parent.getChildren().size() );
session.remove( parent );
}
);
}
@Test
public void testCompositeElementWriteMethodDirtying(SessionFactoryScope scope) {
Container container = new Container( "p1" );
Container.Content c1 = new Container.Content( "c1" );
container.getContents().add( c1 );
Container.Content c2 = new Container.Content( "c2" );
scope.inTransaction(
session -> {
session.persist( container );
session.flush();
// at this point, the set on container has now been replaced with a PersistentSet...
PersistentSet children = (PersistentSet) container.getContents();
assertFalse( children.add( c1 ) );
assertFalse( children.isDirty() );
assertFalse( children.remove( c2 ) );
assertFalse( children.isDirty() );
HashSet otherSet = new HashSet();
otherSet.add( c1 );
assertFalse( children.addAll( otherSet ) );
assertFalse( children.isDirty() );
assertFalse( children.retainAll( otherSet ) );
assertFalse( children.isDirty() );
otherSet = new HashSet();
otherSet.add( c2 );
assertFalse( children.removeAll( otherSet ) );
assertFalse( children.isDirty() );
assertTrue( children.retainAll( otherSet ) );
assertTrue( children.isDirty() );
assertTrue( children.isEmpty() );
children.clear();
assertTrue( children.isDirty() );
session.flush();
children.clear();
assertFalse( children.isDirty() );
session.remove( container );
}
);
}
@Test
@FailureExpected(jiraKey = "HHH-2485")
public void testCompositeElementMerging(SessionFactoryScope scope) {
Container container = new Container( "p1" );
scope.inTransaction(
session -> {
Container.Content c1 = new Container.Content( "c1" );
container.getContents().add( c1 );
session.persist( container );
}
);
CollectionStatistics stats = scope.getSessionFactory().getStatistics()
.getCollectionStatistics( Container.class.getName() + ".contents" );
long recreateCount = stats.getRecreateCount();
long updateCount = stats.getUpdateCount();
container.setName( "another name" );
scope.inTransaction(
session -> {
session.merge( container );
}
);
assertEquals( 1, container.getContents().size() );
assertEquals( recreateCount, stats.getRecreateCount() );
assertEquals( updateCount, stats.getUpdateCount() );
scope.inTransaction(
session -> {
Container c = session.get( Container.class, container.getId() );
assertEquals( 1, container.getContents().size() );
session.remove( container );
}
);
}
@Test
@FailureExpected(jiraKey = "HHH-2485")
public void testCompositeElementCollectionDirtyChecking(SessionFactoryScope scope) {
Container c = new Container( "p1" );
scope.inTransaction(
session -> {
Container.Content c1 = new Container.Content( "c1" );
c.getContents().add( c1 );
session.persist( c );
}
);
CollectionStatistics stats = scope.getSessionFactory().getStatistics()
.getCollectionStatistics( Container.class.getName() + ".contents" );
long recreateCount = stats.getRecreateCount();
long updateCount = stats.getUpdateCount();
scope.inTransaction(
session -> {
Container c1 = session.get( Container.class, c.getId() );
assertEquals( 1, c1.getContents().size() );
}
);
assertEquals( 1, c.getContents().size() );
assertEquals( recreateCount, stats.getRecreateCount() );
assertEquals( updateCount, stats.getUpdateCount() );
scope.inTransaction(
session -> {
Container c1 = session.get( Container.class, c.getId() );
assertEquals( 1, c1.getContents().size() );
session.remove( c1 );
}
);
}
@Test
public void testLoadChildCheckParentContainsChildCache(SessionFactoryScope scope) {
Parent p1 = new Parent( "p1" );
Child c1 = new Child( "c1" );
c1.setDescription( "desc1" );
p1.getChildren().add( c1 );
c1.setParent( p1 );
Child otherChild = new Child( "c2" );
otherChild.setDescription( "desc2" );
p1.getChildren().add( otherChild );
otherChild.setParent( p1 );
scope.inTransaction(
session -> session.persist( p1 )
);
scope.inTransaction(
session -> {
Parent parent = session.get( Parent.class, p1.getName() );
assertTrue( parent.getChildren().contains( c1 ) );
assertTrue( parent.getChildren().contains( otherChild ) );
}
);
scope.inTransaction(
session -> {
Child child = session.get( Child.class, c1.getName() );
assertTrue( child.getParent().getChildren().contains( child ) );
session.clear();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Child> criteria = criteriaBuilder.createQuery( Child.class );
Root<Child> root = criteria.from( Child.class );
criteria.where( criteriaBuilder.equal( root.get( "name" ), "c1" ) );
child = session.createQuery( criteria ).uniqueResult();
// child = ( Child ) session.createCriteria( Child.class, child.getName() )
// .setCacheable( true )
// .add( Restrictions.idEq( "c1" ) )
// .uniqueResult();
assertTrue( child.getParent().getChildren().contains( child ) );
assertTrue( child.getParent().getChildren().contains( otherChild ) );
session.clear();
CriteriaQuery<Child> criteriaQuery = criteriaBuilder.createQuery( Child.class );
Root<Child> childRoot = criteriaQuery.from( Child.class );
criteriaQuery.where( criteriaBuilder.equal( childRoot.get( "name" ), "c1" ) );
Query<Child> query = session.createQuery( criteriaQuery );
query.setCacheable( true );
child = query.uniqueResult();
// child = ( Child ) session.createCriteria( Child.class, child.getName() )
// .setCacheable( true )
// .add( Restrictions.idEq( "c1" ) )
// .uniqueResult();
assertTrue( child.getParent().getChildren().contains( child ) );
assertTrue( child.getParent().getChildren().contains( otherChild ) );
session.clear();
child = (Child) session.createQuery( "from Child where name = 'c1'" )
.setCacheable( true )
.uniqueResult();
assertTrue( child.getParent().getChildren().contains( child ) );
child = (Child) session.createQuery( "from Child where name = 'c1'" )
.setCacheable( true )
.uniqueResult();
assertTrue( child.getParent().getChildren().contains( child ) );
session.remove( child.getParent() );
}
);
}
@Test
public void testLoadChildCheckParentContainsChildNoCache(SessionFactoryScope scope) {
Parent p = new Parent( "p1" );
Child c1 = new Child( "c1" );
p.getChildren().add( c1 );
c1.setParent( p );
Child otherChild = new Child( "c2" );
p.getChildren().add( otherChild );
otherChild.setParent( p );
scope.inTransaction(
session -> session.persist( p )
);
scope.inTransaction(
session -> {
session.setCacheMode( CacheMode.IGNORE );
Parent parent = session.get( Parent.class, p.getName() );
assertTrue( parent.getChildren().contains( c1 ) );
assertTrue( parent.getChildren().contains( otherChild ) );
}
);
scope.inTransaction(
session -> {
session.setCacheMode( CacheMode.IGNORE );
Child child = session.get( Child.class, c1.getName() );
assertTrue( child.getParent().getChildren().contains( child ) );
session.clear();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Child> criteria = criteriaBuilder.createQuery( Child.class );
Root<Child> root = criteria.from( Child.class );
criteria.where( criteriaBuilder.equal( root.get( "name" ), "c1" ) );
child = session.createQuery( criteria ).uniqueResult();
// child = ( Child ) session.createCriteria( Child.class, child.getName() )
// .add( Restrictions.idEq( "c1" ) )
// .uniqueResult();
assertTrue( child.getParent().getChildren().contains( child ) );
assertTrue( child.getParent().getChildren().contains( otherChild ) );
session.clear();
child = (Child) session.createQuery( "from Child where name = 'c1'" ).uniqueResult();
assertTrue( child.getParent().getChildren().contains( child ) );
session.remove( child.getParent() );
}
);
}
}
| PersistentSetTest |
java | apache__flink | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/LimitableBulkFormat.java | {
"start": 4944,
"end": 5930
} | class ____ implements RecordIterator<T> {
private final RecordIterator<T> iterator;
private LimitableIterator(RecordIterator<T> iterator) {
this.iterator = iterator;
}
@Nullable
@Override
public RecordAndPosition<T> next() {
if (reachLimit()) {
return null;
}
RecordAndPosition<T> ret = iterator.next();
if (ret != null) {
numRead.incrementAndGet();
}
return ret;
}
@Override
public void releaseBatch() {
iterator.releaseBatch();
}
}
}
public static <T, SplitT extends FileSourceSplit> BulkFormat<T, SplitT> create(
BulkFormat<T, SplitT> format, Long limit) {
return limit == null ? format : new LimitableBulkFormat<>(format, limit);
}
}
| LimitableIterator |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java | {
"start": 22442,
"end": 22512
} | class ____ extends AbstractMixinConfig {
}
| MixinProxyTargetClassTrueConfig |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/metrics2/impl/TestGangliaMetrics.java | {
"start": 2075,
"end": 7166
} | class ____ {
public static final Logger LOG =
LoggerFactory.getLogger(TestMetricsSystemImpl.class);
// This is the prefix to locate the config file for this particular test
// This is to avoid using the same config file with other test cases,
// which can cause race conditions.
private String testNamePrefix = "gangliametrics";
private final String[] expectedMetrics = {
testNamePrefix + ".s1rec.C1",
testNamePrefix + ".s1rec.G1",
testNamePrefix + ".s1rec.Xxx",
testNamePrefix + ".s1rec.Yyy",
testNamePrefix + ".s1rec.S1NumOps",
testNamePrefix + ".s1rec.S1AvgTime"
};
@Test
public void testTagsForPrefix() throws Exception {
ConfigBuilder cb = new ConfigBuilder()
.add(testNamePrefix + ".sink.ganglia.tagsForPrefix.all", "*")
.add(testNamePrefix + ".sink.ganglia.tagsForPrefix.some",
"NumActiveSinks, " + "NumActiveSources")
.add(testNamePrefix + ".sink.ganglia.tagsForPrefix.none", "");
GangliaSink30 sink = new GangliaSink30();
sink.init(cb.subset(testNamePrefix + ".sink.ganglia"));
List<MetricsTag> tags = new ArrayList<MetricsTag>();
tags.add(new MetricsTag(MsInfo.Context, "all"));
tags.add(new MetricsTag(MsInfo.NumActiveSources, "foo"));
tags.add(new MetricsTag(MsInfo.NumActiveSinks, "bar"));
tags.add(new MetricsTag(MsInfo.NumAllSinks, "haa"));
tags.add(new MetricsTag(MsInfo.Hostname, "host"));
Set<AbstractMetric> metrics = new HashSet<AbstractMetric>();
MetricsRecord record = new MetricsRecordImpl(MsInfo.Context, (long) 1, tags, metrics);
StringBuilder sb = new StringBuilder();
sink.appendPrefix(record, sb);
assertEquals(".NumActiveSources=foo.NumActiveSinks=bar.NumAllSinks=haa", sb.toString());
tags.set(0, new MetricsTag(MsInfo.Context, "some"));
sb = new StringBuilder();
sink.appendPrefix(record, sb);
assertEquals(".NumActiveSources=foo.NumActiveSinks=bar", sb.toString());
tags.set(0, new MetricsTag(MsInfo.Context, "none"));
sb = new StringBuilder();
sink.appendPrefix(record, sb);
assertEquals("", sb.toString());
tags.set(0, new MetricsTag(MsInfo.Context, "nada"));
sb = new StringBuilder();
sink.appendPrefix(record, sb);
assertEquals("", sb.toString());
}
@Test public void testGangliaMetrics2() throws Exception {
// Setting long interval to avoid periodic publishing.
// We manually publish metrics by MeticsSystem#publishMetricsNow here.
ConfigBuilder cb = new ConfigBuilder().add("*.period", 120)
.add(testNamePrefix
+ ".sink.gsink30.context", testNamePrefix) // filter out only "test"
.add(testNamePrefix
+ ".sink.gsink31.context", testNamePrefix) // filter out only "test"
.save(TestMetricsConfig.getTestFilename("hadoop-metrics2-"
+ testNamePrefix));
MetricsSystemImpl ms = new MetricsSystemImpl(testNamePrefix);
ms.start();
TestSource s1 = ms.register("s1", "s1 desc", new TestSource("s1rec"));
s1.c1.incr();
s1.xxx.incr();
s1.g1.set(2);
s1.yyy.incr(2);
s1.s1.add(0);
final int expectedCountFromGanglia30 = expectedMetrics.length;
final int expectedCountFromGanglia31 = 2 * expectedMetrics.length;
// Setup test for GangliaSink30
AbstractGangliaSink gsink30 = new GangliaSink30();
gsink30.init(cb.subset(testNamePrefix));
MockDatagramSocket mockds30 = new MockDatagramSocket();
GangliaMetricsTestHelper.setDatagramSocket(gsink30, mockds30);
// Setup test for GangliaSink31
AbstractGangliaSink gsink31 = new GangliaSink31();
gsink31.init(cb.subset(testNamePrefix));
MockDatagramSocket mockds31 = new MockDatagramSocket();
GangliaMetricsTestHelper.setDatagramSocket(gsink31, mockds31);
// register the sinks
ms.register("gsink30", "gsink30 desc", gsink30);
ms.register("gsink31", "gsink31 desc", gsink31);
ms.publishMetricsNow(); // publish the metrics
ms.stop();
// check GanfliaSink30 data
checkMetrics(mockds30.getCapturedSend(), expectedCountFromGanglia30);
// check GanfliaSink31 data
checkMetrics(mockds31.getCapturedSend(), expectedCountFromGanglia31);
}
// check the expected against the actual metrics
private void checkMetrics(List<byte[]> bytearrlist, int expectedCount) {
boolean[] foundMetrics = new boolean[expectedMetrics.length];
for (byte[] bytes : bytearrlist) {
String binaryStr = new String(bytes, StandardCharsets.UTF_8);
for (int index = 0; index < expectedMetrics.length; index++) {
if (binaryStr.indexOf(expectedMetrics[index]) >= 0) {
foundMetrics[index] = true;
break;
}
}
}
for (int index = 0; index < foundMetrics.length; index++) {
if (!foundMetrics[index]) {
assertTrue(false, "Missing metrics: " + expectedMetrics[index]);
}
}
assertEquals(expectedCount, bytearrlist.size(), "Mismatch in record count: ");
}
@SuppressWarnings("unused")
@Metrics(context="gangliametrics")
private static | TestGangliaMetrics |
java | google__guava | android/guava-testlib/test/com/google/common/testing/RelationshipTesterTest.java | {
"start": 933,
"end": 1164
} | class ____ extends TestCase {
public void testNulls() {
new ClassSanityTester()
.setDefault(ItemReporter.class, /* itemReporter */ Item::toString)
.testNulls(RelationshipTester.class);
}
}
| RelationshipTesterTest |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/streaming/runtime/RecordAttributesPropagationITCase.java | {
"start": 8831,
"end": 9463
} | class ____ extends AbstractStreamOperator<Long>
implements OneInputStreamOperator<Long, Long> {
private static final List<RecordAttributes> receivedRecordAttributes = new ArrayList<>();
@Override
public void processElement(StreamRecord<Long> element) throws Exception {
output.collect(element);
}
@Override
public void processRecordAttributes(RecordAttributes recordAttributes) throws Exception {
receivedRecordAttributes.add(recordAttributes);
super.processRecordAttributes(recordAttributes);
}
}
static | OneInputOperator |
java | processing__processing4 | java/src/processing/mode/java/debug/Debugger.java | {
"start": 2702,
"end": 7127
} | class ____ events
protected List<ClassLoadListener> classLoadListeners = new ArrayList<>();
/// path to the src folder of the current build
protected String srcPath;
/// list of current breakpoints
protected List<LineBreakpoint> breakpoints = new ArrayList<>();
/// the step request we are currently in, or null if not in a step
protected StepRequest requestedStep;
/// maps line number changes at runtime (orig -> changed)
protected Map<LineID, LineID> runtimeLineChanges = new HashMap<>();
/// tab filenames which already have been tracked for runtime changes
protected Set<String> runtimeTabsTracked = new HashSet<>();
/// VM event listener
protected VMEventListener vmEventListener = this::vmEvent;
public Debugger(JavaEditor editor) {
this.editor = editor;
inspector = new VariableInspector(editor);
}
/**
* Creates the debug menu. Includes ActionListeners for the menu items.
*/
public void populateMenu(JMenu modeMenu) {
debugMenu = modeMenu;
JMenuItem item;
debugItem = Toolkit.newJMenuItem(Language.text("menu.debug.enable"), 'D');
debugItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
editor.toggleDebug();
}
});
debugMenu.add(debugItem);
debugMenu.addSeparator();
item = Toolkit.newJMenuItem(Language.text("menu.debug.continue"), KeyEvent.VK_U);
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//editor.handleContinue();
continueDebug();
}
});
debugMenu.add(item);
item.setEnabled(false);
item = Toolkit.newJMenuItemExt("menu.debug.step");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//editor.handleStep(0);
stepOver();
}
});
debugMenu.add(item);
item.setEnabled(false);
item = Toolkit.newJMenuItemExt("menu.debug.step_into");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//handleStep(ActionEvent.SHIFT_MASK);
stepInto();
}
});
debugMenu.add(item);
item.setEnabled(false);
item = Toolkit.newJMenuItemExt("menu.debug.step_out");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//handleStep(ActionEvent.ALT_MASK);
stepOut();
}
});
debugMenu.add(item);
item.setEnabled(false);
debugMenu.addSeparator();
item =
Toolkit.newJMenuItem(Language.text("menu.debug.toggle_breakpoint"), 'B');
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Messages.log("Invoked 'Toggle Breakpoint' menu item");
// TODO wouldn't getCaretLine() do the same thing with less effort?
//toggleBreakpoint(editor.getCurrentLineID().lineIdx());
toggleBreakpoint(editor.getTextArea().getCaretLine());
}
});
debugMenu.add(item);
item.setEnabled(false);
}
public void enableMenuItem(boolean enabled) {
debugItem.setEnabled(enabled);
}
public boolean isEnabled() {
return enabled;
}
public void toggleEnabled() {
enabled = !enabled;
if (enabled) {
debugItem.setText(Language.text("menu.debug.disable"));
} else {
debugItem.setText(Language.text("menu.debug.enable"));
}
inspector.setVisible(enabled);
for (Component item : debugMenu.getMenuComponents()) {
if (item instanceof JMenuItem && item != debugItem) {
item.setEnabled(enabled);
}
}
}
/*
public void handleStep(int modifiers) {
if (modifiers == 0) {
Messages.log("Invoked 'Step Over' menu item");
stepOver();
} else if ((modifiers & ActionEvent.SHIFT_MASK) != 0) {
Messages.log("Invoked 'Step Into' menu item");
stepInto();
} else if ((modifiers & ActionEvent.ALT_MASK) != 0) {
Messages.log("Invoked 'Step Out' menu item");
stepOut();
}
}
public void handleContinue() {
Messages.log("Invoked 'Continue' menu item");
continueDebug();
}
*/
public VirtualMachine vm() {
if (runtime != null) {
return runtime.vm();
}
return null;
}
public JavaEditor getEditor() {
return editor;
}
/**
* Retrieve the main | load |
java | google__guava | android/guava/src/com/google/common/collect/ArrayTable.java | {
"start": 25541,
"end": 26868
} | class ____ extends ArrayMap<R, Map<C, @Nullable V>> {
private RowMap() {
super(rowKeyToIndex);
}
@Override
String getKeyRole() {
return "Row";
}
@Override
Map<C, @Nullable V> getValue(int index) {
return new Row(index);
}
@Override
Map<C, @Nullable V> setValue(int index, Map<C, @Nullable V> newValue) {
throw new UnsupportedOperationException();
}
@Override
public @Nullable Map<C, @Nullable V> put(R key, Map<C, @Nullable V> value) {
throw new UnsupportedOperationException();
}
}
/**
* Returns an unmodifiable collection of all values, which may contain duplicates. Changes to the
* table will update the returned collection.
*
* <p>The returned collection's iterator traverses the values of the first row key, the values of
* the second row key, and so on.
*
* @return collection of values
*/
@Override
public Collection<@Nullable V> values() {
return super.values();
}
@Override
Iterator<@Nullable V> valuesIterator() {
return new AbstractIndexedListIterator<@Nullable V>(size()) {
@Override
protected @Nullable V get(int index) {
return getValue(index);
}
};
}
@GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0;
}
| RowMap |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/cdi/bcextensions/CustomQualifierTest.java | {
"start": 2323,
"end": 2579
} | class ____ implements MyService {
@Override
public String hello() {
return "foo";
}
}
@Singleton
@MyAnnotation("this should be ignored, the value member should be treated as @Nonbinding")
static | MyServiceFoo |
java | alibaba__nacos | test/config-test/src/test/java/com/alibaba/nacos/test/config/ConfigLongPollReturnChangesConfigITCase.java | {
"start": 2176,
"end": 6810
} | class ____ {
@LocalServerPort
private int port;
private ConfigService configService;
@BeforeAll
@AfterAll
static void cleanClientCache() throws Exception {
ConfigCleanUtils.cleanClientCache();
ConfigCleanUtils.changeToNewTestNacosHome(ConfigLongPollReturnChangesConfigITCase.class.getSimpleName());
}
@BeforeEach
void init() throws NacosException {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:" + port);
properties.put(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT, "20000");
properties.put(PropertyKeyConst.CONFIG_RETRY_TIME, "3000");
properties.put(PropertyKeyConst.MAX_RETRY, "5");
configService = NacosFactory.createConfigService(properties);
}
@AfterEach
void destroy() {
try {
configService.shutDown();
} catch (NacosException ex) {
// ignore
}
}
@Test
void testAdd() throws InterruptedException, NacosException {
CountDownLatch latch = new CountDownLatch(1);
final String dataId = "test" + System.currentTimeMillis();
final String group = "DEFAULT_GROUP";
final String content = "config data";
configService.addListener(dataId, group, new AbstractConfigChangeListener() {
@Override
public void receiveConfigChange(ConfigChangeEvent event) {
try {
ConfigChangeItem cci = event.getChangeItem("content");
assertNull(cci.getOldValue());
assertEquals(content, cci.getNewValue());
assertEquals(PropertyChangeType.ADDED, cci.getType());
System.out.println(cci);
} finally {
latch.countDown();
}
}
});
boolean result = configService.publishConfig(dataId, group, content);
assertTrue(result);
configService.getConfig(dataId, group, 50);
latch.await(10_000L, TimeUnit.MILLISECONDS);
}
@Test
void testModify() throws InterruptedException, NacosException {
CountDownLatch latch = new CountDownLatch(1);
final String dataId = "test" + System.currentTimeMillis();
final String group = "DEFAULT_GROUP";
final String oldData = "old data";
final String newData = "new data";
boolean result = configService.publishConfig(dataId, group, oldData);
assertTrue(result);
configService.addListener(dataId, group, new AbstractConfigChangeListener() {
@Override
public void receiveConfigChange(ConfigChangeEvent event) {
try {
ConfigChangeItem cci = event.getChangeItem("content");
assertEquals(oldData, cci.getOldValue());
assertEquals(newData, cci.getNewValue());
assertEquals(PropertyChangeType.MODIFIED, cci.getType());
System.out.println(cci);
} finally {
latch.countDown();
}
}
});
configService.publishConfig(dataId, group, newData);
latch.await(10_000L, TimeUnit.MILLISECONDS);
}
@Test
void testDelete() throws InterruptedException, NacosException {
CountDownLatch latch = new CountDownLatch(1);
final String dataId = "test" + System.currentTimeMillis();
final String group = "DEFAULT_GROUP";
final String oldData = "old data";
boolean result = configService.publishConfig(dataId, group, oldData);
assertTrue(result);
configService.addListener(dataId, group, new AbstractConfigChangeListener() {
@Override
public void receiveConfigChange(ConfigChangeEvent event) {
try {
ConfigChangeItem cci = event.getChangeItem("content");
assertEquals(oldData, cci.getOldValue());
assertNull(cci.getNewValue());
assertEquals(PropertyChangeType.DELETED, cci.getType());
System.out.println(cci);
} finally {
latch.countDown();
}
}
});
configService.removeConfig(dataId, group);
latch.await(10_000L, TimeUnit.MILLISECONDS);
}
}
| ConfigLongPollReturnChangesConfigITCase |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/TestContextAnnotationUtils.java | {
"start": 23241,
"end": 23341
} | class ____ { }
* </pre>
*
* @param <T> the annotation type
*/
public static | UserRepositoryTests |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/ttl/AbstractTtlState.java | {
"start": 1583,
"end": 3947
} | class ____<K, N, SV, TTLSV, S extends InternalKvState<K, N, TTLSV>>
extends AbstractTtlDecorator<S> implements InternalKvState<K, N, SV> {
private final TypeSerializer<SV> valueSerializer;
/** This registered callback is to be called whenever state is accessed for read or write. */
final Runnable accessCallback;
AbstractTtlState(TtlStateContext<S, SV> ttlStateContext) {
super(ttlStateContext.original, ttlStateContext.config, ttlStateContext.timeProvider);
this.valueSerializer = ttlStateContext.valueSerializer;
this.accessCallback = ttlStateContext.accessCallback;
}
<SE extends Throwable, CE extends Throwable, T> T getWithTtlCheckAndUpdate(
SupplierWithException<TtlValue<T>, SE> getter,
ThrowingConsumer<TtlValue<T>, CE> updater)
throws SE, CE {
return getWithTtlCheckAndUpdate(getter, updater, original::clear);
}
@Override
public TypeSerializer<K> getKeySerializer() {
return original.getKeySerializer();
}
@Override
public TypeSerializer<N> getNamespaceSerializer() {
return original.getNamespaceSerializer();
}
@Override
public TypeSerializer<SV> getValueSerializer() {
return valueSerializer;
}
@Override
public void setCurrentNamespace(N namespace) {
original.setCurrentNamespace(namespace);
}
@Override
public byte[] getSerializedValue(
byte[] serializedKeyAndNamespace,
TypeSerializer<K> safeKeySerializer,
TypeSerializer<N> safeNamespaceSerializer,
TypeSerializer<SV> safeValueSerializer) {
throw new FlinkRuntimeException("Queryable state is not currently supported with TTL.");
}
@Override
public void clear() {
original.clear();
accessCallback.run();
}
/**
* Check if state has expired or not and update it if it has partially expired.
*
* @return either non expired (possibly updated) state or null if the state has expired.
*/
@Nullable
public abstract TTLSV getUnexpiredOrNull(@Nonnull TTLSV ttlValue);
@Override
public StateIncrementalVisitor<K, N, SV> getStateIncrementalVisitor(
int recommendedMaxNumberOfReturnedRecords) {
throw new UnsupportedOperationException();
}
}
| AbstractTtlState |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDatanodeRegistration.java | {
"start": 2706,
"end": 18206
} | class ____ extends SecurityManager {
int lookups = 0;
@Override
public void checkPermission(Permission perm) {}
@Override
public void checkConnect(String host, int port) {
if (port == -1) {
lookups++;
}
}
}
/**
* Ensure the datanode manager does not do host lookup after registration,
* especially for node reports.
* @throws Exception
*/
@Test
public void testDNSLookups() throws Exception {
MonitorDNS sm = new MonitorDNS();
try {
System.setSecurityManager(sm);
} catch (UnsupportedOperationException e) {
assumeTrue(false,
"Test is skipped because SecurityManager cannot be set (JEP 411)");
}
MiniDFSCluster cluster = null;
try {
HdfsConfiguration conf = new HdfsConfiguration();
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(8).build();
cluster.waitActive();
int initialLookups = sm.lookups;
assertTrue(initialLookups != 0, "dns security manager is active");
DatanodeManager dm =
cluster.getNamesystem().getBlockManager().getDatanodeManager();
// make sure no lookups occur
dm.refreshNodes(conf);
assertEquals(initialLookups, sm.lookups);
dm.refreshNodes(conf);
assertEquals(initialLookups, sm.lookups);
// ensure none of the reports trigger lookups
dm.getDatanodeListForReport(DatanodeReportType.ALL);
assertEquals(initialLookups, sm.lookups);
dm.getDatanodeListForReport(DatanodeReportType.LIVE);
assertEquals(initialLookups, sm.lookups);
dm.getDatanodeListForReport(DatanodeReportType.DEAD);
assertEquals(initialLookups, sm.lookups);
} finally {
if (cluster != null) {
cluster.shutdown();
}
System.setSecurityManager(null);
}
}
/**
* Regression test for HDFS-894 ensures that, when datanodes
* are restarted, the new IPC port is registered with the
* namenode.
*/
@Test
public void testChangeIpcPort() throws Exception {
HdfsConfiguration conf = new HdfsConfiguration();
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf).build();
InetSocketAddress addr = new InetSocketAddress(
"localhost",
cluster.getNameNodePort());
DFSClient client = new DFSClient(addr, conf);
// Restart datanodes
cluster.restartDataNodes();
// Wait until we get a heartbeat from the new datanode
DatanodeInfo[] report = client.datanodeReport(DatanodeReportType.ALL);
long firstUpdateAfterRestart = report[0].getLastUpdate();
boolean gotHeartbeat = false;
for (int i = 0; i < 10 && !gotHeartbeat; i++) {
try {
Thread.sleep(i*1000);
} catch (InterruptedException ie) {}
report = client.datanodeReport(DatanodeReportType.ALL);
gotHeartbeat = (report[0].getLastUpdate() > firstUpdateAfterRestart);
}
if (!gotHeartbeat) {
fail("Never got a heartbeat from restarted datanode.");
}
int realIpcPort = cluster.getDataNodes().get(0).getIpcPort();
// Now make sure the reported IPC port is the correct one.
assertEquals(realIpcPort, report[0].getIpcPort());
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
@Test
public void testChangeStorageID() throws Exception {
final String DN_IP_ADDR = "127.0.0.1";
final String DN_HOSTNAME = "localhost";
final int DN_XFER_PORT = 12345;
final int DN_INFO_PORT = 12346;
final int DN_INFO_SECURE_PORT = 12347;
final int DN_IPC_PORT = 12348;
Configuration conf = new HdfsConfiguration();
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0)
.build();
InetSocketAddress addr = new InetSocketAddress(
"localhost",
cluster.getNameNodePort());
DFSClient client = new DFSClient(addr, conf);
NamenodeProtocols rpcServer = cluster.getNameNodeRpc();
// register a datanode
DatanodeID dnId = new DatanodeID(DN_IP_ADDR, DN_HOSTNAME,
"fake-datanode-id", DN_XFER_PORT, DN_INFO_PORT, DN_INFO_SECURE_PORT,
DN_IPC_PORT);
long nnCTime = cluster.getNamesystem().getFSImage().getStorage()
.getCTime();
StorageInfo mockStorageInfo = mock(StorageInfo.class);
doReturn(nnCTime).when(mockStorageInfo).getCTime();
doReturn(DataNodeLayoutVersion.getCurrentLayoutVersion())
.when(mockStorageInfo).getLayoutVersion();
DatanodeRegistration dnReg = new DatanodeRegistration(dnId,
mockStorageInfo, null, VersionInfo.getVersion());
rpcServer.registerDatanode(dnReg);
DatanodeInfo[] report = client.datanodeReport(DatanodeReportType.ALL);
assertEquals(1, report.length, "Expected a registered datanode");
// register the same datanode again with a different storage ID
dnId = new DatanodeID(DN_IP_ADDR, DN_HOSTNAME,
"changed-fake-datanode-id", DN_XFER_PORT, DN_INFO_PORT,
DN_INFO_SECURE_PORT, DN_IPC_PORT);
dnReg = new DatanodeRegistration(dnId,
mockStorageInfo, null, VersionInfo.getVersion());
rpcServer.registerDatanode(dnReg);
report = client.datanodeReport(DatanodeReportType.ALL);
assertEquals(1, report.length,
"Datanode with changed storage ID not recognized");
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
@Test
public void testRegistrationWithDifferentSoftwareVersions() throws Exception {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_KEY, "3.0.0");
conf.set(DFSConfigKeys.DFS_NAMENODE_MIN_SUPPORTED_DATANODE_VERSION_KEY, "3.0.0");
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0)
.build();
NamenodeProtocols rpcServer = cluster.getNameNodeRpc();
long nnCTime = cluster.getNamesystem().getFSImage().getStorage().getCTime();
StorageInfo mockStorageInfo = mock(StorageInfo.class);
doReturn(nnCTime).when(mockStorageInfo).getCTime();
DatanodeRegistration mockDnReg = mock(DatanodeRegistration.class);
doReturn(DataNodeLayoutVersion.getCurrentLayoutVersion())
.when(mockDnReg).getVersion();
doReturn("127.0.0.1").when(mockDnReg).getIpAddr();
doReturn(123).when(mockDnReg).getXferPort();
doReturn("fake-storage-id").when(mockDnReg).getDatanodeUuid();
doReturn(mockStorageInfo).when(mockDnReg).getStorageInfo();
doReturn("localhost").when(mockDnReg).getHostName();
// Should succeed when software versions are the same.
doReturn("3.0.0").when(mockDnReg).getSoftwareVersion();
rpcServer.registerDatanode(mockDnReg);
// Should succeed when software version of DN is above minimum required by NN.
doReturn("4.0.0").when(mockDnReg).getSoftwareVersion();
rpcServer.registerDatanode(mockDnReg);
// Should fail when software version of DN is below minimum required by NN.
doReturn("2.0.0").when(mockDnReg).getSoftwareVersion();
try {
rpcServer.registerDatanode(mockDnReg);
fail("Should not have been able to register DN with too-low version.");
} catch (IncorrectVersionException ive) {
GenericTestUtils.assertExceptionContains(
"The reported DataNode version is too low", ive);
LOG.info("Got expected exception", ive);
}
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
@Test
public void testRegistrationWithDifferentSoftwareVersionsDuringUpgrade()
throws Exception {
Configuration conf = new HdfsConfiguration();
conf.set(DFSConfigKeys.DFS_DATANODE_MIN_SUPPORTED_NAMENODE_VERSION_KEY, "1.0.0");
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(0)
.build();
NamenodeProtocols rpcServer = cluster.getNameNodeRpc();
long nnCTime = cluster.getNamesystem().getFSImage().getStorage().getCTime();
StorageInfo mockStorageInfo = mock(StorageInfo.class);
doReturn(nnCTime).when(mockStorageInfo).getCTime();
DatanodeRegistration mockDnReg = mock(DatanodeRegistration.class);
doReturn(DataNodeLayoutVersion.getCurrentLayoutVersion())
.when(mockDnReg).getVersion();
doReturn("fake-storage-id").when(mockDnReg).getDatanodeUuid();
doReturn(mockStorageInfo).when(mockDnReg).getStorageInfo();
// Should succeed when software versions are the same and CTimes are the
// same.
doReturn(VersionInfo.getVersion()).when(mockDnReg).getSoftwareVersion();
doReturn("127.0.0.1").when(mockDnReg).getIpAddr();
doReturn(123).when(mockDnReg).getXferPort();
doReturn("localhost").when(mockDnReg).getHostName();
rpcServer.registerDatanode(mockDnReg);
// Should succeed when software versions are the same and CTimes are
// different.
doReturn(nnCTime + 1).when(mockStorageInfo).getCTime();
rpcServer.registerDatanode(mockDnReg);
// Should fail when software version of DN is different from NN and CTimes
// are different.
doReturn(VersionInfo.getVersion() + ".1").when(mockDnReg).getSoftwareVersion();
try {
rpcServer.registerDatanode(mockDnReg);
fail("Should not have been able to register DN with different software" +
" versions and CTimes");
} catch (IncorrectVersionException ive) {
GenericTestUtils.assertExceptionContains(
"does not match CTime of NN", ive);
LOG.info("Got expected exception", ive);
}
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
// IBRs are async operations to free up IPC handlers. This means the IBR
// response will not contain non-IPC level exceptions - which in practice
// should not occur other than dead/unregistered node which will trigger a
// re-registration. If a non-IPC exception does occur, the safety net is
// a forced re-registration on the next heartbeat.
@Test
public void testForcedRegistration() throws Exception {
final Configuration conf = new HdfsConfiguration();
conf.setInt(DFSConfigKeys.DFS_NAMENODE_HANDLER_COUNT_KEY, 4);
conf.setLong(DFSConfigKeys.DFS_BLOCKREPORT_INTERVAL_MSEC_KEY, Integer.MAX_VALUE);
MiniDFSCluster cluster = null;
try {
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
cluster.waitActive();
cluster.getHttpUri(0);
FSNamesystem fsn = cluster.getNamesystem();
String bpId = fsn.getBlockPoolId();
DataNode dn = cluster.getDataNodes().get(0);
DatanodeDescriptor dnd =
NameNodeAdapter.getDatanode(fsn, dn.getDatanodeId());
DataNodeTestUtils.setHeartbeatsDisabledForTests(dn, true);
DatanodeStorageInfo storage = dnd.getStorageInfos()[0];
// registration should not change after heartbeat.
assertTrue(dnd.isRegistered());
DatanodeRegistration lastReg = dn.getDNRegistrationForBP(bpId);
waitForHeartbeat(dn, dnd);
assertSame(lastReg, dn.getDNRegistrationForBP(bpId));
// force a re-registration on next heartbeat.
dnd.setForceRegistration(true);
assertFalse(dnd.isRegistered());
waitForHeartbeat(dn, dnd);
assertTrue(dnd.isRegistered());
DatanodeRegistration newReg = dn.getDNRegistrationForBP(bpId);
assertNotSame(lastReg, newReg);
lastReg = newReg;
// registration should not change on subsequent heartbeats.
waitForHeartbeat(dn, dnd);
assertTrue(dnd.isRegistered());
assertSame(lastReg, dn.getDNRegistrationForBP(bpId));
assertTrue(waitForBlockReport(dn, dnd),
"block report is not processed for DN " + dnd);
assertTrue(dnd.isRegistered());
assertSame(lastReg, dn.getDNRegistrationForBP(bpId));
// check that block report is not processed and registration didn't
// change.
dnd.setForceRegistration(true);
assertFalse(waitForBlockReport(dn, dnd),
"block report is processed for DN " + dnd);
assertFalse(dnd.isRegistered());
assertSame(lastReg, dn.getDNRegistrationForBP(bpId));
// heartbeat should trigger re-registration, and next block report
// should not change registration.
waitForHeartbeat(dn, dnd);
assertTrue(dnd.isRegistered());
newReg = dn.getDNRegistrationForBP(bpId);
assertNotSame(lastReg, newReg);
lastReg = newReg;
assertTrue(waitForBlockReport(dn, dnd),
"block report is not processed for DN " + dnd);
assertTrue(dnd.isRegistered());
assertSame(lastReg, dn.getDNRegistrationForBP(bpId));
// registration doesn't change.
ExtendedBlock eb = new ExtendedBlock(bpId, 1234);
dn.notifyNamenodeDeletedBlock(eb, storage.getStorageID());
DataNodeTestUtils.triggerDeletionReport(dn);
assertTrue(dnd.isRegistered());
assertSame(lastReg, dn.getDNRegistrationForBP(bpId));
// a failed IBR will effectively unregister the node.
boolean failed = false;
try {
// pass null to cause a failure since there aren't any easy failure
// modes since it shouldn't happen.
fsn.processIncrementalBlockReport(lastReg, null);
} catch (NullPointerException npe) {
failed = true;
}
assertTrue(failed, "didn't fail");
assertFalse(dnd.isRegistered());
// should remain unregistered until next heartbeat.
dn.notifyNamenodeDeletedBlock(eb, storage.getStorageID());
DataNodeTestUtils.triggerDeletionReport(dn);
assertFalse(dnd.isRegistered());
assertSame(lastReg, dn.getDNRegistrationForBP(bpId));
waitForHeartbeat(dn, dnd);
assertTrue(dnd.isRegistered());
assertNotSame(lastReg, dn.getDNRegistrationForBP(bpId));
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
private void waitForHeartbeat(final DataNode dn, final DatanodeDescriptor dnd)
throws Exception {
final long lastUpdate = dnd.getLastUpdateMonotonic();
Thread.sleep(1);
DataNodeTestUtils.setHeartbeatsDisabledForTests(dn, false);
DataNodeTestUtils.triggerHeartbeat(dn);
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return lastUpdate != dnd.getLastUpdateMonotonic();
}
}, 10, 100000);
DataNodeTestUtils.setHeartbeatsDisabledForTests(dn, true);
}
private boolean waitForBlockReport(final DataNode dn,
final DatanodeDescriptor dnd) throws Exception {
final DatanodeStorageInfo storage = dnd.getStorageInfos()[0];
final long lastCount = storage.getBlockReportCount();
dn.triggerBlockReport(
new BlockReportOptions.Factory().setIncremental(false).build());
try {
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
return lastCount != storage.getBlockReportCount();
}
}, 10, 6000);
} catch (TimeoutException te) {
LOG.error("Timeout waiting for block report for {}", dnd);
return false;
}
return true;
}
}
| MonitorDNS |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBeanConfigurationErrorTests.java | {
"start": 5539,
"end": 5665
} | class ____ {
}
@Component("mySelfInjectionScopedProxy")
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
static | MyScopedProxy |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/llama/embeddings/LlamaEmbeddingsModelTests.java | {
"start": 727,
"end": 2050
} | class ____ extends ESTestCase {
public static LlamaEmbeddingsModel createEmbeddingsModel(String modelId, String url, String apiKey) {
return new LlamaEmbeddingsModel(
"id",
TaskType.TEXT_EMBEDDING,
"llama",
new LlamaEmbeddingsServiceSettings(modelId, url, null, null, null, null),
null,
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
}
public static LlamaEmbeddingsModel createEmbeddingsModelWithChunkingSettings(String modelId, String url, String apiKey) {
return new LlamaEmbeddingsModel(
"id",
TaskType.TEXT_EMBEDDING,
"llama",
new LlamaEmbeddingsServiceSettings(modelId, url, null, null, null, null),
createRandomChunkingSettings(),
new DefaultSecretSettings(new SecureString(apiKey.toCharArray()))
);
}
public static LlamaEmbeddingsModel createEmbeddingsModelNoAuth(String modelId, String url) {
return new LlamaEmbeddingsModel(
"id",
TaskType.TEXT_EMBEDDING,
"llama",
new LlamaEmbeddingsServiceSettings(modelId, url, null, null, null, null),
null,
EmptySecretSettings.INSTANCE
);
}
}
| LlamaEmbeddingsModelTests |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/IgniteComputeComponentBuilderFactory.java | {
"start": 1387,
"end": 1889
} | interface ____ {
/**
* Ignite Compute (camel-ignite)
* Run compute operations on an Ignite cluster.
*
* Category: cache,clustering
* Since: 2.17
* Maven coordinates: org.apache.camel:camel-ignite
*
* @return the dsl builder
*/
static IgniteComputeComponentBuilder igniteCompute() {
return new IgniteComputeComponentBuilderImpl();
}
/**
* Builder for the Ignite Compute component.
*/
| IgniteComputeComponentBuilderFactory |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceSessionManagementTests.java | {
"start": 15422,
"end": 15887
} | class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement((sessions) -> sessions
.requireExplicitAuthenticationStrategy(false)
)
.httpBasic(withDefaults());
return http.build();
// @formatter:on
}
@Bean
MockEventListener eventListener() {
return spy(new MockEventListener());
}
}
@Configuration
@EnableWebSecurity
static | SFPPostProcessedConfig |
java | apache__camel | core/camel-main/src/test/java/org/apache/camel/main/PropertyBindingSupportHelperClassFactoryMethodTest.java | {
"start": 1162,
"end": 4335
} | class ____ {
@Test
public void testFactory() {
CamelContext context = new DefaultCamelContext();
context.start();
MyApp target = new MyApp();
PropertyBindingSupport.build()
.withCamelContext(context)
.withTarget(target)
.withProperty("name", "Donald")
.withProperty("myDriver", "#class:" + MyDriver.class.getName()
+ "#" + MyDriverHelper.class.getName()
+ ":createDriver('localhost:2121', 'scott', 'tiger')")
.withRemoveParameters(false).bind();
assertEquals("Donald", target.getName());
assertEquals("localhost:2121", target.getMyDriver().getUrl());
assertEquals("scott", target.getMyDriver().getUsername());
assertEquals("tiger", target.getMyDriver().getPassword());
context.stop();
}
@Test
public void testFactoryPropertyPlaceholder() {
CamelContext context = new DefaultCamelContext();
Properties prop = new Properties();
prop.put("myUsername", "scott");
prop.put("myPassword", "tiger");
prop.put("myUrl", "localhost:2121");
context.getPropertiesComponent().setInitialProperties(prop);
context.start();
MyApp target = new MyApp();
PropertyBindingSupport.build()
.withCamelContext(context)
.withTarget(target)
.withProperty("name", "Donald")
.withProperty("myDriver",
"#class:" + MyDriver.class.getName()
+ "#" + MyDriverHelper.class.getName()
+ ":createDriver('{{myUrl}}', '{{myUsername}}', '{{myPassword}}')")
.withRemoveParameters(false).bind();
assertEquals("Donald", target.getName());
assertEquals("localhost:2121", target.getMyDriver().getUrl());
assertEquals("scott", target.getMyDriver().getUsername());
assertEquals("tiger", target.getMyDriver().getPassword());
context.stop();
}
@Test
public void testFactoryRef() {
CamelContext context = new DefaultCamelContext();
context.getRegistry().bind("myDriverHelper", new MyDriverHelper());
context.start();
MyApp target = new MyApp();
PropertyBindingSupport.build()
.withCamelContext(context)
.withTarget(target)
.withProperty("name", "Donald")
.withProperty("myDriver", "#class:" + MyDriver.class.getName()
+ "#myDriverHelper:createDriver('localhost:2121', 'scott', 'tiger')")
.withRemoveParameters(false).bind();
assertEquals("Donald", target.getName());
assertEquals("localhost:2121", target.getMyDriver().getUrl());
assertEquals("scott", target.getMyDriver().getUsername());
assertEquals("tiger", target.getMyDriver().getPassword());
context.stop();
}
public static | PropertyBindingSupportHelperClassFactoryMethodTest |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/util/ClassUtils.java | {
"start": 2638,
"end": 3939
} | class ____: {@code "$$"}. */
public static final String CGLIB_CLASS_SEPARATOR = "$$";
/** The ".class" file suffix. */
public static final String CLASS_FILE_SUFFIX = ".class";
/** Precomputed value for the combination of private, static and final modifiers. */
private static final int NON_OVERRIDABLE_MODIFIER = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
/** Precomputed value for the combination of public and protected modifiers. */
private static final int OVERRIDABLE_MODIFIER = Modifier.PUBLIC | Modifier.PROTECTED;
/**
* Map with primitive wrapper type as key and corresponding primitive
* type as value, for example: {@code Integer.class -> int.class}.
*/
private static final Map<Class<?>, Class<?>> primitiveWrapperTypeMap = new IdentityHashMap<>(9);
/**
* Map with primitive type as key and corresponding wrapper
* type as value, for example: {@code int.class -> Integer.class}.
*/
private static final Map<Class<?>, Class<?>> primitiveTypeToWrapperMap = new IdentityHashMap<>(9);
/**
* Map with primitive type name as key and corresponding primitive
* type as value, for example: {@code "int" -> int.class}.
*/
private static final Map<String, Class<?>> primitiveTypeNameMap = new HashMap<>(32);
/**
* Map with common Java language | separator |
java | quarkusio__quarkus | independent-projects/tools/devtools-common/src/main/java/io/quarkus/maven/utilities/PomTransformer.java | {
"start": 26819,
"end": 29873
} | class ____ {
public static Gavtcs importBom(String groupId, String artifactId, String version) {
return new Gavtcs(groupId, artifactId, version, ArtifactCoords.TYPE_POM, null, Dependency.SCOPE_IMPORT);
}
public static Gavtcs of(String rawGavtcs) {
String[] gavtcArr = rawGavtcs.split(":");
int i = 0;
final String groupId = gavtcArr[i++];
final String artifactId = gavtcArr[i++];
final String version = gavtcArr[i++];
final String type = i < gavtcArr.length ? emptyToNull(gavtcArr[i++]) : null;
final String classifier = i < gavtcArr.length ? emptyToNull(gavtcArr[i++]) : null;
final String scope = i < gavtcArr.length ? emptyToNull(gavtcArr[i++]) : null;
return new Gavtcs(groupId, artifactId, version, type, classifier, scope);
}
private static String emptyToNull(String string) {
return string != null && !string.isEmpty() ? string : null;
}
private final String groupId;
private final String artifactId;
private final String version;
private final String type;
private final String classifier;
private final String scope;
public Gavtcs(String groupId, String artifactId, String version) {
this(groupId, artifactId, version, null, null, null);
}
public Gavtcs(String groupId, String artifactId, String version, String type, String classifier, String scope) {
super();
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.type = type;
this.classifier = classifier;
this.scope = scope;
}
public String getGroupId() {
return groupId;
}
public String getArtifactId() {
return artifactId;
}
public String getVersion() {
return version;
}
public String getType() {
return type;
}
public String getClassifier() {
return classifier;
}
public String getScope() {
return scope;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder().append(groupId).append(':').append(artifactId).append(':')
.append(version);
if (type != null || classifier != null || scope != null) {
sb.append(':');
if (type != null) {
sb.append(type);
}
if (classifier != null || scope != null) {
sb.append(':');
if (classifier != null) {
sb.append(classifier);
}
if (scope != null) {
sb.append(':').append(scope);
}
}
}
return sb.toString();
}
}
}
| Gavtcs |
java | spring-projects__spring-framework | spring-expression/src/test/java/org/springframework/expression/spel/IndexingTests.java | {
"start": 32162,
"end": 33430
} | class ____ implements IndexAccessor {
private final ObjectMapper objectMapper;
JacksonArrayNodeIndexAccessor(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public Class<?>[] getSpecificTargetClasses() {
return new Class<?>[] { ArrayNode.class };
}
@Override
public boolean canRead(EvaluationContext context, Object target, Object index) {
return (target instanceof ArrayNode && index instanceof Integer);
}
@Override
public TypedValue read(EvaluationContext context, Object target, Object index) {
ArrayNode arrayNode = (ArrayNode) target;
Integer intIndex = (Integer) index;
return new TypedValue(arrayNode.get(intIndex));
}
@Override
public boolean canWrite(EvaluationContext context, Object target, Object index) {
return canRead(context, target, index);
}
@Override
public void write(EvaluationContext context, Object target, Object index, @Nullable Object newValue) {
ArrayNode arrayNode = (ArrayNode) target;
Integer intIndex = (Integer) index;
arrayNode.set(intIndex, this.objectMapper.convertValue(newValue, JsonNode.class));
}
}
}
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@ | JacksonArrayNodeIndexAccessor |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/type/CustomType.java | {
"start": 1933,
"end": 12556
} | class ____<J>
extends AbstractType
implements ConvertedBasicType<J>, ProcedureParameterNamedBinder<J>, ProcedureParameterExtractionAware<J> {
private final UserType<J> userType;
private final String[] registrationKeys;
private final String name;
private final JavaType<J> mappedJavaType;
private final JavaType<?> jdbcJavaType;
private final JdbcType jdbcType;
private final ValueExtractor<J> valueExtractor;
private final ValueBinder<J> valueBinder;
private final JdbcLiteralFormatter<J> jdbcLiteralFormatter;
private final BasicValueConverter<J, ?> converter;
public CustomType(UserType<J> userType, TypeConfiguration typeConfiguration) throws MappingException {
this( userType, EMPTY_STRING_ARRAY, typeConfiguration );
}
public CustomType(UserType<J> userType, String[] registrationKeys, TypeConfiguration typeConfiguration) {
this.userType = userType;
this.registrationKeys = registrationKeys;
name = userType.getClass().getName();
mappedJavaType = getMappedJavaType( userType );
final var valueConverter = userType.getValueConverter();
if ( valueConverter != null ) {
converter = createValueConverter( valueConverter, typeConfiguration.getJavaTypeRegistry() );
// When an explicit value converter is given,
// we configure the custom type to use that instead of adapters that delegate to UserType.
// This is necessary to support selecting a column with multiple domain type representations.
jdbcType = typeConfiguration.getJdbcTypeRegistry().getDescriptor( userType.getSqlType() );
jdbcJavaType = converter.getRelationalJavaType();
//noinspection unchecked
valueExtractor = (ValueExtractor<J>) jdbcType.getExtractor( jdbcJavaType );
//noinspection unchecked
valueBinder = (ValueBinder<J>) jdbcType.getBinder( jdbcJavaType );
//noinspection unchecked
jdbcLiteralFormatter = (JdbcLiteralFormatter<J>) jdbcType.getJdbcLiteralFormatter( jdbcJavaType );
}
else {
// create a JdbcType adapter that uses the UserType binder/extract handling
jdbcType = new UserTypeJdbcTypeAdapter<>( userType, mappedJavaType );
jdbcJavaType = jdbcType.getJdbcRecommendedJavaTypeMapping( null, null, typeConfiguration );
valueExtractor = jdbcType.getExtractor( mappedJavaType );
valueBinder = jdbcType.getBinder( mappedJavaType );
jdbcLiteralFormatter =
userType instanceof EnhancedUserType
? jdbcType.getJdbcLiteralFormatter( mappedJavaType )
: null;
converter = null;
}
}
private JavaType<J> getMappedJavaType(UserType<J> userType) {
return userType instanceof UserVersionType<J> userVersionType
? new UserTypeVersionJavaTypeWrapper<>( userVersionType, this )
: new UserTypeJavaTypeWrapper<>( userType, this );
}
public UserType<J> getUserType() {
return userType;
}
@Override
public ValueExtractor<J> getJdbcValueExtractor() {
return valueExtractor;
}
@Override
public ValueBinder<J> getJdbcValueBinder() {
return valueBinder;
}
@Override
public JdbcLiteralFormatter<J> getJdbcLiteralFormatter() {
return jdbcLiteralFormatter;
}
@Override
public JdbcType getJdbcType() {
return jdbcType;
}
@Override
public int[] getSqlTypeCodes(MappingContext mappingContext) {
return new int[] { jdbcType.getDdlTypeCode() };
}
@Override
public String[] getRegistrationKeys() {
return registrationKeys;
}
@Override
public int getColumnSpan(MappingContext session) {
return 1;
}
@Override
public Class<J> getReturnedClass() {
return getUserType().returnedClass();
}
@Override
public boolean isEqual(Object x, Object y) throws HibernateException {
return getUserType().equals( (J) x, (J) y );
}
@Override
public int getHashCode(Object x) {
return getUserType().hashCode( (J) x );
}
@Override
public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) {
final J assembled = getUserType().assemble( cached, owner );
// Since UserType#assemble is an optional operation,
// we have to handle the fact that it could produce a null value,
// in which case we will try to use a converter for assembling,
// or if that doesn't exist, simply use the relational value as is
return assembled == null && cached != null
? convertToDomainValue( cached )
: assembled;
}
@Override
public Serializable disassemble(Object value, SharedSessionContractImplementor session, Object owner) {
return disassembleForCache( value );
}
@Override
public Serializable disassemble(Object value, SessionFactoryImplementor sessionFactory) {
return disassembleForCache( value );
}
private Serializable disassembleForCache(Object value) {
final Serializable disassembled = getUserType().disassemble( (J) value );
// Since UserType#disassemble is an optional operation,
// we have to handle the fact that it could produce a null value,
// in which case we will try to use a converter for disassembling,
// or if that doesn't exist, simply use the domain value as is
return disassembled == null
? (Serializable) convertToRelationalValue( (J) value )
: disassembled;
}
@Override
public Object disassemble(Object value, SharedSessionContractImplementor session) {
// Use the value converter if available for conversion to the jdbc representation
return convertToRelationalValue( (J) value );
}
@Override
public void addToCacheKey(MutableCacheKeyBuilder cacheKey, Object value, SharedSessionContractImplementor session) {
final Serializable disassembled = getUserType().disassemble( (J) value );
// Since UserType#disassemble is an optional operation,
// we have to handle the fact that it could produce a null value,
// in which case we will try to use a converter for disassembling,
// or if that doesn't exist, simply use the domain value as is
if ( disassembled == null) {
CacheHelper.addBasicValueToCacheKey( cacheKey, value, this, session );
}
else {
cacheKey.addValue( disassembled );
cacheKey.addHashCode( value == null ? 0 : getUserType().hashCode( (J) value ) );
}
}
@Override
public Object replace(
Object original,
Object target,
SharedSessionContractImplementor session,
Object owner,
Map<Object, Object> copyCache) {
return getUserType().replace( (J) original, (J) target, owner );
}
@Override
public void nullSafeSet(
PreparedStatement st,
Object value,
int index,
boolean[] settable,
SharedSessionContractImplementor session) throws SQLException {
if ( settable[0] ) {
//noinspection unchecked
getUserType().nullSafeSet( st, (J) value, index, session );
}
}
@Override
public void nullSafeSet(
PreparedStatement st,
Object value,
int index,
SharedSessionContractImplementor session) throws SQLException {
//noinspection unchecked
getUserType().nullSafeSet( st, (J) value, index, session );
}
@Override
public String getName() {
return name;
}
@Override
public Object deepCopy(Object value, SessionFactoryImplementor factory) throws HibernateException {
return getUserType().deepCopy( (J) value );
}
@Override
public boolean isMutable() {
return getUserType().isMutable();
}
@Override
public String toLoggableString(Object value, SessionFactoryImplementor factory) {
if ( value == null ) {
return "null";
}
else if ( userType instanceof LoggableUserType loggableUserType ) {
return loggableUserType.toLoggableString( value, factory );
}
else if ( userType instanceof EnhancedUserType<?> ) {
return ( (EnhancedUserType<Object>) userType ).toString( value );
}
else {
return value.toString();
}
}
@Override
public boolean[] toColumnNullness(Object value, MappingContext mapping) {
final boolean[] result = new boolean[ getColumnSpan(mapping) ];
if ( value != null ) {
Arrays.fill( result, true );
}
return result;
}
@Override
public boolean isDirty(Object old, Object current, boolean[] checkable, SharedSessionContractImplementor session)
throws HibernateException {
return checkable[0] && isDirty( old, current, session );
}
@Override
public boolean canDoSetting() {
return getUserType() instanceof ProcedureParameterNamedBinder<?> procedureParameterNamedBinder
&& procedureParameterNamedBinder.canDoSetting();
}
@Override
public void nullSafeSet(CallableStatement statement, J value, String name, SharedSessionContractImplementor session)
throws SQLException {
if ( canDoSetting() ) {
//noinspection unchecked
( (ProcedureParameterNamedBinder<J>) getUserType() )
.nullSafeSet( statement, value, name, session );
}
else {
throw new UnsupportedOperationException(
"Type [" + getUserType() + "] does support parameter binding by name"
);
}
}
@Override
public boolean canDoExtraction() {
return getUserType() instanceof ProcedureParameterExtractionAware<?> procedureParameterExtractionAware
&& procedureParameterExtractionAware.canDoExtraction();
}
@Override
public J extract(CallableStatement statement, int startIndex, SharedSessionContractImplementor session)
throws SQLException {
if ( canDoExtraction() ) {
//noinspection unchecked
return ((ProcedureParameterExtractionAware<J>) getUserType() )
.extract( statement, startIndex, session );
}
else {
throw new UnsupportedOperationException(
"Type [" + getUserType() + "] does support parameter value extraction"
);
}
}
@Override
public J extract(CallableStatement statement, String paramName, SharedSessionContractImplementor session)
throws SQLException {
if ( canDoExtraction() ) {
//noinspection unchecked
return ((ProcedureParameterExtractionAware<J>) getUserType() )
.extract( statement, paramName, session );
}
else {
throw new UnsupportedOperationException(
"Type [" + getUserType() + "] does support parameter value extraction"
);
}
}
@Override
public int hashCode() {
return getUserType().hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof CustomType<?> customType
&& getUserType().equals( customType.getUserType() );
}
@Override
public Class<J> getJavaType() {
return mappedJavaType.getJavaTypeClass();
}
@Override
public JavaType<J> getMappedJavaType() {
return mappedJavaType;
}
@Override
public JavaType<J> getExpressibleJavaType() {
return this.getMappedJavaType();
}
@Override
public JavaType<J> getJavaTypeDescriptor() {
return this.getMappedJavaType();
}
@Override
public JavaType<?> getJdbcJavaType() {
return jdbcJavaType;
}
@Override
public BasicValueConverter<J, ?> getValueConverter() {
return converter;
}
}
| CustomType |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Adaptive_Test.java | {
"start": 8472,
"end": 11377
} | class ____ interface "));
assertThat(
expected.getMessage(),
containsString(": not found url parameter or url attribute in parameters of method "));
}
}
@Test
void test_urlHolder_getAdaptiveExtension() throws Exception {
Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension();
Map<String, String> map = new HashMap<String, String>();
map.put("ext2", "impl1");
URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1", map);
UrlHolder holder = new UrlHolder();
holder.setUrl(url);
String echo = ext.echo(holder, "haha");
assertEquals("Ext2Impl1-echo", echo);
}
@Test
void test_urlHolder_getAdaptiveExtension_noExtension() throws Exception {
Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension();
URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1");
UrlHolder holder = new UrlHolder();
holder.setUrl(url);
try {
ext.echo(holder, "haha");
fail();
} catch (IllegalStateException expected) {
assertThat(expected.getMessage(), containsString("Failed to get extension"));
}
url = url.addParameter("ext2", "XXX");
holder.setUrl(url);
try {
ext.echo(holder, "haha");
fail();
} catch (IllegalStateException expected) {
assertThat(expected.getMessage(), containsString("No such extension"));
}
}
@Test
void test_urlHolder_getAdaptiveExtension_UrlNpe() throws Exception {
Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension();
try {
ext.echo(null, "haha");
fail();
} catch (IllegalArgumentException e) {
assertEquals("org.apache.dubbo.common.extension.ext2.UrlHolder argument == null", e.getMessage());
}
try {
ext.echo(new UrlHolder(), "haha");
fail();
} catch (IllegalArgumentException e) {
assertEquals("org.apache.dubbo.common.extension.ext2.UrlHolder argument getUrl() == null", e.getMessage());
}
}
@Test
void test_urlHolder_getAdaptiveExtension_ExceptionWhenNotAdativeMethod() throws Exception {
Ext2 ext = ExtensionLoader.getExtensionLoader(Ext2.class).getAdaptiveExtension();
Map<String, String> map = new HashMap<String, String>();
URL url = new ServiceConfigURL("p1", "1.2.3.4", 1010, "path1", map);
try {
ext.bang(url, 33);
fail();
} catch (UnsupportedOperationException expected) {
assertThat(expected.getMessage(), containsString("method "));
assertThat(
expected.getMessage(),
containsString("of | for |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfAndDirtiesContextTests.java | {
"start": 2886,
"end": 3024
} | class ____ {
@Test
void test() {
fail("This test must be disabled");
}
}
@Configuration
static | DisabledAndDirtiesContextTestCase |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/security/TestGroupsCaching.java | {
"start": 7729,
"end": 29010
} | class ____ extends FakeGroupMapping {
private static boolean invoked = false;
@Override
public List<String> getGroups(String user) throws IOException {
invoked = true;
return super.getGroups(user);
}
}
/*
* Group lookup should not happen for static users
*/
@Test
public void testGroupLookupForStaticUsers() throws Exception {
conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING,
FakeunPrivilegedGroupMapping.class, ShellBasedUnixGroupsMapping.class);
conf.set(CommonConfigurationKeys.HADOOP_USER_GROUP_STATIC_OVERRIDES, "me=;user1=group1;user2=group1,group2");
Groups groups = new Groups(conf);
List<String> userGroups = groups.getGroups("me");
assertTrue(userGroups.isEmpty(), "non-empty groups for static user");
assertFalse(FakeunPrivilegedGroupMapping.invoked,
"group lookup done for static user");
List<String> expected = new ArrayList<String>();
expected.add("group1");
FakeunPrivilegedGroupMapping.invoked = false;
userGroups = groups.getGroups("user1");
assertTrue(expected.equals(userGroups), "groups not correct");
assertFalse(FakeunPrivilegedGroupMapping.invoked,
"group lookup done for unprivileged user");
expected.add("group2");
FakeunPrivilegedGroupMapping.invoked = false;
userGroups = groups.getGroups("user2");
assertTrue(expected.equals(userGroups), "groups not correct");
assertFalse(FakeunPrivilegedGroupMapping.invoked,
"group lookup done for unprivileged user");
}
@Test
public void testNegativeGroupCaching() throws Exception {
final String user = "negcache";
final String failMessage = "Did not throw IOException: ";
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_NEGATIVE_CACHE_SECS, 2);
FakeTimer timer = new FakeTimer();
Groups groups = new Groups(conf, timer);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.addToBlackList(user);
// In the first attempt, the user will be put in the negative cache.
try {
groups.getGroups(user);
fail(failMessage + "Failed to obtain groups from FakeGroupMapping.");
} catch (IOException e) {
// Expects to raise exception for the first time. But the user will be
// put into the negative cache
GenericTestUtils.assertExceptionContains("No groups found for user", e);
}
// The second time, the user is in the negative cache.
try {
groups.getGroups(user);
fail(failMessage + "The user is in the negative cache.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("No groups found for user", e);
}
// Brings back the backend user-group mapping service.
FakeGroupMapping.clearBlackList();
// It should still get groups from the negative cache.
try {
groups.getGroups(user);
fail(failMessage + "The user is still in the negative cache, even " +
"FakeGroupMapping has resumed.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("No groups found for user", e);
}
// Let the elements in the negative cache expire.
timer.advance(4 * 1000);
// The groups for the user is expired in the negative cache, a new copy of
// groups for the user is fetched.
assertEquals(Arrays.asList(myGroups), groups.getGroups(user));
}
@Test
public void testCachePreventsImplRequest() throws Exception {
// Disable negative cache.
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_NEGATIVE_CACHE_SECS, 0);
Groups groups = new Groups(conf);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
assertEquals(0, FakeGroupMapping.getRequestCount());
// First call hits the wire
assertTrue(groups.getGroups("me").size() == 2);
assertEquals(1, FakeGroupMapping.getRequestCount());
// Second count hits cache
assertTrue(groups.getGroups("me").size() == 2);
assertEquals(1, FakeGroupMapping.getRequestCount());
}
@Test
public void testExceptionsFromImplNotCachedInNegativeCache() {
conf.setClass(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING,
ExceptionalGroupMapping.class,
ShellBasedUnixGroupsMapping.class);
conf.setLong(CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_NEGATIVE_CACHE_SECS, 10000);
Groups groups = new Groups(conf);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
assertEquals(0, ExceptionalGroupMapping.getRequestCount());
// First call should hit the wire
try {
groups.getGroups("anything");
fail("Should have thrown");
} catch (IOException e) {
// okay
}
assertEquals(1, ExceptionalGroupMapping.getRequestCount());
// Second call should hit the wire (no negative caching)
try {
groups.getGroups("anything");
fail("Should have thrown");
} catch (IOException e) {
// okay
}
assertEquals(2, ExceptionalGroupMapping.getRequestCount());
}
@Test
public void testOnlyOneRequestWhenNoEntryIsCached() throws Exception {
// Disable negative cache.
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_NEGATIVE_CACHE_SECS, 0);
final Groups groups = new Groups(conf);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
FakeGroupMapping.setGetGroupsDelayMs(100);
ArrayList<SubjectInheritingThread> threads = new ArrayList<SubjectInheritingThread>();
for (int i = 0; i < 10; i++) {
threads.add(new SubjectInheritingThread() {
public void work() {
try {
assertEquals(2, groups.getGroups("me").size());
} catch (IOException e) {
fail("Should not happen");
}
}
});
}
// We start a bunch of threads who all see no cached value
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
t.join();
}
// But only one thread should have made the request
assertEquals(1, FakeGroupMapping.getRequestCount());
}
@Test
public void testOnlyOneRequestWhenExpiredEntryExists() throws Exception {
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS, 1);
FakeTimer timer = new FakeTimer();
final Groups groups = new Groups(conf, timer);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
FakeGroupMapping.setGetGroupsDelayMs(100);
// We make an initial request to populate the cache
groups.getGroups("me");
int startingRequestCount = FakeGroupMapping.getRequestCount();
// Then expire that entry
timer.advance(400 * 1000);
Thread.sleep(100);
ArrayList<SubjectInheritingThread> threads = new ArrayList<SubjectInheritingThread>();
for (int i = 0; i < 10; i++) {
threads.add(new SubjectInheritingThread() {
public void work() {
try {
assertEquals(2, groups.getGroups("me").size());
} catch (IOException e) {
fail("Should not happen");
}
}
});
}
// We start a bunch of threads who all see the cached value
for (Thread t : threads) {
t.start();
}
for (Thread t : threads) {
t.join();
}
// Only one extra request is made
assertEquals(startingRequestCount + 1, FakeGroupMapping.getRequestCount());
}
@Test
public void testThreadNotBlockedWhenExpiredEntryExistsWithBackgroundRefresh()
throws Exception {
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS, 1);
conf.setBoolean(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_BACKGROUND_RELOAD,
true);
FakeTimer timer = new FakeTimer();
final Groups groups = new Groups(conf, timer);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
// We make an initial request to populate the cache
groups.getGroups("me");
// Further lookups will have a delay
FakeGroupMapping.setGetGroupsDelayMs(100);
// add another groups
groups.cacheGroupsAdd(Arrays.asList("grp3"));
int startingRequestCount = FakeGroupMapping.getRequestCount();
// Then expire that entry
timer.advance(4 * 1000);
// Now get the cache entry - it should return immediately
// with the old value and the cache will not have completed
// a request to getGroups yet.
assertThat(groups.getGroups("me").size()).isEqualTo(2);
assertEquals(startingRequestCount, FakeGroupMapping.getRequestCount());
// Now sleep for over the delay time and the request count should
// have completed
Thread.sleep(110);
assertEquals(startingRequestCount + 1, FakeGroupMapping.getRequestCount());
// Another call to get groups should give 3 groups instead of 2
assertThat(groups.getGroups("me").size()).isEqualTo(3);
}
@Test
public void testThreadBlockedWhenExpiredEntryExistsWithoutBackgroundRefresh()
throws Exception {
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS, 1);
conf.setBoolean(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_BACKGROUND_RELOAD,
false);
FakeTimer timer = new FakeTimer();
final Groups groups = new Groups(conf, timer);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
// We make an initial request to populate the cache
groups.getGroups("me");
// Further lookups will have a delay
FakeGroupMapping.setGetGroupsDelayMs(100);
// add another group
groups.cacheGroupsAdd(Arrays.asList("grp3"));
int startingRequestCount = FakeGroupMapping.getRequestCount();
// Then expire that entry
timer.advance(4 * 1000);
// Now get the cache entry - it should block and return the new
// 3 group value
assertThat(groups.getGroups("me").size()).isEqualTo(3);
assertEquals(startingRequestCount + 1, FakeGroupMapping.getRequestCount());
}
@Test
public void testExceptionOnBackgroundRefreshHandled() throws Exception {
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS, 1);
conf.setBoolean(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_BACKGROUND_RELOAD,
true);
FakeTimer timer = new FakeTimer();
final Groups groups = new Groups(conf, timer);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
// We make an initial request to populate the cache
List<String> g1 = groups.getGroups("me");
// add another group
groups.cacheGroupsAdd(Arrays.asList("grp3"));
int startingRequestCount = FakeGroupMapping.getRequestCount();
// Arrange for an exception to occur only on the
// second call
FakeGroupMapping.setThrowException(true);
// Then expire that entry
timer.advance(4 * 1000);
// Pause the getGroups operation and this will delay the cache refresh
FakeGroupMapping.pause();
// Now get the cache entry - it should return immediately
// with the old value and the cache will not have completed
// a request to getGroups yet.
assertThat(groups.getGroups("me").size()).isEqualTo(2);
assertEquals(startingRequestCount, FakeGroupMapping.getRequestCount());
// Resume the getGroups operation and the cache can get refreshed
FakeGroupMapping.resume();
// Now wait for the refresh done, because of the exception, we expect
// a onFailure callback gets called and the counter for failure is 1
waitForGroupCounters(groups, 0, 0, 0, 1);
FakeGroupMapping.setThrowException(false);
assertEquals(startingRequestCount + 1, FakeGroupMapping.getRequestCount());
assertThat(groups.getGroups("me").size()).isEqualTo(2);
// Now the 3rd call to getGroups above will have kicked off
// another refresh that updates the cache, since it no longer gives
// exception, we now expect the counter for success is 1.
waitForGroupCounters(groups, 0, 0, 1, 1);
assertEquals(startingRequestCount + 2, FakeGroupMapping.getRequestCount());
assertThat(groups.getGroups("me").size()).isEqualTo(3);
}
@Test
public void testEntriesExpireIfBackgroundRefreshFails() throws Exception {
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS, 1);
conf.setBoolean(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_BACKGROUND_RELOAD,
true);
FakeTimer timer = new FakeTimer();
final Groups groups = new Groups(conf, timer);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
// We make an initial request to populate the cache
groups.getGroups("me");
// Now make all calls to the FakeGroupMapper throw exceptions
FakeGroupMapping.setThrowException(true);
// The cache entry expires for refresh after 1 second
// It expires for eviction after 1 * 10 seconds after it was last written
// So if we call getGroups repeatedly over 9 seconds, 9 refreshes should
// be triggered which will fail to update the key, but the keys old value
// will be retrievable until it is evicted after about 10 seconds.
for(int i=0; i<9; i++) {
assertThat(groups.getGroups("me").size()).isEqualTo(2);
timer.advance(1 * 1000);
}
// Wait until the 11th second. The call to getGroups should throw
// an exception as the key will have been evicted and FakeGroupMapping
// will throw IO Exception when it is asked for new groups. In this case
// load must be called synchronously as there is no key present
timer.advance(2 * 1000);
try {
groups.getGroups("me");
fail("Should have thrown an exception here");
} catch (Exception e) {
// pass
}
// Finally check groups are retrieve again after FakeGroupMapping
// stops throw exceptions
FakeGroupMapping.setThrowException(false);
assertThat(groups.getGroups("me").size()).isEqualTo(2);
}
@Test
public void testBackgroundRefreshCounters()
throws IOException, InterruptedException {
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS, 1);
conf.setBoolean(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_BACKGROUND_RELOAD,
true);
conf.setInt(
CommonConfigurationKeys.
HADOOP_SECURITY_GROUPS_CACHE_BACKGROUND_RELOAD_THREADS,
2);
FakeTimer timer = new FakeTimer();
final Groups groups = new Groups(conf, timer);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
// populate the cache
String[] grps = {"one", "two", "three", "four", "five"};
for (String g: grps) {
groups.getGroups(g);
}
// expire the cache
timer.advance(2*1000);
FakeGroupMapping.pause();
// Request all groups again, as there are 2 threads to process them
// 3 should get queued and 2 should be running
for (String g: grps) {
groups.getGroups(g);
}
waitForGroupCounters(groups, 3, 2, 0, 0);
FakeGroupMapping.resume();
// Once resumed, all results should be returned immediately
waitForGroupCounters(groups, 0, 0, 5, 0);
// Now run again, this time throwing exceptions but no delay
timer.advance(2*1000);
FakeGroupMapping.setGetGroupsDelayMs(0);
FakeGroupMapping.setThrowException(true);
for (String g: grps) {
groups.getGroups(g);
}
waitForGroupCounters(groups, 0, 0, 5, 5);
}
private void waitForGroupCounters(Groups groups, long expectedQueued,
long expectedRunning, long expectedSuccess, long expectedExpection)
throws InterruptedException {
long[] expected = {expectedQueued, expectedRunning,
expectedSuccess, expectedExpection};
long[] actual = new long[expected.length];
// wait for a certain time until the counters reach
// to expected values. Check values in 20 ms interval.
try {
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
actual[0] = groups.getBackgroundRefreshQueued();
actual[1] = groups.getBackgroundRefreshRunning();
actual[2] = groups.getBackgroundRefreshSuccess();
actual[3] = groups.getBackgroundRefreshException();
return Arrays.equals(actual, expected);
}
}, 20, 1000);
} catch (TimeoutException e) {
fail("Excepted group counter values are not reached in given time,"
+ " expecting (Queued, Running, Success, Exception) : "
+ Arrays.toString(expected) + " but actual : "
+ Arrays.toString(actual));
}
}
@Test
public void testExceptionCallingLoadWithoutBackgroundRefreshReturnsOldValue()
throws Exception {
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS, 1);
conf.setBoolean(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_BACKGROUND_RELOAD,
false);
FakeTimer timer = new FakeTimer();
final Groups groups = new Groups(conf, timer);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
// First populate the cash
assertThat(groups.getGroups("me").size()).isEqualTo(2);
// Advance the timer so a refresh is required
timer.advance(2 * 1000);
// This call should throw an exception
FakeGroupMapping.setThrowException(true);
assertThat(groups.getGroups("me").size()).isEqualTo(2);
}
@Test
public void testCacheEntriesExpire() throws Exception {
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_CACHE_SECS, 1);
FakeTimer timer = new FakeTimer();
final Groups groups = new Groups(conf, timer);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
// We make an entry
groups.getGroups("me");
int startingRequestCount = FakeGroupMapping.getRequestCount();
timer.advance(20 * 1000);
// Cache entry has expired so it results in a new fetch
groups.getGroups("me");
assertEquals(startingRequestCount + 1, FakeGroupMapping.getRequestCount());
}
@Test
public void testNegativeCacheClearedOnRefresh() throws Exception {
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_NEGATIVE_CACHE_SECS, 100);
final Groups groups = new Groups(conf);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
FakeGroupMapping.clearBlackList();
FakeGroupMapping.addToBlackList("dne");
try {
groups.getGroups("dne");
fail("Should have failed to find this group");
} catch (IOException e) {
// pass
}
int startingRequestCount = FakeGroupMapping.getRequestCount();
groups.refresh();
FakeGroupMapping.addToBlackList("dne");
try {
List<String> g = groups.getGroups("dne");
fail("Should have failed to find this group");
} catch (IOException e) {
// pass
}
assertEquals(startingRequestCount + 1, FakeGroupMapping.getRequestCount());
}
@Test
public void testNegativeCacheEntriesExpire() throws Exception {
conf.setLong(
CommonConfigurationKeys.HADOOP_SECURITY_GROUPS_NEGATIVE_CACHE_SECS, 2);
FakeTimer timer = new FakeTimer();
// Ensure that stale entries are removed from negative cache every 2 seconds
Groups groups = new Groups(conf, timer);
groups.cacheGroupsAdd(Arrays.asList(myGroups));
groups.refresh();
// Add both these users to blacklist so that they
// can be added to negative cache
FakeGroupMapping.addToBlackList("user1");
FakeGroupMapping.addToBlackList("user2");
// Put user1 in negative cache.
try {
groups.getGroups("user1");
fail("Did not throw IOException : Failed to obtain groups" +
" from FakeGroupMapping.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("No groups found for user", e);
}
// Check if user1 exists in negative cache
assertTrue(groups.getNegativeCache().contains("user1"));
// Advance fake timer
timer.advance(1000);
// Put user2 in negative cache
try {
groups.getGroups("user2");
fail("Did not throw IOException : Failed to obtain groups" +
" from FakeGroupMapping.");
} catch (IOException e) {
GenericTestUtils.assertExceptionContains("No groups found for user", e);
}
// Check if user2 exists in negative cache
assertTrue(groups.getNegativeCache().contains("user2"));
// Advance timer. Only user2 should be present in negative cache.
timer.advance(1100);
assertFalse(groups.getNegativeCache().contains("user1"));
assertTrue(groups.getNegativeCache().contains("user2"));
// Advance timer. Even user2 should not be present in negative cache.
timer.advance(1000);
assertFalse(groups.getNegativeCache().contains("user2"));
}
}
| FakeunPrivilegedGroupMapping |
java | apache__kafka | metadata/src/main/java/org/apache/kafka/image/loader/LoaderManifestType.java | {
"start": 915,
"end": 971
} | enum ____ {
LOG_DELTA,
SNAPSHOT
}
| LoaderManifestType |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/booleanarray/BooleanArrayAssert_containsOnly_with_Boolean_array_Test.java | {
"start": 1209,
"end": 1936
} | class ____ extends BooleanArrayAssertBaseTest {
@Test
void should_fail_if_values_is_null() {
// GIVEN
Boolean[] values = null;
// WHEN
Throwable thrown = catchThrowable(() -> assertions.containsOnly(values));
// THEN
then(thrown).isInstanceOf(NullPointerException.class)
.hasMessage(shouldNotBeNull("values").create());
}
@Override
protected BooleanArrayAssert invoke_api_method() {
return assertions.containsOnly(new Boolean[] { true, false });
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertContainsOnly(getInfo(assertions), getActual(assertions), arrayOf(true, false));
}
}
| BooleanArrayAssert_containsOnly_with_Boolean_array_Test |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/RedisEndpointBuilderFactory.java | {
"start": 22777,
"end": 28486
} | interface ____
extends
RedisEndpointConsumerBuilder,
RedisEndpointProducerBuilder {
default AdvancedRedisEndpointBuilder advanced() {
return (AdvancedRedisEndpointBuilder) this;
}
/**
* List of topic names or name patterns to subscribe to. Multiple names
* can be separated by comma.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: common
*
* @param channels the value to set
* @return the dsl builder
*/
default RedisEndpointBuilder channels(String channels) {
doSetProperty("channels", channels);
return this;
}
/**
* Default command, which can be overridden by message header. Notice
* the consumer only supports the following commands: PSUBSCRIBE and
* SUBSCRIBE.
*
* The option is a:
* <code>org.apache.camel.component.redis.Command</code> type.
*
* Default: SET
* Group: common
*
* @param command the value to set
* @return the dsl builder
*/
default RedisEndpointBuilder command(org.apache.camel.component.redis.Command command) {
doSetProperty("command", command);
return this;
}
/**
* Default command, which can be overridden by message header. Notice
* the consumer only supports the following commands: PSUBSCRIBE and
* SUBSCRIBE.
*
* The option will be converted to a
* <code>org.apache.camel.component.redis.Command</code> type.
*
* Default: SET
* Group: common
*
* @param command the value to set
* @return the dsl builder
*/
default RedisEndpointBuilder command(String command) {
doSetProperty("command", command);
return this;
}
/**
* Reference to a pre-configured RedisConnectionFactory instance to use.
*
* The option is a:
* <code>org.springframework.data.redis.connection.RedisConnectionFactory</code> type.
*
* Group: common
*
* @param connectionFactory the value to set
* @return the dsl builder
*/
default RedisEndpointBuilder connectionFactory(org.springframework.data.redis.connection.RedisConnectionFactory connectionFactory) {
doSetProperty("connectionFactory", connectionFactory);
return this;
}
/**
* Reference to a pre-configured RedisConnectionFactory instance to use.
*
* The option will be converted to a
* <code>org.springframework.data.redis.connection.RedisConnectionFactory</code> type.
*
* Group: common
*
* @param connectionFactory the value to set
* @return the dsl builder
*/
default RedisEndpointBuilder connectionFactory(String connectionFactory) {
doSetProperty("connectionFactory", connectionFactory);
return this;
}
/**
* Reference to a pre-configured RedisTemplate instance to use.
*
* The option is a:
* <code>org.springframework.data.redis.core.RedisTemplate<java.lang.Object, java.lang.Object></code> type.
*
* Group: common
*
* @param redisTemplate the value to set
* @return the dsl builder
*/
default RedisEndpointBuilder redisTemplate(org.springframework.data.redis.core.RedisTemplate<java.lang.Object, java.lang.Object> redisTemplate) {
doSetProperty("redisTemplate", redisTemplate);
return this;
}
/**
* Reference to a pre-configured RedisTemplate instance to use.
*
* The option will be converted to a
* <code>org.springframework.data.redis.core.RedisTemplate<java.lang.Object, java.lang.Object></code> type.
*
* Group: common
*
* @param redisTemplate the value to set
* @return the dsl builder
*/
default RedisEndpointBuilder redisTemplate(String redisTemplate) {
doSetProperty("redisTemplate", redisTemplate);
return this;
}
/**
* Reference to a pre-configured RedisSerializer instance to use.
*
* The option is a:
* <code>org.springframework.data.redis.serializer.RedisSerializer<java.lang.Object></code> type.
*
* Group: common
*
* @param serializer the value to set
* @return the dsl builder
*/
default RedisEndpointBuilder serializer(org.springframework.data.redis.serializer.RedisSerializer<java.lang.Object> serializer) {
doSetProperty("serializer", serializer);
return this;
}
/**
* Reference to a pre-configured RedisSerializer instance to use.
*
* The option will be converted to a
* <code>org.springframework.data.redis.serializer.RedisSerializer<java.lang.Object></code> type.
*
* Group: common
*
* @param serializer the value to set
* @return the dsl builder
*/
default RedisEndpointBuilder serializer(String serializer) {
doSetProperty("serializer", serializer);
return this;
}
}
/**
* Advanced builder for endpoint for the Spring Redis component.
*/
public | RedisEndpointBuilder |
java | apache__camel | core/camel-management/src/main/java/org/apache/camel/management/mbean/ManagedDynamicRouter.java | {
"start": 1721,
"end": 4804
} | class ____ extends ManagedProcessor implements ManagedDynamicRouterMBean {
private String uri;
private boolean sanitize;
public ManagedDynamicRouter(CamelContext context, DynamicRouter processor, DynamicRouterDefinition<?> definition) {
super(context, processor, definition);
}
@Override
public DynamicRouter getProcessor() {
return (DynamicRouter) super.getProcessor();
}
@Override
public DynamicRouterDefinition<?> getDefinition() {
return (DynamicRouterDefinition<?>) super.getDefinition();
}
@Override
public void init(ManagementStrategy strategy) {
super.init(strategy);
sanitize = strategy.getManagementAgent().getMask() != null ? strategy.getManagementAgent().getMask() : true;
uri = getDefinition().getExpression().getExpression();
if (sanitize) {
uri = URISupport.sanitizeUri(uri);
}
}
@Override
public void reset() {
super.reset();
if (getProcessor().getEndpointUtilizationStatistics() != null) {
getProcessor().getEndpointUtilizationStatistics().clear();
}
}
@Override
public String getDestination() {
return uri;
}
@Override
public Boolean getSupportExtendedInformation() {
return true;
}
@Override
public String getExpression() {
return uri;
}
@Override
public String getExpressionLanguage() {
return getDefinition().getExpression().getLanguage();
}
@Override
public String getUriDelimiter() {
return getProcessor().getUriDelimiter();
}
@Override
public Integer getCacheSize() {
return getProcessor().getCacheSize();
}
@Override
public Boolean isIgnoreInvalidEndpoints() {
return getProcessor().isIgnoreInvalidEndpoints();
}
@Override
public TabularData extendedInformation() {
try {
TabularData answer = new TabularDataSupport(CamelOpenMBeanTypes.endpointsUtilizationTabularType());
EndpointUtilizationStatistics stats = getProcessor().getEndpointUtilizationStatistics();
if (stats != null) {
for (Map.Entry<String, Long> entry : stats.getStatistics().entrySet()) {
CompositeType ct = CamelOpenMBeanTypes.endpointsUtilizationCompositeType();
String url = entry.getKey();
if (sanitize) {
url = URISupport.sanitizeUri(url);
}
Long hits = entry.getValue();
if (hits == null) {
hits = 0L;
}
CompositeData data
= new CompositeDataSupport(ct, new String[] { "url", "hits" }, new Object[] { url, hits });
answer.put(data);
}
}
return answer;
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
}
| ManagedDynamicRouter |
java | google__error-prone | core/src/test/java/com/google/errorprone/refaster/testdata/template/BinaryTemplate.java | {
"start": 909,
"end": 1098
} | class ____ {
@BeforeTemplate
public int divide(int a, int b) {
return (a + b) / 2;
}
@AfterTemplate
public int shift(int a, int b) {
return (a + b) >> 1;
}
}
| BinaryTemplate |
java | quarkusio__quarkus | extensions/devservices/common/src/main/java/io/quarkus/devservices/common/ContainerUtil.java | {
"start": 699,
"end": 8305
} | class ____ {
private static final int CONTAINER_SHORT_ID_LENGTH = 12;
/**
* Convert an InspectContainerResponse to a RunningContainer.
*
* @param inspectContainer The container inspect response.
* @return The running container.
*/
public static RunningContainer toRunningContainer(InspectContainerResponse inspectContainer) {
return new RunningContainer(toContainerInfo(inspectContainer), getContainerEnv(inspectContainer));
}
/**
* Convert an InspectContainerResponse to a ContainerInfo.
*
* @param inspectContainer The container inspect response.
* @return The container info.
*/
public static ContainerInfo toContainerInfo(InspectContainerResponse inspectContainer) {
String[] names = inspectContainer.getNetworkSettings().getNetworks().values().stream()
.flatMap(c -> c.getAliases() == null ? Stream.of() : c.getAliases().stream())
.toArray(String[]::new);
return new ContainerInfo(inspectContainer.getId(), names, inspectContainer.getConfig().getImage(),
inspectContainer.getState().getStatus(), getNetworks(inspectContainer),
inspectContainer.getConfig().getLabels(),
getExposedPorts(inspectContainer));
}
private static Map<String, String[]> getNetworks(InspectContainerResponse container) {
NetworkSettings networkSettings = container.getNetworkSettings();
if (networkSettings == null) {
return null;
}
return getNetworks(networkSettings.getNetworks());
}
public static Map<String, String[]> getNetworks(Map<String, ContainerNetwork> networkSettings) {
if (networkSettings == null) {
return null;
}
return networkSettings.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
e -> {
List<String> aliases = e.getValue().getAliases();
return aliases == null ? new String[0] : aliases.toArray(new String[0]);
}));
}
private static ContainerInfo.ContainerPort[] getExposedPorts(InspectContainerResponse inspectContainer) {
return inspectContainer.getNetworkSettings().getPorts().getBindings().entrySet().stream()
.filter(e -> e.getValue() != null)
.flatMap(e -> Arrays.stream(e.getValue())
.map(b -> new ContainerInfo.ContainerPort(b.getHostIp(),
e.getKey().getPort(),
Integer.parseInt(b.getHostPortSpec()),
e.getKey().getProtocol().toString())))
.toArray(ContainerInfo.ContainerPort[]::new);
}
/**
* Get the environment variables for a container.
*
* @param inspectContainer The container info.
* @return A map of environment variables to their values.
*/
public static Map<String, String> getContainerEnv(InspectContainerResponse inspectContainer) {
String[] env = inspectContainer.getConfig().getEnv();
if (env == null) {
return Collections.emptyMap();
}
return Arrays.stream(env)
.map(e -> e.split("=", 2))
.collect(Collectors.toMap(e -> e[0], e -> e.length > 1 ? e[1] : ""));
}
/**
* Get the environment variable configuration for a list of containers.
*
* @param instances A list of suppliers that provide the container info.
* @param envVarMappingHint A function that maps the container environment variable to config key.
* @return A map of config keys to their values.
*/
public static Map<String, String> getEnvVarConfig(List<? extends Supplier<InspectContainerResponse>> instances,
Function<InspectContainerResponse, Map<String, String>> envVarMappingHint) {
Map<String, String> configs = new HashMap<>();
for (Supplier<InspectContainerResponse> containerResponseSupplier : instances) {
configs.putAll(getEnvVarConfig(containerResponseSupplier, envVarMappingHint));
}
return configs;
}
/**
* Get the environment variable configuration for a container.
*
* @param containerInfoSupplier A supplier that provides the container info.
* @param envVarMappingHint A function that maps the container environment variable to config key.
* @return A map of environment variables to their values.
*/
public static Map<String, String> getEnvVarConfig(Supplier<InspectContainerResponse> containerInfoSupplier,
Function<InspectContainerResponse, Map<String, String>> envVarMappingHint) {
Map<String, String> configs = new HashMap<>();
InspectContainerResponse containerInfo = containerInfoSupplier.get();
// container env var -> env var
Map<String, String> mappings = envVarMappingHint.apply(containerInfo);
if (mappings != null && !mappings.isEmpty()) {
Map<String, String> containerEnv = getContainerEnv(containerInfo);
mappings.forEach((k, v) -> {
String value = containerEnv.get(k);
if (value != null) {
configs.put(v, value);
}
});
}
return configs;
}
/**
* Get the port configuration for a list of containers.
*
* @param instances A list of suppliers that provide the container info.
* @param envVarMappingHint A function that maps the container port to a config key.
* @return A map of config keys to their values.
*/
public static Map<String, String> getPortConfig(List<? extends Supplier<InspectContainerResponse>> instances,
Function<InspectContainerResponse, Map<Integer, String>> envVarMappingHint) {
Map<String, String> configs = new HashMap<>();
for (Supplier<InspectContainerResponse> containerResponseSupplier : instances) {
configs.putAll(getPortConfig(containerResponseSupplier, envVarMappingHint));
}
return configs;
}
/**
* Get the port configuration for a container.
*
* @param containerResponseSupplier A supplier that provides the container info.
* @param envVarMappingHint A function that maps the container port to a config key.
* @return A map of config keys to their values.
*/
public static Map<String, String> getPortConfig(Supplier<InspectContainerResponse> containerResponseSupplier,
Function<InspectContainerResponse, Map<Integer, String>> envVarMappingHint) {
Map<String, String> configs = new HashMap<>();
InspectContainerResponse containerInfo = containerResponseSupplier.get();
// container port -> env var
Map<Integer, String> mappings = envVarMappingHint.apply(containerInfo);
if (mappings != null && !mappings.isEmpty()) {
mappings.forEach((containerPort, envVar) -> {
for (ContainerInfo.ContainerPort exposedPort : getExposedPorts(containerInfo)) {
if (Objects.equals(exposedPort.privatePort(), containerPort)) {
configs.put(envVar, String.valueOf(exposedPort.publicPort()));
break;
}
}
});
}
return configs;
}
public static String getShortId(String id) {
return id.length() > CONTAINER_SHORT_ID_LENGTH ? id.substring(0, CONTAINER_SHORT_ID_LENGTH) : id;
}
}
| ContainerUtil |
java | bumptech__glide | integration/recyclerview/src/main/java/com/bumptech/glide/integration/recyclerview/RecyclerViewPreloader.java | {
"start": 1110,
"end": 1397
} | class ____ works with {@link androidx.recyclerview.widget.LinearLayoutManager} and
* subclasses of {@link androidx.recyclerview.widget.LinearLayoutManager}.
*
* @param <T> The type of the model being displayed in the {@link RecyclerView}.
*/
@SuppressWarnings("unused")
public final | only |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/dynamic/support/ParametrizedTypeInformationUnitTests.java | {
"start": 3846,
"end": 3911
} | interface ____ extends List<Number> {
}
static | ListOfNumber |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/common/network/ThreadWatchdogIT.java | {
"start": 2245,
"end": 3112
} | class ____ extends ESIntegTestCase {
@Override
protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal, otherSettings))
.put(ThreadWatchdog.NETWORK_THREAD_WATCHDOG_INTERVAL.getKey(), "100ms")
.put(ThreadWatchdog.NETWORK_THREAD_WATCHDOG_QUIET_TIME.getKey(), "0")
.build();
}
@SuppressWarnings("unchecked")
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return CollectionUtils.appendToCopyNoNullElements(
super.nodePlugins(),
SlowRequestProcessingPlugin.class,
MockTransportService.TestPlugin.class
);
}
@Override
protected boolean addMockHttpTransport() {
return false;
}
public static | ThreadWatchdogIT |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessor.java | {
"start": 30563,
"end": 31176
} | class ____ implements TypeFilter {
private int excludedCount;
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException {
String className = metadataReader.getClassMetadata().getClassName();
boolean excluded = servicePackagesHolder.isClassScanned(className);
if (excluded) {
excludedCount++;
}
return excluded;
}
public int getExcludedCount() {
return excludedCount;
}
}
}
| ScanExcludeFilter |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/issues/CustomIdIssuesTest.java | {
"start": 1561,
"end": 2632
} | class ____ extends SpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/spring/issues/CustomIdIssueTest.xml");
}
@Test
public void testCustomId() {
RouteDefinition route = context.getRouteDefinition("myRoute");
assertNotNull(route);
assertTrue(route.hasCustomIdAssigned());
FromDefinition from = route.getInput();
assertEquals("fromFile", from.getId());
assertTrue(from.hasCustomIdAssigned());
ChoiceDefinition choice = (ChoiceDefinition) route.getOutputs().get(0);
assertEquals("myChoice", choice.getId());
assertTrue(choice.hasCustomIdAssigned());
WhenDefinition when = choice.getWhenClauses().get(0);
assertTrue(when.hasCustomIdAssigned());
assertEquals("UK", when.getId());
LogDefinition log = (LogDefinition) choice.getOtherwise().getOutputs().get(0);
assertFalse(log.hasCustomIdAssigned());
}
}
| CustomIdIssuesTest |
java | apache__camel | core/camel-management/src/test/java/org/apache/camel/management/ManagedRouteUpdateRouteFromXmlTest.java | {
"start": 1351,
"end": 6084
} | class ____ extends ManagementTestSupport {
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
// enable updating route
context.getManagementStrategy().getManagementAgent().setUpdateRouteEnabled(true);
return context;
}
@Test
public void testUpdateRouteFromXml() throws Exception {
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = getRouteObjectName(mbeanServer);
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
// should be started
String routeId = (String) mbeanServer.getAttribute(on, "RouteId");
assertEquals("myRoute", routeId);
String xml = "<route id=\"myRoute\" xmlns=\"http://camel.apache.org/schema/spring\">"
+ " <from uri=\"direct:start\"/>"
+ " <log message=\"This is a changed route saying ${body}\"/>"
+ " <to uri=\"mock:changed\"/>"
+ "</route>";
mbeanServer.invoke(on, "updateRouteFromXml", new Object[] { xml }, new String[] { "java.lang.String" });
assertEquals(1, context.getRoutes().size());
getMockEndpoint("mock:changed").expectedMessageCount(1);
template.sendBody("direct:start", "Bye World");
assertMockEndpointsSatisfied();
}
@Test
public void testUpdateRouteFromXmlWithoutRouteId() throws Exception {
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = getRouteObjectName(mbeanServer);
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
// should be started
String routeId = (String) mbeanServer.getAttribute(on, "RouteId");
assertEquals("myRoute", routeId);
String xml = "<route xmlns=\"http://camel.apache.org/schema/spring\">"
+ " <from uri=\"direct:start\"/>"
+ " <log message=\"This is a changed route saying ${body}\"/>"
+ " <to uri=\"mock:changed\"/>"
+ "</route>";
mbeanServer.invoke(on, "updateRouteFromXml", new Object[] { xml }, new String[] { "java.lang.String" });
assertEquals(1, context.getRoutes().size());
getMockEndpoint("mock:changed").expectedMessageCount(1);
template.sendBody("direct:start", "Bye World");
assertMockEndpointsSatisfied();
}
@Test
public void testUpdateRouteFromXmlMismatchRouteId() throws Exception {
MBeanServer mbeanServer = getMBeanServer();
ObjectName on = getRouteObjectName(mbeanServer);
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello World");
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
// should be started
String routeId = (String) mbeanServer.getAttribute(on, "RouteId");
assertEquals("myRoute", routeId);
String xml = "<route id=\"foo\" xmlns=\"http://camel.apache.org/schema/spring\">"
+ " <from uri=\"direct:start\"/>"
+ " <log message=\"This is a changed route saying ${body}\"/>"
+ " <to uri=\"mock:changed\"/>"
+ "</route>";
try {
mbeanServer.invoke(on, "updateRouteFromXml", new Object[] { xml }, new String[] { "java.lang.String" });
fail("Should have thrown exception");
} catch (Exception e) {
assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
assertEquals("Cannot update route from XML as routeIds does not match. routeId: myRoute, routeId from XML: foo",
e.getCause().getMessage());
}
}
static ObjectName getRouteObjectName(MBeanServer mbeanServer) throws Exception {
Set<ObjectName> set = mbeanServer.queryNames(new ObjectName("*:type=routes,*"), null);
assertEquals(1, set.size());
return set.iterator().next();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start").routeId("myRoute")
.log("Got ${body}")
.to("mock:result");
}
};
}
}
| ManagedRouteUpdateRouteFromXmlTest |
java | apache__flink | flink-rpc/flink-rpc-akka/src/main/java/org/apache/flink/runtime/rpc/pekko/PekkoUtils.java | {
"start": 2111,
"end": 2350
} | class ____ utility functions for pekko. It contains methods to start an actor system
* with a given Pekko configuration. Furthermore, the Pekko configuration used for starting the
* different actor systems resides in this class.
*/
| contains |
java | hibernate__hibernate-orm | hibernate-vector/src/main/java/org/hibernate/vector/internal/PGVectorJdbcType.java | {
"start": 984,
"end": 3526
} | class ____ extends ArrayJdbcType {
private final int sqlType;
private final String typeName;
public PGVectorJdbcType(JdbcType elementJdbcType, int sqlType, String typeName) {
super( elementJdbcType );
this.sqlType = sqlType;
this.typeName = typeName;
}
@Override
public int getDefaultSqlTypeCode() {
return sqlType;
}
@Override
public <T> JavaType<T> getJdbcRecommendedJavaTypeMapping(
Integer precision,
Integer scale,
TypeConfiguration typeConfiguration) {
return typeConfiguration.getJavaTypeRegistry().getDescriptor( float[].class );
}
@Override
public <T> JdbcLiteralFormatter<T> getJdbcLiteralFormatter(JavaType<T> javaTypeDescriptor) {
return new PGVectorJdbcLiteralFormatterVector<>(
javaTypeDescriptor,
getElementJdbcType().getJdbcLiteralFormatter( elementJavaType( javaTypeDescriptor ) )
);
}
@Override
public void appendWriteExpression(
String writeExpression,
@Nullable Size size,
SqlAppender appender,
Dialect dialect) {
appender.append( "cast(" );
appender.append( writeExpression );
appender.append( " as " );
appender.append( typeName );
appender.append( ')' );
}
@Override
public boolean isWriteExpressionTyped(Dialect dialect) {
return true;
}
@Override
public @Nullable String castFromPattern(JdbcMapping sourceMapping, @Nullable Size size) {
return sourceMapping.getJdbcType().isStringLike() ? "cast(?1 as " + typeName + ")" : null;
}
@Override
public <X> ValueExtractor<X> getExtractor(JavaType<X> javaTypeDescriptor) {
return new BasicExtractor<>( javaTypeDescriptor, this ) {
@Override
protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( parseFloatVector( rs.getString( paramIndex ) ), options );
}
@Override
protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( parseFloatVector( statement.getString( index ) ), options );
}
@Override
protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( parseFloatVector( statement.getString( name ) ), options );
}
};
}
@Override
public boolean equals(Object that) {
return super.equals( that )
&& that instanceof PGVectorJdbcType vectorJdbcType
&& sqlType == vectorJdbcType.sqlType;
}
@Override
public int hashCode() {
return sqlType + 31 * super.hashCode();
}
}
| PGVectorJdbcType |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/FunctionCallUtil.java | {
"start": 4663,
"end": 5569
} | class ____ extends FunctionParam {
public static final String FIELD_NAME_INDEX = "index";
@JsonProperty(FIELD_NAME_INDEX)
public final int index;
@JsonCreator
public FieldRef(@JsonProperty(FIELD_NAME_INDEX) int index) {
this.index = index;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FieldRef that = (FieldRef) o;
return index == that.index;
}
@Override
public int hashCode() {
return Objects.hash(index);
}
}
/** AsyncLookupOptions includes async related options. */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeName("AsyncOptions")
public static | FieldRef |
java | quarkusio__quarkus | integration-tests/test-extension/tests/src/main/java/io/quarkus/it/extension/DummyMapping.java | {
"start": 203,
"end": 313
} | interface ____ {
@WithDefault("foo")
String name();
@WithDefault("50")
int age();
}
| DummyMapping |
java | hibernate__hibernate-orm | hibernate-spatial/src/main/java/org/hibernate/spatial/KeyedSqmFunctionDescriptors.java | {
"start": 318,
"end": 629
} | interface ____ {
/**
* Return the SqmFunctionDescriptors as map of {@code FunctionKey} to {@code SqmFunctionDescriptor}
*
* @return the SqmFunctionDescriptors as map of {@code FunctionKey} to {@code SqmFunctionDescriptor}
*/
Map<FunctionKey, SqmFunctionDescriptor> asMap();
}
| KeyedSqmFunctionDescriptors |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/coordination/JoinHelper.java | {
"start": 23734,
"end": 24371
} | class ____ implements JoinAccumulator {
@Override
public void handleJoinRequest(
DiscoveryNode sender,
CompatibilityVersions compatibilityVersions,
Set<String> features,
ActionListener<Void> joinListener
) {
assert false : "unexpected join from " + sender + " during initialisation";
joinListener.onFailure(new CoordinationStateRejectedException("join target is not initialised yet"));
}
@Override
public String toString() {
return "InitialJoinAccumulator";
}
}
static | InitialJoinAccumulator |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/util/StdConverter.java | {
"start": 426,
"end": 1689
} | class ____<IN,OUT>
implements Converter<IN,OUT>
{
/*
/**********************************************************************
/* Partial Converter API implementation
/**********************************************************************
*/
@Override
public OUT convert(DeserializationContext ctxt, IN value) {
return convert(value);
}
@Override
public OUT convert(SerializationContext ctxt, IN value) {
return convert(value);
}
public abstract OUT convert(IN value);
@Override
public JavaType getInputType(TypeFactory typeFactory) {
return _findConverterType(typeFactory).containedType(0);
}
@Override
public JavaType getOutputType(TypeFactory typeFactory) {
return _findConverterType(typeFactory).containedType(1);
}
protected JavaType _findConverterType(TypeFactory tf) {
JavaType thisType = tf.constructType(getClass());
JavaType convType = thisType.findSuperType(Converter.class);
if (convType == null || convType.containedTypeCount() < 2) {
throw new IllegalStateException("Cannot find OUT type parameter for Converter of type "+getClass().getName());
}
return convType;
}
}
| StdConverter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.