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 | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/event/spi/FlushEntityEvent.java | {
"start": 211,
"end": 3882
} | class ____ extends AbstractSessionEvent {
private Object entity;
private Object[] propertyValues;
private Object[] databaseSnapshot;
private int[] dirtyProperties;
private boolean hasDirtyCollection;
private boolean dirtyCheckPossible;
private boolean dirtyCheckHandledByInterceptor;
private EntityEntry entityEntry;
private boolean allowedToReuse;//allows this event instance to be reused for multiple events: special case to GC
private int instanceGenerationId;//in support of event instance reuse: to double check no recursive/nested use is happening
public FlushEntityEvent(EventSource source, Object entity, EntityEntry entry) {
super(source);
this.entity = entity;
this.entityEntry = entry;
}
public EntityEntry getEntityEntry() {
return entityEntry;
}
public Object[] getDatabaseSnapshot() {
return databaseSnapshot;
}
public void setDatabaseSnapshot(Object[] databaseSnapshot) {
this.databaseSnapshot = databaseSnapshot;
}
public boolean hasDatabaseSnapshot() {
return databaseSnapshot!=null;
}
public boolean isDirtyCheckHandledByInterceptor() {
return dirtyCheckHandledByInterceptor;
}
public void setDirtyCheckHandledByInterceptor(boolean dirtyCheckHandledByInterceptor) {
this.dirtyCheckHandledByInterceptor = dirtyCheckHandledByInterceptor;
}
public boolean isDirtyCheckPossible() {
return dirtyCheckPossible;
}
public void setDirtyCheckPossible(boolean dirtyCheckPossible) {
this.dirtyCheckPossible = dirtyCheckPossible;
}
public int[] getDirtyProperties() {
return dirtyProperties;
}
public void setDirtyProperties(int[] dirtyProperties) {
this.dirtyProperties = dirtyProperties;
}
public boolean hasDirtyProperties() {
return dirtyProperties != null && dirtyProperties.length != 0;
}
public boolean hasDirtyCollection() {
return hasDirtyCollection;
}
public void setHasDirtyCollection(boolean hasDirtyCollection) {
this.hasDirtyCollection = hasDirtyCollection;
}
public Object[] getPropertyValues() {
return propertyValues;
}
public void setPropertyValues(Object[] propertyValues) {
this.propertyValues = propertyValues;
}
public Object getEntity() {
return entity;
}
/**
* This is a terrible anti-pattern, but particular circumstances call for being
* able to reuse the same event instance: this is otherwise allocated in hot loops
* and since each event is escaping the scope it's actually causing allocation issues.
* The flush event does not appear to be used recursively so this is currently safe to
* do, nevertheless we add an allowedToReuse flag to ensure only instances whose
* purpose has completed are being reused.
* N.B. two out of three parameters from the constructor are reset: the same EventSource is implied
* on reuse.
* @param entity same as constructor parameter
* @param entry same as constructor parameter
*/
public void resetAndReuseEventInstance(Object entity, EntityEntry entry) {
this.entity = entity;
this.entityEntry = entry;
this.allowedToReuse = false;
//and reset other fields to the default:
this.propertyValues = null;
this.databaseSnapshot = null;
this.dirtyProperties = null;
this.hasDirtyCollection = false;
this.dirtyCheckPossible = false;
this.dirtyCheckHandledByInterceptor = false;
}
public boolean isAllowedToReuse() {
return this.allowedToReuse;
}
public void setAllowedToReuse(final boolean allowedToReuse) {
this.allowedToReuse = allowedToReuse;
}
public int getInstanceGenerationId() {
return this.instanceGenerationId;
}
public void setInstanceGenerationId(final int instanceGenerationId) {
this.instanceGenerationId = instanceGenerationId;
}
}
| FlushEntityEvent |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/RobolectricShadowDirectlyOnTest.java | {
"start": 1342,
"end": 1875
} | class ____ {
public static <T> T directlyOn(T shadowedObject, Class<T> clazz) {
return null;
}
public static <T> Runnable directlyOn(
T shadowedObject, Class<T> clazz, String baz, ClassParameter<?>... params) {
return null;
}
}
""")
.expectUnchanged()
.addInputLines(
"ReflectionHelpers.java",
"""
package org.robolectric.util;
public | Shadow |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/annotation/requestattributes/RequestAttributeSpec.java | {
"start": 977,
"end": 1800
} | class ____ {
@Test
void testSenderAttributes() {
try (EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer.class)) {
StoryClient client = embeddedServer.getApplicationContext().getBean(StoryClient.class);
StoryClientFilter filter = embeddedServer.getApplicationContext().getBean(StoryClientFilter.class);
Story story = Mono.from(client.getById("jan2019")).block();
assertNotNull(story);
Map<String, Object> attributes = filter.getLatestRequestAttributes();
assertNotNull(attributes);
assertEquals("jan2019", attributes.get("story-id"));
assertEquals("storyClient", attributes.get("client-name"));
assertEquals("1", attributes.get("version"));
}
}
}
| RequestAttributeSpec |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/CancelJobModelSnapshotUpgradeActionResponseTests.java | {
"start": 519,
"end": 1060
} | class ____ extends AbstractWireSerializingTestCase<Response> {
@Override
protected Response createTestInstance() {
return new Response(randomBoolean());
}
@Override
protected Response mutateInstance(Response instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Writeable.Reader<Response> instanceReader() {
return CancelJobModelSnapshotUpgradeAction.Response::new;
}
}
| CancelJobModelSnapshotUpgradeActionResponseTests |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/transaction/TransactionalTestExecutionListenerTests.java | {
"start": 16922,
"end": 17025
} | class ____ {
public void test() {
}
}
@Rollback(false)
| ClassLevelRollbackViaMetaAnnotationTestCase |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/OrderByOneAuditEntityTest.java | {
"start": 2530,
"end": 7237
} | class ____ {
@Id
private Integer id;
private Integer index1;
private Integer index2;
@ManyToOne
private Parent parent;
public Child() {
}
public Child(Integer id, Integer index1) {
this.id = id;
this.index1 = index1;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getIndex1() {
return index1;
}
public void setIndex1(Integer index1) {
this.index1 = index1;
}
public Integer getIndex2() {
return index2;
}
public void setIndex2(Integer index2) {
this.index2 = index2;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Child child = (Child) o;
return Objects.equals( id, child.id ) &&
Objects.equals( index1, child.index1 );
}
@Override
public int hashCode() {
return Objects.hash( id, index1 );
}
@Override
public String toString() {
return "Child{" +
"id=" + id +
", index1=" + index1 +
'}';
}
}
private Integer parentId;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
// Rev 1
this.parentId = scope.fromTransaction( em -> {
final Parent parent = new Parent();
final Child child1 = new Child();
child1.setId( 1 );
child1.setIndex1( 1 );
child1.setIndex2( 1 );
child1.setParent( parent );
parent.getChildren().add( child1 );
final Child child2 = new Child();
child2.setId( 2 );
child2.setIndex1( 2 );
child2.setIndex2( 2 );
child2.setParent( parent );
parent.getChildren().add( child2 );
em.persist( parent );
return parent.getId();
} );
// Rev 2
scope.inTransaction( em -> {
final Parent parent = em.find( Parent.class, parentId );
final Child child = new Child();
child.setId( 3 );
child.setIndex1( 3 );
child.setIndex2( 3 );
child.setParent( parent );
parent.getChildren().add( child );
em.merge( parent );
} );
// Rev 3
scope.inTransaction( em -> {
final Parent parent = em.find( Parent.class, parentId );
parent.getChildren().removeIf( c -> c.getIndex1() == 2 );
em.merge( parent );
} );
// Rev 4
scope.inTransaction( em -> {
final Parent parent = em.find( Parent.class, parentId );
parent.getChildren().clear();
em.merge( parent );
} );
}
@Test
public void testRevisionCounts(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
assertEquals( Arrays.asList( 1, 2, 3, 4 ), AuditReaderFactory.get( em ).getRevisions( Parent.class, this.parentId ) );
assertEquals( Arrays.asList( 1, 4 ), AuditReaderFactory.get( em ).getRevisions( Child.class, 1 ) );
assertEquals( Arrays.asList( 1, 3 ), AuditReaderFactory.get( em ).getRevisions( Child.class, 2 ) );
assertEquals( Arrays.asList( 2, 4 ), AuditReaderFactory.get( em ).getRevisions( Child.class, 3 ) );
} );
}
@Test
public void testRevision1History(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final Parent parent = AuditReaderFactory.get( em ).find( Parent.class, this.parentId, 1 );
assertNotNull( parent );
assertTrue( !parent.getChildren().isEmpty() );
assertEquals( 2, parent.getChildren().size() );
assertEquals( Arrays.asList( new Child( 1, 1 ), new Child( 2, 2 ) ), parent.getChildren() );
} );
}
@Test
public void testRevision2History(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final Parent parent = AuditReaderFactory.get( em ).find( Parent.class, this.parentId, 2 );
assertNotNull( parent );
assertTrue( !parent.getChildren().isEmpty() );
assertEquals( 3, parent.getChildren().size() );
assertEquals( Arrays.asList( new Child( 1, 1 ), new Child( 2, 2 ), new Child( 3, 3 ) ), parent.getChildren() );
} );
}
@Test
public void testRevision3History(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final Parent parent = AuditReaderFactory.get( em ).find( Parent.class, this.parentId, 3 );
assertNotNull( parent );
assertTrue( !parent.getChildren().isEmpty() );
assertEquals( 2, parent.getChildren().size() );
assertEquals( Arrays.asList( new Child( 1, 1 ), new Child( 3, 3 ) ), parent.getChildren() );
} );
}
@Test
public void testRevision4History(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final Parent parent = AuditReaderFactory.get( em ).find( Parent.class, this.parentId, 4 );
assertNotNull( parent );
assertTrue( parent.getChildren().isEmpty() );
} );
}
}
| Child |
java | google__guice | core/test/com/google/inject/MethodInterceptionTest.java | {
"start": 14738,
"end": 14815
} | interface ____ {
RetType aMethod(RetType obj);
}
public static | Interface |
java | apache__hadoop | hadoop-cloud-storage-project/hadoop-tos/src/main/java/org/apache/hadoop/fs/tosfs/TosFileSystem.java | {
"start": 1082,
"end": 1588
} | class ____ extends RawFileSystem {
@Override
public void initialize(URI name, Configuration conf) throws IOException {
Preconditions.checkNotNull(name);
String scheme = name.getScheme();
if (scheme == null || scheme.isEmpty()) {
scheme = FileSystem.getDefaultUri(conf).getScheme();
}
Preconditions.checkArgument(scheme.equals(TOS.TOS_SCHEME),
"Unsupported scheme %s, expected scheme is %s.", scheme, TOS.TOS_SCHEME);
super.initialize(name, conf);
}
}
| TosFileSystem |
java | google__guice | core/test/com/google/inject/MethodInterceptionTest.java | {
"start": 20566,
"end": 20636
} | interface ____ {
String testReturn();
}
abstract static | RawReturn |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/PublicFieldDoubleTest.java | {
"start": 198,
"end": 618
} | class ____ {
public double id;
}
public void test_codec() throws Exception {
VO vo = new VO();
vo.id = 12.34;
String str = JSON.toJSONString(vo);
VO vo1 = JSON.parseObject(str, VO.class);
Assert.assertTrue(vo1.id == vo.id);
}
public void test_nan() throws Exception {
JSON.parseObject("{\"id\":NaN}", VO.class);
}
}
| VO |
java | apache__camel | components/camel-reactive-streams/src/main/java/org/apache/camel/component/reactive/streams/ReactiveStreamsCamelSubscriber.java | {
"start": 1272,
"end": 6981
} | class ____ implements Subscriber<Exchange>, Closeable {
private static final Logger LOG = LoggerFactory.getLogger(ReactiveStreamsCamelSubscriber.class);
/**
* Unbounded as per rule #17. No need to refill.
*/
private static final long UNBOUNDED_REQUESTS = Long.MAX_VALUE;
private final Lock lock = new ReentrantLock();
private final String name;
private ReactiveStreamsConsumer consumer;
private Subscription subscription;
private long requested;
private long inflightCount;
public ReactiveStreamsCamelSubscriber(String name) {
this.name = name;
}
public void attachConsumer(ReactiveStreamsConsumer consumer) {
lock.lock();
try {
if (this.consumer != null) {
throw new IllegalStateException("A consumer is already attached to the stream '" + name + "'");
}
this.consumer = consumer;
} finally {
lock.unlock();
}
refill();
}
public ReactiveStreamsConsumer getConsumer() {
lock.lock();
try {
return consumer;
} finally {
lock.unlock();
}
}
public void detachConsumer() {
lock.lock();
try {
this.consumer = null;
} finally {
lock.unlock();
}
}
@Override
public void onSubscribe(Subscription subscription) {
if (subscription == null) {
throw new NullPointerException("subscription is null for stream '" + name + "'");
}
boolean allowed = true;
lock.lock();
try {
if (this.subscription != null) {
allowed = false;
} else {
this.subscription = subscription;
}
} finally {
lock.unlock();
}
if (!allowed) {
LOG.warn("There is another active subscription: cancelled");
subscription.cancel();
} else {
refill();
}
}
@Override
public void onNext(Exchange exchange) {
if (exchange == null) {
throw new NullPointerException("exchange is null");
}
ReactiveStreamsConsumer target;
lock.lock();
try {
if (requested < UNBOUNDED_REQUESTS) {
// When there are UNBOUNDED_REQUESTS, they remain constant
requested--;
}
target = this.consumer;
if (target != null) {
inflightCount++;
}
} finally {
lock.unlock();
}
if (target != null) {
target.process(exchange, doneSync -> {
lock.lock();
try {
inflightCount--;
} finally {
lock.unlock();
}
refill();
});
} else {
// This may happen when the consumer is stopped
LOG.warn("Message received in stream '{}', but no consumers were attached. Discarding {}.", name, exchange);
}
}
protected void refill() {
Long toBeRequested = null;
Subscription subs = null;
lock.lock();
try {
if (consumer != null && this.subscription != null) {
Integer consMax = consumer.getEndpoint().getMaxInflightExchanges();
long max = (consMax != null && consMax > 0) ? consMax.longValue() : UNBOUNDED_REQUESTS;
if (requested < UNBOUNDED_REQUESTS) {
long lowWatermark = Math.max(0, Math.round(consumer.getEndpoint().getExchangesRefillLowWatermark() * max));
long minRequests = Math.min(max, max - lowWatermark);
long newRequest = max - requested - inflightCount;
if (newRequest > 0 && newRequest >= minRequests) {
toBeRequested = newRequest;
requested += toBeRequested;
subs = this.subscription;
}
}
}
} finally {
lock.unlock();
}
if (toBeRequested != null) {
subs.request(toBeRequested);
}
}
@Override
public void onError(Throwable throwable) {
if (throwable == null) {
throw new NullPointerException("throwable is null");
}
LOG.error("Error in reactive stream '{}'", name, throwable);
ReactiveStreamsConsumer consumer;
lock.lock();
try {
consumer = this.consumer;
this.subscription = null;
} finally {
lock.unlock();
}
if (consumer != null) {
consumer.onError(throwable);
}
}
@Override
public void onComplete() {
LOG.info("Reactive stream '{}' completed", name);
ReactiveStreamsConsumer consumer;
lock.lock();
try {
consumer = this.consumer;
this.subscription = null;
} finally {
lock.unlock();
}
if (consumer != null) {
consumer.onComplete();
}
}
@Override
public void close() throws IOException {
Subscription subscription;
lock.lock();
try {
subscription = this.subscription;
} finally {
lock.unlock();
}
if (subscription != null) {
subscription.cancel();
}
}
public long getRequested() {
return requested;
}
public long getInflightCount() {
return inflightCount;
}
}
| ReactiveStreamsCamelSubscriber |
java | apache__camel | components/camel-olingo2/camel-olingo2-component/src/main/java/org/apache/camel/component/olingo2/Olingo2Endpoint.java | {
"start": 2294,
"end": 5769
} | class ____ extends AbstractApiEndpoint<Olingo2ApiName, Olingo2Configuration>
implements EndpointServiceLocation {
protected static final String RESOURCE_PATH_PROPERTY = "resourcePath";
protected static final String RESPONSE_HANDLER_PROPERTY = "responseHandler";
protected static final String SERVICE_URI_PROPERTY = "serviceUri";
protected static final String FILTER_ALREADY_SEEN = "filterAlreadySeen";
private static final String KEY_PREDICATE_PROPERTY = "keyPredicate";
private static final String QUERY_PARAMS_PROPERTY = "queryParams";
private static final String ENDPOINT_HTTP_HEADERS_PROPERTY = "endpointHttpHeaders";
private static final String READ_METHOD = "read";
private static final String EDM_PROPERTY = "edm";
private static final String DATA_PROPERTY = "data";
private static final String DELETE_METHOD = "delete";
// unparsed variants
private static final String UREAD_METHOD = "uread";
private Set<String> olingo2endpointPropertyNames;
@UriParam
private Olingo2Configuration configuration;
private Olingo2AppWrapper apiProxy;
public Olingo2Endpoint(String uri, Olingo2Component component, Olingo2ApiName apiName, String methodName,
Olingo2Configuration endpointConfiguration) {
super(uri, component, apiName, methodName, Olingo2ApiCollection.getCollection().getHelper(apiName),
endpointConfiguration);
this.configuration = endpointConfiguration;
}
@Override
public String getServiceUrl() {
return configuration.getServiceUri();
}
@Override
public String getServiceProtocol() {
return "odata";
}
@Override
public Producer createProducer() throws Exception {
return new Olingo2Producer(this);
}
@Override
public Consumer createConsumer(Processor processor) throws Exception {
// make sure inBody is not set for consumers
if (inBody != null) {
throw new IllegalArgumentException("Option inBody is not supported for consumer endpoint");
}
// only read method is supported
if (!READ_METHOD.equals(methodName) && !UREAD_METHOD.equals(methodName)) {
throw new IllegalArgumentException("Only read method is supported for consumer endpoints");
}
final Olingo2Consumer consumer = new Olingo2Consumer(this, processor);
consumer.setSplitResult(configuration.isSplitResult());
configureConsumer(consumer);
return consumer;
}
@Override
protected ApiMethodPropertiesHelper<Olingo2Configuration> getPropertiesHelper() {
return Olingo2PropertiesHelper.getHelper(getCamelContext());
}
@Override
protected String getThreadProfileName() {
return Olingo2Constants.THREAD_PROFILE_NAME;
}
@Override
public void configureProperties(Map<String, Object> options) {
// filter out options that are with $ as they are for query
Map<String, Object> query = new CaseInsensitiveMap();
Map<String, Object> known = new CaseInsensitiveMap();
options.forEach((k, v) -> {
if (k.startsWith("$")) {
query.put(k, v);
} else {
known.put(k, v);
}
});
options.keySet().removeIf(known::containsKey);
// configure endpoint first (from the known options) and then specialized configuration | Olingo2Endpoint |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java | {
"start": 8761,
"end": 11012
} | class ____ instance implementing interface "
+ serviceType.getName(),
e);
}
if (mockClass == null || !serviceType.isAssignableFrom(mockClass)) {
throw new IllegalStateException(
"The mock class " + mockClass.getName() + " not implement interface " + serviceType.getName());
}
try {
return mockClass.newInstance();
} catch (InstantiationException e) {
throw new IllegalStateException("No default constructor from mock class " + mockClass.getName(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(e);
}
}
/**
* Normalize mock string:
*
* <ol>
* <li>return => return null</li>
* <li>fail => default</li>
* <li>force => default</li>
* <li>fail:throw/return foo => throw/return foo</li>
* <li>force:throw/return foo => throw/return foo</li>
* </ol>
*
* @param mock mock string
* @return normalized mock string
*/
public static String normalizeMock(String mock) {
if (mock == null) {
return mock;
}
mock = mock.trim();
if (mock.length() == 0) {
return mock;
}
if (RETURN_KEY.equalsIgnoreCase(mock)) {
return RETURN_PREFIX + "null";
}
if (ConfigUtils.isDefault(mock) || "fail".equalsIgnoreCase(mock) || "force".equalsIgnoreCase(mock)) {
return "default";
}
if (mock.startsWith(FAIL_PREFIX)) {
mock = mock.substring(FAIL_PREFIX.length()).trim();
}
if (mock.startsWith(FORCE_PREFIX)) {
mock = mock.substring(FORCE_PREFIX.length()).trim();
}
if (mock.startsWith(RETURN_PREFIX) || mock.startsWith(THROW_PREFIX)) {
mock = mock.replace('`', '"');
}
return mock;
}
@Override
public URL getUrl() {
return this.url;
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public void destroy() {
// do nothing
}
@Override
public Class<T> getInterface() {
return type;
}
}
| or |
java | spring-projects__spring-boot | module/spring-boot-security-test/src/test/java/org/springframework/boot/security/test/autoconfigure/webmvc/AfterSecurityFilter.java | {
"start": 1245,
"end": 1792
} | class ____ implements Filter, Ordered {
@Override
public int getOrder() {
return SecurityFilterProperties.DEFAULT_FILTER_ORDER + 1;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Principal principal = ((HttpServletRequest) request).getUserPrincipal();
if (principal == null) {
throw new ServletException("No user principal");
}
response.getWriter().write(principal.getName());
response.getWriter().flush();
}
}
| AfterSecurityFilter |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/indices/open/TransportOpenIndexAction.java | {
"start": 1752,
"end": 5230
} | class ____ extends TransportMasterNodeAction<OpenIndexRequest, OpenIndexResponse> {
private static final Logger logger = LogManager.getLogger(TransportOpenIndexAction.class);
private final MetadataIndexStateService indexStateService;
private final ProjectResolver projectResolver;
private final IndexNameExpressionResolver indexNameExpressionResolver;
private final DestructiveOperations destructiveOperations;
@Inject
public TransportOpenIndexAction(
TransportService transportService,
ClusterService clusterService,
ThreadPool threadPool,
MetadataIndexStateService indexStateService,
ActionFilters actionFilters,
ProjectResolver projectResolver,
IndexNameExpressionResolver indexNameExpressionResolver,
DestructiveOperations destructiveOperations
) {
super(
OpenIndexAction.NAME,
transportService,
clusterService,
threadPool,
actionFilters,
OpenIndexRequest::new,
OpenIndexResponse::new,
EsExecutors.DIRECT_EXECUTOR_SERVICE
);
this.indexStateService = indexStateService;
this.projectResolver = projectResolver;
this.indexNameExpressionResolver = indexNameExpressionResolver;
this.destructiveOperations = destructiveOperations;
}
@Override
protected void doExecute(Task task, OpenIndexRequest request, ActionListener<OpenIndexResponse> listener) {
destructiveOperations.failDestructive(request.indices());
super.doExecute(task, request, listener);
}
@Override
protected ClusterBlockException checkBlock(OpenIndexRequest request, ClusterState state) {
final ProjectMetadata projectMetadata = projectResolver.getProjectMetadata(state);
return state.blocks()
.indicesBlockedException(
projectMetadata.id(),
ClusterBlockLevel.METADATA_WRITE,
indexNameExpressionResolver.concreteIndexNames(projectMetadata, request)
);
}
@Override
protected void masterOperation(
Task task,
final OpenIndexRequest request,
final ClusterState state,
final ActionListener<OpenIndexResponse> listener
) {
final Index[] concreteIndices = indexNameExpressionResolver.concreteIndices(state, request);
if (concreteIndices == null || concreteIndices.length == 0) {
listener.onResponse(new OpenIndexResponse(true, true));
return;
}
indexStateService.openIndices(
new OpenIndexClusterStateUpdateRequest(
request.masterNodeTimeout(),
request.ackTimeout(),
projectResolver.getProjectId(),
request.waitForActiveShards(),
concreteIndices
),
new ActionListener<>() {
@Override
public void onResponse(ShardsAcknowledgedResponse response) {
listener.onResponse(new OpenIndexResponse(response.isAcknowledged(), response.isShardsAcknowledged()));
}
@Override
public void onFailure(Exception t) {
logger.debug(() -> "failed to open indices [" + Arrays.toString(concreteIndices) + "]", t);
listener.onFailure(t);
}
}
);
}
}
| TransportOpenIndexAction |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GraphqlEndpointBuilderFactory.java | {
"start": 1572,
"end": 8923
} | interface ____
extends
EndpointProducerBuilder {
default AdvancedGraphqlEndpointBuilder advanced() {
return (AdvancedGraphqlEndpointBuilder) this;
}
/**
* The query or mutation name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param operationName the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder operationName(String operationName) {
doSetProperty("operationName", operationName);
return this;
}
/**
* The proxy host in the format hostname:port.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param proxyHost the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder proxyHost(String proxyHost) {
doSetProperty("proxyHost", proxyHost);
return this;
}
/**
* The query text.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param query the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder query(String query) {
doSetProperty("query", query);
return this;
}
/**
* The query file name located in the classpath (or use file: to load
* from file system).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param queryFile the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder queryFile(String queryFile) {
doSetProperty("queryFile", queryFile);
return this;
}
/**
* The name of a header containing the GraphQL query.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param queryHeader the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder queryHeader(String queryHeader) {
doSetProperty("queryHeader", queryHeader);
return this;
}
/**
* Option to disable throwing the HttpOperationFailedException in case
* of failed responses from the remote server. This allows you to get
* all responses regardless of the HTTP status code.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param throwExceptionOnFailure the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder throwExceptionOnFailure(boolean throwExceptionOnFailure) {
doSetProperty("throwExceptionOnFailure", throwExceptionOnFailure);
return this;
}
/**
* Option to disable throwing the HttpOperationFailedException in case
* of failed responses from the remote server. This allows you to get
* all responses regardless of the HTTP status code.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param throwExceptionOnFailure the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder throwExceptionOnFailure(String throwExceptionOnFailure) {
doSetProperty("throwExceptionOnFailure", throwExceptionOnFailure);
return this;
}
/**
* The JsonObject instance containing the operation variables.
*
* The option is a: <code>org.apache.camel.util.json.JsonObject</code>
* type.
*
* Group: producer
*
* @param variables the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder variables(org.apache.camel.util.json.JsonObject variables) {
doSetProperty("variables", variables);
return this;
}
/**
* The JsonObject instance containing the operation variables.
*
* The option will be converted to a
* <code>org.apache.camel.util.json.JsonObject</code> type.
*
* Group: producer
*
* @param variables the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder variables(String variables) {
doSetProperty("variables", variables);
return this;
}
/**
* The name of a header containing a JsonObject instance containing the
* operation variables.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: producer
*
* @param variablesHeader the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder variablesHeader(String variablesHeader) {
doSetProperty("variablesHeader", variablesHeader);
return this;
}
/**
* The access token sent in the Authorization header.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessToken the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder accessToken(String accessToken) {
doSetProperty("accessToken", accessToken);
return this;
}
/**
* The JWT Authorization type. Default is Bearer.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: Bearer
* Group: security
*
* @param jwtAuthorizationType the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder jwtAuthorizationType(String jwtAuthorizationType) {
doSetProperty("jwtAuthorizationType", jwtAuthorizationType);
return this;
}
/**
* The password 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 GraphqlEndpointBuilder password(String password) {
doSetProperty("password", password);
return this;
}
/**
* The username for Basic authentication.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param username the value to set
* @return the dsl builder
*/
default GraphqlEndpointBuilder username(String username) {
doSetProperty("username", username);
return this;
}
}
/**
* Advanced builder for endpoint for the GraphQL component.
*/
public | GraphqlEndpointBuilder |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/naming/selector/NamingResult.java | {
"start": 862,
"end": 927
} | interface ____ extends SelectResult<List<Instance>> {
}
| NamingResult |
java | elastic__elasticsearch | x-pack/plugin/ilm/src/main/java/org/elasticsearch/xpack/ilm/IndexLifecycleTransition.java | {
"start": 2117,
"end": 2426
} | class ____ cluster state transitions
* related to ILM operations. These operations are all at the index level
* (inside of {@link IndexMetadata}) for the index in question.
*
* Each method is static and only changes a given state, no actions are
* performed by methods in this class.
*/
public final | handles |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/DeferredImportSelector.java | {
"start": 2508,
"end": 3002
} | class ____ {
private final AnnotationMetadata metadata;
private final String importClassName;
public Entry(AnnotationMetadata metadata, String importClassName) {
this.metadata = metadata;
this.importClassName = importClassName;
}
/**
* Return the {@link AnnotationMetadata} of the importing
* {@link Configuration} class.
*/
public AnnotationMetadata getMetadata() {
return this.metadata;
}
/**
* Return the fully qualified name of the | Entry |
java | elastic__elasticsearch | x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/token/TransportInvalidateTokenActionTests.java | {
"start": 2358,
"end": 8970
} | class ____ extends ESTestCase {
private static final Settings SETTINGS = Settings.builder()
.put(Node.NODE_NAME_SETTING.getKey(), "TokenServiceTests")
.put(XPackSettings.TOKEN_SERVICE_ENABLED_SETTING.getKey(), true)
.build();
private ThreadPool threadPool;
private TransportService transportService;
private Client client;
private SecurityIndexManager securityIndex;
private ClusterService clusterService;
private MockLicenseState license;
private SecurityContext securityContext;
@Before
public void setup() {
threadPool = new TestThreadPool(getTestName());
transportService = mock(TransportService.class);
securityContext = new SecurityContext(Settings.EMPTY, threadPool.getThreadContext());
client = mock(Client.class);
when(client.threadPool()).thenReturn(threadPool);
when(client.settings()).thenReturn(SETTINGS);
securityIndex = mock(SecurityIndexManager.class);
this.clusterService = ClusterServiceUtils.createClusterService(threadPool);
this.license = mock(MockLicenseState.class);
when(license.isAllowed(Security.TOKEN_SERVICE_FEATURE)).thenReturn(true);
}
public void testInvalidateTokensWhenIndexUnavailable() throws Exception {
SecurityIndexManager.IndexState projectIndex = mock(SecurityIndexManager.IndexState.class);
when(securityIndex.forCurrentProject()).thenReturn(projectIndex);
when(projectIndex.isAvailable(SecurityIndexManager.Availability.SEARCH_SHARDS)).thenReturn(false);
when(projectIndex.indexExists()).thenReturn(true);
when(projectIndex.getUnavailableReason(SecurityIndexManager.Availability.PRIMARY_SHARDS)).thenReturn(
new ElasticsearchException("simulated")
);
final TokenService tokenService = new TokenService(
SETTINGS,
Clock.systemUTC(),
client,
license,
securityContext,
securityIndex,
securityIndex,
clusterService
);
final TransportInvalidateTokenAction action = new TransportInvalidateTokenAction(
transportService,
new ActionFilters(Collections.emptySet()),
tokenService
);
Tuple<byte[], byte[]> newTokenBytes = tokenService.getRandomTokenBytes(true);
InvalidateTokenRequest request = new InvalidateTokenRequest(
tokenService.prependVersionAndEncodeAccessToken(TransportVersion.current(), newTokenBytes.v1()),
ACCESS_TOKEN.getValue(),
null,
null
);
PlainActionFuture<InvalidateTokenResponse> accessTokenfuture = new PlainActionFuture<>();
action.doExecute(null, request, accessTokenfuture);
ElasticsearchSecurityException ese = expectThrows(ElasticsearchSecurityException.class, accessTokenfuture::actionGet);
assertThat(ese.getMessage(), containsString("unable to perform requested action"));
assertThat(ese.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE));
request = new InvalidateTokenRequest(
TokenService.prependVersionAndEncodeRefreshToken(TransportVersion.current(), newTokenBytes.v2()),
REFRESH_TOKEN.getValue(),
null,
null
);
PlainActionFuture<InvalidateTokenResponse> refreshTokenfuture = new PlainActionFuture<>();
action.doExecute(null, request, refreshTokenfuture);
ElasticsearchSecurityException ese2 = expectThrows(ElasticsearchSecurityException.class, refreshTokenfuture::actionGet);
assertThat(ese2.getMessage(), containsString("unable to perform requested action"));
assertThat(ese2.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE));
}
public void testInvalidateTokensWhenIndexClosed() throws Exception {
SecurityIndexManager.IndexState projectIndex = mock(SecurityIndexManager.IndexState.class);
when(securityIndex.forCurrentProject()).thenReturn(projectIndex);
when(projectIndex.isAvailable(SecurityIndexManager.Availability.PRIMARY_SHARDS)).thenReturn(false);
when(projectIndex.indexExists()).thenReturn(true);
when(projectIndex.getUnavailableReason(SecurityIndexManager.Availability.PRIMARY_SHARDS)).thenReturn(
new IndexClosedException(new Index(INTERNAL_SECURITY_TOKENS_INDEX_7, ClusterState.UNKNOWN_UUID))
);
final TokenService tokenService = new TokenService(
SETTINGS,
Clock.systemUTC(),
client,
license,
securityContext,
securityIndex,
securityIndex,
clusterService
);
final TransportInvalidateTokenAction action = new TransportInvalidateTokenAction(
transportService,
new ActionFilters(Collections.emptySet()),
tokenService
);
Tuple<byte[], byte[]> newTokenBytes = tokenService.getRandomTokenBytes(true);
InvalidateTokenRequest request = new InvalidateTokenRequest(
tokenService.prependVersionAndEncodeAccessToken(TransportVersion.current(), newTokenBytes.v1()),
ACCESS_TOKEN.getValue(),
null,
null
);
PlainActionFuture<InvalidateTokenResponse> accessTokenfuture = new PlainActionFuture<>();
action.doExecute(null, request, accessTokenfuture);
ElasticsearchSecurityException ese = expectThrows(ElasticsearchSecurityException.class, accessTokenfuture::actionGet);
assertThat(ese.getMessage(), containsString("failed to invalidate token"));
assertThat(ese.status(), equalTo(RestStatus.BAD_REQUEST));
request = new InvalidateTokenRequest(
TokenService.prependVersionAndEncodeRefreshToken(TransportVersion.current(), tokenService.getRandomTokenBytes(true).v2()),
REFRESH_TOKEN.getValue(),
null,
null
);
PlainActionFuture<InvalidateTokenResponse> refreshTokenfuture = new PlainActionFuture<>();
action.doExecute(null, request, refreshTokenfuture);
ElasticsearchSecurityException ese2 = expectThrows(ElasticsearchSecurityException.class, refreshTokenfuture::actionGet);
assertThat(ese2.getMessage(), containsString("failed to invalidate token"));
assertThat(ese2.status(), equalTo(RestStatus.BAD_REQUEST));
}
@After
public void stopThreadPool() throws Exception {
if (threadPool != null) {
terminate(threadPool);
}
}
}
| TransportInvalidateTokenActionTests |
java | apache__flink | flink-tests/src/test/java/org/apache/flink/test/checkpointing/ChangelogRecoveryITCaseBase.java | {
"start": 13998,
"end": 17939
} | class ____ extends RichSourceFunction<Integer>
implements CheckpointedFunction, CheckpointListener {
private static final long serialVersionUID = 1L;
protected volatile int currentIndex;
protected final AtomicInteger completedCheckpointNum;
protected volatile boolean isCanceled;
private static final List<Integer> sourceList =
Collections.unmodifiableList(initSourceData(TOTAL_ELEMENTS));
private transient ListState<Integer> currentIndexState;
private transient ListState<Integer> completedCheckpointNumState;
public ControlledSource() {
this.completedCheckpointNum = new AtomicInteger();
}
public static List<Integer> initSourceData(int totalNum) {
List<Integer> sourceList = new ArrayList<>(totalNum);
for (int i = 0; i < totalNum; i++) {
sourceList.add(ThreadLocalRandom.current().nextInt(totalNum));
}
return sourceList;
}
public static Map<Integer, Integer> getExpectedResult() {
return sourceList.stream()
.collect(
Collectors.toConcurrentMap(
element -> element % 100, element -> 1, Integer::sum));
}
@Override
public void snapshotState(FunctionSnapshotContext context) throws Exception {
currentIndexState.update(Collections.singletonList(currentIndex));
completedCheckpointNumState.update(
Collections.singletonList(completedCheckpointNum.get()));
}
@Override
public void initializeState(FunctionInitializationContext context) throws Exception {
currentIndexState =
context.getOperatorStateStore()
.getListState(
new ListStateDescriptor<>("currentIndexState", Integer.class));
completedCheckpointNumState =
context.getOperatorStateStore()
.getListState(
new ListStateDescriptor<>(
"completedCheckpointNumState", Integer.class));
if (context.isRestored()) {
currentIndex = get(currentIndexState.get(), 0);
completedCheckpointNum.compareAndSet(0, get(completedCheckpointNumState.get(), 0));
}
}
@Override
public void run(SourceContext<Integer> ctx) throws Exception {
while (!isCanceled && currentIndex < sourceList.size()) {
beforeElement(ctx);
synchronized (ctx.getCheckpointLock()) {
if (!isCanceled && currentIndex < sourceList.size()) {
int currentElement = sourceList.get(currentIndex++);
ctx.collect(currentElement % 100);
}
}
}
}
// it runs without holding the checkpoint lock
protected void beforeElement(SourceContext<Integer> ctx) throws Exception {
// do nothing by default
}
protected void waitWhile(SerializableBooleanSupplierWithException supplier)
throws Exception {
while (supplier.getAsBoolean()) {
Thread.sleep(10);
}
}
protected void throwArtificialFailure() throws Exception {
throw new ArtificialFailure();
}
@Override
public void cancel() {
isCanceled = true;
}
@Override
public void notifyCheckpointComplete(long checkpointId) throws Exception {
completedCheckpointNum.getAndIncrement();
}
}
/** A sink puts the result of WordCount into a Map using for validating. */
protected static | ControlledSource |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/sql/SqlHopTableFunction.java | {
"start": 1508,
"end": 1731
} | class ____ extends SqlWindowTableFunction {
public SqlHopTableFunction() {
super(SqlKind.HOP.name(), new OperandMetadataImpl());
}
/** Operand type checker for HOP. */
private static | SqlHopTableFunction |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/authorization/AuthenticatedAuthorizationManager.java | {
"start": 5321,
"end": 5553
} | class ____ extends AbstractAuthorizationStrategy {
@Override
boolean isGranted(Authentication authentication) {
return this.trustResolver.isAnonymous(authentication);
}
}
private static final | AnonymousAuthorizationStrategy |
java | apache__camel | components/camel-micrometer/src/test/java/org/apache/camel/component/micrometer/MicrometerComponentTest.java | {
"start": 1988,
"end": 9030
} | class ____ {
@Mock
private CamelContext camelContext;
@Mock
private TypeConverter typeConverter;
@Mock
private Registry camelRegistry;
@Mock
private MeterRegistry metricRegistry;
@Mock
private CompositeMeterRegistry compositeMeterRegistry;
private InOrder inOrder;
private MicrometerComponent component;
@BeforeEach
public void setUp() {
component = new MicrometerComponent();
inOrder = Mockito.inOrder(camelContext, camelRegistry, metricRegistry, typeConverter);
}
@Test
public void testCreateNewEndpointForCounter() {
Endpoint endpoint = new MicrometerEndpoint(null, null, metricRegistry, Meter.Type.COUNTER, "a name");
assertThat(endpoint, is(notNullValue()));
assertThat(endpoint, is(instanceOf(MicrometerEndpoint.class)));
}
@Test
public void testCreateNewEndpointForHistogram() {
Endpoint endpoint
= new MicrometerEndpoint(null, null, metricRegistry, Meter.Type.DISTRIBUTION_SUMMARY, "a name");
assertThat(endpoint, is(notNullValue()));
assertThat(endpoint, is(instanceOf(MicrometerEndpoint.class)));
}
@Test
public void testCreateNewEndpointForTimer() {
Endpoint endpoint = new MicrometerEndpoint(null, null, metricRegistry, Meter.Type.TIMER, "a name");
assertThat(endpoint, is(notNullValue()));
assertThat(endpoint, is(instanceOf(MicrometerEndpoint.class)));
}
@Test
public void testGetMetricsType() {
Meter.Type[] supportedTypes = { Meter.Type.COUNTER, Meter.Type.DISTRIBUTION_SUMMARY, Meter.Type.TIMER };
for (Meter.Type type : supportedTypes) {
assertThat(component.getMetricsType(MicrometerUtils.getName(type) + ":metrics-name"), is(type));
}
}
@Test
public void testGetMetricsTypeNotSet() {
assertThat(component.getMetricsType("no-metrics-type"), is(MicrometerComponent.DEFAULT_METER_TYPE));
}
@Test
public void testGetMetricsTypeNotFound() {
assertThrows(RuntimeCamelException.class,
() -> component.getMetricsType("unknown-metrics:metrics-name"));
}
@Test
public void testGetOrCreateMetricRegistryFoundInCamelRegistry() {
when(camelRegistry.lookupByNameAndType("name", CompositeMeterRegistry.class)).thenReturn(null);
when(camelRegistry.findByType(CompositeMeterRegistry.class)).thenReturn(null);
when(camelRegistry.lookupByNameAndType("name", MeterRegistry.class)).thenReturn(metricRegistry);
MeterRegistry result = MicrometerUtils.getOrCreateMeterRegistry(camelRegistry, "name");
assertThat(result, is(metricRegistry));
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", CompositeMeterRegistry.class);
inOrder.verify(camelRegistry, times(1)).findByType(CompositeMeterRegistry.class);
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", MeterRegistry.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetOrCreateCompositeMetricRegistryFoundInCamelRegistry() {
when(camelRegistry.lookupByNameAndType("name", CompositeMeterRegistry.class))
.thenReturn(compositeMeterRegistry);
MeterRegistry result = MicrometerUtils.getOrCreateMeterRegistry(camelRegistry, "name");
assertThat(result, is(compositeMeterRegistry));
inOrder.verify(camelRegistry, times(1))
.lookupByNameAndType("name", CompositeMeterRegistry.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetOrCreateMetricRegistryFoundInCamelRegistryByType() {
when(camelRegistry.lookupByNameAndType("name", CompositeMeterRegistry.class)).thenReturn(null);
when(camelRegistry.findByType(CompositeMeterRegistry.class)).thenReturn(Collections.singleton(null));
when(camelRegistry.lookupByNameAndType("name", MeterRegistry.class)).thenReturn(null);
when(camelRegistry.findByType(MeterRegistry.class)).thenReturn(Collections.singleton(metricRegistry));
MeterRegistry result = MicrometerUtils.getOrCreateMeterRegistry(camelRegistry, "name");
assertThat(result, is(metricRegistry));
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", CompositeMeterRegistry.class);
inOrder.verify(camelRegistry, times(1)).findByType(CompositeMeterRegistry.class);
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", MeterRegistry.class);
inOrder.verify(camelRegistry, times(1)).findByType(MeterRegistry.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetOrCreateCompositeMetricRegistryFoundInCamelRegistryByType() {
when(camelRegistry.lookupByNameAndType("name", CompositeMeterRegistry.class)).thenReturn(null);
when(camelRegistry.findByType(CompositeMeterRegistry.class))
.thenReturn(Collections.singleton(compositeMeterRegistry));
MeterRegistry result = MicrometerUtils.getOrCreateMeterRegistry(camelRegistry, "name");
assertThat(result, is(compositeMeterRegistry));
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", CompositeMeterRegistry.class);
inOrder.verify(camelRegistry, times(1)).findByType(CompositeMeterRegistry.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetMetricRegistryFromCamelRegistry() {
when(camelRegistry.lookupByNameAndType("name", CompositeMeterRegistry.class)).thenReturn(null);
when(camelRegistry.findByType(CompositeMeterRegistry.class)).thenReturn(null);
when(camelRegistry.lookupByNameAndType("name", MeterRegistry.class)).thenReturn(metricRegistry);
MeterRegistry result = MicrometerUtils.getMeterRegistryFromCamelRegistry(camelRegistry, "name");
assertThat(result, is(metricRegistry));
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", CompositeMeterRegistry.class);
inOrder.verify(camelRegistry, times(1)).findByType(CompositeMeterRegistry.class);
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", MeterRegistry.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testGetCompositeMetricRegistryFromCamelRegistry() {
when(camelRegistry.lookupByNameAndType("name", CompositeMeterRegistry.class))
.thenReturn(compositeMeterRegistry);
MeterRegistry result = MicrometerUtils.getMeterRegistryFromCamelRegistry(camelRegistry, "name");
assertThat(result, is(compositeMeterRegistry));
inOrder.verify(camelRegistry, times(1)).lookupByNameAndType("name", CompositeMeterRegistry.class);
inOrder.verifyNoMoreInteractions();
}
@Test
public void testCreateMetricRegistry() {
MeterRegistry registry = MicrometerUtils.createMeterRegistry();
assertThat(registry, isA(SimpleMeterRegistry.class));
}
}
| MicrometerComponentTest |
java | quarkusio__quarkus | extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/QuarkusFlywayResourceProvider.java | {
"start": 472,
"end": 1994
} | class ____ implements ResourceProvider {
private static final Logger log = Logger.getLogger(FlywayRecorder.class);
private final Collection<LoadableResource> resources;
public QuarkusFlywayResourceProvider(Collection<LoadableResource> resources) {
this.resources = resources;
}
@Override
public LoadableResource getResource(String name) {
for (LoadableResource resource : resources) {
String fileName = resource.getRelativePath();
if (fileName.equals(name)) {
return resource;
}
}
return null;
}
/**
* Returns all known resources starting with the specified prefix and ending with any of the specified suffixes.
*
* @param prefix The prefix of the resource names to match.
* @param suffixes The suffixes of the resource names to match.
* @return The resources that were found.
*/
public Collection<LoadableResource> getResources(String prefix, String... suffixes) {
List<LoadableResource> result = new ArrayList<>();
for (LoadableResource resource : resources) {
String fileName = resource.getFilename();
if (StringUtils.startsAndEndsWith(fileName, prefix, suffixes)) {
result.add(resource);
} else {
log.debug("Filtering out resource: " + resource.getAbsolutePath() + " (filename: " + fileName + ")");
}
}
return result;
}
}
| QuarkusFlywayResourceProvider |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/rest/action/document/RestBulkAction.java | {
"start": 2613,
"end": 7270
} | class ____ extends BaseRestHandler {
public static final String TYPES_DEPRECATION_MESSAGE = "[types removal] Specifying types in bulk requests is deprecated.";
public static final String FAILURE_STORE_STATUS_CAPABILITY = "failure_store_status";
private final boolean allowExplicitIndex;
private final IncrementalBulkService bulkHandler;
private final IncrementalBulkService.Enabled incrementalEnabled;
private final Set<String> capabilities;
public RestBulkAction(Settings settings, ClusterSettings clusterSettings, IncrementalBulkService bulkHandler) {
this.allowExplicitIndex = MULTI_ALLOW_EXPLICIT_INDEX.get(settings);
this.bulkHandler = bulkHandler;
this.capabilities = Set.of(FAILURE_STORE_STATUS_CAPABILITY);
this.incrementalEnabled = new IncrementalBulkService.Enabled(clusterSettings);
}
@Override
public List<Route> routes() {
return List.of(
new Route(POST, "/_bulk"),
new Route(PUT, "/_bulk"),
new Route(POST, "/{index}/_bulk"),
new Route(PUT, "/{index}/_bulk")
);
}
@Override
public String getName() {
return "bulk_action";
}
@Override
public boolean supportsContentStream() {
return incrementalEnabled.get();
}
@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
if (request.isStreamedContent() == false) {
BulkRequest bulkRequest = new BulkRequest();
String defaultIndex = request.param("index");
String defaultRouting = request.param("routing");
FetchSourceContext defaultFetchSourceContext = FetchSourceContext.parseFromRestRequest(request);
String defaultPipeline = request.param("pipeline");
boolean defaultListExecutedPipelines = request.paramAsBoolean("list_executed_pipelines", false);
String waitForActiveShards = request.param("wait_for_active_shards");
if (waitForActiveShards != null) {
bulkRequest.waitForActiveShards(ActiveShardCount.parseString(waitForActiveShards));
}
Boolean defaultRequireAlias = request.paramAsBoolean(DocWriteRequest.REQUIRE_ALIAS, false);
boolean defaultRequireDataStream = request.paramAsBoolean(DocWriteRequest.REQUIRE_DATA_STREAM, false);
bulkRequest.timeout(request.paramAsTime("timeout", BulkShardRequest.DEFAULT_TIMEOUT));
bulkRequest.setRefreshPolicy(request.param("refresh"));
bulkRequest.includeSourceOnError(RestUtils.getIncludeSourceOnError(request));
bulkRequest.requestParamsUsed(request.params().keySet());
ReleasableBytesReference content = request.requiredContent();
try {
bulkRequest.add(
content,
defaultIndex,
defaultRouting,
defaultFetchSourceContext,
defaultPipeline,
defaultRequireAlias,
defaultRequireDataStream,
defaultListExecutedPipelines,
allowExplicitIndex,
request.getXContentType(),
request.getRestApiVersion()
);
} catch (Exception e) {
return channel -> new RestToXContentListener<>(channel).onFailure(parseFailureException(e));
}
return channel -> {
content.mustIncRef();
client.bulk(bulkRequest, ActionListener.releaseAfter(new RestRefCountedChunkedToXContentListener<>(channel), content));
};
} else {
request.ensureContent();
String waitForActiveShards = request.param("wait_for_active_shards");
TimeValue timeout = request.paramAsTime("timeout", BulkShardRequest.DEFAULT_TIMEOUT);
String refresh = request.param("refresh");
return new ChunkHandler(
allowExplicitIndex,
request,
() -> bulkHandler.newBulkRequest(waitForActiveShards, timeout, refresh, request.params().keySet())
);
}
}
private static Exception parseFailureException(Exception e) {
if (e instanceof IllegalArgumentException) {
return e;
} else {
// TODO: Maybe improve in follow-up to be XContentParseException and include line number and column
return new ElasticsearchParseException("could not parse bulk request body", e);
}
}
static | RestBulkAction |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/sql/ast/tree/expression/Distinct.java | {
"start": 489,
"end": 1567
} | class ____ implements Expression, SqlExpressible, SqlAstNode {
private final Expression expression;
public Distinct(Expression expression) {
this.expression = expression;
}
public Expression getExpression() {
return expression;
}
@Override
public JdbcMapping getJdbcMapping() {
if ( expression instanceof SqlExpressible sqlExpressible) {
return sqlExpressible.getJdbcMapping();
}
if ( getExpressionType() instanceof SqlExpressible sqlExpressible ) {
return sqlExpressible.getJdbcMapping();
}
if ( getExpressionType() != null ) {
assert getExpressionType().getJdbcTypeCount() == 1;
return getExpressionType().getSingleJdbcMapping();
}
return null;
}
@Override
public JdbcMappingContainer getExpressionType() {
return expression.getExpressionType();
}
@Override
public void accept(SqlAstWalker sqlTreeWalker) {
sqlTreeWalker.visitDistinct( this );
}
@Override
public int forEachJdbcType(int offset, IndexedConsumer<JdbcMapping> action) {
action.accept( offset, getJdbcMapping() );
return getJdbcTypeCount();
}
}
| Distinct |
java | redisson__redisson | redisson/src/main/java/org/redisson/executor/CronExpression.java | {
"start": 2106,
"end": 53343
} | class ____ implements Serializable, Cloneable {
private static final long serialVersionUID = 12423409423L;
protected static final int SECOND = 0;
protected static final int MINUTE = 1;
protected static final int HOUR = 2;
protected static final int DAY_OF_MONTH = 3;
protected static final int MONTH = 4;
protected static final int DAY_OF_WEEK = 5;
protected static final int YEAR = 6;
protected static final int ALL_SPEC_INT = 99; // '*'
protected static final int NO_SPEC_INT = 98; // '?'
protected static final Integer ALL_SPEC = ALL_SPEC_INT;
protected static final Integer NO_SPEC = NO_SPEC_INT;
protected static final Map<String, Integer> monthMap = new HashMap<String, Integer>(20);
protected static final Map<String, Integer> dayMap = new HashMap<String, Integer>(60);
static {
monthMap.put("JAN", 0);
monthMap.put("FEB", 1);
monthMap.put("MAR", 2);
monthMap.put("APR", 3);
monthMap.put("MAY", 4);
monthMap.put("JUN", 5);
monthMap.put("JUL", 6);
monthMap.put("AUG", 7);
monthMap.put("SEP", 8);
monthMap.put("OCT", 9);
monthMap.put("NOV", 10);
monthMap.put("DEC", 11);
dayMap.put("SUN", 1);
dayMap.put("MON", 2);
dayMap.put("TUE", 3);
dayMap.put("WED", 4);
dayMap.put("THU", 5);
dayMap.put("FRI", 6);
dayMap.put("SAT", 7);
}
private final String cronExpression;
private TimeZone timeZone = null;
protected transient TreeSet<Integer> seconds;
protected transient TreeSet<Integer> minutes;
protected transient TreeSet<Integer> hours;
protected transient TreeSet<Integer> daysOfMonth;
protected transient TreeSet<Integer> months;
protected transient TreeSet<Integer> daysOfWeek;
protected transient TreeSet<Integer> years;
protected transient boolean lastdayOfWeek = false;
protected transient int nthdayOfWeek = 0;
protected transient boolean lastdayOfMonth = false;
protected transient boolean nearestWeekday = false;
protected transient int lastdayOffset = 0;
protected transient boolean expressionParsed = false;
public static final int MAX_YEAR = Calendar.getInstance().get(Calendar.YEAR) + 100;
/**
* Constructs a new <CODE>CronExpression</CODE> based on the specified
* parameter.
*
* @param cronExpression String representation of the cron expression the
* new object should represent
*/
public CronExpression(String cronExpression) {
if (cronExpression == null) {
throw new IllegalArgumentException("cronExpression cannot be null");
}
this.cronExpression = cronExpression.toUpperCase(Locale.US);
try {
buildExpression(this.cronExpression);
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Constructs a new {@code CronExpression} as a copy of an existing
* instance.
*
* @param expression
* The existing cron expression to be copied
*/
public CronExpression(CronExpression expression) {
/*
* We don't call the other constructor here since we need to swallow the
* ParseException. We also elide some of the sanity checking as it is
* not logically trippable.
*/
this.cronExpression = expression.getCronExpression();
try {
buildExpression(cronExpression);
} catch (ParseException ex) {
throw new AssertionError();
}
if (expression.getTimeZone() != null) {
setTimeZone((TimeZone) expression.getTimeZone().clone());
}
}
/**
* Indicates whether the given date satisfies the cron expression. Note that
* milliseconds are ignored, so two Dates falling on different milliseconds
* of the same second will always have the same result here.
*
* @param date the date to evaluate
* @return a boolean indicating whether the given date satisfies the cron
* expression
*/
public boolean isSatisfiedBy(Date date) {
Calendar testDateCal = Calendar.getInstance(getTimeZone());
testDateCal.setTime(date);
testDateCal.set(Calendar.MILLISECOND, 0);
Date originalDate = testDateCal.getTime();
testDateCal.add(Calendar.SECOND, -1);
Date timeAfter = getTimeAfter(testDateCal.getTime());
return ((timeAfter != null) && (timeAfter.equals(originalDate)));
}
/**
* Returns the next date/time <I>after</I> the given date/time which
* satisfies the cron expression.
*
* @param date the date/time at which to begin the search for the next valid
* date/time
* @return the next valid date/time
*/
public Date getNextValidTimeAfter(Date date) {
return getTimeAfter(date);
}
/**
* Returns the next date/time <I>after</I> the given date/time which does
* <I>not</I> satisfy the expression
*
* @param date the date/time at which to begin the search for the next
* invalid date/time
* @return the next valid date/time
*/
public Date getNextInvalidTimeAfter(Date date) {
long difference = 1000;
//move back to the nearest second so differences will be accurate
Calendar adjustCal = Calendar.getInstance(getTimeZone());
adjustCal.setTime(date);
adjustCal.set(Calendar.MILLISECOND, 0);
Date lastDate = adjustCal.getTime();
Date newDate;
//FUTURE_TODO: (QUARTZ-481) IMPROVE THIS! The following is a BAD solution to this problem. Performance will be very bad here, depending on the cron expression. It is, however A solution.
//keep getting the next included time until it's farther than one second
// apart. At that point, lastDate is the last valid fire time. We return
// the second immediately following it.
while (difference == 1000) {
newDate = getTimeAfter(lastDate);
if(newDate == null)
break;
difference = newDate.getTime() - lastDate.getTime();
if (difference == 1000) {
lastDate = newDate;
}
}
return new Date(lastDate.getTime() + 1000);
}
/**
* Returns the time zone for which this <code>CronExpression</code>
* will be resolved.
*
* @return time zone
*/
public TimeZone getTimeZone() {
if (timeZone == null) {
timeZone = TimeZone.getDefault();
}
return timeZone;
}
/**
* Sets the time zone for which this <code>CronExpression</code>
* will be resolved.
*
* @param timeZone object
*/
public void setTimeZone(TimeZone timeZone) {
this.timeZone = timeZone;
}
/**
* Returns the string representation of the <CODE>CronExpression</CODE>
*
* @return a string representation of the <CODE>CronExpression</CODE>
*/
@Override
public String toString() {
return cronExpression;
}
/**
* Indicates whether the specified cron expression can be parsed into a
* valid cron expression
*
* @param cronExpression the expression to evaluate
* @return a boolean indicating whether the given expression is a valid cron
* expression
*/
public static boolean isValidExpression(String cronExpression) {
try {
new CronExpression(cronExpression);
} catch (IllegalArgumentException pe) {
return false;
}
return true;
}
public static void validateExpression(String cronExpression) throws ParseException {
new CronExpression(cronExpression);
}
////////////////////////////////////////////////////////////////////////////
//
// Expression Parsing Functions
//
////////////////////////////////////////////////////////////////////////////
protected void buildExpression(String expression) throws ParseException {
expressionParsed = true;
try {
if (seconds == null) {
seconds = new TreeSet<Integer>();
}
if (minutes == null) {
minutes = new TreeSet<Integer>();
}
if (hours == null) {
hours = new TreeSet<Integer>();
}
if (daysOfMonth == null) {
daysOfMonth = new TreeSet<Integer>();
}
if (months == null) {
months = new TreeSet<Integer>();
}
if (daysOfWeek == null) {
daysOfWeek = new TreeSet<Integer>();
}
if (years == null) {
years = new TreeSet<Integer>();
}
int exprOn = SECOND;
StringTokenizer exprsTok = new StringTokenizer(expression, " \t",
false);
while (exprsTok.hasMoreTokens() && exprOn <= YEAR) {
String expr = exprsTok.nextToken().trim();
// throw an exception if L is used with other days of the month
if(exprOn == DAY_OF_MONTH && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) {
throw new ParseException("Support for specifying 'L' and 'LW' with other days of the month is not implemented", -1);
}
// throw an exception if L is used with other days of the week
if(exprOn == DAY_OF_WEEK && expr.indexOf('L') != -1 && expr.length() > 1 && expr.contains(",")) {
throw new ParseException("Support for specifying 'L' with other days of the week is not implemented", -1);
}
if(exprOn == DAY_OF_WEEK && expr.indexOf('#') != -1 && expr.indexOf('#', expr.indexOf('#') +1) != -1) {
throw new ParseException("Support for specifying multiple \"nth\" days is not implemented.", -1);
}
StringTokenizer vTok = new StringTokenizer(expr, ",");
while (vTok.hasMoreTokens()) {
String v = vTok.nextToken();
storeExpressionVals(0, v, exprOn);
}
exprOn++;
}
if (exprOn <= DAY_OF_WEEK) {
throw new ParseException("Unexpected end of expression.",
expression.length());
}
if (exprOn <= YEAR) {
storeExpressionVals(0, "*", YEAR);
}
TreeSet<Integer> dow = getSet(DAY_OF_WEEK);
TreeSet<Integer> dom = getSet(DAY_OF_MONTH);
// Copying the logic from the UnsupportedOperationException below
boolean dayOfMSpec = !dom.contains(NO_SPEC);
boolean dayOfWSpec = !dow.contains(NO_SPEC);
if (!dayOfMSpec || dayOfWSpec) {
if (!dayOfWSpec || dayOfMSpec) {
throw new ParseException(
"Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.", 0);
}
}
} catch (ParseException pe) {
throw pe;
} catch (Exception e) {
throw new ParseException("Illegal cron expression format ("
+ e.toString() + ")", 0);
}
}
protected int storeExpressionVals(int pos, String s, int type)
throws ParseException {
int incr = 0;
int i = skipWhiteSpace(pos, s);
if (i >= s.length()) {
return i;
}
char c = s.charAt(i);
if ((c >= 'A') && (c <= 'Z') && (!s.equals("L")) && (!s.equals("LW")) && (!s.matches("^L-[0-9]*[W]?"))) {
String sub = s.substring(i, i + 3);
int sval = -1;
int eval = -1;
if (type == MONTH) {
sval = getMonthNumber(sub) + 1;
if (sval <= 0) {
throw new ParseException("Invalid Month value: '" + sub + "'", i);
}
if (s.length() > i + 3) {
c = s.charAt(i + 3);
if (c == '-') {
i += 4;
sub = s.substring(i, i + 3);
eval = getMonthNumber(sub) + 1;
if (eval <= 0) {
throw new ParseException("Invalid Month value: '" + sub + "'", i);
}
}
}
} else if (type == DAY_OF_WEEK) {
sval = getDayOfWeekNumber(sub);
if (sval < 0) {
throw new ParseException("Invalid Day-of-Week value: '"
+ sub + "'", i);
}
if (s.length() > i + 3) {
c = s.charAt(i + 3);
if (c == '-') {
i += 4;
sub = s.substring(i, i + 3);
eval = getDayOfWeekNumber(sub);
if (eval < 0) {
throw new ParseException(
"Invalid Day-of-Week value: '" + sub
+ "'", i);
}
} else if (c == '#') {
try {
i += 4;
nthdayOfWeek = Integer.parseInt(s.substring(i));
if (nthdayOfWeek < 1 || nthdayOfWeek > 5) {
throw new Exception();
}
} catch (Exception e) {
throw new ParseException(
"A numeric value between 1 and 5 must follow the '#' option",
i);
}
} else if (c == 'L') {
lastdayOfWeek = true;
i++;
}
}
} else {
throw new ParseException(
"Illegal characters for this position: '" + sub + "'",
i);
}
if (eval != -1) {
incr = 1;
}
addToSet(sval, eval, incr, type);
return (i + 3);
}
if (c == '?') {
i++;
if ((i + 1) < s.length()
&& (s.charAt(i) != ' ' && s.charAt(i + 1) != '\t')) {
throw new ParseException("Illegal character after '?': "
+ s.charAt(i), i);
}
if (type != DAY_OF_WEEK && type != DAY_OF_MONTH) {
throw new ParseException(
"'?' can only be specfied for Day-of-Month or Day-of-Week.",
i);
}
if (type == DAY_OF_WEEK && !lastdayOfMonth) {
int val = daysOfMonth.last();
if (val == NO_SPEC_INT) {
throw new ParseException(
"'?' can only be specfied for Day-of-Month -OR- Day-of-Week.",
i);
}
}
addToSet(NO_SPEC_INT, -1, 0, type);
return i;
}
if (c == '*' || c == '/') {
if (c == '*' && (i + 1) >= s.length()) {
addToSet(ALL_SPEC_INT, -1, incr, type);
return i + 1;
} else if (c == '/'
&& ((i + 1) >= s.length() || s.charAt(i + 1) == ' ' || s
.charAt(i + 1) == '\t')) {
throw new ParseException("'/' must be followed by an integer.", i);
} else if (c == '*') {
i++;
}
c = s.charAt(i);
if (c == '/') { // is an increment specified?
i++;
if (i >= s.length()) {
throw new ParseException("Unexpected end of string.", i);
}
incr = getNumericValue(s, i);
i++;
if (incr > 10) {
i++;
}
if (incr > 59 && (type == SECOND || type == MINUTE)) {
throw new ParseException("Increment > 60 : " + incr, i);
} else if (incr > 23 && (type == HOUR)) {
throw new ParseException("Increment > 24 : " + incr, i);
} else if (incr > 31 && (type == DAY_OF_MONTH)) {
throw new ParseException("Increment > 31 : " + incr, i);
} else if (incr > 7 && (type == DAY_OF_WEEK)) {
throw new ParseException("Increment > 7 : " + incr, i);
} else if (incr > 12 && (type == MONTH)) {
throw new ParseException("Increment > 12 : " + incr, i);
}
} else {
incr = 1;
}
addToSet(ALL_SPEC_INT, -1, incr, type);
return i;
} else if (c == 'L') {
i++;
if (type == DAY_OF_MONTH) {
lastdayOfMonth = true;
}
if (type == DAY_OF_WEEK) {
addToSet(7, 7, 0, type);
}
if(type == DAY_OF_MONTH && s.length() > i) {
c = s.charAt(i);
if(c == '-') {
ValueSet vs = getValue(0, s, i+1);
lastdayOffset = vs.value;
if(lastdayOffset > 30)
throw new ParseException("Offset from last day must be <= 30", i+1);
i = vs.pos;
}
if(s.length() > i) {
c = s.charAt(i);
if(c == 'W') {
nearestWeekday = true;
i++;
}
}
}
return i;
} else if (c >= '0' && c <= '9') {
int val = Integer.parseInt(String.valueOf(c));
i++;
if (i >= s.length()) {
addToSet(val, -1, -1, type);
} else {
c = s.charAt(i);
if (c >= '0' && c <= '9') {
ValueSet vs = getValue(val, s, i);
val = vs.value;
i = vs.pos;
}
i = checkNext(i, s, val, type);
return i;
}
} else {
throw new ParseException("Unexpected character: " + c, i);
}
return i;
}
protected int checkNext(int pos, String s, int val, int type)
throws ParseException {
int end = -1;
int i = pos;
if (i >= s.length()) {
addToSet(val, end, -1, type);
return i;
}
char c = s.charAt(pos);
if (c == 'L') {
if (type == DAY_OF_WEEK) {
if(val < 1 || val > 7)
throw new ParseException("Day-of-Week values must be between 1 and 7", -1);
lastdayOfWeek = true;
} else {
throw new ParseException("'L' option is not valid here. (pos=" + i + ")", i);
}
TreeSet<Integer> set = getSet(type);
set.add(val);
i++;
return i;
}
if (c == 'W') {
if (type == DAY_OF_MONTH) {
nearestWeekday = true;
} else {
throw new ParseException("'W' option is not valid here. (pos=" + i + ")", i);
}
if(val > 31)
throw new ParseException("The 'W' option does not make sense with values larger than 31 (max number of days in a month)", i);
TreeSet<Integer> set = getSet(type);
set.add(val);
i++;
return i;
}
if (c == '#') {
if (type != DAY_OF_WEEK) {
throw new ParseException("'#' option is not valid here. (pos=" + i + ")", i);
}
i++;
try {
nthdayOfWeek = Integer.parseInt(s.substring(i));
if (nthdayOfWeek < 1 || nthdayOfWeek > 5) {
throw new Exception();
}
} catch (Exception e) {
throw new ParseException(
"A numeric value between 1 and 5 must follow the '#' option",
i);
}
TreeSet<Integer> set = getSet(type);
set.add(val);
i++;
return i;
}
if (c == '-') {
i++;
c = s.charAt(i);
int v = Integer.parseInt(String.valueOf(c));
end = v;
i++;
if (i >= s.length()) {
addToSet(val, end, 1, type);
return i;
}
c = s.charAt(i);
if (c >= '0' && c <= '9') {
ValueSet vs = getValue(v, s, i);
end = vs.value;
i = vs.pos;
}
if (i < s.length() && ((c = s.charAt(i)) == '/')) {
i++;
c = s.charAt(i);
int v2 = Integer.parseInt(String.valueOf(c));
i++;
if (i >= s.length()) {
addToSet(val, end, v2, type);
return i;
}
c = s.charAt(i);
if (c >= '0' && c <= '9') {
ValueSet vs = getValue(v2, s, i);
int v3 = vs.value;
addToSet(val, end, v3, type);
i = vs.pos;
return i;
} else {
addToSet(val, end, v2, type);
return i;
}
} else {
addToSet(val, end, 1, type);
return i;
}
}
if (c == '/') {
i++;
c = s.charAt(i);
int v2 = Integer.parseInt(String.valueOf(c));
i++;
if (i >= s.length()) {
addToSet(val, end, v2, type);
return i;
}
c = s.charAt(i);
if (c >= '0' && c <= '9') {
ValueSet vs = getValue(v2, s, i);
int v3 = vs.value;
addToSet(val, end, v3, type);
i = vs.pos;
return i;
} else {
throw new ParseException("Unexpected character '" + c + "' after '/'", i);
}
}
addToSet(val, end, 0, type);
i++;
return i;
}
public String getCronExpression() {
return cronExpression;
}
public String getExpressionSummary() {
StringBuilder buf = new StringBuilder();
buf.append("seconds: ");
buf.append(getExpressionSetSummary(seconds));
buf.append("\n");
buf.append("minutes: ");
buf.append(getExpressionSetSummary(minutes));
buf.append("\n");
buf.append("hours: ");
buf.append(getExpressionSetSummary(hours));
buf.append("\n");
buf.append("daysOfMonth: ");
buf.append(getExpressionSetSummary(daysOfMonth));
buf.append("\n");
buf.append("months: ");
buf.append(getExpressionSetSummary(months));
buf.append("\n");
buf.append("daysOfWeek: ");
buf.append(getExpressionSetSummary(daysOfWeek));
buf.append("\n");
buf.append("lastdayOfWeek: ");
buf.append(lastdayOfWeek);
buf.append("\n");
buf.append("nearestWeekday: ");
buf.append(nearestWeekday);
buf.append("\n");
buf.append("NthDayOfWeek: ");
buf.append(nthdayOfWeek);
buf.append("\n");
buf.append("lastdayOfMonth: ");
buf.append(lastdayOfMonth);
buf.append("\n");
buf.append("years: ");
buf.append(getExpressionSetSummary(years));
buf.append("\n");
return buf.toString();
}
protected String getExpressionSetSummary(java.util.Set<Integer> set) {
if (set.contains(NO_SPEC)) {
return "?";
}
if (set.contains(ALL_SPEC)) {
return "*";
}
StringBuilder buf = new StringBuilder();
Iterator<Integer> itr = set.iterator();
boolean first = true;
while (itr.hasNext()) {
Integer iVal = itr.next();
String val = iVal.toString();
if (!first) {
buf.append(",");
}
buf.append(val);
first = false;
}
return buf.toString();
}
protected String getExpressionSetSummary(java.util.ArrayList<Integer> list) {
if (list.contains(NO_SPEC)) {
return "?";
}
if (list.contains(ALL_SPEC)) {
return "*";
}
StringBuilder buf = new StringBuilder();
Iterator<Integer> itr = list.iterator();
boolean first = true;
while (itr.hasNext()) {
Integer iVal = itr.next();
String val = iVal.toString();
if (!first) {
buf.append(",");
}
buf.append(val);
first = false;
}
return buf.toString();
}
protected int skipWhiteSpace(int i, String s) {
for (; i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == '\t'); i++) {
;
}
return i;
}
protected int findNextWhiteSpace(int i, String s) {
for (; i < s.length() && (s.charAt(i) != ' ' || s.charAt(i) != '\t'); i++) {
;
}
return i;
}
protected void addToSet(int val, int end, int incr, int type)
throws ParseException {
TreeSet<Integer> set = getSet(type);
if (type == SECOND || type == MINUTE) {
if ((val < 0 || val > 59 || end > 59) && (val != ALL_SPEC_INT)) {
throw new ParseException(
"Minute and Second values must be between 0 and 59",
-1);
}
} else if (type == HOUR) {
if ((val < 0 || val > 23 || end > 23) && (val != ALL_SPEC_INT)) {
throw new ParseException(
"Hour values must be between 0 and 23", -1);
}
} else if (type == DAY_OF_MONTH) {
if ((val < 1 || val > 31 || end > 31) && (val != ALL_SPEC_INT)
&& (val != NO_SPEC_INT)) {
throw new ParseException(
"Day of month values must be between 1 and 31", -1);
}
} else if (type == MONTH) {
if ((val < 1 || val > 12 || end > 12) && (val != ALL_SPEC_INT)) {
throw new ParseException(
"Month values must be between 1 and 12", -1);
}
} else if (type == DAY_OF_WEEK) {
if ((val == 0 || val > 7 || end > 7) && (val != ALL_SPEC_INT)
&& (val != NO_SPEC_INT)) {
throw new ParseException(
"Day-of-Week values must be between 1 and 7", -1);
}
}
if ((incr == 0 || incr == -1) && val != ALL_SPEC_INT) {
if (val != -1) {
set.add(val);
} else {
set.add(NO_SPEC);
}
return;
}
int startAt = val;
int stopAt = end;
if (val == ALL_SPEC_INT && incr <= 0) {
incr = 1;
set.add(ALL_SPEC); // put in a marker, but also fill values
}
if (type == SECOND || type == MINUTE) {
if (stopAt == -1) {
stopAt = 59;
}
if (startAt == -1 || startAt == ALL_SPEC_INT) {
startAt = 0;
}
} else if (type == HOUR) {
if (stopAt == -1) {
stopAt = 23;
}
if (startAt == -1 || startAt == ALL_SPEC_INT) {
startAt = 0;
}
} else if (type == DAY_OF_MONTH) {
if (stopAt == -1) {
stopAt = 31;
}
if (startAt == -1 || startAt == ALL_SPEC_INT) {
startAt = 1;
}
} else if (type == MONTH) {
if (stopAt == -1) {
stopAt = 12;
}
if (startAt == -1 || startAt == ALL_SPEC_INT) {
startAt = 1;
}
} else if (type == DAY_OF_WEEK) {
if (stopAt == -1) {
stopAt = 7;
}
if (startAt == -1 || startAt == ALL_SPEC_INT) {
startAt = 1;
}
} else if (type == YEAR) {
if (stopAt == -1) {
stopAt = MAX_YEAR;
}
if (startAt == -1 || startAt == ALL_SPEC_INT) {
startAt = 1970;
}
}
// if the end of the range is before the start, then we need to overflow into
// the next day, month etc. This is done by adding the maximum amount for that
// type, and using modulus max to determine the value being added.
int max = -1;
if (stopAt < startAt) {
switch (type) {
case SECOND : max = 60; break;
case MINUTE : max = 60; break;
case HOUR : max = 24; break;
case MONTH : max = 12; break;
case DAY_OF_WEEK : max = 7; break;
case DAY_OF_MONTH : max = 31; break;
case YEAR : throw new IllegalArgumentException("Start year must be less than stop year");
default : throw new IllegalArgumentException("Unexpected type encountered");
}
stopAt += max;
}
for (int i = startAt; i <= stopAt; i += incr) {
if (max == -1) {
// ie: there's no max to overflow over
set.add(i);
} else {
// take the modulus to get the real value
int i2 = i % max;
// 1-indexed ranges should not include 0, and should include their max
if (i2 == 0 && (type == MONTH || type == DAY_OF_WEEK || type == DAY_OF_MONTH) ) {
i2 = max;
}
set.add(i2);
}
}
}
TreeSet<Integer> getSet(int type) {
switch (type) {
case SECOND:
return seconds;
case MINUTE:
return minutes;
case HOUR:
return hours;
case DAY_OF_MONTH:
return daysOfMonth;
case MONTH:
return months;
case DAY_OF_WEEK:
return daysOfWeek;
case YEAR:
return years;
default:
return null;
}
}
protected ValueSet getValue(int v, String s, int i) {
char c = s.charAt(i);
StringBuilder s1 = new StringBuilder(String.valueOf(v));
while (c >= '0' && c <= '9') {
s1.append(c);
i++;
if (i >= s.length()) {
break;
}
c = s.charAt(i);
}
ValueSet val = new ValueSet();
val.pos = (i < s.length()) ? i : i + 1;
val.value = Integer.parseInt(s1.toString());
return val;
}
protected int getNumericValue(String s, int i) {
int endOfVal = findNextWhiteSpace(i, s);
String val = s.substring(i, endOfVal);
return Integer.parseInt(val);
}
protected int getMonthNumber(String s) {
Integer integer = monthMap.get(s);
if (integer == null) {
return -1;
}
return integer;
}
protected int getDayOfWeekNumber(String s) {
Integer integer = dayMap.get(s);
if (integer == null) {
return -1;
}
return integer;
}
////////////////////////////////////////////////////////////////////////////
//
// Computation Functions
//
////////////////////////////////////////////////////////////////////////////
public Date getTimeAfter(Date afterTime) {
// Computation is based on Gregorian year only.
Calendar cl = new java.util.GregorianCalendar(getTimeZone());
// move ahead one second, since we're computing the time *after* the
// given time
afterTime = new Date(afterTime.getTime() + 1000);
// CronTrigger does not deal with milliseconds
cl.setTime(afterTime);
cl.set(Calendar.MILLISECOND, 0);
boolean gotOne = false;
// loop until we've computed the next time, or we've past the endTime
while (!gotOne) {
//if (endTime != null && cl.getTime().after(endTime)) return null;
if(cl.get(Calendar.YEAR) > 2999) { // prevent endless loop...
return null;
}
SortedSet<Integer> st = null;
int t = 0;
int sec = cl.get(Calendar.SECOND);
int min = cl.get(Calendar.MINUTE);
// get second.................................................
st = seconds.tailSet(sec);
if (st != null && st.size() != 0) {
sec = st.first();
} else {
sec = seconds.first();
min++;
cl.set(Calendar.MINUTE, min);
}
cl.set(Calendar.SECOND, sec);
min = cl.get(Calendar.MINUTE);
int hr = cl.get(Calendar.HOUR_OF_DAY);
t = -1;
// get minute.................................................
st = minutes.tailSet(min);
if (st != null && st.size() != 0) {
t = min;
min = st.first();
} else {
min = minutes.first();
hr++;
}
if (min != t) {
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, min);
setCalendarHour(cl, hr);
continue;
}
cl.set(Calendar.MINUTE, min);
hr = cl.get(Calendar.HOUR_OF_DAY);
int day = cl.get(Calendar.DAY_OF_MONTH);
t = -1;
// get hour...................................................
st = hours.tailSet(hr);
if (st != null && st.size() != 0) {
t = hr;
hr = st.first();
} else {
hr = hours.first();
day++;
}
if (hr != t) {
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.DAY_OF_MONTH, day);
setCalendarHour(cl, hr);
continue;
}
cl.set(Calendar.HOUR_OF_DAY, hr);
day = cl.get(Calendar.DAY_OF_MONTH);
int mon = cl.get(Calendar.MONTH) + 1;
// '+ 1' because calendar is 0-based for this field, and we are
// 1-based
t = -1;
int tmon = mon;
// get day...................................................
boolean dayOfMSpec = !daysOfMonth.contains(NO_SPEC);
boolean dayOfWSpec = !daysOfWeek.contains(NO_SPEC);
if (dayOfMSpec && !dayOfWSpec) { // get day by day of month rule
st = daysOfMonth.tailSet(day);
if (lastdayOfMonth) {
if(!nearestWeekday) {
t = day;
day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
day -= lastdayOffset;
if(t > day) {
mon++;
if(mon > 12) {
mon = 1;
tmon = 3333; // ensure test of mon != tmon further below fails
cl.add(Calendar.YEAR, 1);
}
day = 1;
}
} else {
t = day;
day = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
day -= lastdayOffset;
java.util.Calendar tcal = java.util.Calendar.getInstance(getTimeZone());
tcal.set(Calendar.SECOND, 0);
tcal.set(Calendar.MINUTE, 0);
tcal.set(Calendar.HOUR_OF_DAY, 0);
tcal.set(Calendar.DAY_OF_MONTH, day);
tcal.set(Calendar.MONTH, mon - 1);
tcal.set(Calendar.YEAR, cl.get(Calendar.YEAR));
int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
int dow = tcal.get(Calendar.DAY_OF_WEEK);
if(dow == Calendar.SATURDAY && day == 1) {
day += 2;
} else if(dow == Calendar.SATURDAY) {
day -= 1;
} else if(dow == Calendar.SUNDAY && day == ldom) {
day -= 2;
} else if(dow == Calendar.SUNDAY) {
day += 1;
}
tcal.set(Calendar.SECOND, sec);
tcal.set(Calendar.MINUTE, min);
tcal.set(Calendar.HOUR_OF_DAY, hr);
tcal.set(Calendar.DAY_OF_MONTH, day);
tcal.set(Calendar.MONTH, mon - 1);
Date nTime = tcal.getTime();
if(nTime.before(afterTime)) {
day = 1;
mon++;
}
}
} else if(nearestWeekday) {
t = day;
day = daysOfMonth.first();
java.util.Calendar tcal = java.util.Calendar.getInstance(getTimeZone());
tcal.set(Calendar.SECOND, 0);
tcal.set(Calendar.MINUTE, 0);
tcal.set(Calendar.HOUR_OF_DAY, 0);
tcal.set(Calendar.DAY_OF_MONTH, day);
tcal.set(Calendar.MONTH, mon - 1);
tcal.set(Calendar.YEAR, cl.get(Calendar.YEAR));
int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
int dow = tcal.get(Calendar.DAY_OF_WEEK);
if(dow == Calendar.SATURDAY && day == 1) {
day += 2;
} else if(dow == Calendar.SATURDAY) {
day -= 1;
} else if(dow == Calendar.SUNDAY && day == ldom) {
day -= 2;
} else if(dow == Calendar.SUNDAY) {
day += 1;
}
tcal.set(Calendar.SECOND, sec);
tcal.set(Calendar.MINUTE, min);
tcal.set(Calendar.HOUR_OF_DAY, hr);
tcal.set(Calendar.DAY_OF_MONTH, day);
tcal.set(Calendar.MONTH, mon - 1);
Date nTime = tcal.getTime();
if(nTime.before(afterTime)) {
day = daysOfMonth.first();
mon++;
}
} else if (st != null && st.size() != 0) {
t = day;
day = st.first();
// make sure we don't over-run a short month, such as february
int lastDay = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
if (day > lastDay) {
day = daysOfMonth.first();
mon++;
}
} else {
day = daysOfMonth.first();
mon++;
}
if (day != t || mon != tmon) {
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.DAY_OF_MONTH, day);
cl.set(Calendar.MONTH, mon - 1);
// '- 1' because calendar is 0-based for this field, and we
// are 1-based
continue;
}
} else if (dayOfWSpec && !dayOfMSpec) { // get day by day of week rule
if (lastdayOfWeek) { // are we looking for the last XXX day of
// the month?
int dow = daysOfWeek.first(); // desired
// d-o-w
int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w
int daysToAdd = 0;
if (cDow < dow) {
daysToAdd = dow - cDow;
}
if (cDow > dow) {
daysToAdd = dow + (7 - cDow);
}
int lDay = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
if (day + daysToAdd > lDay) { // did we already miss the
// last one?
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.DAY_OF_MONTH, 1);
cl.set(Calendar.MONTH, mon);
// no '- 1' here because we are promoting the month
continue;
}
// find date of last occurrence of this day in this month...
while ((day + daysToAdd + 7) <= lDay) {
daysToAdd += 7;
}
day += daysToAdd;
if (daysToAdd > 0) {
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.DAY_OF_MONTH, day);
cl.set(Calendar.MONTH, mon - 1);
// '- 1' here because we are not promoting the month
continue;
}
} else if (nthdayOfWeek != 0) {
// are we looking for the Nth XXX day in the month?
int dow = daysOfWeek.first(); // desired
// d-o-w
int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w
int daysToAdd = 0;
if (cDow < dow) {
daysToAdd = dow - cDow;
} else if (cDow > dow) {
daysToAdd = dow + (7 - cDow);
}
boolean dayShifted = false;
if (daysToAdd > 0) {
dayShifted = true;
}
day += daysToAdd;
int weekOfMonth = day / 7;
if (day % 7 > 0) {
weekOfMonth++;
}
daysToAdd = (nthdayOfWeek - weekOfMonth) * 7;
day += daysToAdd;
if (daysToAdd < 0
|| day > getLastDayOfMonth(mon, cl
.get(Calendar.YEAR))) {
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.DAY_OF_MONTH, 1);
cl.set(Calendar.MONTH, mon);
// no '- 1' here because we are promoting the month
continue;
} else if (daysToAdd > 0 || dayShifted) {
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.DAY_OF_MONTH, day);
cl.set(Calendar.MONTH, mon - 1);
// '- 1' here because we are NOT promoting the month
continue;
}
} else {
int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w
int dow = daysOfWeek.first(); // desired
// d-o-w
st = daysOfWeek.tailSet(cDow);
if (st != null && st.size() > 0) {
dow = st.first();
}
int daysToAdd = 0;
if (cDow < dow) {
daysToAdd = dow - cDow;
}
if (cDow > dow) {
daysToAdd = dow + (7 - cDow);
}
int lDay = getLastDayOfMonth(mon, cl.get(Calendar.YEAR));
if (day + daysToAdd > lDay) { // will we pass the end of
// the month?
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.DAY_OF_MONTH, 1);
cl.set(Calendar.MONTH, mon);
// no '- 1' here because we are promoting the month
continue;
} else if (daysToAdd > 0) { // are we swithing days?
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.DAY_OF_MONTH, day + daysToAdd);
cl.set(Calendar.MONTH, mon - 1);
// '- 1' because calendar is 0-based for this field,
// and we are 1-based
continue;
}
}
} else { // dayOfWSpec && !dayOfMSpec
throw new UnsupportedOperationException(
"Support for specifying both a day-of-week AND a day-of-month parameter is not implemented.");
}
cl.set(Calendar.DAY_OF_MONTH, day);
mon = cl.get(Calendar.MONTH) + 1;
// '+ 1' because calendar is 0-based for this field, and we are
// 1-based
int year = cl.get(Calendar.YEAR);
t = -1;
// test for expressions that never generate a valid fire date,
// but keep looping...
if (year > MAX_YEAR) {
return null;
}
// get month...................................................
st = months.tailSet(mon);
if (st != null && st.size() != 0) {
t = mon;
mon = st.first();
} else {
mon = months.first();
year++;
}
if (mon != t) {
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.DAY_OF_MONTH, 1);
cl.set(Calendar.MONTH, mon - 1);
// '- 1' because calendar is 0-based for this field, and we are
// 1-based
cl.set(Calendar.YEAR, year);
continue;
}
cl.set(Calendar.MONTH, mon - 1);
// '- 1' because calendar is 0-based for this field, and we are
// 1-based
year = cl.get(Calendar.YEAR);
t = -1;
// get year...................................................
st = years.tailSet(year);
if (st != null && st.size() != 0) {
t = year;
year = st.first();
} else {
return null; // ran out of years...
}
if (year != t) {
cl.set(Calendar.SECOND, 0);
cl.set(Calendar.MINUTE, 0);
cl.set(Calendar.HOUR_OF_DAY, 0);
cl.set(Calendar.DAY_OF_MONTH, 1);
cl.set(Calendar.MONTH, 0);
// '- 1' because calendar is 0-based for this field, and we are
// 1-based
cl.set(Calendar.YEAR, year);
continue;
}
cl.set(Calendar.YEAR, year);
gotOne = true;
} // while( !done )
return cl.getTime();
}
/**
* Advance the calendar to the particular hour paying particular attention
* to daylight saving problems.
*
* @param cal the calendar to operate on
* @param hour the hour to set
*/
protected void setCalendarHour(Calendar cal, int hour) {
cal.set(java.util.Calendar.HOUR_OF_DAY, hour);
if (cal.get(java.util.Calendar.HOUR_OF_DAY) != hour && hour != 24) {
cal.set(java.util.Calendar.HOUR_OF_DAY, hour + 1);
}
}
public Date getTimeBefore(Date endTime) {
// FUTURE_TODO: implement QUARTZ-423
return null;
}
public Date getFinalFireTime() {
// FUTURE_TODO: implement QUARTZ-423
return null;
}
protected boolean isLeapYear(int year) {
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
protected int getLastDayOfMonth(int monthNum, int year) {
switch (monthNum) {
case 1:
return 31;
case 2:
return (isLeapYear(year)) ? 29 : 28;
case 3:
return 31;
case 4:
return 30;
case 5:
return 31;
case 6:
return 30;
case 7:
return 31;
case 8:
return 31;
case 9:
return 30;
case 10:
return 31;
case 11:
return 30;
case 12:
return 31;
default:
throw new IllegalArgumentException("Illegal month number: "
+ monthNum);
}
}
private void readObject(java.io.ObjectInputStream stream)
throws java.io.IOException, ClassNotFoundException {
stream.defaultReadObject();
try {
buildExpression(cronExpression);
} catch (Exception ignore) {
} // never happens
}
@Override
@Deprecated
public Object clone() {
return new CronExpression(this);
}
}
@SuppressWarnings("VisibilityModifier")
| CronExpression |
java | apache__camel | dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/DependencyRuntimeTest.java | {
"start": 1341,
"end": 3972
} | class ____ extends CamelCommandBaseTest {
@TempDir
File tempDir;
DependencyRuntime command;
Path pomFilePath;
private static Stream<Arguments> testOutputArguments() {
return Stream.of(
Arguments.of(TestArguments.MAIN_POM, TestArguments.MAIN_POM_OUTPUT),
Arguments.of(TestArguments.QUARKUS_POM, TestArguments.QUARKUS_POM_OUTPUT),
Arguments.of(TestArguments.SPRING_BOOT_POM, TestArguments.SPRING_BOOT_POM_OUTPUT));
}
private static Stream<Arguments> testJsonOutputArguments() {
return Stream.of(
Arguments.of(TestArguments.MAIN_POM, TestArguments.MAIN_POM_JSON_OUTPUT),
Arguments.of(TestArguments.QUARKUS_POM, TestArguments.QUARKUS_POM_JSON_OUTPUT),
Arguments.of(TestArguments.SPRING_BOOT_POM, TestArguments.SPRING_BOOT_POM_JSON_OUTPUT));
}
@BeforeEach
void setUp() {
command = new DependencyRuntime(new CamelJBangMain().withPrinter(printer));
pomFilePath = tempDir.toPath().resolve("pom.xml");
command.pomXml = pomFilePath;
}
@AfterEach
void tearDown() throws Exception {
Files.deleteIfExists(pomFilePath);
}
@Test
void testNoPomFile() throws Exception {
command.pomXml = tempDir.toPath().resolve("non-existing/pom.xml");
int exit = command.doCall();
assertEquals(1, exit);
}
@ParameterizedTest
@MethodSource("testOutputArguments")
void testStringOutput(String testPomXmlFile, String output) throws Exception {
try (var in = getClass().getClassLoader().getResourceAsStream(testPomXmlFile)) {
if (in == null) {
throw new IllegalStateException(String.format("Resource not found: %s", testPomXmlFile));
}
Files.copy(in, pomFilePath);
}
int exit = command.doCall();
assertEquals(0, exit);
assertEquals(output, printer.getOutput());
}
@ParameterizedTest
@MethodSource("testJsonOutputArguments")
void testJsonOutput(String testPomXmlFile, String jsonOutput) throws Exception {
try (var in = getClass().getClassLoader().getResourceAsStream(testPomXmlFile)) {
if (in == null) {
throw new IllegalStateException(String.format("Resource not found: %s", testPomXmlFile));
}
Files.copy(in, pomFilePath);
}
command.jsonOutput = true;
int exit = command.doCall();
assertEquals(0, exit);
assertEquals(jsonOutput, printer.getOutput());
}
private static | DependencyRuntimeTest |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableToSingleTest.java | {
"start": 882,
"end": 3127
} | class ____ extends RxJavaTest {
@Test
public void justSingleItemObservable() {
TestSubscriber<String> subscriber = TestSubscriber.create();
Single<String> single = Flowable.just("Hello World!").single("");
single.toFlowable().subscribe(subscriber);
subscriber.assertResult("Hello World!");
}
@Test
public void errorObservable() {
TestSubscriber<String> subscriber = TestSubscriber.create();
IllegalArgumentException error = new IllegalArgumentException("Error");
Single<String> single = Flowable.<String>error(error).single("");
single.toFlowable().subscribe(subscriber);
subscriber.assertError(error);
}
@Test
public void justTwoEmissionsObservableThrowsError() {
TestSubscriber<String> subscriber = TestSubscriber.create();
Single<String> single = Flowable.just("First", "Second").single("");
single.toFlowable().subscribe(subscriber);
subscriber.assertError(IllegalArgumentException.class);
}
@Test
public void emptyObservable() {
TestSubscriber<String> subscriber = TestSubscriber.create();
Single<String> single = Flowable.<String>empty().single("");
single.toFlowable().subscribe(subscriber);
subscriber.assertResult("");
}
@Test
public void repeatObservableThrowsError() {
TestSubscriber<String> subscriber = TestSubscriber.create();
Single<String> single = Flowable.just("First", "Second").repeat().single("");
single.toFlowable().subscribe(subscriber);
subscriber.assertError(IllegalArgumentException.class);
}
@Test
public void shouldUseUnsafeSubscribeInternallyNotSubscribe() {
TestSubscriber<String> subscriber = TestSubscriber.create();
final AtomicBoolean unsubscribed = new AtomicBoolean(false);
Single<String> single = Flowable.just("Hello World!").doOnCancel(new Action() {
@Override
public void run() {
unsubscribed.set(true);
}}).single("");
single.toFlowable().subscribe(subscriber);
subscriber.assertComplete();
Assert.assertFalse(unsubscribed.get());
}
}
| FlowableToSingleTest |
java | spring-projects__spring-boot | module/spring-boot-data-redis/src/main/java/org/springframework/boot/data/redis/autoconfigure/DataRedisProperties.java | {
"start": 4593,
"end": 4775
} | enum ____ {
/**
* Use the Lettuce redis client.
*/
LETTUCE,
/**
* Use the Jedis redis client.
*/
JEDIS
}
/**
* Pool properties.
*/
public static | ClientType |
java | resilience4j__resilience4j | resilience4j-ratelimiter/src/main/java/io/github/resilience4j/ratelimiter/RateLimiterConfig.java | {
"start": 5565,
"end": 9865
} | class ____ {
private Duration timeoutDuration = Duration.ofSeconds(5);
private Duration limitRefreshPeriod = Duration.ofNanos(500);
private int limitForPeriod = 50;
private Predicate<Either<? extends Throwable, ?>> drainPermissionsOnResult = any -> false;
private boolean writableStackTraceEnabled = DEFAULT_WRITABLE_STACK_TRACE_ENABLED;
public Builder() {
}
public Builder(RateLimiterConfig prototype) {
this.timeoutDuration = prototype.timeoutDuration;
this.limitRefreshPeriod = prototype.limitRefreshPeriod;
this.limitForPeriod = prototype.limitForPeriod;
this.drainPermissionsOnResult = prototype.drainPermissionsOnResult;
this.writableStackTraceEnabled = prototype.writableStackTraceEnabled;
}
/**
* Builds a RateLimiterConfig
*
* @return the RateLimiterConfig
*/
public RateLimiterConfig build() {
return new RateLimiterConfig(timeoutDuration, limitRefreshPeriod, limitForPeriod,
drainPermissionsOnResult, writableStackTraceEnabled);
}
/**
* Enables writable stack traces. When set to false, {@link Exception#getStackTrace()}
* returns a zero length array. This may be used to reduce log spam when the circuit breaker
* is open as the cause of the exceptions is already known (the circuit breaker is
* short-circuiting calls).
*
* @param writableStackTraceEnabled flag to control if stack trace is writable
* @return the BulkheadConfig.Builder
*/
public Builder writableStackTraceEnabled(boolean writableStackTraceEnabled) {
this.writableStackTraceEnabled = writableStackTraceEnabled;
return this;
}
/**
* Allows you to check the result of a call decorated by this rate limiter and make a decision
* should we drain all the permissions left it the current period. Useful in situations when
* despite using a RateLimiter the underlining called service will say that you passed the maximum number of calls for a given period.
*
* @param drainPermissionsOnResult your function should return true when the permissions drain
* should happen
* @return the RateLimiterConfig.Builder
* @see RateLimiter#drainPermissions()
*/
public Builder drainPermissionsOnResult(
Predicate<Either<? extends Throwable, ?>> drainPermissionsOnResult) {
this.drainPermissionsOnResult = drainPermissionsOnResult;
return this;
}
/**
* Configures the default wait for permission duration. Default value is 5 seconds.
*
* @param timeoutDuration the default wait for permission duration
* @return the RateLimiterConfig.Builder
*/
public Builder timeoutDuration(final Duration timeoutDuration) {
this.timeoutDuration = checkTimeoutDuration(timeoutDuration);
return this;
}
/**
* Configures the period of limit refresh. After each period rate limiter sets its
* permissions count to {@link RateLimiterConfig#limitForPeriod} value. Default value is 500
* nanoseconds.
*
* @param limitRefreshPeriod the period of limit refresh
* @return the RateLimiterConfig.Builder
*/
public Builder limitRefreshPeriod(final Duration limitRefreshPeriod) {
this.limitRefreshPeriod = checkLimitRefreshPeriod(limitRefreshPeriod);
return this;
}
/**
* Configures the permissions limit for refresh period. Count of permissions available
* during one rate limiter period specified by {@link RateLimiterConfig#limitRefreshPeriod}
* value. Default value is 50.
*
* @param limitForPeriod the permissions limit for refresh period
* @return the RateLimiterConfig.Builder
*/
public Builder limitForPeriod(final int limitForPeriod) {
this.limitForPeriod = checkLimitForPeriod(limitForPeriod);
return this;
}
}
}
| Builder |
java | apache__hadoop | hadoop-cloud-storage-project/hadoop-tos/src/main/java/org/apache/hadoop/fs/tosfs/common/Chain.java | {
"start": 3354,
"end": 3449
} | interface ____<T extends Closeable> {
T newItem() throws IOException;
}
public | ItemFactory |
java | apache__rocketmq | tools/src/main/java/org/apache/rocketmq/tools/command/broker/UpdateBrokerConfigSubCommand.java | {
"start": 1351,
"end": 4557
} | class ____ implements SubCommand {
@Override
public String commandName() {
return "updateBrokerConfig";
}
@Override
public String commandDesc() {
return "Update broker's config.";
}
@Override
public Options buildCommandlineOptions(Options options) {
Option opt = new Option("b", "brokerAddr", true, "update which broker");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("c", "clusterName", true, "update which cluster");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("a", "updateAllBroker", true, "update all brokers include slave");
opt.setRequired(false);
options.addOption(opt);
opt = new Option("k", "key", true, "config key");
opt.setRequired(true);
options.addOption(opt);
opt = new Option("v", "value", true, "config value");
opt.setRequired(true);
options.addOption(opt);
return options;
}
@Override
public void execute(CommandLine commandLine, Options options, RPCHook rpcHook) throws SubCommandException {
DefaultMQAdminExt defaultMQAdminExt = new DefaultMQAdminExt(rpcHook);
defaultMQAdminExt.setInstanceName(Long.toString(System.currentTimeMillis()));
try {
String key = commandLine.getOptionValue('k').trim();
String value = commandLine.getOptionValue('v').trim();
Properties properties = new Properties();
properties.put(key, value);
if (commandLine.hasOption('b')) {
String brokerAddr = commandLine.getOptionValue('b').trim();
defaultMQAdminExt.start();
defaultMQAdminExt.updateBrokerConfig(brokerAddr, properties);
System.out.printf("update broker config success, %s\n", brokerAddr);
return;
} else if (commandLine.hasOption('c')) {
String clusterName = commandLine.getOptionValue('c').trim();
defaultMQAdminExt.start();
Set<String> brokerAddrSet;
if (commandLine.hasOption('a')) {
brokerAddrSet = CommandUtil.fetchMasterAndSlaveAddrByClusterName(defaultMQAdminExt, clusterName);
} else {
brokerAddrSet = CommandUtil.fetchMasterAddrByClusterName(defaultMQAdminExt, clusterName);
}
for (String brokerAddr : brokerAddrSet) {
try {
defaultMQAdminExt.updateBrokerConfig(brokerAddr, properties);
System.out.printf("update broker config success, %s\n", brokerAddr);
} catch (Exception e) {
e.printStackTrace();
}
}
return;
}
ServerUtil.printCommandLineHelp("mqadmin " + this.commandName(), options);
} catch (Exception e) {
throw new SubCommandException(this.getClass().getSimpleName() + " command failed", e);
} finally {
defaultMQAdminExt.shutdown();
}
}
}
| UpdateBrokerConfigSubCommand |
java | apache__camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/SharedCamelInternalProcessor.java | {
"start": 8445,
"end": 10715
} | class ____ implements AsyncCallback {
private final Object state;
private final Exchange exchange;
private final AsyncCallback callback;
private final Processor resultProcessor;
private InternalCallback(Object state, Exchange exchange, AsyncCallback callback, Processor resultProcessor) {
this.state = state;
this.exchange = exchange;
this.callback = callback;
this.resultProcessor = resultProcessor;
}
@Override
public void done(boolean doneSync) {
// NOTE: if you are debugging Camel routes, then all the code in the for loop below is internal only
// so you can step straight to the finally-block and invoke the callback
if (resultProcessor != null) {
try {
resultProcessor.process(exchange);
} catch (Exception e) {
exchange.setException(e);
}
}
// we should call after in reverse order
try {
AdviceIterator.runAfterTask(advice, state, exchange);
} finally {
// callback must be called
if (callback != null) {
reactiveExecutor.schedule(callback);
}
}
}
}
/**
* Strategy to determine if we should continue processing the {@link Exchange}.
*/
protected boolean continueProcessing(Exchange exchange) {
if (exchange.isRouteStop()) {
LOG.debug("Exchange is marked to stop routing: {}", exchange);
return false;
}
if (shutdownStrategy.isForceShutdown()) {
if (LOG.isDebugEnabled() || exchange.getException() == null) {
String msg = "Run not allowed as ShutdownStrategy is forcing shutting down, will reject executing exchange: "
+ exchange;
LOG.debug(msg);
if (exchange.getException() == null) {
exchange.setException(new RejectedExecutionException(msg));
}
}
return false;
}
// yes we can continue
return true;
}
}
| InternalCallback |
java | apache__camel | components/camel-spring-parent/camel-spring-ws/src/test/java/org/apache/camel/component/spring/ws/MessageFilterResolvingTest.java | {
"start": 1717,
"end": 3893
} | class ____ extends AbstractSmockClientTest {
@Autowired
private ProducerTemplate template;
private String body = "<customerCountRequest xmlns='http://springframework.org/spring-ws'>"
+ "<customerName>John Doe</customerName>" + "</customerCountRequest>";
@Test
public void globalTestHeaderAttribute() {
expect(soapHeader(new QName("http://newHeaderSupport/", "testHeaderValue1")))
.andExpect(soapHeader(new QName("http://virtualCheck/", "globalFilter")));
template.sendBodyAndHeader("direct:sendWithGlobalFilter", body, "headerKey",
new QName("http://newHeaderSupport/", "testHeaderValue1"));
}
@Test
public void localTestHeaderAttribute() {
expect(soapHeader(new QName("http://newHeaderSupport/", "testHeaderValue1")))
.andExpect(soapHeader(new QName("http://virtualCheck/", "localFilter")));
template.sendBodyAndHeader("direct:sendWithLocalFilter", body, "headerKey",
new QName("http://newHeaderSupport/", "testHeaderValue1"));
}
@Test
public void emptyTestHeaderAttribute() {
expect(doesntContains(soapHeader(new QName("http://newHeaderSupport/", "testHeaderValue1"))));
template.sendBodyAndHeader("direct:sendWithoutFilter", body, "headerKey",
new QName("http://newHeaderSupport/", "testHeaderValue1"));
}
private RequestMatcher doesntContains(final RequestMatcher soapHeader) {
return new RequestMatcher() {
public void match(URI uri, WebServiceMessage request) throws IOException, AssertionError {
try {
soapHeader.match(uri, request);
} catch (AssertionError e) {
// ok
return;
}
throw new AssertionError("Should failed!");
}
};
}
@Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
createServer(applicationContext);
}
@Override
@AfterEach
public void verify() {
super.verify();
}
}
| MessageFilterResolvingTest |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/MimeType.java | {
"start": 939,
"end": 1911
} | enum ____ {
JSON("application/json"),
PROTOBUF("application/protobuf"),
PROTOBUF_BINARY("protobuf/binary"),
PROTOBUF_STRUCT("protobuf/x-struct"),
PROTOBUF_JAVA_OBJECT("protobuf/x-java-object"),
AVRO("application/avro"),
AVRO_BINARY("avro/binary"),
AVRO_STRUCT("avro/x-struct"),
AVRO_JAVA_OBJECT("avro/x-java-object"),
BINARY("application/octet-stream"),
TEXT("text/plain"),
JAVA_OBJECT("application/x-java-object"),
STRUCT("application/x-struct");
private static final MimeType[] VALUES = values();
private final String type;
MimeType(String type) {
this.type = type;
}
public String type() {
return type;
}
public static MimeType of(String type) {
for (MimeType mt : VALUES) {
if (Objects.equals(type, mt.type)) {
return mt;
}
}
throw new IllegalArgumentException("Unsupported type: " + type);
}
}
| MimeType |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/nullargs/NullEntityManagerArgumentsTest.java | {
"start": 448,
"end": 1013
} | class ____ {
@Test void test(EntityManagerFactoryScope scope) {
scope.inTransaction( em -> {
var operations = List.<Consumer<?>>of(
em::persist,
em::refresh,
em::merge,
em::detach,
em::remove,
e -> em.lock( e, LockModeType.NONE ),
em::getLockMode,
em::contains
);
operations.forEach( c -> {
try {
c.accept( null );
}
catch ( IllegalArgumentException e ) {
assertTrue( e.getMessage().startsWith( "Entity may not be null" ) );
}
} );
} );
}
}
| NullEntityManagerArgumentsTest |
java | elastic__elasticsearch | x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/index/mapper/ShapeFieldMapper.java | {
"start": 3425,
"end": 6405
} | class ____ extends FieldMapper.Builder {
final Parameter<Boolean> indexed = Parameter.indexParam(m -> builder(m).indexed.get(), true);
final Parameter<Boolean> hasDocValues;
private final IndexVersion version;
final Parameter<Explicit<Boolean>> ignoreMalformed;
final Parameter<Explicit<Boolean>> ignoreZValue = ignoreZValueParam(m -> builder(m).ignoreZValue.get());
final Parameter<Explicit<Boolean>> coerce;
final Parameter<Explicit<Orientation>> orientation = orientationParam(m -> builder(m).orientation.get());
final Parameter<Map<String, String>> meta = Parameter.metaParam();
public Builder(String name, IndexVersion version, boolean ignoreMalformedByDefault, boolean coerceByDefault) {
super(name);
this.version = version;
this.ignoreMalformed = ignoreMalformedParam(m -> builder(m).ignoreMalformed.get(), ignoreMalformedByDefault);
this.coerce = coerceParam(m -> builder(m).coerce.get(), coerceByDefault);
this.hasDocValues = Parameter.docValuesParam(m -> builder(m).hasDocValues.get(), IndexVersions.V_8_4_0.onOrBefore(version));
}
@Override
protected Parameter<?>[] getParameters() {
return new Parameter<?>[] { indexed, hasDocValues, ignoreMalformed, ignoreZValue, coerce, orientation, meta };
}
@Override
public ShapeFieldMapper build(MapperBuilderContext context) {
if (multiFieldsBuilder.hasMultiFields()) {
/*
* We have no plans to fail on multifields because it isn't worth breaking
* even the tiny fraction of users.
*/
DEPRECATION_LOGGER.warn(
DeprecationCategory.MAPPINGS,
"shape_multifields",
"Adding multifields to [shape] mappers has no effect"
);
}
GeometryParser geometryParser = new GeometryParser(
orientation.get().value().getAsBoolean(),
coerce.get().value(),
ignoreZValue.get().value()
);
Parser<Geometry> parser = new ShapeParser(geometryParser);
ShapeFieldType ft = new ShapeFieldType(
context.buildFullName(leafName()),
indexed.get(),
hasDocValues.get(),
orientation.get().value(),
parser,
context.isSourceSynthetic(),
meta.get()
);
return new ShapeFieldMapper(leafName(), ft, builderParams(this, context), parser, this);
}
}
public static final TypeParser PARSER = new TypeParser(
(n, c) -> new Builder(
n,
c.indexVersionCreated(),
IGNORE_MALFORMED_SETTING.get(c.getSettings()),
COERCE_SETTING.get(c.getSettings())
)
);
public static final | Builder |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/util/Sets_newHashSet_Test.java | {
"start": 850,
"end": 1368
} | class ____ {
@Test
void should_return_empty_mutable_Set() {
HashSet<Object> set = Sets.newHashSet();
assertThat(set).isEmpty();
set.add("element");
assertThat(set).containsExactly("element");
}
@Test
void should_return_new_HashSet() {
HashSet<Object> set1 = Sets.newHashSet();
HashSet<Object> set2 = Sets.newHashSet();
assertThat(set2).isNotSameAs(set1);
// be sure they have nothing in common
set1.add("element");
assertThat(set2).isEmpty();
}
}
| Sets_newHashSet_Test |
java | junit-team__junit5 | junit-platform-commons/src/main/java/org/junit/platform/commons/util/ReflectionUtils.java | {
"start": 2937,
"end": 3220
} | class ____ {
private static final Logger logger = LoggerFactory.getLogger(ReflectionUtils.class);
private ReflectionUtils() {
/* no-op */
}
/**
* Modes in which a hierarchy can be traversed — for example, when
* searching for methods or fields within a | ReflectionUtils |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/resume/ConsumerListener.java | {
"start": 886,
"end": 1176
} | interface ____ listening to consumer events and allow proxying between a consumer predicate and the Camel
* component. The whole of the consumer predicate is that of evaluating whether the consumption (from the internal Camel
* consumer) can continue or should be put on pause.
*/
public | for |
java | spring-projects__spring-framework | framework-docs/src/main/java/org/springframework/docs/web/websocket/stomp/websocketstompserverconfig/JettyWebSocketConfiguration.java | {
"start": 1333,
"end": 1945
} | class ____ implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/portfolio").setHandshakeHandler(handshakeHandler());
}
@Bean
public DefaultHandshakeHandler handshakeHandler() {
JettyRequestUpgradeStrategy strategy = new JettyRequestUpgradeStrategy();
strategy.addWebSocketConfigurer(configurable -> {
configurable.setInputBufferSize(4 * 8192);
configurable.setIdleTimeout(Duration.ofSeconds(600));
});
return new DefaultHandshakeHandler(strategy);
}
}
// end::snippet[]
| JettyWebSocketConfiguration |
java | quarkusio__quarkus | extensions/kubernetes-config/runtime/src/main/java/io/quarkus/kubernetes/config/runtime/KubernetesConfigBuildTimeConfig.java | {
"start": 383,
"end": 852
} | interface ____ {
/**
* Whether configuration can be read from secrets.
* If set to {@code true}, Kubernetes resources allowing access to secrets (role and role binding) will be generated.
*/
@WithName("secrets.enabled")
@WithDefault("false")
boolean secretsEnabled();
/**
* Role configuration to generate if the "secrets-enabled" property is true.
*/
SecretsRoleConfig secretsRoleConfig();
}
| KubernetesConfigBuildTimeConfig |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/actions/webhook/WebhookAction.java | {
"start": 4690,
"end": 5339
} | class ____ extends Action.Result implements Result {
private final HttpRequest request;
public Simulated(HttpRequest request) {
super(TYPE, Status.SIMULATED);
this.request = request;
}
public HttpRequest request() {
return request;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.startObject(type).field(Field.REQUEST.getPreferredName(), request, params).endObject();
}
}
}
public static | Simulated |
java | google__dagger | hilt-android-testing/main/java/dagger/hilt/testing/TestInstallIn.java | {
"start": 1330,
"end": 1625
} | class ____ {
* {@literal @}Provides
* static Foo provideFoo() {
* return new FakeFoo();
* }
* }
* </code></pre>
*
* @see <a href="https://dagger.dev/hilt/modules">Hilt Modules</a>
*/
@Retention(CLASS)
@Target({ElementType.TYPE})
@GeneratesRootInput
public @ | FakeFooModule |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/querydsl/agg/PercentileRanksAgg.java | {
"start": 619,
"end": 1236
} | class ____ extends DefaultAggSourceLeafAgg {
private final List<Double> values;
private final PercentilesConfig percentilesConfig;
public PercentileRanksAgg(String id, AggSource source, List<Double> values, PercentilesConfig percentilesConfig) {
super(id, source);
this.values = values;
this.percentilesConfig = percentilesConfig;
}
@Override
Function<String, ValuesSourceAggregationBuilder<?>> builder() {
return s -> percentileRanks(s, values.stream().mapToDouble(Double::doubleValue).toArray()).percentilesConfig(percentilesConfig);
}
}
| PercentileRanksAgg |
java | spring-projects__spring-boot | test-support/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/resources/Resources.java | {
"start": 1427,
"end": 5452
} | class ____ {
private final Path root;
private final Map<String, Resource> resources = new HashMap<>();
Resources(Path root) {
this.root = root;
}
Resources addPackage(String packageName, String[] resourceNames) {
Set<String> unmatchedNames = new HashSet<>(Arrays.asList(resourceNames));
withPathsForPackage(packageName, (packagePath) -> {
for (String resourceName : resourceNames) {
Path resource = packagePath.resolve(resourceName);
if (Files.exists(resource) && !Files.isDirectory(resource)) {
Path target = this.root.resolve(resourceName);
Path targetDirectory = target.getParent();
if (!Files.isDirectory(targetDirectory)) {
Files.createDirectories(targetDirectory);
}
Files.copy(resource, target);
register(resourceName, target, true);
unmatchedNames.remove(resourceName);
}
}
});
Assert.isTrue(unmatchedNames.isEmpty(),
"Package '" + packageName + "' did not contain resources: " + unmatchedNames);
return this;
}
private void withPathsForPackage(String packageName, ThrowingConsumer<Path> consumer) {
try {
List<URL> sources = Collections
.list(getClass().getClassLoader().getResources(packageName.replace(".", "/")));
for (URL source : sources) {
URI sourceUri = source.toURI();
try {
consumer.accept(Paths.get(sourceUri));
}
catch (FileSystemNotFoundException ex) {
try (FileSystem fileSystem = FileSystems.newFileSystem(sourceUri, Collections.emptyMap())) {
consumer.accept(Paths.get(sourceUri));
}
}
}
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
catch (URISyntaxException ex) {
throw new RuntimeException(ex);
}
}
Resources addResource(String name, String content, boolean additional) {
Path resourcePath = this.root.resolve(name);
if (Files.isDirectory(resourcePath)) {
throw new IllegalStateException(
"Cannot create resource '" + name + "' as a directory already exists at that location");
}
Path parent = resourcePath.getParent();
try {
if (!Files.isDirectory(resourcePath)) {
Files.createDirectories(parent);
}
Files.writeString(resourcePath, processContent(content));
register(name, resourcePath, additional);
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
private void register(String name, Path resourcePath, boolean additional) {
Resource resource = new Resource(resourcePath, additional);
register(name, resource);
Path ancestor = resourcePath.getParent();
while (!this.root.equals(ancestor)) {
Resource ancestorResource = new Resource(ancestor, additional);
register(this.root.relativize(ancestor).toString(), ancestorResource);
ancestor = ancestor.getParent();
}
}
private void register(String name, Resource resource) {
String normalized = name.replace("\\", "/");
this.resources.put(normalized, resource);
if (Files.isDirectory(resource.path())) {
if (normalized.endsWith("/")) {
this.resources.put(normalized.substring(0, normalized.length() - 1), resource);
}
else {
this.resources.put(normalized + "/", resource);
}
}
}
private String processContent(String content) {
return content.replace("${resourceRoot}", this.root.toString());
}
Resources addDirectory(String name) {
Path directoryPath = this.root.resolve(name);
if (Files.isRegularFile(directoryPath)) {
throw new IllegalStateException(
"Cannot create directory '" + name + " as a file already exists at that location");
}
try {
Files.createDirectories(directoryPath);
register(name, directoryPath, true);
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
return this;
}
void delete() {
try {
FileSystemUtils.deleteRecursively(this.root);
this.resources.clear();
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
Path getRoot() {
return this.root;
}
Resource find(String name) {
return this.resources.get(name);
}
}
| Resources |
java | quarkusio__quarkus | extensions/spring-data-jpa/deployment/src/test/java/io/quarkus/spring/data/deployment/nested/fields/CustomerRepositoryNestedFieldsDerivedMethodsTest.java | {
"start": 838,
"end": 3194
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addAsResource("import_customers.sql", "import.sql")
.addClasses(Customer.class, CustomerRepository.class))
.withConfigurationResource("application.properties");
@Autowired
private CustomerRepository customerRepository;
@Test
@Transactional
void findByAddressZipCode() {
List<Customer> allByAddressZipCode = customerRepository.findAllByAddressZipCode("28004");
assertEquals(2, allByAddressZipCode.size());
assertThat(allByAddressZipCode.stream().map(c -> c.getName()).collect(Collectors.toList()))
.containsExactlyInAnyOrder("Adam", "Tim");
}
@Test
@Transactional
void findByAddressCountryIsoCode() {
assertEquals(2, customerRepository.findAllByAddressCountryIsoCode("ES")
.size());
assertEquals(2, customerRepository.findAllByAddress_CountryIsoCode("ES")
.size());
assertEquals(2, customerRepository.findAllByAddress_Country_IsoCode("ES")
.size());
}
@Test
@Transactional
void findByAddressCountry() {
QueryArgumentException exception = assertThrows(QueryArgumentException.class,
() -> customerRepository.findAllByAddressCountry("Spain"));
assertThat(exception).hasMessageContaining("Argument [Spain] of type [java.lang.String] did not match parameter type");
assertThrows(QueryArgumentException.class,
() -> customerRepository.findAllByAddress_Country("Spain"));
assertThat(exception).hasMessageContaining("Argument [Spain] of type [java.lang.String] did not match parameter type");
}
@Test
@Transactional
void shouldCountSpanishCustomers() {
long spanishCustomers = customerRepository.countCustomerByAddressCountryName("Spain");
Assertions.assertEquals(2, spanishCustomers);
}
@Test
@Transactional
void shouldCountCustomersByZipCode() {
long spanishCustomers = customerRepository.countCustomerByAddress_ZipCode("28004");
Assertions.assertEquals(2, spanishCustomers);
}
}
| CustomerRepositoryNestedFieldsDerivedMethodsTest |
java | spring-projects__spring-boot | module/spring-boot-pulsar/src/main/java/org/springframework/boot/pulsar/testcontainers/DeprecatedPulsarContainerConnectionDetailsFactory.java | {
"start": 1914,
"end": 2363
} | class ____ extends ContainerConnectionDetails<PulsarContainer>
implements PulsarConnectionDetails {
private PulsarContainerConnectionDetails(ContainerConnectionSource<PulsarContainer> source) {
super(source);
}
@Override
public String getBrokerUrl() {
return getContainer().getPulsarBrokerUrl();
}
@Override
public String getAdminUrl() {
return getContainer().getHttpServiceUrl();
}
}
}
| PulsarContainerConnectionDetails |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/ValidateTest.java | {
"start": 34833,
"end": 36012
} | class ____ {
@Test
void shouldNotThrowExceptionForNonEmptyArray() {
Validate.noNullElements(new String[] {"a", "b"}, "MSG");
}
@Test
void shouldReturnSameInstance() {
final String[] array = {"a", "b"};
assertSame(array, Validate.noNullElements(array, "MSG"));
}
@Test
void shouldThrowIllegalArgumentExceptionWithGivenMessageForArrayWithNullElement() {
final IllegalArgumentException ex = assertIllegalArgumentException(
() -> Validate.noNullElements(new String[] {"a", null}, "MSG"));
assertEquals("MSG", ex.getMessage());
}
@Test
void shouldThrowNullPointerExceptionWithDefaultMessageForNullArray() {
final NullPointerException ex = assertNullPointerException(() -> Validate.noNullElements((Object[]) null, "MSG"));
assertEquals("array", ex.getMessage());
}
}
@Nested
final | WithMessage |
java | elastic__elasticsearch | x-pack/plugin/security/qa/smoke-test-all-realms/src/javaRestTest/java/org/elasticsearch/xpack/security/authc/ReservedRealmAuthIT.java | {
"start": 739,
"end": 1705
} | class ____ extends SecurityRealmSmokeTestCase {
private static final String USERNAME = "kibana_system";
private static final String ROLE_NAME = "kibana_system";
private SecureString password;
@Before
public void setUserPassword() throws IOException {
this.password = new SecureString(randomAlphaOfLengthBetween(14, 20).toCharArray());
changePassword(USERNAME, password);
}
public void testAuthenticationUsingReservedRealm() throws IOException {
Map<String, Object> authenticate = super.authenticate(
RequestOptions.DEFAULT.toBuilder().addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(USERNAME, password))
);
assertUsername(authenticate, USERNAME);
assertRealm(authenticate, "reserved", "reserved");
assertRoles(authenticate, ROLE_NAME);
assertNoApiKeyInfo(authenticate, Authentication.AuthenticationType.REALM);
}
}
| ReservedRealmAuthIT |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/ErasureCodeBenchmarkThroughput.java | {
"start": 11987,
"end": 14513
} | class ____ extends CallableBase {
private final boolean statefulRead;
public ReadCallable(int dataSizeMB, boolean isEc, int id,
boolean statefulRead) throws IOException {
super(dataSizeMB, isEc, id);
this.statefulRead = statefulRead;
}
private long doStateful(FSDataInputStream inputStream) throws IOException {
long count = 0;
long bytesRead;
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE_MB * 1024 * 1024);
while (true) {
bytesRead = inputStream.read(buffer);
if (bytesRead < 0) {
break;
}
count += bytesRead;
buffer.clear();
}
return count;
}
private long doPositional(FSDataInputStream inputStream)
throws IOException {
long count = 0;
long bytesRead;
byte buf[] = new byte[BUFFER_SIZE_MB * 1024 * 1024];
while (true) {
bytesRead = inputStream.read(count, buf, 0, buf.length);
if (bytesRead < 0) {
break;
}
count += bytesRead;
}
return count;
}
private long readFile(Path path) throws IOException {
try (FSDataInputStream inputStream = fs.open(path)) {
StopWatch sw = new StopWatch().start();
System.out.println((statefulRead ? "Stateful reading " :
"Positional reading ") + path);
long totalRead = statefulRead ? doStateful(inputStream) :
doPositional(inputStream);
System.out.println(
(statefulRead ? "Finished stateful read " :
"Finished positional read ") + path + ". Time taken: " +
sw.now(TimeUnit.SECONDS) + " s.");
return totalRead;
}
}
@Override
public Long call() throws Exception {
Path path = new Path(getFilePathForThread());
if (!fs.exists(path) || fs.isDirectory(path)) {
System.out.println("File not found at " + path +
". Call gen first?");
return 0L;
}
long bytesRead = readFile(path);
long dataSize = dataSizeMB * 1024 * 1024L;
Preconditions.checkArgument(bytesRead == dataSize,
"Specified data size: " + dataSize + ", actually read " + bytesRead);
return bytesRead;
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new HdfsConfiguration();
FileSystem fs = FileSystem.get(conf);
int res = ToolRunner.run(conf,
new ErasureCodeBenchmarkThroughput(fs), args);
System.exit(res);
}
}
| ReadCallable |
java | elastic__elasticsearch | x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/search/aggregations/bucket/geogrid/GeoHexGridAggregationBuilder.java | {
"start": 1509,
"end": 4572
} | class ____ extends GeoGridAggregationBuilder {
public static final String NAME = "geohex_grid";
private static final int DEFAULT_PRECISION = 5;
private static final int DEFAULT_MAX_NUM_CELLS = 10000;
public static final ValuesSourceRegistry.RegistryKey<GeoGridAggregatorSupplier> REGISTRY_KEY = new ValuesSourceRegistry.RegistryKey<>(
NAME,
GeoGridAggregatorSupplier.class
);
public static final ObjectParser<GeoHexGridAggregationBuilder, String> PARSER = createParser(
NAME,
GeoHexGridAggregationBuilder::parsePrecision,
GeoHexGridAggregationBuilder::new
);
static int parsePrecision(XContentParser parser) throws IOException, ElasticsearchParseException {
final Object node = parser.currentToken().equals(XContentParser.Token.VALUE_NUMBER)
? Integer.valueOf(parser.intValue())
: parser.text();
return XContentMapValues.nodeIntegerValue(node);
}
public GeoHexGridAggregationBuilder(String name) {
super(name);
precision(DEFAULT_PRECISION);
size(DEFAULT_MAX_NUM_CELLS);
shardSize = -1;
}
public GeoHexGridAggregationBuilder(StreamInput in) throws IOException {
super(in);
}
@Override
public GeoGridAggregationBuilder precision(int precision) {
if (precision < 0 || precision > H3.MAX_H3_RES) {
throw new IllegalArgumentException(
"Invalid geohex aggregation precision of " + precision + "" + ". Must be between 0 and " + H3.MAX_H3_RES
);
}
this.precision = precision;
return this;
}
@Override
protected ValuesSourceAggregatorFactory createFactory(
String name,
ValuesSourceConfig config,
int precision,
int requiredSize,
int shardSize,
GeoBoundingBox geoBoundingBox,
AggregationContext context,
AggregatorFactory parent,
AggregatorFactories.Builder subFactoriesBuilder,
Map<String, Object> metadata
) throws IOException {
return new GeoHexGridAggregatorFactory(
name,
config,
precision,
requiredSize,
shardSize,
geoBoundingBox,
context,
parent,
subFactoriesBuilder,
metadata
);
}
private GeoHexGridAggregationBuilder(
GeoHexGridAggregationBuilder clone,
AggregatorFactories.Builder factoriesBuilder,
Map<String, Object> metadata
) {
super(clone, factoriesBuilder, metadata);
}
@Override
protected AggregationBuilder shallowCopy(AggregatorFactories.Builder factoriesBuilder, Map<String, Object> metadata) {
return new GeoHexGridAggregationBuilder(this, factoriesBuilder, metadata);
}
@Override
public String getType() {
return NAME;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_1_0;
}
}
| GeoHexGridAggregationBuilder |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByCheckerTest.java | {
"start": 18587,
"end": 19143
} | class ____ extends A {
@GuardedBy("lock")
boolean b = false;
void m() {
synchronized (lock) {
b = true;
}
;
}
}
""")
.doTest();
}
@Test
public void enclosingSuperAccess() {
compilationHelper
.addSourceLines(
"threadsafety/Test.java",
"""
package threadsafety;
import com.google.errorprone.annotations.concurrent.GuardedBy;
| B |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/config/SpringErrorHandlerConfigTest.java | {
"start": 1276,
"end": 2917
} | class ____ extends SpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/spring/config/SpringErrorHandlerConfigTest.xml");
}
@Test
public void testOk() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
getMockEndpoint("mock:dlc").expectedMessageCount(0);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Test
public void testDLC() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:dlc").expectedBodiesReceived("Kaboom");
template.sendBody("direct:start", "Kaboom");
assertMockEndpointsSatisfied();
}
@Test
public void testDefaultEH() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(0);
getMockEndpoint("mock:dlc").expectedMessageCount(0);
Exchange exchange = template.send("direct:start", new Processor() {
public void process(Exchange exchange) throws Exception {
exchange.getIn().setBody("Damn");
}
});
assertMockEndpointsSatisfied();
assertTrue(exchange.isFailed());
assertEquals("Damn cannot do this", exchange.getException(IllegalArgumentException.class).getMessage());
assertEquals(true, exchange.getIn().getHeader(Exchange.REDELIVERED));
assertEquals(2, exchange.getIn().getHeader(Exchange.REDELIVERY_COUNTER));
}
}
| SpringErrorHandlerConfigTest |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/aggregations/bucket/histogram/InternalDateHistogramTests.java | {
"start": 1468,
"end": 10503
} | class ____ extends InternalMultiBucketAggregationTestCase<InternalDateHistogram> {
private boolean keyed;
private DocValueFormat format;
private long intervalMillis;
private long baseMillis;
private long minDocCount;
private InternalDateHistogram.EmptyBucketInfo emptyBucketInfo;
@Override
public void setUp() throws Exception {
super.setUp();
keyed = randomBoolean();
format = randomDateDocValueFormat();
// in order for reduction to work properly (and be realistic) we need to use the same interval, minDocCount, emptyBucketInfo
// and base in all randomly created aggs as part of the same test run. This is particularly important when minDocCount is
// set to 0 as empty buckets need to be added to fill the holes.
long interval = randomIntBetween(1, 3);
intervalMillis = randomFrom(timeValueSeconds(interval), timeValueMinutes(interval), timeValueHours(interval)).getMillis();
Rounding rounding = Rounding.builder(TimeValue.timeValueMillis(intervalMillis)).build();
long now = System.currentTimeMillis();
baseMillis = rounding.prepare(now, now).round(now);
if (randomBoolean()) {
minDocCount = randomIntBetween(1, 10);
emptyBucketInfo = null;
} else {
minDocCount = 0;
LongBounds extendedBounds = null;
if (randomBoolean()) {
// it's ok if min and max are outside the range of the generated buckets, that will just mean that
// empty buckets won't be added before the first bucket and/or after the last one
long min = baseMillis - intervalMillis * randomNumberOfBuckets();
long max = baseMillis + randomNumberOfBuckets() * intervalMillis;
extendedBounds = new LongBounds(min, max);
}
emptyBucketInfo = new InternalDateHistogram.EmptyBucketInfo(rounding, InternalAggregations.EMPTY, extendedBounds);
}
}
@Override
protected boolean supportsSampling() {
return true;
}
@Override
protected InternalDateHistogram createTestInstance(String name, Map<String, Object> metadata, InternalAggregations aggregations) {
return createTestInstance(name, metadata, aggregations, format);
}
@Override
protected InternalDateHistogram createTestInstanceForXContent(String name, Map<String, Object> metadata, InternalAggregations subAggs) {
// We have to force a format that won't throw away precision and cause duplicate fields
DocValueFormat xContentCompatibleFormat = new DocValueFormat.DateTime(
DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER,
ZoneOffset.UTC,
Resolution.MILLISECONDS
);
return createTestInstance(name, metadata, subAggs, xContentCompatibleFormat);
}
private InternalDateHistogram createTestInstance(
String name,
Map<String, Object> metadata,
InternalAggregations aggregations,
DocValueFormat format
) {
int nbBuckets = randomNumberOfBuckets();
List<InternalDateHistogram.Bucket> buckets = new ArrayList<>(nbBuckets);
// avoid having different random instance start from exactly the same base
long startingDate = baseMillis - intervalMillis * randomNumberOfBuckets();
for (int i = 0; i < nbBuckets; i++) {
// rarely leave some holes to be filled up with empty buckets in case minDocCount is set to 0
if (frequently()) {
long key = startingDate + intervalMillis * i;
buckets.add(new InternalDateHistogram.Bucket(key, randomIntBetween(1, 100), format, aggregations));
}
}
BucketOrder order = BucketOrder.key(randomBoolean());
return new InternalDateHistogram(name, buckets, order, minDocCount, 0L, emptyBucketInfo, format, keyed, false, metadata);
}
@Override
protected void assertReduced(InternalDateHistogram reduced, List<InternalDateHistogram> inputs) {
TreeMap<Long, Long> expectedCounts = new TreeMap<>();
for (Histogram histogram : inputs) {
for (Histogram.Bucket bucket : histogram.getBuckets()) {
expectedCounts.compute(
((ZonedDateTime) bucket.getKey()).toInstant().toEpochMilli(),
(key, oldValue) -> (oldValue == null ? 0 : oldValue) + bucket.getDocCount()
);
}
}
if (minDocCount == 0) {
long minBound = -1;
long maxBound = -1;
if (emptyBucketInfo.bounds != null) {
Rounding.Prepared prepared = emptyBucketInfo.rounding.prepare(
emptyBucketInfo.bounds.getMin(),
emptyBucketInfo.bounds.getMax()
);
minBound = prepared.round(emptyBucketInfo.bounds.getMin());
maxBound = prepared.round(emptyBucketInfo.bounds.getMax());
if (expectedCounts.isEmpty() && minBound <= maxBound) {
expectedCounts.put(minBound, 0L);
}
}
if (expectedCounts.isEmpty() == false) {
Long nextKey = expectedCounts.firstKey();
while (nextKey < expectedCounts.lastKey()) {
expectedCounts.putIfAbsent(nextKey, 0L);
nextKey += intervalMillis;
}
if (emptyBucketInfo.bounds != null) {
while (minBound < expectedCounts.firstKey()) {
expectedCounts.put(expectedCounts.firstKey() - intervalMillis, 0L);
}
while (expectedCounts.lastKey() < maxBound) {
expectedCounts.put(expectedCounts.lastKey() + intervalMillis, 0L);
}
}
}
} else {
expectedCounts.entrySet().removeIf(doubleLongEntry -> doubleLongEntry.getValue() < minDocCount);
}
Map<Long, Long> actualCounts = new TreeMap<>();
for (Histogram.Bucket bucket : reduced.getBuckets()) {
actualCounts.compute(
((ZonedDateTime) bucket.getKey()).toInstant().toEpochMilli(),
(key, oldValue) -> (oldValue == null ? 0 : oldValue) + bucket.getDocCount()
);
}
assertEquals(expectedCounts, actualCounts);
}
@Override
protected InternalDateHistogram mutateInstance(InternalDateHistogram instance) {
String name = instance.getName();
List<InternalDateHistogram.Bucket> buckets = instance.getBuckets();
BucketOrder order = instance.getOrder();
long minDocCount = instance.getMinDocCount();
long offset = instance.getOffset();
InternalDateHistogram.EmptyBucketInfo emptyBucketInfo = instance.emptyBucketInfo;
Map<String, Object> metadata = instance.getMetadata();
switch (between(0, 5)) {
case 0 -> name += randomAlphaOfLength(5);
case 1 -> {
buckets = new ArrayList<>(buckets);
buckets.add(
new InternalDateHistogram.Bucket(randomNonNegativeLong(), randomIntBetween(1, 100), format, InternalAggregations.EMPTY)
);
}
case 2 -> order = BucketOrder.count(randomBoolean());
case 3 -> {
minDocCount += between(1, 10);
emptyBucketInfo = null;
}
case 4 -> offset += between(1, 20);
case 5 -> {
if (metadata == null) {
metadata = Maps.newMapWithExpectedSize(1);
} else {
metadata = new HashMap<>(instance.getMetadata());
}
metadata.put(randomAlphaOfLength(15), randomInt());
}
default -> throw new AssertionError("Illegal randomisation branch");
}
return new InternalDateHistogram(name, buckets, order, minDocCount, offset, emptyBucketInfo, format, keyed, false, metadata);
}
public void testLargeReduce() {
InternalDateHistogram largeHisto = new InternalDateHistogram(
"h",
List.of(),
BucketOrder.key(true),
0,
0,
new InternalDateHistogram.EmptyBucketInfo(
Rounding.builder(DateTimeUnit.SECOND_OF_MINUTE).build(),
InternalAggregations.EMPTY,
new LongBounds(
DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parseMillis("2020-01-01T00:00:00Z"),
DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.parseMillis("2023-01-01T00:00:00Z")
)
),
DocValueFormat.RAW,
false,
false,
null
);
expectReduceUsesTooManyBuckets(largeHisto, 100000);
expectReduceThrowsRealMemoryBreaker(largeHisto);
}
}
| InternalDateHistogramTests |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/support/NonStaticConfigInnerClassesTestCase.java | {
"start": 965,
"end": 1033
} | class ____ {
}
// Intentionally not static
@Configuration
| FooConfig |
java | apache__camel | test-infra/camel-test-infra-hivemq/src/test/java/org/apache/camel/test/infra/hivemq/services/HiveMQServiceFactory.java | {
"start": 1124,
"end": 2912
} | class ____ extends SingletonService<HiveMQService> implements HiveMQService {
public SingletonHiveMQService(HiveMQService service, String name) {
super(service, name);
}
@Override
public int getMqttPort() {
return getService().getMqttPort();
}
@Override
public String getMqttHost() {
return getService().getMqttHost();
}
@Override
public boolean isRunning() {
return getService().isRunning();
}
@Override
public String getUserName() {
return getService().getUserName();
}
@Override
public char[] getUserPassword() {
return getService().getUserPassword();
}
}
private HiveMQServiceFactory() {
}
public static SimpleTestServiceBuilder<HiveMQService> builder() {
return new SimpleTestServiceBuilder<HiveMQService>(HiveMQProperties.HIVEMQ_TEST_SERVICE_NAME)
.withPropertyNameFormat(HiveMQProperties.HIVEMQ_PROPERTY_NAME_FORMAT);
}
public static HiveMQService createService() {
return builder()
.addLocalMapping(LocalHiveMQService::new)
.addRemoteMapping(RemoteHiveMQService::new)
.addMapping(HiveMQProperties.HIVEMQ_SPARKPLUG_INSTANCE_SELECTOR, LocalHiveMQSparkplugTCKService::new)
.build();
}
public static HiveMQService createSingletonService() {
return SingletonServiceHolder.INSTANCE;
}
public static HiveMQService createSingletonService(String mappingName) {
System.setProperty(HiveMQProperties.HIVEMQ_INSTANCE_TYPE, mappingName);
return createSingletonService();
}
private static | SingletonHiveMQService |
java | netty__netty | codec-base/src/main/java/io/netty/handler/codec/serialization/ClassResolver.java | {
"start": 1329,
"end": 1429
} | interface ____ {
Class<?> resolve(String className) throws ClassNotFoundException;
}
| ClassResolver |
java | apache__dubbo | dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/route/DefaultRequestRouter.java | {
"start": 1448,
"end": 2929
} | class ____ implements RequestRouter {
private final HttpMessageAdapterFactory<HttpRequest, HttpMetadata, Void> httpMessageAdapterFactory;
private final List<RequestHandlerMapping> requestHandlerMappings;
@SuppressWarnings("unchecked")
public DefaultRequestRouter(FrameworkModel frameworkModel) {
httpMessageAdapterFactory = frameworkModel.getFirstActivateExtension(HttpMessageAdapterFactory.class);
requestHandlerMappings = frameworkModel.getActivateExtensions(RequestHandlerMapping.class);
}
@Override
public RpcInvocationBuildContext route(URL url, RequestMetadata metadata, HttpChannel httpChannel) {
HttpRequest request = httpMessageAdapterFactory.adaptRequest(metadata, httpChannel);
HttpResponse response = httpMessageAdapterFactory.adaptResponse(request, metadata);
for (int i = 0, size = requestHandlerMappings.size(); i < size; i++) {
RequestHandlerMapping mapping = requestHandlerMappings.get(i);
RequestHandler handler = mapping.getRequestHandler(url, request, response);
if (handler == null) {
continue;
}
handler.setAttribute(TripleConstants.HANDLER_TYPE_KEY, mapping.getType());
handler.setAttribute(TripleConstants.HTTP_REQUEST_KEY, request);
handler.setAttribute(TripleConstants.HTTP_RESPONSE_KEY, response);
return handler;
}
return null;
}
}
| DefaultRequestRouter |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/proxy/ProxyConfiguration.java | {
"start": 362,
"end": 2614
} | class ____<T> {
private Class<?> anchorClass;
private String proxyNameSuffix;
private ClassLoader classLoader;
private Class<T> superClass;
private List<Class<?>> additionalInterfaces = new ArrayList<>(0);
private ClassOutput classOutput;
private boolean allowPackagePrivate = false;
public List<Class<?>> getAdditionalInterfaces() {
return Collections.unmodifiableList(additionalInterfaces);
}
public ProxyConfiguration<T> addAdditionalInterface(final Class<?> iface) {
if (!Modifier.isInterface(iface.getModifiers())) {
throw new IllegalArgumentException("Class " + iface.getName() + " is not an interface");
}
additionalInterfaces.add(iface);
return this;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public ProxyConfiguration<T> setClassLoader(final ClassLoader classLoader) {
this.classLoader = classLoader;
return this;
}
public Class<?> getAnchorClass() {
return anchorClass;
}
public ProxyConfiguration<T> setAnchorClass(Class<?> anchorClass) {
this.anchorClass = anchorClass;
return this;
}
public String getProxyNameSuffix() {
return proxyNameSuffix;
}
public ProxyConfiguration<T> setProxyNameSuffix(final String proxyNameSuffix) {
this.proxyNameSuffix = proxyNameSuffix;
return this;
}
public String getProxyName() {
return getAnchorClass().getName() + proxyNameSuffix;
}
public Class<T> getSuperClass() {
return superClass;
}
public ProxyConfiguration<T> setSuperClass(final Class<T> superClass) {
this.superClass = superClass;
return this;
}
public ClassOutput getClassOutput() {
return classOutput;
}
public ProxyConfiguration<T> setClassOutput(ClassOutput classOutput) {
this.classOutput = classOutput;
return this;
}
public boolean isAllowPackagePrivate() {
return allowPackagePrivate;
}
public ProxyConfiguration<T> setAllowPackagePrivate(boolean allowPackagePrivate) {
this.allowPackagePrivate = allowPackagePrivate;
return this;
}
}
| ProxyConfiguration |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/web/method/support/HandlerMethodArgumentResolverCompositeTests.java | {
"start": 1086,
"end": 2756
} | class ____ {
private HandlerMethodArgumentResolverComposite resolverComposite;
private MethodParameter paramInt;
private MethodParameter paramStr;
@BeforeEach
void setup() throws Exception {
this.resolverComposite = new HandlerMethodArgumentResolverComposite();
Method method = getClass().getDeclaredMethod("handle", Integer.class, String.class);
paramInt = new MethodParameter(method, 0);
paramStr = new MethodParameter(method, 1);
}
@Test
void supportsParameter() {
this.resolverComposite.addResolver(new StubArgumentResolver(Integer.class));
assertThat(this.resolverComposite.supportsParameter(paramInt)).isTrue();
assertThat(this.resolverComposite.supportsParameter(paramStr)).isFalse();
}
@Test
void resolveArgument() throws Exception {
this.resolverComposite.addResolver(new StubArgumentResolver(55));
Object resolvedValue = this.resolverComposite.resolveArgument(paramInt, null, null, null);
assertThat(resolvedValue).isEqualTo(55);
}
@Test
void checkArgumentResolverOrder() throws Exception {
this.resolverComposite.addResolver(new StubArgumentResolver(1));
this.resolverComposite.addResolver(new StubArgumentResolver(2));
Object resolvedValue = this.resolverComposite.resolveArgument(paramInt, null, null, null);
assertThat(resolvedValue).as("Didn't use the first registered resolver").isEqualTo(1);
}
@Test
void noSuitableArgumentResolver() {
assertThatIllegalArgumentException().isThrownBy(() ->
this.resolverComposite.resolveArgument(paramStr, null, null, null));
}
@SuppressWarnings("unused")
private void handle(Integer arg1, String arg2) {
}
}
| HandlerMethodArgumentResolverCompositeTests |
java | google__gson | gson/src/main/java/com/google/gson/annotations/JsonAdapter.java | {
"start": 4197,
"end": 4498
} | class ____
* field is serialized or deserialized.
*
* @since 2.3
* @author Inderjeet Singh
* @author Joel Leitch
* @author Jesse Wilson
*/
// Note that the above example is taken from AdaptAnnotationTest.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @ | or |
java | quarkusio__quarkus | integration-tests/test-extension/extension/deployment/src/test/java/io/quarkus/extest/AdditionalLocationsTest.java | {
"start": 3179,
"end": 3472
} | class ____ {
@Inject
Router router;
@Inject
Config config;
public void register(@Observes StartupEvent ev) {
router.get("/config").handler(rc -> rc.response().end(config.getValue("additional.property", String.class)));
}
}
}
| DevBean |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/impl/prefetch/TestBufferPool.java | {
"start": 1254,
"end": 4953
} | class ____ extends AbstractHadoopTestBase {
private static final int POOL_SIZE = 2;
private static final int BUFFER_SIZE = 10;
private final PrefetchingStatistics statistics =
EmptyPrefetchingStatistics.getInstance();
@Test
public void testArgChecks() throws Exception {
// Should not throw.
BufferPool pool = new BufferPool(POOL_SIZE, BUFFER_SIZE, statistics);
// Verify it throws correctly.
intercept(IllegalArgumentException.class,
"'size' must be a positive integer",
() -> new BufferPool(0, 10, statistics));
intercept(IllegalArgumentException.class,
"'size' must be a positive integer",
() -> new BufferPool(-1, 10, statistics));
intercept(IllegalArgumentException.class,
"'bufferSize' must be a positive integer",
() -> new BufferPool(10, 0, statistics));
intercept(IllegalArgumentException.class,
"'bufferSize' must be a positive integer",
() -> new BufferPool(1, -10, statistics));
intercept(NullPointerException.class,
() -> new BufferPool(1, 10, null));
intercept(IllegalArgumentException.class,
"'blockNumber' must not be negative",
() -> pool.acquire(-1));
intercept(IllegalArgumentException.class,
"'blockNumber' must not be negative",
() -> pool.tryAcquire(-1));
intercept(NullPointerException.class, "data",
() -> pool.release((BufferData) null));
}
@Test
public void testGetAndRelease() {
BufferPool pool = new BufferPool(POOL_SIZE, BUFFER_SIZE, statistics);
assertInitialState(pool, POOL_SIZE);
int count = 0;
for (BufferData data : pool.getAll()) {
count++;
}
assertEquals(0, count);
BufferData data1 = this.acquire(pool, 1);
BufferData data2 = this.acquire(pool, 2);
BufferData data3 = pool.tryAcquire(3);
assertNull(data3);
count = 0;
for (BufferData data : pool.getAll()) {
count++;
}
assertEquals(2, count);
assertEquals(2, pool.numCreated());
assertEquals(0, pool.numAvailable());
data1.updateState(BufferData.State.READY, BufferData.State.BLANK);
pool.release(data1);
assertEquals(2, pool.numCreated());
assertEquals(1, pool.numAvailable());
data2.updateState(BufferData.State.READY, BufferData.State.BLANK);
pool.release(data2);
assertEquals(2, pool.numCreated());
assertEquals(2, pool.numAvailable());
}
@Test
public void testRelease() throws Exception {
testReleaseHelper(BufferData.State.BLANK, true);
testReleaseHelper(BufferData.State.PREFETCHING, true);
testReleaseHelper(BufferData.State.CACHING, true);
testReleaseHelper(BufferData.State.READY, false);
}
private void testReleaseHelper(BufferData.State stateBeforeRelease,
boolean expectThrow)
throws Exception {
BufferPool pool = new BufferPool(POOL_SIZE, BUFFER_SIZE, statistics);
assertInitialState(pool, POOL_SIZE);
BufferData data = this.acquire(pool, 1);
data.updateState(stateBeforeRelease, BufferData.State.BLANK);
if (expectThrow) {
intercept(IllegalArgumentException.class, "Unable to release buffer",
() -> pool.release(data));
} else {
pool.release(data);
}
}
private BufferData acquire(BufferPool pool, int blockNumber) {
BufferData data = pool.acquire(blockNumber);
assertNotNull(data);
assertSame(data, pool.acquire(blockNumber));
assertEquals(blockNumber, data.getBlockNumber());
return data;
}
private void assertInitialState(BufferPool pool, int poolSize) {
assertEquals(poolSize, pool.numAvailable());
assertEquals(0, pool.numCreated());
}
}
| TestBufferPool |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java | {
"start": 2070,
"end": 16468
} | class ____ {
private static String originalThreadName;
private static volatile int listenerCalled = 0;
private static int listenerConstructed = 0;
@BeforeEach
void setUp() {
originalThreadName = Thread.currentThread().getName();
listenerCalled = 0;
listenerConstructed = 0;
}
@Test
void asyncMethods() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncMethodBean.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
context.refresh();
AsyncMethodBean asyncTest = context.getBean("asyncTest", AsyncMethodBean.class);
asyncTest.doNothing(5);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
CompletableFuture<String> completableFuture = asyncTest.returnSomethingCompletable(20);
assertThat(completableFuture.get()).isEqualTo("20");
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> asyncTest.returnSomething(0).get())
.withCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> asyncTest.returnSomething(-1).get())
.withCauseInstanceOf(IOException.class);
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> asyncTest.returnSomethingCompletable(0).get())
.withCauseInstanceOf(IllegalArgumentException.class);
}
@Test
void asyncMethodsThroughInterface() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(SimpleAsyncMethodBean.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
context.refresh();
SimpleInterface asyncTest = context.getBean("asyncTest", SimpleInterface.class);
asyncTest.doNothing(5);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void asyncMethodsWithQualifier() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncMethodWithQualifierBean.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
context.registerBeanDefinition("e0", new RootBeanDefinition(ThreadPoolTaskExecutor.class));
context.registerBeanDefinition("e1", new RootBeanDefinition(ThreadPoolTaskExecutor.class));
context.registerBeanDefinition("e2", new RootBeanDefinition(ThreadPoolTaskExecutor.class));
context.refresh();
AsyncMethodWithQualifierBean asyncTest = context.getBean("asyncTest", AsyncMethodWithQualifierBean.class);
asyncTest.doNothing(5);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
Future<String> future2 = asyncTest.returnSomething2(30);
assertThat(future2.get()).isEqualTo("30");
}
@Test
void asyncMethodsWithQualifierThroughInterface() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(SimpleAsyncMethodWithQualifierBean.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
context.registerBeanDefinition("e0", new RootBeanDefinition(ThreadPoolTaskExecutor.class));
context.registerBeanDefinition("e1", new RootBeanDefinition(ThreadPoolTaskExecutor.class));
context.registerBeanDefinition("e2", new RootBeanDefinition(ThreadPoolTaskExecutor.class));
context.refresh();
SimpleInterface asyncTest = context.getBean("asyncTest", SimpleInterface.class);
asyncTest.doNothing(5);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
Future<String> future2 = asyncTest.returnSomething2(30);
assertThat(future2.get()).isEqualTo("30");
}
@Test
void asyncClass() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncClassBean.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
context.refresh();
AsyncClassBean asyncTest = context.getBean("asyncTest", AsyncClassBean.class);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
CompletableFuture<String> completableFuture = asyncTest.returnSomethingCompletable(20);
assertThat(completableFuture.get()).isEqualTo("20");
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> asyncTest.returnSomething(0).get())
.withCauseInstanceOf(IllegalArgumentException.class);
assertThatExceptionOfType(ExecutionException.class)
.isThrownBy(() -> asyncTest.returnSomethingCompletable(0).get())
.withCauseInstanceOf(IllegalArgumentException.class);
}
@Test
void asyncClassWithPostProcessor() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncClassBean.class));
context.registerBeanDefinition("asyncProcessor", new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class));
context.refresh();
AsyncClassBean asyncTest = context.getBean("asyncTest", AsyncClassBean.class);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void asyncClassWithInterface() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncClassBeanWithInterface.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
context.refresh();
RegularInterface asyncTest = context.getBean("asyncTest", RegularInterface.class);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void asyncClassWithInterfaceAndPostProcessor() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncClassBeanWithInterface.class));
context.registerBeanDefinition("asyncProcessor", new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class));
context.refresh();
RegularInterface asyncTest = context.getBean("asyncTest", RegularInterface.class);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void asyncInterface() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncInterfaceBean.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
context.refresh();
AsyncInterface asyncTest = context.getBean("asyncTest", AsyncInterface.class);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void asyncInterfaceWithPostProcessor() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncInterfaceBean.class));
context.registerBeanDefinition("asyncProcessor", new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class));
context.refresh();
AsyncInterface asyncTest = context.getBean("asyncTest", AsyncInterface.class);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void dynamicAsyncInterface() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(DynamicAsyncInterfaceBean.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
context.refresh();
AsyncInterface asyncTest = context.getBean("asyncTest", AsyncInterface.class);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void dynamicAsyncInterfaceWithPostProcessor() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(DynamicAsyncInterfaceBean.class));
context.registerBeanDefinition("asyncProcessor", new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class));
context.refresh();
AsyncInterface asyncTest = context.getBean("asyncTest", AsyncInterface.class);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void asyncMethodsInInterface() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncMethodsInterfaceBean.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
context.refresh();
AsyncMethodsInterface asyncTest = context.getBean("asyncTest", AsyncMethodsInterface.class);
asyncTest.doNothing(5);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void asyncMethodsInInterfaceWithPostProcessor() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncMethodsInterfaceBean.class));
context.registerBeanDefinition("asyncProcessor", new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class));
context.refresh();
AsyncMethodsInterface asyncTest = context.getBean("asyncTest", AsyncMethodsInterface.class);
asyncTest.doNothing(5);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void dynamicAsyncMethodsInInterfaceWithPostProcessor() throws Exception {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(DynamicAsyncMethodsInterfaceBean.class));
context.registerBeanDefinition("asyncProcessor", new RootBeanDefinition(AsyncAnnotationBeanPostProcessor.class));
context.refresh();
AsyncMethodsInterface asyncTest = context.getBean("asyncTest", AsyncMethodsInterface.class);
asyncTest.doSomething(10);
Future<String> future = asyncTest.returnSomething(20);
assertThat(future.get()).isEqualTo("20");
}
@Test
void asyncMethodListener() {
// Arrange
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncMethodListener.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
// Act
context.refresh();
// Assert
Awaitility.await()
.atMost(5, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> listenerCalled == 1);
context.close();
}
@Test
void asyncClassListener() {
// Arrange
GenericApplicationContext context = new GenericApplicationContext();
context.registerBeanDefinition("asyncTest", new RootBeanDefinition(AsyncClassListener.class));
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
// Act
context.refresh();
context.close();
// Assert
Awaitility.await()
.atMost(5, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> listenerCalled == 2);
assertThat(listenerConstructed).isEqualTo(1);
}
@Test
void asyncPrototypeClassListener() {
// Arrange
GenericApplicationContext context = new GenericApplicationContext();
RootBeanDefinition listenerDef = new RootBeanDefinition(AsyncClassListener.class);
listenerDef.setScope(BeanDefinition.SCOPE_PROTOTYPE);
context.registerBeanDefinition("asyncTest", listenerDef);
context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class));
context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class));
// Act
context.refresh();
context.close();
// Assert
Awaitility.await()
.atMost(5, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.until(() -> listenerCalled == 2);
assertThat(listenerConstructed).isEqualTo(2);
}
public | AsyncExecutionTests |
java | apache__rocketmq | test/src/main/java/org/apache/rocketmq/test/util/RandomUtil.java | {
"start": 987,
"end": 8674
} | class ____ {
private static final int UNICODE_START = '\u4E00';
private static final int UNICODE_END = '\u9FA0';
private static Random rd = new Random();
private RandomUtil() {
}
public static long getLong() {
return rd.nextLong();
}
public static long getLongMoreThanZero() {
long res = rd.nextLong();
while (res <= 0) {
res = rd.nextLong();
}
return res;
}
public static long getLongLessThan(long n) {
long res = rd.nextLong();
return res % n;
}
public static long getLongMoreThanZeroLessThan(long n) {
long res = getLongLessThan(n);
while (res <= 0) {
res = getLongLessThan(n);
}
return res;
}
public static long getLongBetween(long n, long m) {
if (m <= n) {
return n;
}
long res = getLongMoreThanZero();
return n + res % (m - n);
}
public static int getInteger() {
return rd.nextInt();
}
public static int getIntegerMoreThanZero() {
int res = rd.nextInt();
while (res <= 0) {
res = rd.nextInt();
}
return res;
}
public static int getIntegerLessThan(int n) {
int res = rd.nextInt();
return res % n;
}
public static int getIntegerMoreThanZeroLessThan(int n) {
int res = rd.nextInt(n);
while (res == 0) {
res = rd.nextInt(n);
}
return res;
}
public static int getIntegerBetween(int n, int m)// m��ֵ����Ϊ���أ�
{
if (m == n) {
return n;
}
int res = getIntegerMoreThanZero();
return n + res % (m - n);
}
private static char getChar(int[] arg) {
int size = arg.length;
int c = rd.nextInt(size / 2);
c = c * 2;
return (char) (getIntegerBetween(arg[c], arg[c + 1]));
}
private static String getString(int n, int[] arg) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < n; i++) {
res.append(getChar(arg));
}
return res.toString();
}
public static String getStringWithCharacter(int n) {
int[] arg = new int[] {'a', 'z' + 1, 'A', 'Z' + 1};
return getString(n, arg);
}
public static String getStringWithNumber(int n) {
int[] arg = new int[] {'0', '9' + 1};
return getString(n, arg);
}
public static String getStringWithNumAndCha(int n) {
int[] arg = new int[] {'a', 'z' + 1, 'A', 'Z' + 1, '0', '9' + 1};
return getString(n, arg);
}
public static String getStringShortenThan(int n) {
int len = getIntegerMoreThanZeroLessThan(n);
return getStringWithCharacter(len);
}
public static String getStringWithNumAndChaShortenThan(int n) {
int len = getIntegerMoreThanZeroLessThan(n);
return getStringWithNumAndCha(len);
}
public static String getStringBetween(int n, int m) {
int len = getIntegerBetween(n, m);
return getStringWithCharacter(len);
}
public static String getStringWithNumAndChaBetween(int n, int m) {
int len = getIntegerBetween(n, m);
return getStringWithNumAndCha(len);
}
public static String getStringWithPrefix(int n, String prefix) {
int len = prefix.length();
if (n <= len)
return prefix;
else {
len = n - len;
StringBuilder res = new StringBuilder(prefix);
res.append(getStringWithCharacter(len));
return res.toString();
}
}
public static String getStringWithSuffix(int n, String suffix) {
int len = suffix.length();
if (n <= len)
return suffix;
else {
len = n - len;
StringBuilder res = new StringBuilder();
res.append(getStringWithCharacter(len));
res.append(suffix);
return res.toString();
}
}
public static String getStringWithBoth(int n, String prefix, String suffix) {
int len = prefix.length() + suffix.length();
StringBuilder res = new StringBuilder(prefix);
if (n <= len)
return res.append(suffix).toString();
else {
len = n - len;
res.append(getStringWithCharacter(len));
res.append(suffix);
return res.toString();
}
}
public static String getCheseWordWithPrifix(int n, String prefix) {
int len = prefix.length();
if (n <= len)
return prefix;
else {
len = n - len;
StringBuilder res = new StringBuilder(prefix);
res.append(getCheseWord(len));
return res.toString();
}
}
public static String getCheseWordWithSuffix(int n, String suffix) {
int len = suffix.length();
if (n <= len)
return suffix;
else {
len = n - len;
StringBuilder res = new StringBuilder();
res.append(getCheseWord(len));
res.append(suffix);
return res.toString();
}
}
public static String getCheseWordWithBoth(int n, String prefix, String suffix) {
int len = prefix.length() + suffix.length();
StringBuilder res = new StringBuilder(prefix);
if (n <= len)
return res.append(suffix).toString();
else {
len = n - len;
res.append(getCheseWord(len));
res.append(suffix);
return res.toString();
}
}
public static String getCheseWord(int len) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < len; i++) {
char str = getCheseChar();
res.append(str);
}
return res.toString();
}
private static char getCheseChar() {
return (char) (UNICODE_START + rd.nextInt(UNICODE_END - UNICODE_START));
}
public static boolean getBoolean() {
return getIntegerMoreThanZeroLessThan(3) == 1;
}
public static String getStringByUUID() {
return UUID.randomUUID().toString();
}
public static int[] getRandomArray(int min, int max, int n) {
int len = max - min + 1;
if (max < min || n > len) {
return null;
}
int[] source = new int[len];
for (int i = min; i < min + len; i++) {
source[i - min] = i;
}
int[] result = new int[n];
Random rd = new Random();
int index = 0;
for (int i = 0; i < result.length; i++) {
index = rd.nextInt(len--);
result[i] = source[index];
source[index] = source[len];
}
return result;
}
public static Collection<Integer> getRandomCollection(int min, int max, int n) {
Set<Integer> res = new HashSet<Integer>();
int mx = max;
int mn = min;
if (n == (max + 1 - min)) {
for (int i = 1; i <= n; i++) {
res.add(i);
}
return res;
}
for (int i = 0; i < n; i++) {
int v = getIntegerBetween(mn, mx);
if (v == mx) {
mx--;
}
if (v == mn) {
mn++;
}
while (res.contains(v)) {
v = getIntegerBetween(mn, mx);
if (v == mx) {
mx = v;
}
if (v == mn) {
mn = v;
}
}
res.add(v);
}
return res;
}
}
| RandomUtil |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/collect/Iterators.java | {
"start": 5461,
"end": 6799
} | class ____<T, U> implements Iterator<U> {
private final Iterator<? extends T> input;
private final Function<T, ? extends U> fn;
MapIterator(Iterator<? extends T> input, Function<T, ? extends U> fn) {
this.input = input;
this.fn = fn;
}
@Override
public boolean hasNext() {
return input.hasNext();
}
@Override
public U next() {
return fn.apply(input.next());
}
@Override
public void forEachRemaining(Consumer<? super U> action) {
input.forEachRemaining(t -> action.accept(fn.apply(t)));
}
}
/**
* @param input An iterator over <i>non-null</i> values.
* @param predicate The predicate with which to filter the input.
* @return an iterator which returns the values from {@code input} which match {@code predicate}.
*/
public static <T> Iterator<T> filter(Iterator<? extends T> input, Predicate<T> predicate) {
while (input.hasNext()) {
final var value = input.next();
assert value != null;
if (predicate.test(value)) {
return new FilterIterator<>(value, input, predicate);
}
}
return Collections.emptyIterator();
}
private static final | MapIterator |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/bulk/Retry.java | {
"start": 3213,
"end": 9116
} | class ____ extends DelegatingActionListener<BulkResponse, BulkResponse> {
private static final RestStatus RETRY_STATUS = RestStatus.TOO_MANY_REQUESTS;
private static final Logger logger = LogManager.getLogger(RetryHandler.class);
private final Scheduler scheduler;
private final BiConsumer<BulkRequest, ActionListener<BulkResponse>> consumer;
private final Iterator<TimeValue> backoff;
// Access only when holding a client-side lock, see also #addResponses()
private final List<BulkItemResponse> responses = new ArrayList<>();
private final long startTimestampNanos;
// needed to construct the next bulk request based on the response to the previous one
// volatile as we're called from a scheduled thread
private volatile BulkRequest currentBulkRequest;
private volatile Scheduler.Cancellable retryCancellable;
RetryHandler(
BackoffPolicy backoffPolicy,
BiConsumer<BulkRequest, ActionListener<BulkResponse>> consumer,
ActionListener<BulkResponse> listener,
Scheduler scheduler
) {
super(listener);
this.backoff = backoffPolicy.iterator();
this.consumer = consumer;
this.scheduler = scheduler;
// in contrast to System.currentTimeMillis(), nanoTime() uses a monotonic clock under the hood
this.startTimestampNanos = System.nanoTime();
}
@Override
public void onResponse(BulkResponse bulkItemResponses) {
if (bulkItemResponses.hasFailures() == false) {
// we're done here, include all responses
addResponses(bulkItemResponses, Predicates.always());
finishHim();
} else {
if (canRetry(bulkItemResponses)) {
addResponses(bulkItemResponses, (r -> r.isFailed() == false));
retry(createBulkRequestForRetry(bulkItemResponses));
} else {
addResponses(bulkItemResponses, Predicates.always());
finishHim();
}
}
}
@Override
public void onFailure(Exception e) {
if (ExceptionsHelper.status(e) == RETRY_STATUS && backoff.hasNext()) {
retry(currentBulkRequest);
} else {
try {
super.onFailure(e);
} finally {
if (retryCancellable != null) {
retryCancellable.cancel();
}
}
}
}
private void retry(BulkRequest bulkRequestForRetry) {
assert backoff.hasNext();
TimeValue next = backoff.next();
logger.trace("Retry of bulk request scheduled in {} ms.", next.millis());
retryCancellable = scheduler.schedule(() -> this.execute(bulkRequestForRetry), next, EsExecutors.DIRECT_EXECUTOR_SERVICE);
}
private BulkRequest createBulkRequestForRetry(BulkResponse bulkItemResponses) {
BulkRequest requestToReissue = new BulkRequest();
int index = 0;
for (BulkItemResponse bulkItemResponse : bulkItemResponses.getItems()) {
if (bulkItemResponse.isFailed()) {
DocWriteRequest<?> originalBulkItemRequest = currentBulkRequest.requests().get(index);
if (originalBulkItemRequest instanceof IndexRequest item) {
item.reset();
}
requestToReissue.add(originalBulkItemRequest);
}
index++;
}
return requestToReissue;
}
private boolean canRetry(BulkResponse bulkItemResponses) {
if (backoff.hasNext() == false) {
return false;
}
for (BulkItemResponse bulkItemResponse : bulkItemResponses) {
if (bulkItemResponse.isFailed()) {
final RestStatus status = bulkItemResponse.status();
if (status != RETRY_STATUS) {
return false;
}
}
}
return true;
}
private void finishHim() {
try {
delegate.onResponse(getAccumulatedResponse());
} finally {
if (retryCancellable != null) {
retryCancellable.cancel();
}
}
}
private void addResponses(BulkResponse response, Predicate<BulkItemResponse> filter) {
for (BulkItemResponse bulkItemResponse : response) {
if (filter.test(bulkItemResponse)) {
// Use client-side lock here to avoid visibility issues. This method may be called multiple times
// (based on how many retries we have to issue) and relying that the response handling code will be
// scheduled on the same thread is fragile.
synchronized (responses) {
responses.add(bulkItemResponse);
}
}
}
}
private BulkResponse getAccumulatedResponse() {
BulkItemResponse[] itemResponses;
synchronized (responses) {
itemResponses = responses.toArray(new BulkItemResponse[0]);
}
long stopTimestamp = System.nanoTime();
long totalLatencyMs = TimeValue.timeValueNanos(stopTimestamp - startTimestampNanos).millis();
return new BulkResponse(itemResponses, totalLatencyMs);
}
public void execute(BulkRequest bulkRequest) {
this.currentBulkRequest = bulkRequest;
consumer.accept(bulkRequest, this);
}
}
}
| RetryHandler |
java | apache__avro | lang/java/avro/src/main/java/org/apache/avro/reflect/MapEntry.java | {
"start": 1490,
"end": 1884
} | class ____<K, V> implements Map.Entry<K, V> {
K key;
V value;
public MapEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
}
| MapEntry |
java | google__guava | android/guava-tests/test/com/google/common/io/CloserTest.java | {
"start": 9834,
"end": 10199
} | class ____ implements Closer.Suppressor {
private final List<Suppression> suppressions = new ArrayList<>();
@Override
public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) {
suppressions.add(new Suppression(closeable, thrown, suppressed));
}
}
/** Record of a call to suppress. */
private static | TestSuppressor |
java | hibernate__hibernate-orm | hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/sequence/IngresLegacySequenceSupport.java | {
"start": 360,
"end": 585
} | class ____ extends ANSISequenceSupport {
public static final SequenceSupport INSTANCE = new IngresLegacySequenceSupport();
@Override
public boolean supportsPooledSequences() {
return false;
}
}
| IngresLegacySequenceSupport |
java | apache__camel | components/camel-jcache/src/main/java/org/apache/camel/component/jcache/processor/aggregate/JCacheAggregationRepository.java | {
"start": 1936,
"end": 8914
} | class ____ extends ServiceSupport
implements CamelContextAware, OptimisticLockingAggregationRepository {
private static final Logger LOG = LoggerFactory.getLogger(JCacheAggregationRepository.class);
private CamelContext camelContext;
private Cache<String, DefaultExchangeHolder> cache;
private JCacheManager<String, DefaultExchangeHolder> cacheManager;
@Metadata(description = "Configuration for JCache")
private JCacheConfiguration configuration;
@Metadata(description = "Whether optimistic locking is in use")
private boolean optimistic;
@Metadata(label = "advanced",
description = "Whether headers on the Exchange that are Java objects and Serializable should be included and saved to the repository")
private boolean allowSerializedHeaders;
public JCacheAggregationRepository() {
this.configuration = new JCacheConfiguration();
}
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
public JCacheConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(JCacheConfiguration configuration) {
this.configuration = configuration;
}
public String getCacheName() {
return configuration.getCacheName();
}
public void setCacheName(String cacheName) {
configuration.setCacheName(cacheName);
}
public Cache<String, DefaultExchangeHolder> getCache() {
return cache;
}
public void setCache(Cache<String, DefaultExchangeHolder> cache) {
this.cache = cache;
}
public boolean isOptimistic() {
return optimistic;
}
public void setOptimistic(boolean optimistic) {
this.optimistic = optimistic;
}
public boolean isAllowSerializedHeaders() {
return allowSerializedHeaders;
}
public void setAllowSerializedHeaders(boolean allowSerializedHeaders) {
this.allowSerializedHeaders = allowSerializedHeaders;
}
@Override
public Exchange add(CamelContext camelContext, String key, Exchange oldExchange, Exchange newExchange)
throws OptimisticLockingException {
if (!optimistic) {
throw new UnsupportedOperationException();
}
LOG.trace("Adding an Exchange with ID {} for key {} in an optimistic manner.", newExchange.getExchangeId(), key);
if (oldExchange == null) {
DefaultExchangeHolder newHolder = DefaultExchangeHolder.marshal(newExchange, true, allowSerializedHeaders);
DefaultExchangeHolder oldHolder = cache.getAndPut(key, newHolder);
if (oldHolder != null) {
Exchange exchange = unmarshallExchange(camelContext, oldHolder);
LOG.error(
"Optimistic locking failed for exchange with key {}: IMap#putIfAbsend returned Exchange with ID {}, while it's expected no exchanges to be returned",
key,
exchange != null ? exchange.getExchangeId() : "<null>");
throw new OptimisticLockingException();
}
} else {
DefaultExchangeHolder oldHolder = DefaultExchangeHolder.marshal(oldExchange, true, allowSerializedHeaders);
DefaultExchangeHolder newHolder = DefaultExchangeHolder.marshal(newExchange, true, allowSerializedHeaders);
if (!cache.replace(key, oldHolder, newHolder)) {
LOG.error(
"Optimistic locking failed for exchange with key {}: IMap#replace returned no Exchanges, while it's expected to replace one",
key);
throw new OptimisticLockingException();
}
}
LOG.trace("Added an Exchange with ID {} for key {} in optimistic manner.", newExchange.getExchangeId(), key);
return oldExchange;
}
@Override
public Exchange add(CamelContext camelContext, String key, Exchange exchange) {
if (optimistic) {
throw new UnsupportedOperationException();
}
LOG.trace("Adding an Exchange with ID {} for key {} in a thread-safe manner.", exchange.getExchangeId(), key);
DefaultExchangeHolder newHolder = DefaultExchangeHolder.marshal(exchange, true, allowSerializedHeaders);
DefaultExchangeHolder oldHolder = cache.getAndPut(key, newHolder);
return unmarshallExchange(camelContext, oldHolder);
}
@Override
public Exchange get(CamelContext camelContext, String key) {
return unmarshallExchange(camelContext, cache.get(key));
}
@Override
public void remove(CamelContext camelContext, String key, Exchange exchange) {
DefaultExchangeHolder holder = DefaultExchangeHolder.marshal(exchange, true, allowSerializedHeaders);
if (optimistic) {
LOG.trace("Removing an exchange with ID {} for key {} in an optimistic manner.", exchange.getExchangeId(), key);
if (!cache.remove(key, holder)) {
LOG.error(
"Optimistic locking failed for exchange with key {}: IMap#remove removed no Exchanges, while it's expected to remove one.",
key);
throw new OptimisticLockingException();
}
LOG.trace("Removed an exchange with ID {} for key {} in an optimistic manner.", exchange.getExchangeId(), key);
} else {
cache.remove(key);
}
}
@Override
public void confirm(CamelContext camelContext, String exchangeId) {
LOG.trace("Confirming an exchange with ID {}.", exchangeId);
}
@Override
public Set<String> getKeys() {
Set<String> keys = new HashSet<>();
Iterator<Cache.Entry<String, DefaultExchangeHolder>> entries = cache.iterator();
while (entries.hasNext()) {
keys.add(entries.next().getKey());
}
return Collections.unmodifiableSet(keys);
}
@Override
protected void doStart() throws Exception {
ObjectHelper.notNull(camelContext, "camelContext");
ObjectHelper.notNull(configuration, "configuration");
if (cache != null) {
cacheManager = new JCacheManager<>(cache);
} else {
cacheManager = JCacheHelper.createManager(getCamelContext(), configuration);
cache = cacheManager.getCache();
}
}
@Override
protected void doStop() throws Exception {
cacheManager.close();
}
protected Exchange unmarshallExchange(CamelContext camelContext, DefaultExchangeHolder holder) {
Exchange exchange = null;
if (holder != null) {
exchange = new DefaultExchange(camelContext);
DefaultExchangeHolder.unmarshal(exchange, holder);
}
return exchange;
}
}
| JCacheAggregationRepository |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/MockStorageInterface.java | {
"start": 9467,
"end": 12058
} | class ____ extends CloudBlobDirectoryWrapper {
private URI uri;
public MockCloudBlobDirectoryWrapper(URI uri) {
this.uri = uri;
}
@Override
public CloudBlobContainer getContainer() throws URISyntaxException,
StorageException {
return null;
}
@Override
public CloudBlobDirectory getParent() throws URISyntaxException,
StorageException {
return null;
}
@Override
public URI getUri() {
return uri;
}
@Override
public Iterable<ListBlobItem> listBlobs(String prefix,
boolean useFlatBlobListing, EnumSet<BlobListingDetails> listingDetails,
BlobRequestOptions options, OperationContext opContext)
throws URISyntaxException, StorageException {
ArrayList<ListBlobItem> ret = new ArrayList<ListBlobItem>();
URI searchUri = null;
if (prefix == null) {
searchUri = uri;
} else {
try {
searchUri = UriBuilder.fromUri(uri).path(prefix).build();
} catch (UriBuilderException e) {
throw new AssertionError("Failed to encode path: " + prefix);
}
}
String fullPrefix = convertUriToDecodedString(searchUri);
boolean includeMetadata = listingDetails.contains(BlobListingDetails.METADATA);
HashSet<String> addedDirectories = new HashSet<String>();
for (InMemoryBlockBlobStore.ListBlobEntry current : backingStore.listBlobs(
fullPrefix, includeMetadata)) {
int indexOfSlash = current.getKey().indexOf('/', fullPrefix.length());
if (useFlatBlobListing || indexOfSlash < 0) {
if (current.isPageBlob()) {
ret.add(new MockCloudPageBlobWrapper(
convertKeyToEncodedUri(current.getKey()),
current.getMetadata(),
current.getContentLength()));
} else {
ret.add(new MockCloudBlockBlobWrapper(
convertKeyToEncodedUri(current.getKey()),
current.getMetadata(),
current.getContentLength()));
}
} else {
String directoryName = current.getKey().substring(0, indexOfSlash);
if (!addedDirectories.contains(directoryName)) {
addedDirectories.add(current.getKey());
ret.add(new MockCloudBlobDirectoryWrapper(new URI(
directoryName + "/")));
}
}
}
return ret;
}
@Override
public StorageUri getStorageUri() {
throw new NotImplementedException("Code is not implemented");
}
}
abstract | MockCloudBlobDirectoryWrapper |
java | apache__thrift | lib/java/src/main/java/org/apache/thrift/TEnumHelper.java | {
"start": 1041,
"end": 1758
} | class ____ integer value, this method will return the associated constant from the
* given TEnum class. This method MUST be modified should the name of the 'findByValue' method
* change.
*
* @param enumClass TEnum from which to return a matching constant.
* @param value Value for which to return the constant.
* @return The constant in 'enumClass' whose value is 'value' or null if something went wrong.
*/
public static TEnum getByValue(Class<? extends TEnum> enumClass, int value) {
try {
Method method = enumClass.getMethod("findByValue", int.class);
return (TEnum) method.invoke(null, value);
} catch (ReflectiveOperationException nsme) {
return null;
}
}
}
| and |
java | quarkusio__quarkus | extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/CertificateRevocationListTest.java | {
"start": 402,
"end": 1332
} | class ____ {
private static final String configuration = """
quarkus.tls.certificate-revocation-list=src/test/resources/revocations/revoked-cert.der
quarkus.tls.foo.certificate-revocation-list=src/test/resources/revocations/revoked-cert.der
""";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.add(new StringAsset(configuration), "application.properties"));
@Inject
TlsConfigurationRegistry certificates;
@Test
void test() {
TlsConfiguration def = certificates.getDefault().orElseThrow();
TlsConfiguration foo = certificates.get("foo").orElseThrow();
assertThat(def.getSSLOptions().getCrlValues()).hasSize(1);
assertThat(foo.getSSLOptions().getCrlValues()).hasSize(1);
}
}
| CertificateRevocationListTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/impl/DefaultUuidGeneratorTest.java | {
"start": 1175,
"end": 2050
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(DefaultUuidGeneratorTest.class);
@Test
public void testGenerateUUID() {
UuidGenerator uuidGenerator = new DefaultUuidGenerator();
String firstUUID = uuidGenerator.generateUuid();
String secondUUID = uuidGenerator.generateUuid();
assertNotSame(firstUUID, secondUUID);
}
@Test
public void testPerformance() {
UuidGenerator uuidGenerator = new DefaultUuidGenerator();
StopWatch watch = new StopWatch();
LOG.info("First id: {}", uuidGenerator.generateUuid());
for (int i = 0; i < 500000; i++) {
uuidGenerator.generateUuid();
}
LOG.info("Last id: {}", uuidGenerator.generateUuid());
LOG.info("Took {}", TimeUtils.printDuration(watch.taken(), true));
}
}
| DefaultUuidGeneratorTest |
java | apache__flink | flink-table/flink-sql-jdbc-driver/src/main/java/org/apache/flink/table/jdbc/FlinkConnection.java | {
"start": 1825,
"end": 8586
} | class ____ extends BaseConnection {
private final String url;
private final Executor executor;
private final List<Statement> statements;
private boolean closed = false;
public FlinkConnection(DriverUri driverUri) {
this.url = driverUri.getURL();
this.statements = new ArrayList<>();
this.executor =
Executor.create(
new DefaultContext(
DriverUtils.fromProperties(driverUri.getProperties()),
Collections.emptyList()),
driverUri.getAddress(),
UUID.randomUUID().toString(),
RowFormat.JSON);
driverUri.getCatalog().ifPresent(this::setSessionCatalog);
driverUri.getDatabase().ifPresent(this::setSessionSchema);
}
@VisibleForTesting
FlinkConnection(Executor executor) {
this.url = null;
this.statements = new ArrayList<>();
this.executor = executor;
}
@Override
public Statement createStatement() throws SQLException {
ensureOpen();
final Statement statement = new FlinkStatement(this);
statements.add(statement);
return statement;
}
// TODO We currently do not support this, but we can't throw a SQLException here because we want
// to support jdbc tools such as beeline and sqlline.
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {}
// TODO We currently do not support this, but we can't throw a SQLException here because we want
// to support jdbc tools such as beeline and sqlline.
@Override
public boolean getAutoCommit() throws SQLException {
return true;
}
@VisibleForTesting
Executor getExecutor() {
return this.executor;
}
private void ensureOpen() throws SQLException {
if (isClosed()) {
throw new SQLException("The current connection is closed.");
}
}
@Override
public void close() throws SQLException {
if (closed) {
return;
}
List<Statement> remainStatements = new ArrayList<>(statements);
for (Statement statement : remainStatements) {
statement.close();
}
remainStatements.clear();
statements.clear();
try {
this.executor.close();
} catch (Exception e) {
throw new SQLException("Close connection fail", e);
}
this.closed = true;
}
@Override
public boolean isClosed() throws SQLException {
return closed;
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
ensureOpen();
return new FlinkDatabaseMetaData(url, this, createStatement());
}
@Override
public void setCatalog(String catalog) throws SQLException {
ensureOpen();
try {
setSessionCatalog(catalog);
} catch (Exception e) {
throw new SQLException(String.format("Set catalog[%s] fail", catalog), e);
}
}
private void setSessionCatalog(String catalog) {
executor.configureSession(String.format("USE CATALOG %s;", catalog));
}
@Override
public String getCatalog() throws SQLException {
ensureOpen();
try (StatementResult result = executor.executeStatement("SHOW CURRENT CATALOG;")) {
if (result.hasNext()) {
String catalog = result.next().getString(0).toString();
checkArgument(!result.hasNext(), "There are more than one current catalog.");
return catalog;
} else {
throw new SQLException("No catalog");
}
}
}
// TODO We currently do not support this, but we can't throw a SQLException here because we want
// to support jdbc tools such as beeline and sqlline.
@Override
public void setTransactionIsolation(int level) throws SQLException {}
// TODO We currently do not support this, but we can't throw a SQLException here because we want
// to support jdbc tools such as beeline and sqlline.
@Override
public int getTransactionIsolation() throws SQLException {
return Connection.TRANSACTION_NONE;
}
// TODO We currently do not support this, but we can't throw a SQLException here because we want
// to support jdbc tools such as beeline and sqlline.
@Override
public SQLWarning getWarnings() throws SQLException {
return null;
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
try {
ensureOpen();
} catch (SQLException e) {
throw new SQLClientInfoException("Connection is closed", new HashMap<>(), e);
}
executor.configureSession(String.format("SET '%s'='%s';", name, value));
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
for (Object key : properties.keySet()) {
setClientInfo(key.toString(), properties.getProperty(key.toString()));
}
}
@Override
public String getClientInfo(String name) throws SQLException {
ensureOpen();
Map<String, String> configuration = executor.getSessionConfigMap();
return configuration.get(name);
}
@Override
public Properties getClientInfo() throws SQLException {
ensureOpen();
Properties properties = new Properties();
Map<String, String> configuration = executor.getSessionConfigMap();
configuration.forEach(properties::setProperty);
return properties;
}
@Override
public void setSchema(String schema) throws SQLException {
ensureOpen();
try {
setSessionSchema(schema);
} catch (Exception e) {
throw new SQLException(String.format("Set schema[%s] fail", schema), e);
}
}
private void setSessionSchema(String schema) {
executor.configureSession(String.format("USE %s;", schema));
}
@Override
public String getSchema() throws SQLException {
ensureOpen();
try (StatementResult result = executor.executeStatement("SHOW CURRENT DATABASE;")) {
if (result.hasNext()) {
String schema = result.next().getString(0).toString();
checkArgument(!result.hasNext(), "There are more than one current database.");
return schema;
} else {
throw new SQLException("No database");
}
}
}
void removeStatement(FlinkStatement statement) {
statements.remove(statement);
}
}
| FlinkConnection |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/security/ssl/CommonNameLoggingSslEngineFactory.java | {
"start": 1015,
"end": 1517
} | class ____ extends DefaultSslEngineFactory {
@Override
protected TrustManager[] getTrustManagers(SecurityStore truststore, String tmfAlgorithm) throws NoSuchAlgorithmException, KeyStoreException {
CommonNameLoggingTrustManagerFactoryWrapper tmf = CommonNameLoggingTrustManagerFactoryWrapper.getInstance(tmfAlgorithm);
KeyStore ts = truststore == null ? null : truststore.get();
tmf.init(ts);
return tmf.getTrustManagers();
}
}
| CommonNameLoggingSslEngineFactory |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafeCheckerTest.java | {
"start": 8081,
"end": 8202
} | interface ____ {}
""")
.addSourceLines(
"MyTest.java",
"""
final | Test |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/convert/ConvertingSerializerTest.java | {
"start": 3675,
"end": 3891
} | class ____ {
@JsonSerialize(as = List.class, contentAs = Source.class)
public List<Source> stuff = Arrays.asList(new Source());
}
@JsonSerialize(using = TargetSerializer.class)
static | Bean359 |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/resultmatches/ContentAssertionTests.java | {
"start": 4553,
"end": 4926
} | class ____ {
@RequestMapping(path="/handle", produces="text/plain")
@ResponseBody
String handle() {
return "Hello world!";
}
@RequestMapping(path="/handleUtf8", produces="text/plain;charset=UTF-8")
@ResponseBody
String handleWithCharset() {
return "\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01"; // "Hello world!" (Japanese)
}
}
}
| SimpleController |
java | quarkusio__quarkus | extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/ConfigImplicitConverterTest.java | {
"start": 470,
"end": 1042
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(Configured.class, Foo.class, Bar.class)
.addAsResource(new StringAsset("foo=1\nbar=1"), "application.properties"));
@Inject
Configured configured;
@Test
public void testFoo() {
assertEquals("1", configured.getFooValue());
assertEquals("1", configured.getBarProviderValue());
}
@ApplicationScoped
static | ConfigImplicitConverterTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/mapper/RoutingFieldMapper.java | {
"start": 822,
"end": 1118
} | class ____ extends MetadataFieldMapper {
public static final String NAME = "_routing";
public static final String CONTENT_TYPE = "_routing";
@Override
public FieldMapper.Builder getMergeBuilder() {
return new Builder().init(this);
}
public static | RoutingFieldMapper |
java | apache__camel | components/camel-aws/camel-aws-bedrock/src/test/java/org/apache/camel/component/aws2/bedrock/agent/integration/BedrockAgentConsumerIT.java | {
"start": 1720,
"end": 2514
} | class ____ extends CamelTestSupport {
@EndpointInject
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint result;
@Test
public void sendInOnly() throws Exception {
result.expectedMessageCount(1);
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("aws-bedrock-agent:label?accessKey=RAW({{aws.manual.access.key}})&secretKey=RAW({{aws.manual.secret.key}}®ion=us-east-1&knowledgeBaseId=AJHTAIUSJP&dataSourceId=AJX8Z7JX9J&ingestionJobId=YOWE23OBEB")
.to(result);
}
};
}
}
| BedrockAgentConsumerIT |
java | quarkusio__quarkus | extensions/panache/panache-mock/src/main/java/io/quarkus/panache/mock/impl/PanacheMockMethodCustomizer.java | {
"start": 412,
"end": 1417
} | class ____ implements PanacheMethodCustomizer {
private final static String PANACHE_MOCK_BINARY_NAME = PanacheMock.class.getName().replace('.', '/');
private final static String PANACHE_MOCK_INVOKE_REAL_METHOD_EXCEPTION_BINARY_NAME = PanacheMock.InvokeRealMethodException.class
.getName().replace('.', '/');
@Override
public void customize(Type entityClassSignature, MethodInfo method, MethodVisitor mv) {
/*
* Generated code:
*
* if(PanacheMock.IsMockEnabled && PanacheMock.isMocked(TestClass.class)) {
* try {
* return (int)PanacheMock.mockMethod(TestClass.class, "foo", new Class<?>[] {int.class}, new Object[] {arg});
* } catch (PanacheMock.InvokeRealMethodException e) {
* // fall-through
* }
* }
*
* Bytecode approx:
*
* 0: getstatic #16 // Field PanacheMock.IsMockEnabled:Z
* 3: ifeq 50
* 6: ldc #1 // | PanacheMockMethodCustomizer |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/utils/Shell.java | {
"start": 1305,
"end": 5443
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(Shell.class);
/** Return an array containing the command name and its parameters */
protected abstract String[] execString();
/** Parse the execution result */
protected abstract void parseExecResult(BufferedReader lines) throws IOException;
private final long timeout;
private int exitCode;
private Process process; // sub process used to execute the command
/* If or not script finished executing */
private volatile AtomicBoolean completed;
/**
* @param timeout Specifies the time in milliseconds, after which the command will be killed. -1 means no timeout.
*/
public Shell(long timeout) {
this.timeout = timeout;
}
/** get the exit code
* @return the exit code of the process
*/
public int exitCode() {
return exitCode;
}
/** get the current sub-process executing the given command
* @return process executing the command
*/
public Process process() {
return process;
}
protected void run() throws IOException {
exitCode = 0; // reset for next run
runCommand();
}
/** Run a command */
private void runCommand() throws IOException {
ProcessBuilder builder = new ProcessBuilder(execString());
Timer timeoutTimer = null;
completed = new AtomicBoolean(false);
process = builder.start();
if (timeout > -1) {
timeoutTimer = new Timer();
//One time scheduling.
timeoutTimer.schedule(new ShellTimeoutTimerTask(this), timeout);
}
final BufferedReader errReader = new BufferedReader(
new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8));
BufferedReader inReader = new BufferedReader(
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
final StringBuffer errMsg = new StringBuffer();
// read error and input streams as this would free up the buffers
// free the error stream buffer
Thread errThread = KafkaThread.nonDaemon("kafka-shell-thread", () -> {
try {
String line = errReader.readLine();
while ((line != null) && !Thread.currentThread().isInterrupted()) {
errMsg.append(line);
errMsg.append(System.lineSeparator());
line = errReader.readLine();
}
} catch (IOException ioe) {
LOG.warn("Error reading the error stream", ioe);
}
});
errThread.start();
try {
parseExecResult(inReader); // parse the output
// wait for the process to finish and check the exit code
exitCode = process.waitFor();
try {
// make sure that the error thread exits
errThread.join();
} catch (InterruptedException ie) {
LOG.warn("Interrupted while reading the error stream", ie);
}
completed.set(true);
//the timeout thread handling
//taken care in finally block
if (exitCode != 0) {
throw new ExitCodeException(exitCode, errMsg.toString());
}
} catch (InterruptedException ie) {
throw new IOException(ie.toString());
} finally {
if (timeoutTimer != null)
timeoutTimer.cancel();
// close the input stream
try {
inReader.close();
} catch (IOException ioe) {
LOG.warn("Error while closing the input stream", ioe);
}
if (!completed.get())
errThread.interrupt();
try {
errReader.close();
} catch (IOException ioe) {
LOG.warn("Error while closing the error stream", ioe);
}
process.destroy();
}
}
/**
* This is an IOException with exit code added.
*/
public static | Shell |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/context/exceptions/MessageUtils.java | {
"start": 1035,
"end": 7780
} | class ____ {
/**
* Builds an appropriate error message.
*
* @param resolutionContext The resolution context
* @param message The message
* @return The message
*/
static String buildMessage(BeanResolutionContext resolutionContext, String message) {
BeanResolutionContext.Path path = resolutionContext.getPath();
BeanDefinition declaringType;
boolean hasPath = !path.isEmpty();
if (hasPath) {
BeanResolutionContext.Segment segment = path.peek();
declaringType = segment.getDeclaringType();
} else {
declaringType = resolutionContext.getRootDefinition();
}
String ls = CachedEnvironment.getProperty("line.separator");
StringBuilder builder = new StringBuilder("Error instantiating bean of type [");
builder
.append(declaringType.getName())
.append("]")
.append(ls)
.append(ls);
if (message != null) {
builder.append("Message: ").append(message).append(ls);
}
if (hasPath) {
String pathString = path.toString();
builder.append("Path Taken:").append(pathString);
}
return builder.toString();
}
static String buildMessage(BeanResolutionContext resolutionContext, String message, boolean circular) {
BeanResolutionContext.Segment<?, ?> currentSegment = resolutionContext.getPath().peek();
if (currentSegment instanceof AbstractBeanResolutionContext.ConstructorSegment) {
return buildMessage(resolutionContext, currentSegment.getArgument(), message, circular);
}
if (currentSegment instanceof AbstractBeanResolutionContext.MethodSegment) {
return buildMessageForMethod(resolutionContext, currentSegment.getDeclaringType(), currentSegment.getName(), currentSegment.getArgument(), message, circular);
}
if (currentSegment instanceof AbstractBeanResolutionContext.FieldSegment) {
return buildMessageForField(resolutionContext, currentSegment.getDeclaringType(), currentSegment.getName(), message, circular);
}
if (currentSegment instanceof AbstractBeanResolutionContext.AnnotationSegment) {
return buildMessage(resolutionContext, currentSegment.getArgument(), message, circular);
}
throw new IllegalStateException("Unknown segment: " + currentSegment);
}
/**
* Builds an appropriate error message.
*
* @param resolutionContext The resolution context
* @param declaringType The declaring type
* @param methodName The method name
* @param argument The argument
* @param message The message
* @param circular Is the path circular
* @return The message
*/
static String buildMessageForMethod(BeanResolutionContext resolutionContext, BeanDefinition declaringType, String methodName, Argument argument, String message, boolean circular) {
StringBuilder builder = new StringBuilder("Failed to inject value for parameter [");
String ls = CachedEnvironment.getProperty("line.separator");
String declaringTypeName = declaringType.getName();
if (declaringType.hasAnnotation(Factory.class)) {
declaringTypeName = declaringType.getConstructor().getDeclaringBeanType().getName();
}
builder
.append(argument.getName()).append("] of method [")
.append(methodName)
.append("] of class: ")
.append(declaringTypeName)
.append(ls)
.append(ls);
if (message != null) {
builder.append("Message: ").append(message).append(ls);
}
appendPath(resolutionContext, circular, builder, ls);
return builder.toString();
}
/**
* Builds an appropriate error message.
*
* @param resolutionContext The resolution context
* @param declaringType The declaring type
* @param fieldName The field name
* @param message The message
* @param circular Is the path circular
* @return The message
*/
static String buildMessageForField(BeanResolutionContext resolutionContext, BeanDefinition declaringType, String fieldName, String message, boolean circular) {
StringBuilder builder = new StringBuilder("Failed to inject value for field [");
String ls = CachedEnvironment.getProperty("line.separator");
builder
.append(fieldName).append("] of class: ")
.append(declaringType.getName())
.append(ls)
.append(ls);
if (message != null) {
builder.append("Message: ").append(message).append(ls);
}
appendPath(resolutionContext, circular, builder, ls);
return builder.toString();
}
/**
* Builds an appropriate error message for a constructor argument.
*
* @param resolutionContext The resolution context
* @param argument The argument
* @param message The message
* @param circular Is the path circular
* @return The message
*/
static String buildMessage(BeanResolutionContext resolutionContext, Argument argument, String message, boolean circular) {
StringBuilder builder = new StringBuilder("Failed to inject value for parameter [");
String ls = CachedEnvironment.getProperty("line.separator");
BeanResolutionContext.Path path = resolutionContext.getPath();
builder
.append(argument.getName()).append("] of class: ")
.append(path.peek().getDeclaringType().getName())
.append(ls)
.append(ls);
if (message != null) {
builder.append("Message: ").append(message).append(ls);
}
appendPath(circular, builder, ls, path);
return builder.toString();
}
private static void appendPath(BeanResolutionContext resolutionContext, boolean circular, StringBuilder builder, String ls) {
BeanResolutionContext.Path path = resolutionContext.getPath();
if (!path.isEmpty()) {
appendPath(circular, builder, ls, path);
}
}
private static void appendPath(boolean circular, StringBuilder builder, String ls, BeanResolutionContext.Path path) {
builder.append("Path Taken:");
if (circular) {
builder.append(ls).append(path.toConsoleCircularString(false));
} else {
builder.append(" ").append(path);
}
}
}
| MessageUtils |
java | quarkusio__quarkus | extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/management/ManagementWithPemAndNamedTlsRegistryTest.java | {
"start": 1111,
"end": 3064
} | class ____ {
private static final String configuration = """
quarkus.management.enabled=true
quarkus.management.root-path=/management
quarkus.management.tls-configuration-name=mgt
quarkus.tls.mgt.key-store.pem.0.cert=server.crt
quarkus.tls.mgt.key-store.pem.0.key=server.key
""";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addAsResource(new StringAsset(configuration), "application.properties")
.addAsResource(new File("target/certs/ssl-management-interface-test.key"), "server.key")
.addAsResource(new File("target/certs/ssl-management-interface-test.crt"), "server.crt")
.addClasses(MyObserver.class))
.addBuildChainCustomizer(buildCustomizer());
static Consumer<BuildChainBuilder> buildCustomizer() {
return new Consumer<BuildChainBuilder>() {
@Override
public void accept(BuildChainBuilder builder) {
builder.addBuildStep(new BuildStep() {
@Override
public void execute(BuildContext context) {
NonApplicationRootPathBuildItem buildItem = context.consume(NonApplicationRootPathBuildItem.class);
context.produce(buildItem.routeBuilder()
.management()
.route("my-route")
.handler(new MyHandler())
.blockingRoute()
.build());
}
}).produces(RouteBuildItem.class)
.consumes(NonApplicationRootPathBuildItem.class)
.build();
}
};
}
public static | ManagementWithPemAndNamedTlsRegistryTest |
java | apache__kafka | coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/CoordinatorExecutor.java | {
"start": 1332,
"end": 1585
} | interface ____<R> {
R run() throws Throwable;
}
/**
* The task's write operation to handle the output
* of the task.
*
* @param <T> The record type.
* @param <R> The return type of the task.
*/
| TaskRunnable |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/customtype/ExtendedEnumTypeTest.java | {
"start": 1865,
"end": 2109
} | class ____ {
// An extended type to trigger the need for Envers to supply type information in the HBM mappings.
// This should be treated the same as any other property annotated as Enumerated or uses an Enum.
public static | ExtendedEnumTypeTest |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeTimestampTest.java | {
"start": 1023,
"end": 2832
} | class ____ {
@Test
public void just() {
Maybe.just(1)
.timestamp()
.test()
.assertValueCount(1)
.assertNoErrors()
.assertComplete();
}
@Test
public void empty() {
Maybe.empty()
.timestamp()
.test()
.assertResult();
}
@Test
public void error() {
Maybe.error(new TestException())
.timestamp()
.test()
.assertFailure(TestException.class);
}
@Test
public void justSeconds() {
Maybe.just(1)
.timestamp(TimeUnit.SECONDS)
.test()
.assertValueCount(1)
.assertNoErrors()
.assertComplete();
}
@Test
public void justScheduler() {
Maybe.just(1)
.timestamp(Schedulers.single())
.test()
.assertValueCount(1)
.assertNoErrors()
.assertComplete();
}
@Test
public void justSecondsScheduler() {
Maybe.just(1)
.timestamp(TimeUnit.SECONDS, Schedulers.single())
.test()
.assertValueCount(1)
.assertNoErrors()
.assertComplete();
}
@Test
public void doubleOnSubscribe() {
TestHelper.checkDoubleOnSubscribeMaybe(m -> m.timestamp());
}
@Test
public void dispose() {
TestHelper.checkDisposed(MaybeSubject.create().timestamp());
}
@Test
public void timeInfo() {
TestScheduler scheduler = new TestScheduler();
MaybeSubject<Integer> ms = MaybeSubject.create();
TestObserver<Timed<Integer>> to = ms
.timestamp(scheduler)
.test();
scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS);
ms.onSuccess(1);
to.assertResult(new Timed<>(1, 1000L, TimeUnit.MILLISECONDS));
}
}
| MaybeTimestampTest |
java | eclipse-vertx__vert.x | vertx-core/src/test/java/io/vertx/tests/json/JacksonTest.java | {
"start": 1126,
"end": 1243
} | class ____ extends VertxTestBase {
private final JacksonCodec codec = new JacksonCodec();
public static | JacksonTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_78_is_unkown.java | {
"start": 1086,
"end": 2766
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "select 20 = any (select col1 from t1) is not unknown as t;";
System.out.println(sql);
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, JdbcConstants.MYSQL, SQLParserFeature.OptimizedForParameterized);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
assertEquals(1, statementList.size());
SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.MYSQL);
stmt.accept(visitor);
{
String output = SQLUtils.toMySqlString(stmt);
assertEquals("SELECT 20 = ANY (\n" +
"\t\tSELECT col1\n" +
"\t\tFROM t1\n" +
"\t) IS NOT unknown AS t;", //
output);
}
{
String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
assertEquals("select 20 = any (\n" +
"\t\tselect col1\n" +
"\t\tfrom t1\n" +
"\t) is not unknown as t;", //
output);
}
{
String output = SQLUtils.toMySqlString(stmt, new SQLUtils.FormatOption(true, true, true));
assertEquals("SELECT ? = ANY (\n" +
"\t\tSELECT col1\n" +
"\t\tFROM t1\n" +
"\t) IS NOT unknown AS t;", //
output);
}
}
}
| MySqlSelectTest_78_is_unkown |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/EqualsIncompatibleTypeTest.java | {
"start": 13024,
"end": 13152
} | class ____ implements EntityKey<EK1> {
@Override
public int compareTo(EK1 o) {
return 0;
}
}
static final | EK1 |
java | google__error-prone | core/src/test/java/com/google/errorprone/refaster/ULabeledStatementTest.java | {
"start": 968,
"end": 1450
} | class ____ {
@Test
public void equality() {
new EqualsTester()
.addEqualityGroup(ULabeledStatement.create("foo", USkip.INSTANCE))
.addEqualityGroup(ULabeledStatement.create("bar", USkip.INSTANCE))
.addEqualityGroup(ULabeledStatement.create("bar", UBlock.create()))
.testEquals();
}
@Test
public void serialization() {
SerializableTester.reserializeAndAssert(ULabeledStatement.create("foo", USkip.INSTANCE));
}
}
| ULabeledStatementTest |
java | spring-projects__spring-security | saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/internal/Saml2Utils.java | {
"start": 2425,
"end": 2898
} | class ____ {
private final String decoded;
private boolean deflate;
private EncodingConfigurer(String decoded) {
this.decoded = decoded;
}
EncodingConfigurer deflate(boolean deflate) {
this.deflate = deflate;
return this;
}
String encode() {
byte[] bytes = (this.deflate) ? Saml2Utils.samlDeflate(this.decoded)
: this.decoded.getBytes(StandardCharsets.UTF_8);
return Saml2Utils.samlEncode(bytes);
}
}
static final | EncodingConfigurer |
java | elastic__elasticsearch | x-pack/plugin/watcher/src/internalClusterTest/java/org/elasticsearch/xpack/watcher/test/integration/BootStrapTests.java | {
"start": 3492,
"end": 16699
} | class ____ extends AbstractWatcherIntegrationTestCase {
@Override
protected boolean timeWarped() {
return false;
}
public void testLoadMalformedWatchRecord() throws Exception {
prepareIndex(Watch.INDEX).setId("_id")
.setSource(
jsonBuilder().startObject()
.startObject(WatchField.TRIGGER.getPreferredName())
.startObject("schedule")
.field("cron", "0/5 * * * * ? 2050")
.endObject()
.endObject()
.startObject(WatchField.ACTIONS.getPreferredName())
.endObject()
.endObject()
)
.get();
// valid watch record:
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
Wid wid = new Wid("_id", now);
ScheduleTriggerEvent event = new ScheduleTriggerEvent("_id", now, now);
ExecutableCondition condition = InternalAlwaysCondition.INSTANCE;
prepareIndex(HistoryStoreField.DATA_STREAM).setId(wid.value())
.setOpType(DocWriteRequest.OpType.CREATE)
.setSource(
jsonBuilder().startObject()
.field("@timestamp", ZonedDateTime.now())
.startObject(WatchRecord.TRIGGER_EVENT.getPreferredName())
.field(event.type(), event)
.endObject()
.startObject(WatchField.CONDITION.getPreferredName())
.field(condition.type(), condition)
.endObject()
.startObject(WatchField.INPUT.getPreferredName())
.startObject("none")
.endObject()
.endObject()
.endObject()
)
.setWaitForActiveShards(ActiveShardCount.ALL)
.setRefreshPolicy(IMMEDIATE)
.get();
// unknown condition:
wid = new Wid("_id", now);
prepareIndex(HistoryStoreField.DATA_STREAM).setId(wid.value())
.setOpType(DocWriteRequest.OpType.CREATE)
.setSource(
jsonBuilder().startObject()
.field("@timestamp", ZonedDateTime.now())
.startObject(WatchRecord.TRIGGER_EVENT.getPreferredName())
.field(event.type(), event)
.endObject()
.startObject(WatchField.CONDITION.getPreferredName())
.startObject("unknown")
.endObject()
.endObject()
.startObject(WatchField.INPUT.getPreferredName())
.startObject("none")
.endObject()
.endObject()
.endObject()
)
.setWaitForActiveShards(ActiveShardCount.ALL)
.setRefreshPolicy(IMMEDIATE)
.get();
// unknown trigger:
wid = new Wid("_id", now);
prepareIndex(HistoryStoreField.DATA_STREAM).setId(wid.value())
.setOpType(DocWriteRequest.OpType.CREATE)
.setSource(
jsonBuilder().startObject()
.field("@timestamp", ZonedDateTime.now())
.startObject(WatchRecord.TRIGGER_EVENT.getPreferredName())
.startObject("unknown")
.endObject()
.endObject()
.startObject(WatchField.CONDITION.getPreferredName())
.field(condition.type(), condition)
.endObject()
.startObject(WatchField.INPUT.getPreferredName())
.startObject("none")
.endObject()
.endObject()
.endObject()
)
.setWaitForActiveShards(ActiveShardCount.ALL)
.setRefreshPolicy(IMMEDIATE)
.get();
stopWatcher();
startWatcher();
assertBusy(() -> {
WatcherStatsResponse response = new WatcherStatsRequestBuilder(client()).get();
assertThat(response.getWatchesCount(), equalTo(1L));
});
}
public void testLoadExistingWatchesUponStartup() throws Exception {
stopWatcher();
int numWatches = scaledRandomIntBetween(16, 128);
WatcherSearchTemplateRequest request = templateRequest(searchSource().query(termQuery("field", "value")), "my-index");
BulkRequestBuilder bulkRequestBuilder = client().prepareBulk();
for (int i = 0; i < numWatches; i++) {
bulkRequestBuilder.add(
prepareIndex(Watch.INDEX).setId("_id" + i)
.setSource(
watchBuilder().trigger(schedule(cron("0 0/5 * * * ? 2050")))
.input(searchInput(request))
.condition(new CompareCondition("ctx.payload.hits.total.value", CompareCondition.Op.EQ, 1L))
.buildAsBytes(XContentType.JSON),
XContentType.JSON
)
.setWaitForActiveShards(ActiveShardCount.ALL)
);
}
bulkRequestBuilder.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get();
assertHitCount(prepareSearch(Watch.INDEX).setSize(0), numWatches);
startWatcher();
assertBusy(() -> {
WatcherStatsResponse response = new WatcherStatsRequestBuilder(client()).get();
assertThat(response.getWatchesCount(), equalTo((long) numWatches));
});
}
public void testMixedTriggeredWatchLoading() throws Exception {
createIndex("output");
prepareIndex("my-index").setId("bar").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).setSource("field", "value").get();
WatcherStatsResponse response = new WatcherStatsRequestBuilder(client()).get();
assertThat(response.getWatchesCount(), equalTo(0L));
WatcherSearchTemplateRequest request = templateRequest(searchSource().query(termQuery("field", "value")), "my-index");
ensureGreen("output", "my-index");
int numWatches = 8;
for (int i = 0; i < numWatches; i++) {
String watchId = "_id" + i;
new PutWatchRequestBuilder(client()).setId(watchId)
.setSource(
watchBuilder().trigger(schedule(cron("0/5 * * * * ? 2050")))
.input(searchInput(request))
.condition(InternalAlwaysCondition.INSTANCE)
.addAction("_id", indexAction("output"))
.defaultThrottlePeriod(TimeValue.timeValueMillis(0))
)
.get();
}
stopWatcher();
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
final int numRecords = scaledRandomIntBetween(numWatches, 128);
BulkRequestBuilder bulkRequestBuilder = client().prepareBulk();
for (int i = 0; i < numRecords; i++) {
String watchId = "_id" + (i % numWatches);
now = now.plusMinutes(1);
ScheduleTriggerEvent event = new ScheduleTriggerEvent(watchId, now, now);
Wid wid = new Wid(watchId, now);
TriggeredWatch triggeredWatch = new TriggeredWatch(wid, event);
bulkRequestBuilder.add(
prepareIndex(TriggeredWatchStoreField.INDEX_NAME).setId(triggeredWatch.id().value())
.setSource(jsonBuilder().value(triggeredWatch))
.request()
);
}
bulkRequestBuilder.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get();
logger.info("Added [{}] triggered watches for [{}] different watches, starting watcher again", numRecords, numWatches);
startWatcher();
assertSingleExecutionAndCompleteWatchHistory(numWatches, numRecords);
}
public void testTriggeredWatchLoading() throws Exception {
cluster().wipeIndices(TriggeredWatchStoreField.INDEX_NAME);
createIndex("output");
prepareIndex("my-index").setId("bar").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).setSource("field", "value").get();
WatcherStatsResponse response = new WatcherStatsRequestBuilder(client()).get();
assertThat(response.getWatchesCount(), equalTo(0L));
String watchId = "_id";
WatcherSearchTemplateRequest request = templateRequest(searchSource().query(termQuery("field", "value")), "my-index");
new PutWatchRequestBuilder(client()).setId(watchId)
.setSource(
watchBuilder().trigger(schedule(cron("0/5 * * * * ? 2050")))
.input(searchInput(request))
.condition(InternalAlwaysCondition.INSTANCE)
.addAction("_id", indexAction("output"))
.defaultThrottlePeriod(TimeValue.timeValueMillis(0))
)
.get();
stopWatcher();
ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
final int numRecords = scaledRandomIntBetween(2, 12);
BulkRequestBuilder bulkRequestBuilder = client().prepareBulk();
for (int i = 0; i < numRecords; i++) {
now = now.plusMinutes(1);
ScheduleTriggerEvent event = new ScheduleTriggerEvent(watchId, now, now);
Wid wid = new Wid(watchId, now);
TriggeredWatch triggeredWatch = new TriggeredWatch(wid, event);
bulkRequestBuilder.add(
prepareIndex(TriggeredWatchStoreField.INDEX_NAME).setId(triggeredWatch.id().value())
.setSource(jsonBuilder().value(triggeredWatch))
.setWaitForActiveShards(ActiveShardCount.ALL)
);
}
bulkRequestBuilder.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get();
startWatcher();
assertSingleExecutionAndCompleteWatchHistory(1, numRecords);
}
private void assertSingleExecutionAndCompleteWatchHistory(final long numberOfWatches, final int expectedWatchHistoryCount)
throws Exception {
assertBusy(() -> {
// We need to wait until all the records are processed from the internal execution queue, only then we can assert
// that numRecords watch records have been processed as part of starting up.
WatcherStatsResponse response = new WatcherStatsRequestBuilder(client()).setIncludeCurrentWatches(true).get();
long maxSize = response.getNodes().stream().map(WatcherStatsResponse.Node::getSnapshots).mapToLong(List::size).sum();
assertThat(maxSize, equalTo(0L));
AtomicLong successfulWatchExecutions = new AtomicLong();
refresh();
assertResponse(prepareSearch("output"), searchResponse -> {
assertThat(searchResponse.getHits().getTotalHits().value(), is(greaterThanOrEqualTo(numberOfWatches)));
successfulWatchExecutions.set(searchResponse.getHits().getTotalHits().value());
});
// the watch history should contain entries for each triggered watch, which a few have been marked as not executed
assertResponse(prepareSearch(HistoryStoreField.INDEX_PREFIX + "*").setSize(10000), historySearchResponse -> {
assertHitCount(historySearchResponse, expectedWatchHistoryCount);
long notExecutedCount = Arrays.stream(historySearchResponse.getHits().getHits())
.filter(hit -> hit.getSourceAsMap().get("state").equals(ExecutionState.NOT_EXECUTED_ALREADY_QUEUED.id()))
.count();
logger.info(
"Watches not executed: [{}]: expected watch history count [{}] - [{}] successful watch exections",
notExecutedCount,
expectedWatchHistoryCount,
successfulWatchExecutions
);
assertThat(notExecutedCount, is(expectedWatchHistoryCount - successfulWatchExecutions.get()));
});
}, 20, TimeUnit.SECONDS);
}
public void testManuallyStopped() throws Exception {
WatcherStatsResponse response = new WatcherStatsRequestBuilder(client()).get();
assertThat(response.watcherMetadata().manuallyStopped(), is(false));
stopWatcher();
response = new WatcherStatsRequestBuilder(client()).get();
assertThat(response.watcherMetadata().manuallyStopped(), is(true));
startWatcher();
response = new WatcherStatsRequestBuilder(client()).get();
assertThat(response.watcherMetadata().manuallyStopped(), is(false));
}
public void testWatchRecordSavedTwice() throws Exception {
// Watcher could prevent to start if a watch record tried to executed twice or more and the watch didn't exist
// for that watch record or the execution threadpool rejected the watch record.
// A watch record without a watch is the easiest to simulate, so that is what this test does.
if (indexExists(Watch.INDEX) == false) {
// we rarely create an .watches alias in the base | BootStrapTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/id/hhh12973/SequenceMismatchStrategyWithoutSequenceGeneratorTest.java | {
"start": 4249,
"end": 4469
} | class ____ {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
}
}
| ApplicationConfiguration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.