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/test/java/org/hibernate/orm/test/version/sybase/User.java
{ "start": 235, "end": 1160 }
class ____ { private Integer id; private byte[] timestamp; private String username; private Set<Group> groups; private Set<Permission> permissions; public User() { } public User(Integer id, String username) { this.id = id; this.username = username; } public Integer getId() { return id; } protected void setId(Integer id) { this.id = id; } public byte[] getTimestamp() { return timestamp; } public void setTimestamp(byte[] timestamp) { this.timestamp = timestamp; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Set<Group> getGroups() { return groups; } public void setGroups(Set<Group> groups) { this.groups = groups; } public Set<Permission> getPermissions() { return permissions; } public void setPermissions(Set<Permission> permissions) { this.permissions = permissions; } }
User
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DaprEndpointBuilderFactory.java
{ "start": 44381, "end": 44668 }
interface ____ extends AdvancedDaprEndpointConsumerBuilder, AdvancedDaprEndpointProducerBuilder { default DaprEndpointBuilder basic() { return (DaprEndpointBuilder) this; } } public
AdvancedDaprEndpointBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/associations/OneToOneUnidirectionalTest.java
{ "start": 1147, "end": 1881 }
class ____ { @Id @GeneratedValue private Long id; @Column(name = "`number`") private String number; @OneToOne @JoinColumn(name = "details_id") private PhoneDetails details; //Getters and setters are omitted for brevity //end::associations-one-to-one-unidirectional-example[] public Phone() { } public Phone(String number) { this.number = number; } public Long getId() { return id; } public String getNumber() { return number; } public PhoneDetails getDetails() { return details; } public void setDetails(PhoneDetails details) { this.details = details; } //tag::associations-one-to-one-unidirectional-example[] } @Entity(name = "PhoneDetails") public static
Phone
java
ReactiveX__RxJava
src/jmh/java/io/reactivex/rxjava3/core/RxVsStreamPerf.java
{ "start": 1072, "end": 3391 }
class ____ { @Param({ "1", "1000", "1000000" }) public int times; Flowable<Integer> range; Observable<Integer> rangeObservable; Flowable<Integer> rangeFlatMap; Observable<Integer> rangeObservableFlatMap; Flowable<Integer> rangeFlatMapJust; Observable<Integer> rangeObservableFlatMapJust; List<Integer> values; @Setup public void setup() { range = Flowable.range(1, times); rangeFlatMapJust = range.flatMap(new Function<Integer, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Integer v) { return Flowable.just(v); } }); rangeFlatMap = range.flatMap(new Function<Integer, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Integer v) { return Flowable.range(v, 2); } }); rangeObservable = Observable.range(1, times); rangeObservableFlatMapJust = rangeObservable.flatMap(new Function<Integer, Observable<Integer>>() { @Override public Observable<Integer> apply(Integer v) { return Observable.just(v); } }); rangeObservableFlatMap = rangeObservable.flatMap(new Function<Integer, Observable<Integer>>() { @Override public Observable<Integer> apply(Integer v) { return Observable.range(v, 2); } }); values = range.toList().blockingGet(); } @Benchmark public void range(Blackhole bh) { range.subscribe(new PerfSubscriber(bh)); } @Benchmark public void rangeObservable(Blackhole bh) { rangeObservable.subscribe(new PerfObserver(bh)); } @Benchmark public void rangeFlatMap(Blackhole bh) { rangeFlatMap.subscribe(new PerfSubscriber(bh)); } @Benchmark public void rangeObservableFlatMap(Blackhole bh) { rangeObservableFlatMap.subscribe(new PerfObserver(bh)); } @Benchmark public void rangeFlatMapJust(Blackhole bh) { rangeFlatMapJust.subscribe(new PerfSubscriber(bh)); } @Benchmark public void rangeObservableFlatMapJust(Blackhole bh) { rangeObservableFlatMapJust.subscribe(new PerfObserver(bh)); } }
RxVsStreamPerf
java
apache__camel
components/camel-telemetry/src/main/java/org/apache/camel/telemetry/decorators/SjmsSpanDecorator.java
{ "start": 927, "end": 1619 }
class ____ extends AbstractMessagingSpanDecorator { @Override public String getComponent() { return "sjms"; } @Override protected String getDestination(Exchange exchange, Endpoint endpoint) { // when using toD for dynamic destination then extract from header String destination = exchange.getMessage().getHeader("CamelJMSDestinationName", String.class); if (destination == null) { destination = super.getDestination(exchange, endpoint); } return destination; } @Override public String getComponentClassName() { return "org.apache.camel.component.sjms.SjmsComponent"; } }
SjmsSpanDecorator
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/rest/Empty.java
{ "start": 992, "end": 1421 }
class ____ { public static final Empty INSTANCE = new Empty(); @JsonCreator public Empty() { } @Override public boolean equals(Object o) { if (this == o) return true; return o != null && getClass() == o.getClass(); } @Override public int hashCode() { return 1; } @Override public String toString() { return JsonUtil.toJsonString(this); } }
Empty
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/reflect/InstantiationUtils.java
{ "start": 2458, "end": 5739 }
class ____ {@link io.micronaut.core.beans.BeanIntrospector}. * * @param type The type * @param propertiesMap The properties values {@link Map} of the instance * @param context The Conversion context * @param <T> The generic type * @return The instantiated instance or {@link Optional#empty()} * @throws InstantiationException When an error occurs */ public static @NonNull <T> Optional<T> tryInstantiate(@NonNull Class<T> type, Map propertiesMap, ConversionContext context) { ArgumentUtils.requireNonNull("type", type); if (propertiesMap.isEmpty()) { return tryInstantiate(type); } final Supplier<T> reflectionFallback = () -> { Logger log = LoggerFactory.getLogger(InstantiationUtils.class); if (log.isDebugEnabled()) { log.debug("Tried, but could not instantiate type: {}", type); } return null; }; T result = BeanIntrospector.SHARED.findIntrospection(type).map(introspection -> { T instance; Argument[] constructorArguments = introspection.getConstructorArguments(); List<Object> arguments = new ArrayList<>(constructorArguments.length); try { if (constructorArguments.length > 0) { Map bindMap = CollectionUtils.newLinkedHashMap(propertiesMap.size()); Set<Map.Entry<?, ?>> entries = propertiesMap.entrySet(); for (Map.Entry<?, ?> entry : entries) { Object key = entry.getKey(); bindMap.put(NameUtils.decapitalize(NameUtils.dehyphenate(key.toString())), entry.getValue()); } for (Argument<?> argument : constructorArguments) { if (bindMap.containsKey(argument.getName())) { Object converted = ConversionService.SHARED.convert(bindMap.get(argument.getName()), argument.getType(), ConversionContext.of(argument)).orElseThrow(() -> new ConversionErrorException(argument, context.getLastError() .orElse(() -> new IllegalArgumentException("Value [" + bindMap.get(argument.getName()) + "] cannot be converted to type : " + argument.getType()))) ); arguments.add(converted); } else if (argument.isDeclaredNullable()) { arguments.add(null); } else { context.reject(new ConversionErrorException(argument, () -> new IllegalArgumentException("No Value found for argument " + argument.getName()))); } } instance = introspection.instantiate(arguments.toArray()); } else { instance = introspection.instantiate(); } return instance; } catch (InstantiationException e) { return reflectionFallback.get(); } }).orElseGet(reflectionFallback); return Optional.ofNullable(result); } /** * Try to instantiate the given
using
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/FileInputFormatCounter.java
{ "start": 1071, "end": 1115 }
enum ____ { BYTES_READ }
FileInputFormatCounter
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJAroundAdvice.java
{ "start": 1252, "end": 2633 }
class ____ extends AbstractAspectJAdvice implements MethodInterceptor, Serializable { public AspectJAroundAdvice( Method aspectJAroundAdviceMethod, AspectJExpressionPointcut pointcut, AspectInstanceFactory aif) { super(aspectJAroundAdviceMethod, pointcut, aif); } @Override public boolean isBeforeAdvice() { return false; } @Override public boolean isAfterAdvice() { return false; } @Override protected boolean supportsProceedingJoinPoint() { return true; } @Override public @Nullable Object invoke(MethodInvocation mi) throws Throwable { if (!(mi instanceof ProxyMethodInvocation pmi)) { throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi); } ProceedingJoinPoint pjp = lazyGetProceedingJoinPoint(pmi); JoinPointMatch jpm = getJoinPointMatch(pmi); return invokeAdviceMethod(pjp, jpm, null, null); } /** * Return the ProceedingJoinPoint for the current invocation, * instantiating it lazily if it hasn't been bound to the thread already. * @param rmi the current Spring AOP ReflectiveMethodInvocation, * which we'll use for attribute binding * @return the ProceedingJoinPoint to make available to advice methods */ protected ProceedingJoinPoint lazyGetProceedingJoinPoint(ProxyMethodInvocation rmi) { return new MethodInvocationProceedingJoinPoint(rmi); } }
AspectJAroundAdvice
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportCancelJobModelSnapshotUpgradeAction.java
{ "start": 2074, "end": 8019 }
class ____ extends HandledTransportAction<Request, Response> { private static final Logger logger = LogManager.getLogger(TransportCancelJobModelSnapshotUpgradeAction.class); private final JobConfigProvider jobConfigProvider; private final ClusterService clusterService; private final PersistentTasksService persistentTasksService; @Inject public TransportCancelJobModelSnapshotUpgradeAction( TransportService transportService, ActionFilters actionFilters, JobConfigProvider jobConfigProvider, ClusterService clusterService, PersistentTasksService persistentTasksService ) { super(CancelJobModelSnapshotUpgradeAction.NAME, transportService, actionFilters, Request::new, EsExecutors.DIRECT_EXECUTOR_SERVICE); this.jobConfigProvider = jobConfigProvider; this.clusterService = clusterService; this.persistentTasksService = persistentTasksService; } @Override public void doExecute(Task task, Request request, ActionListener<Response> listener) { logger.debug("[{}] cancel model snapshot [{}] upgrades", request.getJobId(), request.getSnapshotId()); // 2. Now that we have the job IDs, find the relevant model snapshot upgrade tasks ActionListener<List<Job.Builder>> expandIdsListener = listener.delegateFailureAndWrap((delegate, jobs) -> { SimpleIdsMatcher matcher = new SimpleIdsMatcher(request.getSnapshotId()); Set<String> jobIds = jobs.stream().map(Job.Builder::getId).collect(Collectors.toSet()); PersistentTasksCustomMetadata tasksInProgress = PersistentTasksCustomMetadata.get( clusterService.state().metadata().getDefaultProject() ); // allow_no_match plays no part here. The reason is that we have a principle that stopping // a stopped entity is a no-op, and upgrades that have already completed won't have a task. // This is a bit different to jobs and datafeeds, where the entity continues to exist even // after it's stopped. Upgrades cease to exist after they're stopped so the match validation // cannot be as thorough. List<PersistentTasksCustomMetadata.PersistentTask<?>> upgradeTasksToCancel = MlTasks.snapshotUpgradeTasks(tasksInProgress) .stream() .filter(t -> jobIds.contains(((SnapshotUpgradeTaskParams) t.getParams()).getJobId())) .filter(t -> matcher.idMatches(((SnapshotUpgradeTaskParams) t.getParams()).getSnapshotId())) .collect(Collectors.toList()); removePersistentTasks(request, upgradeTasksToCancel, delegate); }); // 1. Expand jobs - this will throw if a required job ID match isn't made. Jobs being deleted are included here. jobConfigProvider.expandJobs(request.getJobId(), request.allowNoMatch(), false, null, expandIdsListener); } private void removePersistentTasks( Request request, List<PersistentTasksCustomMetadata.PersistentTask<?>> upgradeTasksToCancel, ActionListener<Response> listener ) { final int numberOfTasks = upgradeTasksToCancel.size(); if (numberOfTasks == 0) { listener.onResponse(new Response(true)); return; } final AtomicInteger counter = new AtomicInteger(); final AtomicArray<Exception> failures = new AtomicArray<>(numberOfTasks); for (PersistentTasksCustomMetadata.PersistentTask<?> task : upgradeTasksToCancel) { persistentTasksService.sendRemoveRequest( task.getId(), MachineLearning.HARD_CODED_MACHINE_LEARNING_MASTER_NODE_TIMEOUT, new ActionListener<>() { @Override public void onResponse(PersistentTasksCustomMetadata.PersistentTask<?> task) { if (counter.incrementAndGet() == numberOfTasks) { sendResponseOrFailure(listener, failures); } } @Override public void onFailure(Exception e) { final int slot = counter.incrementAndGet(); // Not found is not an error - it just means the upgrade completed before we could cancel it. if (ExceptionsHelper.unwrapCause(e) instanceof ResourceNotFoundException == false) { failures.set(slot - 1, e); } if (slot == numberOfTasks) { sendResponseOrFailure(listener, failures); } } private void sendResponseOrFailure(ActionListener<Response> listener, AtomicArray<Exception> failures) { List<Exception> caughtExceptions = failures.asList(); if (caughtExceptions.isEmpty()) { listener.onResponse(new Response(true)); return; } String msg = "Failed to cancel model snapshot upgrade for [" + request.getSnapshotId() + "] on job [" + request.getJobId() + "]. Total failures [" + caughtExceptions.size() + "], rethrowing first. All Exceptions: [" + caughtExceptions.stream().map(Exception::getMessage).collect(Collectors.joining(", ")) + "]"; ElasticsearchStatusException e = exceptionArrayToStatusException(failures, msg); listener.onFailure(e); } } ); } } }
TransportCancelJobModelSnapshotUpgradeAction
java
google__guice
extensions/dagger-adapter/test/com/google/inject/daggeradapter/IntoMapTest.java
{ "start": 5097, "end": 5261 }
class ____ { @dagger.Provides @IntoMap @Wrapped(i = 1, l = 1, defaultValue = "1") int ones() { return 1; } } @dagger.Module
HasConflict
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/WallDenyTableTest.java
{ "start": 782, "end": 1065 }
class ____ extends TestCase { public void testORACLE() throws Exception { String sql = "SELECT *FROM T UNION SELECT F1, F2 FROM SYS.ABC"; OracleWallProvider provider = new OracleWallProvider(); assertFalse(provider.checkValid(sql)); } }
WallDenyTableTest
java
greenrobot__EventBus
EventBusTest/src/org/greenrobot/eventbus/EventBusMainThreadTest.java
{ "start": 833, "end": 1823 }
class ____ extends AbstractAndroidEventBusTest { @Test public void testPost() throws InterruptedException { eventBus.register(this); eventBus.post("Hello"); waitForEventCount(1, 1000); assertEquals("Hello", lastEvent); assertEquals(Looper.getMainLooper().getThread(), lastThread); } @Test public void testPostInBackgroundThread() throws InterruptedException { TestBackgroundPoster backgroundPoster = new TestBackgroundPoster(eventBus); backgroundPoster.start(); eventBus.register(this); backgroundPoster.post("Hello"); waitForEventCount(1, 1000); assertEquals("Hello", lastEvent); assertEquals(Looper.getMainLooper().getThread(), lastThread); backgroundPoster.shutdown(); backgroundPoster.join(); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(String event) { trackEvent(event); } }
EventBusMainThreadTest
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/utils/MD5UtilsTest.java
{ "start": 3548, "end": 4932 }
class ____ implements Runnable { private final String input; private final String expected; private final MD5Utils md5Utils; private final CountDownLatch latch; private final List<Throwable> errorCollector; public Md5Task( String input, String expected, MD5Utils md5Utils, CountDownLatch latch, List<Throwable> errorCollector) { this.input = input; this.expected = expected; this.md5Utils = md5Utils; this.latch = latch; this.errorCollector = errorCollector; } @Override public void run() { int i = 0; long start = System.currentTimeMillis(); try { for (; i < 200; i++) { Assertions.assertEquals(expected, md5Utils.getMd5(input)); md5Utils.getMd5("test#" + i); } } catch (Throwable e) { errorCollector.add(e); e.printStackTrace(); } finally { long cost = System.currentTimeMillis() - start; logger.info( "[{}] progress: {}, cost: {}", Thread.currentThread().getName(), i, cost); latch.countDown(); } } } }
Md5Task
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/filecontroller/LogAggregationDFSException.java
{ "start": 934, "end": 994 }
class ____ an issue during log aggregation. */ public
indicates
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/CheckForDecommissioningNodesResponse.java
{ "start": 1157, "end": 1684 }
class ____ { @Private @Unstable public static CheckForDecommissioningNodesResponse newInstance( Set<NodeId> decommissioningNodes) { CheckForDecommissioningNodesResponse response = Records .newRecord(CheckForDecommissioningNodesResponse.class); response.setDecommissioningNodes(decommissioningNodes); return response; } public abstract void setDecommissioningNodes(Set<NodeId> decommissioningNodes); public abstract Set<NodeId> getDecommissioningNodes(); }
CheckForDecommissioningNodesResponse
java
apache__rocketmq
common/src/main/java/org/apache/rocketmq/common/utils/ServiceProvider.java
{ "start": 3212, "end": 8084 }
class ____ isn't an ancestor of the calling class's class * loader, or if security permissions are restricted. */ } return classLoader; } protected static InputStream getResourceAsStream(ClassLoader loader, String name) { if (loader != null) { return loader.getResourceAsStream(name); } else { return ClassLoader.getSystemResourceAsStream(name); } } public static <T> List<T> load(Class<?> clazz) { String fullName = PREFIX + clazz.getName(); return load(fullName, clazz); } public static <T> List<T> load(String name, Class<?> clazz) { LOG.info("Looking for a resource file of name [{}] ...", name); List<T> services = new ArrayList<>(); InputStream is = getResourceAsStream(getContextClassLoader(), name); if (is == null) { LOG.warn("No resource file with name [{}] found.", name); return services; } try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { String serviceName = reader.readLine(); List<String> names = new ArrayList<>(); while (serviceName != null && !"".equals(serviceName)) { LOG.info( "Creating an instance as specified by file {} which was present in the path of the context classloader.", name); if (!names.contains(serviceName)) { names.add(serviceName); services.add(initService(getContextClassLoader(), serviceName, clazz)); } serviceName = reader.readLine(); } } catch (Exception e) { LOG.error("Error occurred when looking for resource file " + name, e); } return services; } public static <T> T loadClass(Class<?> clazz) { String fullName = PREFIX + clazz.getName(); return loadClass(fullName, clazz); } public static <T> T loadClass(String name, Class<?> clazz) { LOG.info("Looking for a resource file of name [{}] ...", name); T s = null; InputStream is = getResourceAsStream(getContextClassLoader(), name); if (is == null) { LOG.warn("No resource file with name [{}] found.", name); return null; } try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { String serviceName = reader.readLine(); if (serviceName != null && !"".equals(serviceName)) { s = initService(getContextClassLoader(), serviceName, clazz); } else { LOG.warn("ServiceName is empty!"); } } catch (Exception e) { LOG.warn("Error occurred when looking for resource file " + name, e); } return s; } protected static <T> T initService(ClassLoader classLoader, String serviceName, Class<?> clazz) { Class<?> serviceClazz = null; try { if (classLoader != null) { try { // Warning: must typecast here & allow exception to be generated/caught & recast properly serviceClazz = classLoader.loadClass(serviceName); if (clazz.isAssignableFrom(serviceClazz)) { LOG.info("Loaded class {} from classloader {}", serviceClazz.getName(), objectId(classLoader)); } else { // This indicates a problem with the ClassLoader tree. An incompatible ClassLoader was used to load the implementation. LOG.error( "Class {} loaded from classloader {} does not extend {} as loaded by this classloader.", serviceClazz.getName(), objectId(serviceClazz.getClassLoader()), clazz.getName()); } return (T) serviceClazz.getDeclaredConstructor().newInstance(); } catch (ClassNotFoundException ex) { if (classLoader == thisClassLoader) { // Nothing more to try, onwards. LOG.warn("Unable to locate any class {} via classloader {}", serviceName, objectId(classLoader)); throw ex; } // Ignore exception, continue } catch (NoClassDefFoundError e) { if (classLoader == thisClassLoader) { // Nothing more to try, onwards. LOG.warn( "Class {} cannot be loaded via classloader {}.it depends on some other
loader
java
apache__kafka
group-coordinator/src/main/java/org/apache/kafka/coordinator/group/modern/MemberSubscriptionAndAssignmentImpl.java
{ "start": 1247, "end": 3744 }
class ____ implements MemberSubscription, MemberAssignment { private final Optional<String> rackId; private final Optional<String> instanceId; private final Set<Uuid> subscribedTopicIds; private final Assignment memberAssignment; /** * Constructs a new {@code MemberSubscriptionAndAssignmentImpl}. * * @param rackId The rack Id. * @param subscribedTopicIds The set of subscribed topic Ids. * @param memberAssignment The current member assignment. */ public MemberSubscriptionAndAssignmentImpl( Optional<String> rackId, Optional<String> instanceId, Set<Uuid> subscribedTopicIds, Assignment memberAssignment ) { this.rackId = Objects.requireNonNull(rackId); this.instanceId = Objects.requireNonNull(instanceId); this.subscribedTopicIds = Objects.requireNonNull(subscribedTopicIds); this.memberAssignment = Objects.requireNonNull(memberAssignment); } @Override public Optional<String> rackId() { return rackId; } @Override public Optional<String> instanceId() { return instanceId; } @Override public Set<Uuid> subscribedTopicIds() { return subscribedTopicIds; } @Override public Map<Uuid, Set<Integer>> partitions() { return memberAssignment.partitions(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MemberSubscriptionAndAssignmentImpl that = (MemberSubscriptionAndAssignmentImpl) o; return rackId.equals(that.rackId) && instanceId.equals(that.instanceId) && subscribedTopicIds.equals(that.subscribedTopicIds) && memberAssignment.equals(that.memberAssignment); } @Override public int hashCode() { int result = rackId.hashCode(); result = 31 * result + instanceId.hashCode(); result = 31 * result + subscribedTopicIds.hashCode(); result = 31 * result + memberAssignment.hashCode(); return result; } @Override public String toString() { return "MemberSubscriptionAndAssignmentImpl(rackId=" + rackId.orElse("N/A") + ", instanceId=" + instanceId + ", subscribedTopicIds=" + subscribedTopicIds + ", memberAssignment=" + memberAssignment + ')'; } }
MemberSubscriptionAndAssignmentImpl
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/operator/SequenceBooleanBlockSourceOperator.java
{ "start": 778, "end": 2114 }
class ____ extends AbstractBlockSourceOperator { static final int DEFAULT_MAX_PAGE_POSITIONS = 8 * 1024; private final boolean[] values; public SequenceBooleanBlockSourceOperator(BlockFactory blockFactory, Stream<Boolean> values) { this(blockFactory, values.toList()); } public SequenceBooleanBlockSourceOperator(BlockFactory blockFactory, List<Boolean> values) { this(blockFactory, values, DEFAULT_MAX_PAGE_POSITIONS); } public SequenceBooleanBlockSourceOperator(BlockFactory blockFactory, List<Boolean> values, int maxPagePositions) { super(blockFactory, maxPagePositions); this.values = new boolean[values.size()]; for (int i = 0; i < values.size(); i++) { this.values[i] = values.get(i); } } @Override protected Page createPage(int positionOffset, int length) { try (BooleanVector.FixedBuilder builder = blockFactory.newBooleanVectorFixedBuilder(length)) { for (int i = 0; i < length; i++) { builder.appendBoolean(i, values[positionOffset + i]); } currentPosition += length; return new Page(builder.build().asBlock()); } } protected int remaining() { return values.length - currentPosition; } }
SequenceBooleanBlockSourceOperator
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LdapEndpointBuilderFactory.java
{ "start": 1544, "end": 4805 }
interface ____ extends EndpointProducerBuilder { default AdvancedLdapEndpointBuilder advanced() { return (AdvancedLdapEndpointBuilder) this; } /** * The base DN for searches. * * The option is a: <code>java.lang.String</code> type. * * Default: ou=system * Group: producer * * @param base the value to set * @return the dsl builder */ default LdapEndpointBuilder base(String base) { doSetProperty("base", base); return this; } /** * When specified the ldap module uses paging to retrieve all results * (most LDAP Servers throw an exception when trying to retrieve more * than 1000 entries in one query). To be able to use this a LdapContext * (subclass of DirContext) has to be passed in as ldapServerBean * (otherwise an exception is thrown). * * The option is a: <code>java.lang.Integer</code> type. * * Group: producer * * @param pageSize the value to set * @return the dsl builder */ default LdapEndpointBuilder pageSize(Integer pageSize) { doSetProperty("pageSize", pageSize); return this; } /** * When specified the ldap module uses paging to retrieve all results * (most LDAP Servers throw an exception when trying to retrieve more * than 1000 entries in one query). To be able to use this a LdapContext * (subclass of DirContext) has to be passed in as ldapServerBean * (otherwise an exception is thrown). * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Group: producer * * @param pageSize the value to set * @return the dsl builder */ default LdapEndpointBuilder pageSize(String pageSize) { doSetProperty("pageSize", pageSize); return this; } /** * Comma-separated list of attributes that should be set in each entry * of the result. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param returnedAttributes the value to set * @return the dsl builder */ default LdapEndpointBuilder returnedAttributes(String returnedAttributes) { doSetProperty("returnedAttributes", returnedAttributes); return this; } /** * Specifies how deeply to search the tree of entries, starting at the * base DN. * * The option is a: <code>java.lang.String</code> type. * * Default: subtree * Group: producer * * @param scope the value to set * @return the dsl builder */ default LdapEndpointBuilder scope(String scope) { doSetProperty("scope", scope); return this; } } /** * Advanced builder for endpoint for the LDAP component. */ public
LdapEndpointBuilder
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/collection/EntityMapTest.java
{ "start": 2239, "end": 2498 }
class ____ extends AbstractEntity { @ElementCollection private Map<B, C> map = new HashMap<>(); public Map<B, C> getMap() { return map; } public void setMap(Map<B, C> map) { this.map = map; } } @Entity(name = "B") @Audited public static
A
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SalesforceComponentBuilderFactory.java
{ "start": 68412, "end": 85134 }
class ____ extends AbstractComponentBuilder<SalesforceComponent> implements SalesforceComponentBuilder { @Override protected SalesforceComponent buildConcreteComponent() { return new SalesforceComponent(); } private org.apache.camel.component.salesforce.SalesforceEndpointConfig getOrCreateConfiguration(SalesforceComponent component) { if (component.getConfig() == null) { component.setConfig(new org.apache.camel.component.salesforce.SalesforceEndpointConfig()); } return component.getConfig(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "apexMethod": getOrCreateConfiguration((SalesforceComponent) component).setApexMethod((java.lang.String) value); return true; case "apexQueryParams": getOrCreateConfiguration((SalesforceComponent) component).setApexQueryParams((java.util.Map) value); return true; case "apiVersion": getOrCreateConfiguration((SalesforceComponent) component).setApiVersion((java.lang.String) value); return true; case "backoffIncrement": getOrCreateConfiguration((SalesforceComponent) component).setBackoffIncrement((long) value); return true; case "batchId": getOrCreateConfiguration((SalesforceComponent) component).setBatchId((java.lang.String) value); return true; case "contentType": getOrCreateConfiguration((SalesforceComponent) component).setContentType((org.apache.camel.component.salesforce.api.dto.bulk.ContentType) value); return true; case "defaultReplayId": getOrCreateConfiguration((SalesforceComponent) component).setDefaultReplayId((java.lang.Long) value); return true; case "fallBackReplayId": getOrCreateConfiguration((SalesforceComponent) component).setFallBackReplayId((java.lang.Long) value); return true; case "format": getOrCreateConfiguration((SalesforceComponent) component).setFormat((org.apache.camel.component.salesforce.internal.PayloadFormat) value); return true; case "httpClient": getOrCreateConfiguration((SalesforceComponent) component).setHttpClient((org.apache.camel.component.salesforce.SalesforceHttpClient) value); return true; case "httpClientConnectionTimeout": ((SalesforceComponent) component).setHttpClientConnectionTimeout((long) value); return true; case "httpClientIdleTimeout": ((SalesforceComponent) component).setHttpClientIdleTimeout((long) value); return true; case "httpMaxContentLength": ((SalesforceComponent) component).setHttpMaxContentLength((java.lang.Integer) value); return true; case "httpRequestBufferSize": ((SalesforceComponent) component).setHttpRequestBufferSize((java.lang.Integer) value); return true; case "httpRequestTimeout": ((SalesforceComponent) component).setHttpRequestTimeout((long) value); return true; case "includeDetails": getOrCreateConfiguration((SalesforceComponent) component).setIncludeDetails((java.lang.Boolean) value); return true; case "initialReplayIdMap": getOrCreateConfiguration((SalesforceComponent) component).setInitialReplayIdMap((java.util.Map) value); return true; case "instanceId": getOrCreateConfiguration((SalesforceComponent) component).setInstanceId((java.lang.String) value); return true; case "jobId": getOrCreateConfiguration((SalesforceComponent) component).setJobId((java.lang.String) value); return true; case "limit": getOrCreateConfiguration((SalesforceComponent) component).setLimit((java.lang.Integer) value); return true; case "locator": getOrCreateConfiguration((SalesforceComponent) component).setLocator((java.lang.String) value); return true; case "maxBackoff": getOrCreateConfiguration((SalesforceComponent) component).setMaxBackoff((long) value); return true; case "maxRecords": getOrCreateConfiguration((SalesforceComponent) component).setMaxRecords((java.lang.Integer) value); return true; case "notFoundBehaviour": getOrCreateConfiguration((SalesforceComponent) component).setNotFoundBehaviour((org.apache.camel.component.salesforce.NotFoundBehaviour) value); return true; case "notifyForFields": getOrCreateConfiguration((SalesforceComponent) component).setNotifyForFields((org.apache.camel.component.salesforce.internal.dto.NotifyForFieldsEnum) value); return true; case "notifyForOperationCreate": getOrCreateConfiguration((SalesforceComponent) component).setNotifyForOperationCreate((java.lang.Boolean) value); return true; case "notifyForOperationDelete": getOrCreateConfiguration((SalesforceComponent) component).setNotifyForOperationDelete((java.lang.Boolean) value); return true; case "notifyForOperations": getOrCreateConfiguration((SalesforceComponent) component).setNotifyForOperations((org.apache.camel.component.salesforce.internal.dto.NotifyForOperationsEnum) value); return true; case "notifyForOperationUndelete": getOrCreateConfiguration((SalesforceComponent) component).setNotifyForOperationUndelete((java.lang.Boolean) value); return true; case "notifyForOperationUpdate": getOrCreateConfiguration((SalesforceComponent) component).setNotifyForOperationUpdate((java.lang.Boolean) value); return true; case "objectMapper": getOrCreateConfiguration((SalesforceComponent) component).setObjectMapper((com.fasterxml.jackson.databind.ObjectMapper) value); return true; case "packages": ((SalesforceComponent) component).setPackages((java.lang.String) value); return true; case "pkChunking": getOrCreateConfiguration((SalesforceComponent) component).setPkChunking((java.lang.Boolean) value); return true; case "pkChunkingChunkSize": getOrCreateConfiguration((SalesforceComponent) component).setPkChunkingChunkSize((java.lang.Integer) value); return true; case "pkChunkingParent": getOrCreateConfiguration((SalesforceComponent) component).setPkChunkingParent((java.lang.String) value); return true; case "pkChunkingStartRow": getOrCreateConfiguration((SalesforceComponent) component).setPkChunkingStartRow((java.lang.String) value); return true; case "queryLocator": getOrCreateConfiguration((SalesforceComponent) component).setQueryLocator((java.lang.String) value); return true; case "rawPayload": getOrCreateConfiguration((SalesforceComponent) component).setRawPayload((boolean) value); return true; case "reportId": getOrCreateConfiguration((SalesforceComponent) component).setReportId((java.lang.String) value); return true; case "reportMetadata": getOrCreateConfiguration((SalesforceComponent) component).setReportMetadata((org.apache.camel.component.salesforce.api.dto.analytics.reports.ReportMetadata) value); return true; case "resultId": getOrCreateConfiguration((SalesforceComponent) component).setResultId((java.lang.String) value); return true; case "sObjectBlobFieldName": getOrCreateConfiguration((SalesforceComponent) component).setSObjectBlobFieldName((java.lang.String) value); return true; case "sObjectClass": getOrCreateConfiguration((SalesforceComponent) component).setSObjectClass((java.lang.String) value); return true; case "sObjectFields": getOrCreateConfiguration((SalesforceComponent) component).setSObjectFields((java.lang.String) value); return true; case "sObjectId": getOrCreateConfiguration((SalesforceComponent) component).setSObjectId((java.lang.String) value); return true; case "sObjectIdName": getOrCreateConfiguration((SalesforceComponent) component).setSObjectIdName((java.lang.String) value); return true; case "sObjectIdValue": getOrCreateConfiguration((SalesforceComponent) component).setSObjectIdValue((java.lang.String) value); return true; case "sObjectName": getOrCreateConfiguration((SalesforceComponent) component).setSObjectName((java.lang.String) value); return true; case "sObjectQuery": getOrCreateConfiguration((SalesforceComponent) component).setSObjectQuery((java.lang.String) value); return true; case "sObjectSearch": getOrCreateConfiguration((SalesforceComponent) component).setSObjectSearch((java.lang.String) value); return true; case "streamQueryResult": getOrCreateConfiguration((SalesforceComponent) component).setStreamQueryResult((java.lang.Boolean) value); return true; case "updateTopic": getOrCreateConfiguration((SalesforceComponent) component).setUpdateTopic((boolean) value); return true; case "config": ((SalesforceComponent) component).setConfig((org.apache.camel.component.salesforce.SalesforceEndpointConfig) value); return true; case "httpClientProperties": ((SalesforceComponent) component).setHttpClientProperties((java.util.Map) value); return true; case "longPollingTransportProperties": ((SalesforceComponent) component).setLongPollingTransportProperties((java.util.Map) value); return true; case "workerPoolMaxSize": ((SalesforceComponent) component).setWorkerPoolMaxSize((int) value); return true; case "workerPoolSize": ((SalesforceComponent) component).setWorkerPoolSize((int) value); return true; case "bridgeErrorHandler": ((SalesforceComponent) component).setBridgeErrorHandler((boolean) value); return true; case "fallbackToLatestReplayId": getOrCreateConfiguration((SalesforceComponent) component).setFallbackToLatestReplayId((boolean) value); return true; case "pubSubBatchSize": getOrCreateConfiguration((SalesforceComponent) component).setPubSubBatchSize((int) value); return true; case "pubSubDeserializeType": getOrCreateConfiguration((SalesforceComponent) component).setPubSubDeserializeType((org.apache.camel.component.salesforce.PubSubDeserializeType) value); return true; case "pubSubPojoClass": getOrCreateConfiguration((SalesforceComponent) component).setPubSubPojoClass((java.lang.String) value); return true; case "replayPreset": getOrCreateConfiguration((SalesforceComponent) component).setReplayPreset((com.salesforce.eventbus.protobuf.ReplayPreset) value); return true; case "consumerWorkerPoolEnabled": ((SalesforceComponent) component).setConsumerWorkerPoolEnabled((boolean) value); return true; case "consumerWorkerPoolExecutorService": ((SalesforceComponent) component).setConsumerWorkerPoolExecutorService((java.util.concurrent.ExecutorService) value); return true; case "consumerWorkerPoolMaxSize": ((SalesforceComponent) component).setConsumerWorkerPoolMaxSize((int) value); return true; case "consumerWorkerPoolSize": ((SalesforceComponent) component).setConsumerWorkerPoolSize((int) value); return true; case "initialReplyIdTimeout": ((SalesforceComponent) component).setInitialReplyIdTimeout((int) value); return true; case "allOrNone": getOrCreateConfiguration((SalesforceComponent) component).setAllOrNone((boolean) value); return true; case "apexUrl": getOrCreateConfiguration((SalesforceComponent) component).setApexUrl((java.lang.String) value); return true; case "compositeMethod": getOrCreateConfiguration((SalesforceComponent) component).setCompositeMethod((java.lang.String) value); return true; case "eventName": getOrCreateConfiguration((SalesforceComponent) component).setEventName((java.lang.String) value); return true; case "eventSchemaFormat": getOrCreateConfiguration((SalesforceComponent) component).setEventSchemaFormat((org.apache.camel.component.salesforce.internal.dto.EventSchemaFormatEnum) value); return true; case "eventSchemaId": getOrCreateConfiguration((SalesforceComponent) component).setEventSchemaId((java.lang.String) value); return true; case "lazyStartProducer": ((SalesforceComponent) component).setLazyStartProducer((boolean) value); return true; case "rawHttpHeaders": getOrCreateConfiguration((SalesforceComponent) component).setRawHttpHeaders((java.lang.String) value); return true; case "rawMethod": getOrCreateConfiguration((SalesforceComponent) component).setRawMethod((java.lang.String) value); return true; case "rawPath": getOrCreateConfiguration((SalesforceComponent) component).setRawPath((java.lang.String) value); return true; case "rawQueryParameters": getOrCreateConfiguration((SalesforceComponent) component).setRawQueryParameters((java.lang.String) value); return true; case "autowiredEnabled": ((SalesforceComponent) component).setAutowiredEnabled((boolean) value); return true; case "httpProxyExcludedAddresses": ((SalesforceComponent) component).setHttpProxyExcludedAddresses((java.util.Set) value); return true; case "httpProxyHost": ((SalesforceComponent) component).setHttpProxyHost((java.lang.String) value); return true; case "httpProxyIncludedAddresses": ((SalesforceComponent) component).setHttpProxyIncludedAddresses((java.util.Set) value); return true; case "httpProxyPort": ((SalesforceComponent) component).setHttpProxyPort((java.lang.Integer) value); return true; case "httpProxySocks4": ((SalesforceComponent) component).setHttpProxySocks4((boolean) value); return true; case "pubsubAllowUseSystemProxy": ((SalesforceComponent) component).setPubsubAllowUseSystemProxy((boolean) value); return true; case "authenticationType": ((SalesforceComponent) component).setAuthenticationType((org.apache.camel.component.salesforce.AuthenticationType) value); return true; case "clientId": ((SalesforceComponent) component).setClientId((java.lang.String) value); return true; case "clientSecret": ((SalesforceComponent) component).setClientSecret((java.lang.String) value); return true; case "httpProxyAuthUri": ((SalesforceComponent) component).setHttpProxyAuthUri((java.lang.String) value); return true; case "httpProxyPassword": ((SalesforceComponent) component).setHttpProxyPassword((java.lang.String) value); return true; case "httpProxyRealm": ((SalesforceComponent) component).setHttpProxyRealm((java.lang.String) value); return true; case "httpProxySecure": ((SalesforceComponent) component).setHttpProxySecure((boolean) value); return true; case "httpProxyUseDigestAuth": ((SalesforceComponent) component).setHttpProxyUseDigestAuth((boolean) value); return true; case "httpProxyUsername": ((SalesforceComponent) component).setHttpProxyUsername((java.lang.String) value); return true; case "instanceUrl": ((SalesforceComponent) component).setInstanceUrl((java.lang.String) value); return true; case "jwtAudience": ((SalesforceComponent) component).setJwtAudience((java.lang.String) value); return true; case "keystore": ((SalesforceComponent) component).setKeystore((org.apache.camel.support.jsse.KeyStoreParameters) value); return true; case "lazyLogin": ((SalesforceComponent) component).setLazyLogin((boolean) value); return true; case "loginConfig": ((SalesforceComponent) component).setLoginConfig((org.apache.camel.component.salesforce.SalesforceLoginConfig) value); return true; case "loginUrl": ((SalesforceComponent) component).setLoginUrl((java.lang.String) value); return true; case "password": ((SalesforceComponent) component).setPassword((java.lang.String) value); return true; case "pubSubHost": ((SalesforceComponent) component).setPubSubHost((java.lang.String) value); return true; case "pubSubPort": ((SalesforceComponent) component).setPubSubPort((int) value); return true; case "refreshToken": ((SalesforceComponent) component).setRefreshToken((java.lang.String) value); return true; case "sslContextParameters": ((SalesforceComponent) component).setSslContextParameters((org.apache.camel.support.jsse.SSLContextParameters) value); return true; case "useGlobalSslContextParameters": ((SalesforceComponent) component).setUseGlobalSslContextParameters((boolean) value); return true; case "userName": ((SalesforceComponent) component).setUserName((java.lang.String) value); return true; default: return false; } } } }
SalesforceComponentBuilderImpl
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ext/javatime/ser/OffsetDateTimeSerializer.java
{ "start": 186, "end": 2485 }
class ____ extends InstantSerializerBase<OffsetDateTime> { public static final OffsetDateTimeSerializer INSTANCE = new OffsetDateTimeSerializer(); protected OffsetDateTimeSerializer() { super(OffsetDateTime.class, dt -> dt.toInstant().toEpochMilli(), OffsetDateTime::toEpochSecond, OffsetDateTime::getNano, DateTimeFormatter.ISO_OFFSET_DATE_TIME); } protected OffsetDateTimeSerializer(OffsetDateTimeSerializer base, Boolean useTimestamp, DateTimeFormatter formatter, JsonFormat.Shape shape) { this(base, formatter, useTimestamp, base._useNanoseconds, shape); } protected OffsetDateTimeSerializer(OffsetDateTimeSerializer base, DateTimeFormatter formatter, Boolean useTimestamp, Boolean useNanoseconds, JsonFormat.Shape shape) { super(base, formatter, useTimestamp, useNanoseconds, shape); } /** * Method for constructing a new {@code OffsetDateTimeSerializer} with settings * of this serializer but with custom {@link DateTimeFormatter} overrides. * Commonly used on {@code INSTANCE} like so: *<pre> * DateTimeFormatter dtf = new DateTimeFormatterBuilder() * .append(DateTimeFormatter.ISO_LOCAL_DATE) * .appendLiteral('T') * // and so on * .toFormatter(); * OffsetDateTimeSerializer ser = OffsetDateTimeSerializer.INSTANCE * .withFormatter(dtf); * // register via Module *</pre> * * @since 2.21 / 3.1 */ public OffsetDateTimeSerializer withFormatter(DateTimeFormatter formatter) { return new OffsetDateTimeSerializer(this, _useTimestamp, formatter, _shape); } @Override protected JSR310FormattedSerializerBase<?> withFormat(DateTimeFormatter formatter, Boolean useTimestamp, JsonFormat.Shape shape) { return new OffsetDateTimeSerializer(this, useTimestamp, formatter, shape); } @Override protected JSR310FormattedSerializerBase<?> withFeatures(Boolean writeZoneId, Boolean writeNanoseconds) { return new OffsetDateTimeSerializer(this, _formatter, _useTimestamp, writeNanoseconds, _shape); } }
OffsetDateTimeSerializer
java
apache__camel
components/camel-atmosphere-websocket/src/main/java/org/apache/camel/component/atmosphere/websocket/MemoryWebSocketStore.java
{ "start": 1079, "end": 3706 }
class ____ implements WebSocketStore { private static final transient Logger LOG = LoggerFactory.getLogger(MemoryWebSocketStore.class); private Map<String, WebSocket> values; private Map<WebSocket, String> keys; public MemoryWebSocketStore() { values = new ConcurrentHashMap<>(); keys = new ConcurrentHashMap<>(); } /* (non-Javadoc) * @see org.apache.camel.Service#start() */ @Override public void start() { } /* (non-Javadoc) * @see org.apache.camel.Service#stop() */ @Override public void stop() { values.clear(); keys.clear(); } /* (non-Javadoc) * @see org.apache.camel.component.websocket2.WebsocketStore#addWebSocket(java.lang.String, org.atmosphere.websocket.WebSocket) */ @Override public void addWebSocket(String connectionKey, WebSocket websocket) { values.put(connectionKey, websocket); keys.put(websocket, connectionKey); if (LOG.isDebugEnabled()) { LOG.debug("added websocket {} => {}", connectionKey, websocket); } } /* (non-Javadoc) * @see org.apache.camel.component.websocket2.WebsocketStore#removeWebSocket(java.lang.String) */ @Override public void removeWebSocket(String connectionKey) { Object obj = values.remove(connectionKey); if (obj != null) { keys.remove(obj); } LOG.debug("removed websocket {}", connectionKey); } /* (non-Javadoc) * @see org.apache.camel.component.websocket2.WebsocketStore#removeWebSocket(org.atmosphere.websocket.WebSocket) */ @Override public void removeWebSocket(WebSocket websocket) { Object obj = keys.remove(websocket); if (obj != null) { values.remove(obj); } LOG.debug("removed websocket {}", websocket); } /* (non-Javadoc) * @see org.apache.camel.component.websocket2.WebsocketStore#getConnectionKey(org.atmosphere.websocket.WebSocket) */ @Override public String getConnectionKey(WebSocket websocket) { return keys.get(websocket); } /* (non-Javadoc) * @see org.apache.camel.component.websocket2.WebsocketStore#getWebSocket(java.lang.String) */ @Override public WebSocket getWebSocket(String connectionKey) { return values.get(connectionKey); } /* (non-Javadoc) * @see org.apache.camel.component.websocket2.WebsocketStore#getAllWebSockets() */ @Override public Collection<WebSocket> getAllWebSockets() { return values.values(); } }
MemoryWebSocketStore
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/schedulers/Schedulers.java
{ "start": 14823, "end": 17245 }
class ____ been initialized, you can override the returned {@code Scheduler} instance * via the {@link RxJavaPlugins#setNewThreadSchedulerHandler(io.reactivex.rxjava3.functions.Function)} method. * <p> * It is possible to create a fresh instance of this scheduler with a custom {@link ThreadFactory}, via the * {@link RxJavaPlugins#createNewThreadScheduler(ThreadFactory)} method. Note that such custom * instances require a manual call to {@link Scheduler#shutdown()} to allow the JVM to exit or the * (J2EE) container to unload properly. * <p>Operators on the base reactive classes that use this scheduler are marked with the * &#64;{@link io.reactivex.rxjava3.annotations.SchedulerSupport SchedulerSupport}({@link io.reactivex.rxjava3.annotations.SchedulerSupport#NEW_THREAD NEW_TRHEAD}) * annotation. * @return a {@code Scheduler} that creates new threads */ @NonNull public static Scheduler newThread() { return RxJavaPlugins.onNewThreadScheduler(NEW_THREAD); } /** * Returns a default, shared, single-thread-backed {@link Scheduler} instance for work * requiring strongly-sequential execution on the same background thread. * <p> * Uses: * <ul> * <li>event loop</li> * <li>support {@code Schedulers.from(}{@link Executor}{@code )} and {@code from(}{@link ExecutorService}{@code )} with delayed scheduling</li> * <li>support benchmarks that pipeline data from some thread to another thread and * avoid core-bashing of computation's round-robin nature</li> * </ul> * <p> * Unhandled errors will be delivered to the scheduler Thread's {@link java.lang.Thread.UncaughtExceptionHandler}. * <p> * This type of scheduler is less sensitive to leaking {@link io.reactivex.rxjava3.core.Scheduler.Worker} instances, although * not disposing a worker that has timed/delayed tasks not cancelled by other means may leak resources and/or * execute those tasks "unexpectedly". * <p> * If the {@link RxJavaPlugins#setFailOnNonBlockingScheduler(boolean)} is set to {@code true}, attempting to execute * operators that block while running on this scheduler will throw an {@link IllegalStateException}. * <p> * You can control certain properties of this standard scheduler via system properties that have to be set * before the {@code Schedulers}
has
java
netty__netty
codec-base/src/main/java/io/netty/handler/codec/EmptyHeaders.java
{ "start": 871, "end": 11946 }
class ____<K, V, T extends Headers<K, V, T>> implements Headers<K, V, T> { @Override public V get(K name) { return null; } @Override public V get(K name, V defaultValue) { return defaultValue; } @Override public V getAndRemove(K name) { return null; } @Override public V getAndRemove(K name, V defaultValue) { return defaultValue; } @Override public List<V> getAll(K name) { return Collections.emptyList(); } @Override public List<V> getAllAndRemove(K name) { return Collections.emptyList(); } @Override public Boolean getBoolean(K name) { return null; } @Override public boolean getBoolean(K name, boolean defaultValue) { return defaultValue; } @Override public Byte getByte(K name) { return null; } @Override public byte getByte(K name, byte defaultValue) { return defaultValue; } @Override public Character getChar(K name) { return null; } @Override public char getChar(K name, char defaultValue) { return defaultValue; } @Override public Short getShort(K name) { return null; } @Override public short getShort(K name, short defaultValue) { return defaultValue; } @Override public Integer getInt(K name) { return null; } @Override public int getInt(K name, int defaultValue) { return defaultValue; } @Override public Long getLong(K name) { return null; } @Override public long getLong(K name, long defaultValue) { return defaultValue; } @Override public Float getFloat(K name) { return null; } @Override public float getFloat(K name, float defaultValue) { return defaultValue; } @Override public Double getDouble(K name) { return null; } @Override public double getDouble(K name, double defaultValue) { return defaultValue; } @Override public Long getTimeMillis(K name) { return null; } @Override public long getTimeMillis(K name, long defaultValue) { return defaultValue; } @Override public Boolean getBooleanAndRemove(K name) { return null; } @Override public boolean getBooleanAndRemove(K name, boolean defaultValue) { return defaultValue; } @Override public Byte getByteAndRemove(K name) { return null; } @Override public byte getByteAndRemove(K name, byte defaultValue) { return defaultValue; } @Override public Character getCharAndRemove(K name) { return null; } @Override public char getCharAndRemove(K name, char defaultValue) { return defaultValue; } @Override public Short getShortAndRemove(K name) { return null; } @Override public short getShortAndRemove(K name, short defaultValue) { return defaultValue; } @Override public Integer getIntAndRemove(K name) { return null; } @Override public int getIntAndRemove(K name, int defaultValue) { return defaultValue; } @Override public Long getLongAndRemove(K name) { return null; } @Override public long getLongAndRemove(K name, long defaultValue) { return defaultValue; } @Override public Float getFloatAndRemove(K name) { return null; } @Override public float getFloatAndRemove(K name, float defaultValue) { return defaultValue; } @Override public Double getDoubleAndRemove(K name) { return null; } @Override public double getDoubleAndRemove(K name, double defaultValue) { return defaultValue; } @Override public Long getTimeMillisAndRemove(K name) { return null; } @Override public long getTimeMillisAndRemove(K name, long defaultValue) { return defaultValue; } @Override public boolean contains(K name) { return false; } @Override public boolean contains(K name, V value) { return false; } @Override public boolean containsObject(K name, Object value) { return false; } @Override public boolean containsBoolean(K name, boolean value) { return false; } @Override public boolean containsByte(K name, byte value) { return false; } @Override public boolean containsChar(K name, char value) { return false; } @Override public boolean containsShort(K name, short value) { return false; } @Override public boolean containsInt(K name, int value) { return false; } @Override public boolean containsLong(K name, long value) { return false; } @Override public boolean containsFloat(K name, float value) { return false; } @Override public boolean containsDouble(K name, double value) { return false; } @Override public boolean containsTimeMillis(K name, long value) { return false; } @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public Set<K> names() { return Collections.emptySet(); } @Override public T add(K name, V value) { throw new UnsupportedOperationException("read only"); } @Override public T add(K name, Iterable<? extends V> values) { throw new UnsupportedOperationException("read only"); } @Override public T add(K name, V... values) { throw new UnsupportedOperationException("read only"); } @Override public T addObject(K name, Object value) { throw new UnsupportedOperationException("read only"); } @Override public T addObject(K name, Iterable<?> values) { throw new UnsupportedOperationException("read only"); } @Override public T addObject(K name, Object... values) { throw new UnsupportedOperationException("read only"); } @Override public T addBoolean(K name, boolean value) { throw new UnsupportedOperationException("read only"); } @Override public T addByte(K name, byte value) { throw new UnsupportedOperationException("read only"); } @Override public T addChar(K name, char value) { throw new UnsupportedOperationException("read only"); } @Override public T addShort(K name, short value) { throw new UnsupportedOperationException("read only"); } @Override public T addInt(K name, int value) { throw new UnsupportedOperationException("read only"); } @Override public T addLong(K name, long value) { throw new UnsupportedOperationException("read only"); } @Override public T addFloat(K name, float value) { throw new UnsupportedOperationException("read only"); } @Override public T addDouble(K name, double value) { throw new UnsupportedOperationException("read only"); } @Override public T addTimeMillis(K name, long value) { throw new UnsupportedOperationException("read only"); } @Override public T add(Headers<? extends K, ? extends V, ?> headers) { throw new UnsupportedOperationException("read only"); } @Override public T set(K name, V value) { throw new UnsupportedOperationException("read only"); } @Override public T set(K name, Iterable<? extends V> values) { throw new UnsupportedOperationException("read only"); } @Override public T set(K name, V... values) { throw new UnsupportedOperationException("read only"); } @Override public T setObject(K name, Object value) { throw new UnsupportedOperationException("read only"); } @Override public T setObject(K name, Iterable<?> values) { throw new UnsupportedOperationException("read only"); } @Override public T setObject(K name, Object... values) { throw new UnsupportedOperationException("read only"); } @Override public T setBoolean(K name, boolean value) { throw new UnsupportedOperationException("read only"); } @Override public T setByte(K name, byte value) { throw new UnsupportedOperationException("read only"); } @Override public T setChar(K name, char value) { throw new UnsupportedOperationException("read only"); } @Override public T setShort(K name, short value) { throw new UnsupportedOperationException("read only"); } @Override public T setInt(K name, int value) { throw new UnsupportedOperationException("read only"); } @Override public T setLong(K name, long value) { throw new UnsupportedOperationException("read only"); } @Override public T setFloat(K name, float value) { throw new UnsupportedOperationException("read only"); } @Override public T setDouble(K name, double value) { throw new UnsupportedOperationException("read only"); } @Override public T setTimeMillis(K name, long value) { throw new UnsupportedOperationException("read only"); } @Override public T set(Headers<? extends K, ? extends V, ?> headers) { throw new UnsupportedOperationException("read only"); } @Override public T setAll(Headers<? extends K, ? extends V, ?> headers) { throw new UnsupportedOperationException("read only"); } @Override public boolean remove(K name) { return false; } @Override public T clear() { return thisT(); } /** * Equivalent to {@link #getAll(Object)} but no intermediate list is generated. * @param name the name of the header to retrieve * @return an {@link Iterator} of header values corresponding to {@code name}. */ public Iterator<V> valueIterator(@SuppressWarnings("unused") K name) { List<V> empty = Collections.emptyList(); return empty.iterator(); } @Override public Iterator<Entry<K, V>> iterator() { List<Entry<K, V>> empty = Collections.emptyList(); return empty.iterator(); } @Override public boolean equals(Object o) { if (!(o instanceof Headers)) { return false; } Headers<?, ?, ?> rhs = (Headers<?, ?, ?>) o; return isEmpty() && rhs.isEmpty(); } @Override public int hashCode() { return HASH_CODE_SEED; } @Override public String toString() { return new StringBuilder(getClass().getSimpleName()).append('[').append(']').toString(); } @SuppressWarnings("unchecked") private T thisT() { return (T) this; } }
EmptyHeaders
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/ApplicationArchiveImpl.java
{ "start": 610, "end": 3814 }
class ____ extends MultiBuildItem implements ApplicationArchive { private final IndexView indexView; private final OpenPathTree openTree; private final ResolvedDependency resolvedDependency; public ApplicationArchiveImpl(IndexView indexView, OpenPathTree openTree, ResolvedDependency resolvedDependency) { this.indexView = indexView; this.openTree = openTree; this.resolvedDependency = resolvedDependency; } @Override public IndexView getIndex() { return indexView; } @Override @Deprecated public Path getArchiveLocation() { return openTree.getOriginalTree().getRoots().iterator().next(); } @Override @Deprecated public PathsCollection getRootDirs() { return PathsCollection.from(openTree.getRoots()); } @Override public PathCollection getRootDirectories() { return PathList.from(openTree.getRoots()); } @Override @Deprecated public PathsCollection getPaths() { return PathsCollection.from(openTree.getOriginalTree().getRoots()); } @Override public PathCollection getResolvedPaths() { return PathList.from(openTree.getOriginalTree().getRoots()); } @Override @Deprecated /** * @deprecated in favor of {@link #getKey()} * @return archive key */ public AppArtifactKey getArtifactKey() { if (resolvedDependency == null) { return null; } ArtifactKey artifactKey = resolvedDependency.getKey(); return new AppArtifactKey(artifactKey.getGroupId(), artifactKey.getArtifactId(), artifactKey.getClassifier(), artifactKey.getType()); } @Override public ArtifactKey getKey() { return resolvedDependency != null ? resolvedDependency.getKey() : null; } @Override public ResolvedDependency getResolvedDependency() { return resolvedDependency; } @Override public <T> T apply(Function<OpenPathTree, T> func) { if (openTree.isOpen()) { try { return func.apply(openTree); } catch (Exception e) { if (openTree.isOpen()) { throw e; } } } try (OpenPathTree openTree = this.openTree.getOriginalTree().open()) { return func.apply(openTree); } catch (IOException e) { throw new UncheckedIOException("Failed to open path tree with root " + openTree.getOriginalTree().getRoots(), e); } } @Override public void accept(Consumer<OpenPathTree> func) { if (openTree.isOpen()) { try { func.accept(openTree); return; } catch (Exception e) { if (openTree.isOpen()) { throw e; } } } try (OpenPathTree openTree = this.openTree.getOriginalTree().open()) { func.accept(openTree); } catch (IOException e) { throw new UncheckedIOException("Failed to open path tree with root " + openTree.getOriginalTree().getRoots(), e); } } }
ApplicationArchiveImpl
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/PutDatafeedAction.java
{ "start": 2995, "end": 4162 }
class ____ extends ActionResponse implements ToXContentObject { private final DatafeedConfig datafeed; public Response(DatafeedConfig datafeed) { this.datafeed = datafeed; } public Response(StreamInput in) throws IOException { datafeed = new DatafeedConfig(in); } public DatafeedConfig getResponse() { return datafeed; } @Override public void writeTo(StreamOutput out) throws IOException { datafeed.writeTo(out); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { datafeed.toXContent(builder, params); return builder; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Response response = (Response) o; return Objects.equals(datafeed, response.datafeed); } @Override public int hashCode() { return Objects.hash(datafeed); } } }
Response
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/config/mapFormat/VehicleSpec.java
{ "start": 848, "end": 1614 }
class ____ { @Test void testStartVehicle() { // tag::start[] Map<String, Object> map = new LinkedHashMap<>(2); map.put("my.engine.cylinders", "8"); Map<Integer, String> map1 = new LinkedHashMap<>(2); map1.put(0, "thermostat"); map1.put(1, "fuel pressure"); map.put("my.engine.sensors", map1); map.put( "spec.name", "VehicleMapFormatSpec"); ApplicationContext applicationContext = ApplicationContext.run(map, "test"); Vehicle vehicle = applicationContext.getBean(Vehicle.class); System.out.println(vehicle.start()); // end::start[] assertEquals("Engine Starting V8 [sensors=2]", vehicle.start()); applicationContext.close(); } }
VehicleSpec
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/ReservedSpaceCalculator.java
{ "start": 6422, "end": 7425 }
class ____ extends ReservedSpaceCalculator { private final long reservedBytes; private final long reservedPct; public ReservedSpaceCalculatorAggressive(Configuration conf, DF usage, StorageType storageType, String dir) { super(conf, usage, storageType, dir); this.reservedBytes = getReservedFromConf(DFS_DATANODE_DU_RESERVED_KEY, DFS_DATANODE_DU_RESERVED_DEFAULT); this.reservedPct = getReservedFromConf( DFS_DATANODE_DU_RESERVED_PERCENTAGE_KEY, DFS_DATANODE_DU_RESERVED_PERCENTAGE_DEFAULT); } long getReservedBytes() { return reservedBytes; } long getReservedPct() { return reservedPct; } @Override long getReserved() { return Math.min(getReservedBytes(), getPercentage(getUsage().getCapacity(), getReservedPct())); } } private static long getPercentage(long total, long percentage) { return (total * percentage) / 100; } }
ReservedSpaceCalculatorAggressive
java
apache__kafka
tools/src/main/java/org/apache/kafka/tools/VerifiableShareConsumer.java
{ "start": 3341, "end": 4091 }
class ____ implements Closeable, AcknowledgementCommitCallback { private static final Logger log = LoggerFactory.getLogger(VerifiableShareConsumer.class); private final ObjectMapper mapper = new ObjectMapper(); private final PrintStream out; private final KafkaShareConsumer<String, String> consumer; private final Admin adminClient; private final String topic; private final AcknowledgementMode acknowledgementMode; private final String offsetResetStrategy; private final Boolean verbose; private final int maxMessages; private Integer totalAcknowledged = 0; private final String groupId; private final CountDownLatch shutdownLatch = new CountDownLatch(1); public static
VerifiableShareConsumer
java
google__guava
android/guava/src/com/google/common/reflect/ClassPath.java
{ "start": 14214, "end": 14461 }
class ____ on. * For example, {@link NoClassDefFoundError}. */ public Class<?> load() { try { return loader.loadClass(className); } catch (ClassNotFoundException e) { // Shouldn't happen, since the
depends
java
apache__camel
components/camel-aws/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/KclKinesis2Consumer.java
{ "start": 3508, "end": 9396 }
class ____ implements ShardRecordProcessorFactory { public ShardRecordProcessor shardRecordProcessor() { return new CamelKinesisRecordProcessor(getEndpoint()); } } @Override protected void doStart() throws Exception { super.doStart(); LOG.debug("Starting KCL Consumer"); DynamoDbAsyncClient dynamoDbAsyncClient = null; CloudWatchAsyncClient cloudWatchAsyncClient = null; KinesisAsyncClient kinesisAsyncClient = getEndpoint().getAsyncClient() != null ? getEndpoint().getAsyncClient() : getEndpoint().getConfiguration().getAmazonKinesisAsyncClient(); Kinesis2Configuration configuration = getEndpoint().getConfiguration(); if (ObjectHelper.isEmpty(getEndpoint().getConfiguration().getDynamoDbAsyncClient())) { DynamoDbAsyncClientBuilder clientBuilder = DynamoDbAsyncClient.builder(); if (ObjectHelper.isNotEmpty(configuration.getAccessKey()) && ObjectHelper.isNotEmpty(configuration.getSecretKey())) { clientBuilder = clientBuilder.credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create(configuration.getAccessKey(), configuration.getSecretKey()))); } else if (ObjectHelper.isNotEmpty(configuration.getProfileCredentialsName())) { clientBuilder = clientBuilder .credentialsProvider( ProfileCredentialsProvider.create(configuration.getProfileCredentialsName())); } else if (ObjectHelper.isNotEmpty(configuration.getAccessKey()) && ObjectHelper.isNotEmpty(configuration.getSecretKey()) && ObjectHelper.isNotEmpty(configuration.getSessionToken())) { clientBuilder = clientBuilder.credentialsProvider(StaticCredentialsProvider .create(AwsSessionCredentials.create(configuration.getAccessKey(), configuration.getSecretKey(), configuration.getSessionToken()))); } if (ObjectHelper.isNotEmpty(configuration.getRegion())) { clientBuilder = clientBuilder.region(Region.of(configuration.getRegion())); } dynamoDbAsyncClient = clientBuilder.build(); } else { dynamoDbAsyncClient = getEndpoint().getConfiguration().getDynamoDbAsyncClient(); } if (ObjectHelper.isEmpty(getEndpoint().getConfiguration().getCloudWatchAsyncClient())) { CloudWatchAsyncClientBuilder clientBuilder = CloudWatchAsyncClient.builder(); if (ObjectHelper.isNotEmpty(configuration.getAccessKey()) && ObjectHelper.isNotEmpty(configuration.getSecretKey())) { clientBuilder = clientBuilder.credentialsProvider(StaticCredentialsProvider.create( AwsBasicCredentials.create(configuration.getAccessKey(), configuration.getSecretKey()))); } else if (ObjectHelper.isNotEmpty(configuration.getProfileCredentialsName())) { clientBuilder = clientBuilder .credentialsProvider( ProfileCredentialsProvider.create(configuration.getProfileCredentialsName())); } else if (ObjectHelper.isNotEmpty(configuration.getAccessKey()) && ObjectHelper.isNotEmpty(configuration.getSecretKey()) && ObjectHelper.isNotEmpty(configuration.getSessionToken())) { clientBuilder = clientBuilder.credentialsProvider(StaticCredentialsProvider .create(AwsSessionCredentials.create(configuration.getAccessKey(), configuration.getSecretKey(), configuration.getSessionToken()))); } if (ObjectHelper.isNotEmpty(configuration.getRegion())) { clientBuilder = clientBuilder.region(Region.of(configuration.getRegion())); } cloudWatchAsyncClient = clientBuilder.build(); } else { cloudWatchAsyncClient = getEndpoint().getConfiguration().getCloudWatchAsyncClient(); } this.executor = this.getEndpoint().createExecutor(this); this.executor.submit(new KclKinesisConsumingTask( configuration.getStreamName(), configuration.getApplicationName(), kinesisAsyncClient, dynamoDbAsyncClient, cloudWatchAsyncClient, configuration.isKclDisableCloudwatchMetricsExport())); } @Override protected void doStop() throws Exception { LOG.debug("Stopping KCL Consumer"); if (this.executor != null) { if (this.getEndpoint() != null && this.getEndpoint().getCamelContext() != null) { this.getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(this.executor); } else { this.executor.shutdownNow(); } } if (this.schedulerKcl != null) { Future<Boolean> gracefulShutdownFuture = schedulerKcl.startGracefulShutdown(); LOG.info("Waiting up to 20 seconds for scheduler shutdown to complete."); try { gracefulShutdownFuture.get(20, TimeUnit.SECONDS); } catch (InterruptedException e) { LOG.debug("Interrupted while waiting for graceful shutdown. Continuing."); } catch (ExecutionException e) { LOG.debug("Exception while executing graceful shutdown.", e); } catch (TimeoutException e) { LOG.debug("Timeout while waiting for shutdown. Scheduler may not have exited."); } LOG.debug("Completed, shutting down now."); } this.executor = null; super.doStop(); }
CamelKinesisRecordProcessorFactory
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/stream/compact/CompactMessages.java
{ "start": 3172, "end": 3287 }
interface ____ extends Serializable {} /** The unit of a single compaction. */ public static
CoordinatorOutput
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/transport/WriteQueue.java
{ "start": 1179, "end": 2866 }
class ____ { static final int DEQUE_CHUNK_SIZE = 128; private final Queue<QueuedCommand> queue; private final AtomicBoolean scheduled; public WriteQueue() { queue = new ConcurrentLinkedQueue<>(); scheduled = new AtomicBoolean(false); } public ChannelFuture enqueue(QueuedCommand command, boolean rst) { return enqueue(command); } public ChannelFuture enqueue(QueuedCommand command) { ChannelPromise promise = command.promise(); if (promise == null) { Channel ch = command.channel(); promise = ch.newPromise(); command.promise(promise); } queue.add(command); scheduleFlush(command.channel()); return promise; } public void scheduleFlush(Channel ch) { if (scheduled.compareAndSet(false, true)) { ch.parent().eventLoop().execute(this::flush); } } private void flush() { Channel ch = null; try { QueuedCommand cmd; int i = 0; boolean flushedOnce = false; while ((cmd = queue.poll()) != null) { ch = cmd.channel(); cmd.run(ch); i++; if (i == DEQUE_CHUNK_SIZE) { i = 0; ch.parent().flush(); flushedOnce = true; } } if (ch != null && (i != 0 || !flushedOnce)) { ch.parent().flush(); } } finally { scheduled.set(false); if (!queue.isEmpty()) { scheduleFlush(ch); } } } }
WriteQueue
java
quarkusio__quarkus
extensions/flyway/deployment/src/test/java/io/quarkus/flyway/test/FlywayExtensionCDICallback.java
{ "start": 306, "end": 1329 }
class ____ implements Callback { public static List<Event> DEFAULT_EVENTS = Arrays.asList( Event.BEFORE_BASELINE, Event.AFTER_BASELINE, Event.BEFORE_MIGRATE, Event.BEFORE_EACH_MIGRATE, Event.AFTER_EACH_MIGRATE, Event.AFTER_VERSIONED, Event.AFTER_MIGRATE, Event.AFTER_MIGRATE_OPERATION_FINISH); @Override public boolean supports(Event event, Context context) { return DEFAULT_EVENTS.contains(event); } @Override public boolean canHandleInTransaction(Event event, Context context) { return true; } @Override public void handle(Event event, Context context) { try { CDI.current().select(Flyway.class).get(); } catch (Exception exception) { throw new IllegalStateException(exception); } } @Override public String getCallbackName() { return "Quarked Flyway Callback with CDI"; } }
FlywayExtensionCDICallback
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ext/javatime/deser/key/LocalDateTimeKeyDeserializer.java
{ "start": 274, "end": 886 }
class ____ extends Jsr310KeyDeserializer { public static final LocalDateTimeKeyDeserializer INSTANCE = new LocalDateTimeKeyDeserializer(); private LocalDateTimeKeyDeserializer() { // singleton } @Override protected LocalDateTime deserialize(String key, DeserializationContext ctxt) throws JacksonException { try { return LocalDateTime.parse(key, DateTimeFormatter.ISO_LOCAL_DATE_TIME); } catch (DateTimeException e) { return _handleDateTimeException(ctxt, LocalDateTime.class, e, key); } } }
LocalDateTimeKeyDeserializer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/boot/models/xml/complete/SimpleCompleteXmlTests.java
{ "start": 1291, "end": 4015 }
class ____ { @Test @ServiceRegistry void testSimpleCompleteEntity(ServiceRegistryScope registryScope) { final AdditionalManagedResourcesImpl.Builder managedResourcesBuilder = new AdditionalManagedResourcesImpl.Builder(); managedResourcesBuilder.addXmlMappings( "mappings/models/complete/simple-complete.xml" ); final ManagedResources managedResources = managedResourcesBuilder.build(); final ModelsContext ModelsContext = createBuildingContext( managedResources, registryScope.getRegistry() ); final ClassDetailsRegistry classDetailsRegistry = ModelsContext.getClassDetailsRegistry(); final ClassDetails classDetails = classDetailsRegistry.getClassDetails( SimpleEntity.class.getName() ); final FieldDetails idField = classDetails.findFieldByName( "id" ); assertThat( idField.getDirectAnnotationUsage( Basic.class ) ).isNotNull(); assertThat( idField.getDirectAnnotationUsage( Id.class ) ).isNotNull(); final Column idColumnAnn = idField.getDirectAnnotationUsage( Column.class ); assertThat( idColumnAnn ).isNotNull(); assertThat( idColumnAnn.name() ).isEqualTo( "pk" ); final FieldDetails nameField = classDetails.findFieldByName( "name" ); assertThat( nameField.getDirectAnnotationUsage( Basic.class ) ).isNotNull(); final Column nameColumnAnn = nameField.getDirectAnnotationUsage( Column.class ); assertThat( nameColumnAnn ).isNotNull(); assertThat( nameColumnAnn.name() ).isEqualTo( "description" ); final SQLRestriction sqlRestriction = classDetails.getDirectAnnotationUsage( SQLRestriction.class ); assertThat( sqlRestriction ).isNotNull(); assertThat( sqlRestriction.value() ).isEqualTo( "name is not null" ); validateSqlInsert( classDetails.getDirectAnnotationUsage( SQLInsert.class )); validateFilterUsage( classDetails.getAnnotationUsage( Filter.class, ModelsContext ) ); } private void validateFilterUsage(Filter filter) { assertThat( filter ).isNotNull(); assertThat( filter.name() ).isEqualTo( "name_filter" ); assertThat( filter.condition() ).isEqualTo( "{t}.name = :name" ); final SqlFragmentAlias[] aliases = filter.aliases(); assertThat( aliases ).hasSize( 1 ); assertThat( aliases[0].alias() ).isEqualTo( "t" ); assertThat( aliases[0].table() ).isEqualTo( "SimpleEntity" ); assertThat( aliases[0].entity().getName() ).isEqualTo( SimpleEntity.class.getName() ); } private void validateSqlInsert(SQLInsert sqlInsert) { assertThat( sqlInsert ).isNotNull(); assertThat( sqlInsert.sql() ).isEqualTo( "insertSimpleEntity(?)" ); assertThat( sqlInsert.callable() ).isTrue(); assertThat( sqlInsert.check() ).isEqualTo( ResultCheckStyle.COUNT ); assertThat( sqlInsert.table() ).isEqualTo( "SimpleEntity" ); } }
SimpleCompleteXmlTests
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSInputStreamBlockLocations.java
{ "start": 9422, "end": 11027 }
interface ____ { void accept(DFSInputStream fin) throws IOException; } private void testWithRegistrationMethod(ThrowingConsumer registrationMethod) throws IOException { final String fileName = "/test_cache_locations"; filePath = createFile(fileName); DFSInputStream fin = null; try { fin = dfsClient.open(fileName); assertFalse(dfsClient.getLocatedBlockRefresher().isInputStreamTracked(fin), "should not be tracking input stream on open"); // still not registered because it hasn't been an hour by the time we call this registrationMethod.accept(fin); assertFalse(dfsClient.getLocatedBlockRefresher().isInputStreamTracked(fin), "should not be tracking input stream after first read"); // artificially make it have been an hour fin.setLastRefreshedBlocksAtForTesting(Time.monotonicNow() - (dfsInputLocationsTimeout + 1)); registrationMethod.accept(fin); assertEquals(enableBlkExpiration, dfsClient.getLocatedBlockRefresher().isInputStreamTracked(fin), "SHOULD be tracking input stream on read after interval, only if enabled"); } finally { if (fin != null) { fin.close(); assertFalse(dfsClient.getLocatedBlockRefresher().isInputStreamTracked(fin)); } fs.delete(filePath, true); } } private Path createFile(String fileName) throws IOException { Path path = new Path(fileName); try (FSDataOutputStream fout = fs.create(path, REPLICATION_FACTOR)) { fout.write(new byte[(fileLength)]); } return path; } }
ThrowingConsumer
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/TestAMRMProxyTokenSecretManager.java
{ "start": 1635, "end": 4738 }
class ____ { private YarnConfiguration conf; private AMRMProxyTokenSecretManager secretManager; private NMMemoryStateStoreService stateStore; @BeforeEach public void setup() { conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.NM_RECOVERY_ENABLED, true); stateStore = new NMMemoryStateStoreService(); stateStore.init(conf); stateStore.start(); secretManager = new AMRMProxyTokenSecretManager(stateStore); secretManager.init(conf); secretManager.start(); } @AfterEach public void breakdown() { if (secretManager != null) { secretManager.stop(); } if (stateStore != null) { stateStore.stop(); } } @Test public void testNormalCase() throws IOException { ApplicationId appId = ApplicationId.newInstance(1, 1); ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance(appId, 1); Token<AMRMTokenIdentifier> localToken = secretManager.createAndGetAMRMToken(attemptId); AMRMTokenIdentifier identifier = secretManager.createIdentifier(); identifier.readFields(new DataInputStream( new ByteArrayInputStream(localToken.getIdentifier()))); secretManager.retrievePassword(identifier); secretManager.applicationMasterFinished(attemptId); try { secretManager.retrievePassword(identifier); fail("Expect InvalidToken exception"); } catch (InvalidToken e) { } } @Test public void testRecovery() throws IOException { ApplicationId appId = ApplicationId.newInstance(1, 1); ApplicationAttemptId attemptId = ApplicationAttemptId.newInstance(appId, 1); Token<AMRMTokenIdentifier> localToken = secretManager.createAndGetAMRMToken(attemptId); AMRMTokenIdentifier identifier = secretManager.createIdentifier(); identifier.readFields(new DataInputStream( new ByteArrayInputStream(localToken.getIdentifier()))); secretManager.retrievePassword(identifier); // Generate next master key secretManager.rollMasterKey(); // Restart and recover secretManager.stop(); secretManager = new AMRMProxyTokenSecretManager(stateStore); secretManager.init(conf); secretManager.recover(stateStore.loadAMRMProxyState()); secretManager.start(); // Recover the app secretManager.createAndGetAMRMToken(attemptId); // Current master key should be recovered, and thus pass here secretManager.retrievePassword(identifier); // Roll key, current master key will be replaced secretManager.activateNextMasterKey(); // Restart and recover secretManager.stop(); secretManager = new AMRMProxyTokenSecretManager(stateStore); secretManager.init(conf); secretManager.recover(stateStore.loadAMRMProxyState()); secretManager.start(); // Recover the app secretManager.createAndGetAMRMToken(attemptId); try { secretManager.retrievePassword(identifier); fail("Expect InvalidToken exception because the " + "old master key should have expired"); } catch (InvalidToken e) { } } }
TestAMRMProxyTokenSecretManager
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/env/SystemEnvironmentPropertySourceTests.java
{ "start": 979, "end": 5457 }
class ____ { private Map<String, Object> envMap; private PropertySource<?> ps; @BeforeEach void setUp() { envMap = new HashMap<>(); ps = new SystemEnvironmentPropertySource("sysEnv", envMap); } @Test void none() { assertThat(ps.containsProperty("a.key")).isFalse(); assertThat(ps.getProperty("a.key")).isNull(); } @Test void normalWithoutPeriod() { envMap.put("akey", "avalue"); assertThat(ps.containsProperty("akey")).isTrue(); assertThat(ps.getProperty("akey")).isEqualTo("avalue"); } @Test void normalWithPeriod() { envMap.put("a.key", "a.value"); assertThat(ps.containsProperty("a.key")).isTrue(); assertThat(ps.getProperty("a.key")).isEqualTo("a.value"); } @Test void withUnderscore() { envMap.put("a_key", "a_value"); assertThat(ps.containsProperty("a_key")).isTrue(); assertThat(ps.containsProperty("a.key")).isTrue(); assertThat(ps.getProperty("a_key")).isEqualTo("a_value"); assertThat( ps.getProperty("a.key")).isEqualTo("a_value"); } @Test void withBothPeriodAndUnderscore() { envMap.put("a_key", "a_value"); envMap.put("a.key", "a.value"); assertThat(ps.getProperty("a_key")).isEqualTo("a_value"); assertThat( ps.getProperty("a.key")).isEqualTo("a.value"); } @Test void withUppercase() { envMap.put("A_KEY", "a_value"); envMap.put("A_LONG_KEY", "a_long_value"); envMap.put("A_DOT.KEY", "a_dot_value"); envMap.put("A_HYPHEN-KEY", "a_hyphen_value"); assertThat(ps.containsProperty("A_KEY")).isTrue(); assertThat(ps.containsProperty("A.KEY")).isTrue(); assertThat(ps.containsProperty("A-KEY")).isTrue(); assertThat(ps.containsProperty("a_key")).isTrue(); assertThat(ps.containsProperty("a.key")).isTrue(); assertThat(ps.containsProperty("a-key")).isTrue(); assertThat(ps.containsProperty("A_LONG_KEY")).isTrue(); assertThat(ps.containsProperty("A.LONG.KEY")).isTrue(); assertThat(ps.containsProperty("A-LONG-KEY")).isTrue(); assertThat(ps.containsProperty("A.LONG-KEY")).isTrue(); assertThat(ps.containsProperty("A-LONG.KEY")).isTrue(); assertThat(ps.containsProperty("A_long_KEY")).isTrue(); assertThat(ps.containsProperty("A.long.KEY")).isTrue(); assertThat(ps.containsProperty("A-long-KEY")).isTrue(); assertThat(ps.containsProperty("A.long-KEY")).isTrue(); assertThat(ps.containsProperty("A-long.KEY")).isTrue(); assertThat(ps.containsProperty("A_DOT.KEY")).isTrue(); assertThat(ps.containsProperty("A-DOT.KEY")).isTrue(); assertThat(ps.containsProperty("A_dot.KEY")).isTrue(); assertThat(ps.containsProperty("A-dot.KEY")).isTrue(); assertThat(ps.containsProperty("A_HYPHEN-KEY")).isTrue(); assertThat(ps.containsProperty("A.HYPHEN-KEY")).isTrue(); assertThat(ps.containsProperty("A_hyphen-KEY")).isTrue(); assertThat(ps.containsProperty("A.hyphen-KEY")).isTrue(); assertThat(ps.getProperty("A_KEY")).isEqualTo("a_value"); assertThat(ps.getProperty("A.KEY")).isEqualTo("a_value"); assertThat(ps.getProperty("A-KEY")).isEqualTo("a_value"); assertThat(ps.getProperty("a_key")).isEqualTo("a_value"); assertThat(ps.getProperty("a.key")).isEqualTo("a_value"); assertThat(ps.getProperty("a-key")).isEqualTo("a_value"); assertThat(ps.getProperty("A_LONG_KEY")).isEqualTo("a_long_value"); assertThat(ps.getProperty("A.LONG.KEY")).isEqualTo("a_long_value"); assertThat(ps.getProperty("A-LONG-KEY")).isEqualTo("a_long_value"); assertThat(ps.getProperty("A.LONG-KEY")).isEqualTo("a_long_value"); assertThat(ps.getProperty("A-LONG.KEY")).isEqualTo("a_long_value"); assertThat(ps.getProperty("A_long_KEY")).isEqualTo("a_long_value"); assertThat(ps.getProperty("A.long.KEY")).isEqualTo("a_long_value"); assertThat(ps.getProperty("A-long-KEY")).isEqualTo("a_long_value"); assertThat(ps.getProperty("A.long-KEY")).isEqualTo("a_long_value"); assertThat(ps.getProperty("A-long.KEY")).isEqualTo("a_long_value"); assertThat(ps.getProperty("A_DOT.KEY")).isEqualTo("a_dot_value"); assertThat(ps.getProperty("A-DOT.KEY")).isEqualTo("a_dot_value"); assertThat(ps.getProperty("A_dot.KEY")).isEqualTo("a_dot_value"); assertThat(ps.getProperty("A-dot.KEY")).isEqualTo("a_dot_value"); assertThat(ps.getProperty("A_HYPHEN-KEY")).isEqualTo("a_hyphen_value"); assertThat(ps.getProperty("A.HYPHEN-KEY")).isEqualTo("a_hyphen_value"); assertThat(ps.getProperty("A_hyphen-KEY")).isEqualTo("a_hyphen_value"); assertThat(ps.getProperty("A.hyphen-KEY")).isEqualTo("a_hyphen_value"); } }
SystemEnvironmentPropertySourceTests
java
apache__thrift
lib/java/src/main/java/org/apache/thrift/protocol/TSet.java
{ "start": 907, "end": 1265 }
class ____ { public TSet() { this(TType.STOP, 0); } public TSet(byte t, int s) { elemType = t; size = s; } public TSet(TList list) { this(list.elemType, list.size); } public final byte elemType; public final int size; public byte getElemType() { return elemType; } public int getSize() { return size; } }
TSet
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/lazytoone/collectioninitializer/Offer.java
{ "start": 338, "end": 788 }
class ____ { @Id private Long id; @ManyToOne(fetch = LAZY, optional = false) private CostCenter costCenter; @Override public String toString() { return "Offer{" + "id=" + getId() + '}'; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public CostCenter getCostCenter() { return costCenter; } public void setCostCenter(CostCenter costCenter) { this.costCenter = costCenter; } }
Offer
java
grpc__grpc-java
core/src/test/java/io/grpc/internal/FailingClientTransportTest.java
{ "start": 1199, "end": 1831 }
class ____ { @Test public void newStreamStart() { Status error = Status.UNAVAILABLE; RpcProgress rpcProgress = RpcProgress.DROPPED; FailingClientTransport transport = new FailingClientTransport(error, rpcProgress); ClientStream stream = transport.newStream( TestMethodDescriptors.voidMethod(), new Metadata(), CallOptions.DEFAULT, new ClientStreamTracer[] { new ClientStreamTracer() {} }); ClientStreamListener listener = mock(ClientStreamListener.class); stream.start(listener); verify(listener).closed(eq(error), eq(rpcProgress), any(Metadata.class)); } }
FailingClientTransportTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/TestingPhysicalSlotPayload.java
{ "start": 885, "end": 1106 }
class ____ implements PhysicalSlot.Payload { @Override public void release(Throwable cause) {} @Override public boolean willOccupySlotIndefinitely() { return false; } }
TestingPhysicalSlotPayload
java
apache__maven
impl/maven-testing/src/test/java/org/apache/maven/api/plugin/testing/MojoRealSessionTest.java
{ "start": 2622, "end": 3263 }
class ____ { @Inject Session session; @Provides @Singleton static Session createSession() { Path basedir = Paths.get(System.getProperty("basedir", "")); Path localRepoPath = basedir.resolve("target/local-repo"); // Rely on DI discovery for SecDispatcherProvider to avoid duplicate bindings return ApiRunner.createSession(null, localRepoPath); } @Test void customProviderWinsOverFlag() { assertNotNull(session); assertFalse(Mockito.mockingDetails(session).isMock()); } } }
CustomRealOverridesFlag
java
google__dagger
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
{ "start": 10112, "end": 10469 }
interface ____ {", " Foo<Bar<String>> getFooBarString();", "}"); Source module = CompilerTests.javaSource( "test.TestModule", "package test;", "", "import dagger.Module;", "import dagger.Provides;", "", "@Module", "
TestComponent
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/netty/PartitionRequestClientFactoryTest.java
{ "start": 14661, "end": 15297 }
class ____ extends NettyClient { private final NettyClient nettyClient; private int retry; UnstableNettyClient(NettyClient nettyClient, int retry) { super(null); this.nettyClient = nettyClient; this.retry = retry; } @Override ChannelFuture connect(final InetSocketAddress serverSocketAddress) { if (retry > 0) { retry--; throw new ChannelException("Simulate connect failure"); } return nettyClient.connect(serverSocketAddress); } } private static
UnstableNettyClient
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/SqlParameterSource.java
{ "start": 1490, "end": 3404 }
interface ____ { /** * Constant that indicates an unknown (or unspecified) SQL type. * To be returned from {@code getType} when no specific SQL type known. * @see #getSqlType * @see java.sql.Types */ int TYPE_UNKNOWN = JdbcUtils.TYPE_UNKNOWN; /** * Determine whether there is a value for the specified named parameter. * @param paramName the name of the parameter * @return whether there is a value defined */ boolean hasValue(String paramName); /** * Return the parameter value for the requested named parameter. * @param paramName the name of the parameter * @return the value of the specified parameter * @throws IllegalArgumentException if there is no value for the requested parameter */ @Nullable Object getValue(String paramName) throws IllegalArgumentException; /** * Determine the SQL type for the specified named parameter. * @param paramName the name of the parameter * @return the SQL type of the specified parameter, * or {@code TYPE_UNKNOWN} if not known * @see #TYPE_UNKNOWN */ default int getSqlType(String paramName) { return TYPE_UNKNOWN; } /** * Determine the type name for the specified named parameter. * @param paramName the name of the parameter * @return the type name of the specified parameter, * or {@code null} if not known */ default @Nullable String getTypeName(String paramName) { return null; } /** * Enumerate all available parameter names if possible. * <p>This is an optional operation, primarily for use with * {@link org.springframework.jdbc.core.simple.SimpleJdbcInsert} * and {@link org.springframework.jdbc.core.simple.SimpleJdbcCall}. * @return the array of parameter names, or {@code null} if not determinable * @since 5.0.3 * @see SqlParameterSourceUtils#extractCaseInsensitiveParameterNames */ default String @Nullable [] getParameterNames() { return null; } }
SqlParameterSource
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java
{ "start": 14880, "end": 16437 }
class ____ implements Rule { private final Locale locale; private final int style; private final String standard; private final String daylight; /** * Constructs an instance of {@link TimeZoneNameRule} with the specified properties. * * @param timeZone the time zone. * @param locale the locale. * @param style the style. */ TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) { this.locale = LocaleUtils.toLocale(locale); this.style = style; this.standard = getTimeZoneDisplay(timeZone, false, style, locale); this.daylight = getTimeZoneDisplay(timeZone, true, style, locale); } /** * {@inheritDoc} */ @Override public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { final TimeZone zone = calendar.getTimeZone(); final boolean daylight = calendar.get(Calendar.DST_OFFSET) != 0; buffer.append(getTimeZoneDisplay(zone, daylight, style, locale)); } /** * {@inheritDoc} */ @Override public int estimateLength() { // We have no access to the Calendar object that will be passed to // appendTo so base estimate on the TimeZone passed to the // constructor return Math.max(standard.length(), daylight.length()); } } /** * Inner
TimeZoneNameRule
java
spring-projects__spring-security
saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2AuthenticationTokens.java
{ "start": 1014, "end": 1705 }
class ____ { private TestSaml2AuthenticationTokens() { } public static Saml2AuthenticationToken token() { RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.relyingPartyRegistration() .build(); return new Saml2AuthenticationToken(relyingPartyRegistration, "saml2-xml-response-object"); } public static Saml2AuthenticationToken tokenRequested() { RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.relyingPartyRegistration() .build(); return new Saml2AuthenticationToken(relyingPartyRegistration, "saml2-xml-response-object", TestSaml2PostAuthenticationRequests.create()); } }
TestSaml2AuthenticationTokens
java
grpc__grpc-java
api/src/context/java/io/grpc/Context.java
{ "start": 29412, "end": 33794 }
class ____ and should not be used. * If you must know whether a Context is the current context, check whether it is the same * object returned by {@link Context#current()}. */ //TODO(spencerfang): The superclass's method is package-private, so this should really match. @Override @Deprecated public boolean isCurrent() { return uncancellableSurrogate.isCurrent(); } /** * Cancel this context and optionally provide a cause (can be {@code null}) for the * cancellation. This will trigger notification of listeners. It is safe to call this method * multiple times. Only the first call will have any effect. * * <p>Calling {@code cancel(null)} is the same as calling {@link #close}. * * @return {@code true} if this context cancelled the context and notified listeners, * {@code false} if the context was already cancelled. */ @CanIgnoreReturnValue public boolean cancel(Throwable cause) { boolean triggeredCancel = false; ScheduledFuture<?> localPendingDeadline = null; synchronized (this) { if (!cancelled) { cancelled = true; if (pendingDeadline != null) { // If we have a scheduled cancellation pending attempt to cancel it. localPendingDeadline = pendingDeadline; pendingDeadline = null; } this.cancellationCause = cause; triggeredCancel = true; } } if (localPendingDeadline != null) { localPendingDeadline.cancel(false); } if (triggeredCancel) { notifyAndClearListeners(); } return triggeredCancel; } /** * Notify all listeners that this context has been cancelled and immediately release * any reference to them so that they may be garbage collected. */ private void notifyAndClearListeners() { ArrayList<ExecutableListener> tmpListeners; CancellationListener tmpParentListener; synchronized (this) { if (listeners == null) { return; } tmpParentListener = parentListener; parentListener = null; tmpListeners = listeners; listeners = null; } // Deliver events to this context listeners before we notify child contexts. We do this // to cancel higher level units of work before child units. This allows for a better error // handling paradigm where the higher level unit of work knows it is cancelled and so can // ignore errors that bubble up as a result of cancellation of lower level units. for (ExecutableListener tmpListener : tmpListeners) { if (tmpListener.context == this) { tmpListener.deliver(); } } for (ExecutableListener tmpListener : tmpListeners) { if (!(tmpListener.context == this)) { tmpListener.deliver(); } } if (cancellableAncestor != null) { cancellableAncestor.removeListener(tmpParentListener); } } @Override int listenerCount() { synchronized (this) { return listeners == null ? 0 : listeners.size(); } } /** * Cancel this context and detach it as the current context. * * @param toAttach context to make current. * @param cause of cancellation, can be {@code null}. */ public void detachAndCancel(Context toAttach, Throwable cause) { try { detach(toAttach); } finally { cancel(cause); } } @Override public boolean isCancelled() { synchronized (this) { if (cancelled) { return true; } } // Detect cancellation of parent in the case where we have no listeners and // record it. if (super.isCancelled()) { cancel(super.cancellationCause()); return true; } return false; } @Override public Throwable cancellationCause() { if (isCancelled()) { return cancellationCause; } return null; } @Override public Deadline getDeadline() { return deadline; } /** * Cleans up this object by calling {@code cancel(null)}. */ @Override public void close() { cancel(null); } } /** * A listener notified on context cancellation. */ public
encapsulation
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/annotation/AnnotationTypeMappingsTests.java
{ "start": 25802, "end": 26122 }
interface ____ { // attempted implicit alias via attribute override @AliasFor(annotation = AliasPair.class, attribute = "b") String b() default ""; // explicit local alias @AliasFor("b") String a() default ""; } @Retention(RetentionPolicy.RUNTIME) @AliasPair @
AliasForWithMixedImplicitAndExplicitAliasesV1
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/aggfunctions/MinWithRetractAggFunctionTest.java
{ "start": 11336, "end": 12603 }
class ____ extends MinWithRetractAggFunctionTestBase<TimestampData> { @Override protected List<List<TimestampData>> getInputValueSets() { return Arrays.asList( Arrays.asList( TimestampData.fromEpochMillis(0), TimestampData.fromEpochMillis(1000), TimestampData.fromEpochMillis(100), null, TimestampData.fromEpochMillis(10)), Arrays.asList(null, null, null, null, null), Arrays.asList(null, TimestampData.fromEpochMillis(1))); } @Override protected List<TimestampData> getExpectedResults() { return Arrays.asList( TimestampData.fromEpochMillis(0), null, TimestampData.fromEpochMillis(1)); } @Override protected AggregateFunction<TimestampData, MinWithRetractAccumulator<TimestampData>> getAggregator() { return new MinWithRetractAggFunction<>(DataTypes.TIMESTAMP(3).getLogicalType()); } } /** Test for {@link TimestampType} with precision 9. */ @Nested final
TimestampMinWithRetractAggFunctionTest
java
apache__camel
components/camel-whatsapp/src/main/java/org/apache/camel/component/whatsapp/WhatsAppEndpoint.java
{ "start": 1870, "end": 5160 }
class ____ extends ScheduledPollEndpoint implements WebhookCapableEndpoint { private static final Logger LOG = LoggerFactory.getLogger(WhatsAppEndpoint.class); @UriParam private WhatsAppConfiguration configuration; @UriParam(label = "advanced", description = "HttpClient implementation") private HttpClient httpClient; @UriParam(label = "advanced", description = "WhatsApp service implementation") private WhatsAppService whatsappService; private WebhookConfiguration webhookConfiguration; public WhatsAppEndpoint(String endpointUri, Component component, WhatsAppConfiguration configuration, HttpClient client) { super(endpointUri, component); this.configuration = configuration; this.httpClient = client; } @Override protected void doStart() throws Exception { super.doStart(); if (httpClient == null) { httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).connectTimeout(Duration.ofSeconds(10)).build(); } if (whatsappService == null) { whatsappService = new WhatsAppServiceRestAPIAdapter( httpClient, configuration.getBaseUri(), configuration.getApiVersion(), configuration.getPhoneNumberId(), configuration.getAuthorizationToken()); } LOG.debug("client {}", httpClient); LOG.debug("whatsappService {}", whatsappService); } @Override protected void doStop() throws Exception { super.doStop(); // ensure client is closed when stopping httpClient = null; } @Override public Producer createProducer() throws Exception { return new WhatsAppProducer(this); } @Override public Consumer createConsumer(Processor processor) throws Exception { throw new UnsupportedOperationException("consumer not supported"); } @Override public Processor createWebhookHandler(Processor next) { return new WhatsAppWebhookProcessor(next, configuration); } @Override public List<String> getWebhookMethods() { return List.of("POST", "GET"); } @Override public void registerWebhook() throws Exception { } @Override public void setWebhookConfiguration(WebhookConfiguration webhookConfiguration) { webhookConfiguration.setWebhookPath(configuration.getWebhookPath()); this.webhookConfiguration = webhookConfiguration; } @Override public void unregisterWebhook() throws Exception { } public WhatsAppConfiguration getConfiguration() { return configuration; } public void setConfiguration(WhatsAppConfiguration configuration) { this.configuration = configuration; } public WhatsAppService getWhatsappService() { return whatsappService; } public void setWhatsappService(WhatsAppService whatsappService) { this.whatsappService = whatsappService; } public HttpClient getHttpClient() { return httpClient; } public void setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; } public WebhookConfiguration getWebhookConfiguration() { return webhookConfiguration; } }
WhatsAppEndpoint
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/ValidateJobConfigAction.java
{ "start": 836, "end": 1166 }
class ____ extends ActionType<AcknowledgedResponse> { public static final ValidateJobConfigAction INSTANCE = new ValidateJobConfigAction(); public static final String NAME = "cluster:admin/xpack/ml/job/validate"; protected ValidateJobConfigAction() { super(NAME); } public static
ValidateJobConfigAction
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/userinfo/DefaultOAuth2UserService.java
{ "start": 2942, "end": 11016 }
class ____ implements OAuth2UserService<OAuth2UserRequest, OAuth2User> { private static final String MISSING_USER_INFO_URI_ERROR_CODE = "missing_user_info_uri"; private static final String MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE = "missing_user_name_attribute"; private static final String INVALID_USER_INFO_RESPONSE_ERROR_CODE = "invalid_user_info_response"; private static final ParameterizedTypeReference<Map<String, Object>> PARAMETERIZED_RESPONSE_TYPE = new ParameterizedTypeReference<>() { }; private Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter = new OAuth2UserRequestEntityConverter(); private Converter<OAuth2UserRequest, Converter<Map<String, Object>, Map<String, Object>>> attributesConverter = ( request) -> (attributes) -> attributes; private RestOperations restOperations; public DefaultOAuth2UserService() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler()); this.restOperations = restTemplate; } @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { Assert.notNull(userRequest, "userRequest cannot be null"); String userNameAttributeName = getUserNameAttributeName(userRequest); RequestEntity<?> request = this.requestEntityConverter.convert(userRequest); ResponseEntity<Map<String, Object>> response = getResponse(userRequest, request); OAuth2AccessToken token = userRequest.getAccessToken(); Map<String, Object> attributes = this.attributesConverter.convert(userRequest).convert(response.getBody()); Collection<GrantedAuthority> authorities = getAuthorities(token, attributes, userNameAttributeName); return new DefaultOAuth2User(authorities, attributes, userNameAttributeName); } /** * Use this strategy to adapt user attributes into a format understood by Spring * Security; by default, the original attributes are preserved. * * <p> * This can be helpful, for example, if the user attribute is nested. Since Spring * Security needs the username attribute to be at the top level, you can use this * method to do: * * <pre> * DefaultOAuth2UserService userService = new DefaultOAuth2UserService(); * userService.setAttributesConverter((userRequest) -> (attributes) -> * Map&lt;String, Object&gt; userObject = (Map&lt;String, Object&gt;) attributes.get("user"); * attributes.put("user-name", userObject.get("user-name")); * return attributes; * }); * </pre> * @param attributesConverter the attribute adaptation strategy to use * @since 6.3 */ public void setAttributesConverter( Converter<OAuth2UserRequest, Converter<Map<String, Object>, Map<String, Object>>> attributesConverter) { Assert.notNull(attributesConverter, "attributesConverter cannot be null"); this.attributesConverter = attributesConverter; } private ResponseEntity<Map<String, Object>> getResponse(OAuth2UserRequest userRequest, RequestEntity<?> request) { try { return this.restOperations.exchange(request, PARAMETERIZED_RESPONSE_TYPE); } catch (OAuth2AuthorizationException ex) { OAuth2Error oauth2Error = ex.getError(); StringBuilder errorDetails = new StringBuilder(); errorDetails.append("Error details: ["); errorDetails.append("UserInfo Uri: ") .append(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri()); errorDetails.append(", Error Code: ").append(oauth2Error.getErrorCode()); if (oauth2Error.getDescription() != null) { errorDetails.append(", Error Description: ").append(oauth2Error.getDescription()); } errorDetails.append("]"); oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, "An error occurred while attempting to retrieve the UserInfo Resource: " + errorDetails.toString(), null); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex); } catch (UnknownContentTypeException ex) { String errorMessage = "An error occurred while attempting to retrieve the UserInfo Resource from '" + userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri() + "': response contains invalid content type '" + ex.getContentType().toString() + "'. " + "The UserInfo Response should return a JSON object (content type 'application/json') " + "that contains a collection of name and value pairs of the claims about the authenticated End-User. " + "Please ensure the UserInfo Uri in UserInfoEndpoint for Client Registration '" + userRequest.getClientRegistration().getRegistrationId() + "' conforms to the UserInfo Endpoint, " + "as defined in OpenID Connect 1.0: 'https://openid.net/specs/openid-connect-core-1_0.html#UserInfo'"; OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, errorMessage, null); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex); } catch (RestClientException ex) { OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, "An error occurred while attempting to retrieve the UserInfo Resource: " + ex.getMessage(), null); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex); } } private String getUserNameAttributeName(OAuth2UserRequest userRequest) { if (!StringUtils .hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) { OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE, "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } String userNameAttributeName = userRequest.getClientRegistration() .getProviderDetails() .getUserInfoEndpoint() .getUserNameAttributeName(); if (!StringUtils.hasText(userNameAttributeName)) { OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE, "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } return userNameAttributeName; } private Collection<GrantedAuthority> getAuthorities(OAuth2AccessToken token, Map<String, Object> attributes, String userNameAttributeName) { Collection<GrantedAuthority> authorities = new LinkedHashSet<>(); authorities.add(new OAuth2UserAuthority(attributes, userNameAttributeName)); for (String authority : token.getScopes()) { authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority)); } return authorities; } /** * Sets the {@link Converter} used for converting the {@link OAuth2UserRequest} to a * {@link RequestEntity} representation of the UserInfo Request. * @param requestEntityConverter the {@link Converter} used for converting to a * {@link RequestEntity} representation of the UserInfo Request * @since 5.1 */ public final void setRequestEntityConverter(Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter) { Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null"); this.requestEntityConverter = requestEntityConverter; } /** * Sets the {@link RestOperations} used when requesting the UserInfo resource. * * <p> * <b>NOTE:</b> At a minimum, the supplied {@code restOperations} must be configured * with the following: * <ol> * <li>{@link ResponseErrorHandler} - {@link OAuth2ErrorResponseErrorHandler}</li> * </ol> * @param restOperations the {@link RestOperations} used when requesting the UserInfo * resource * @since 5.1 */ public final void setRestOperations(RestOperations restOperations) { Assert.notNull(restOperations, "restOperations cannot be null"); this.restOperations = restOperations; } }
DefaultOAuth2UserService
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/CheckpointStateStoreConfigTest.java
{ "start": 955, "end": 2588 }
class ____ { SmallRyeConfig config; @AfterEach void tearDown() { if (config != null) { ConfigProviderResolver.instance().releaseConfig(config); } } private void createConfig(Map<String, String> configMap) { config = new SmallRyeConfigBuilder() .withSources(new MapBackedConfigSource("test", configMap) { }) .build(); } @Test void testHasStateStoreConfigWithConnectorConfig() { createConfig(Map.of("mp.messaging.connector.smallrye-kafka.checkpoint.state-store", HIBERNATE_ORM_STATE_STORE)); assertTrue(hasStateStoreConfig(HIBERNATE_ORM_STATE_STORE, config)); } @Test void testHasStateStoreConfigWithChannelConfig() { createConfig(Map.of("mp.messaging.incoming.my-channel.checkpoint.state-store", HIBERNATE_REACTIVE_STATE_STORE)); assertTrue(hasStateStoreConfig(HIBERNATE_REACTIVE_STATE_STORE, config)); } @Test void testHasStateStoreConfigWithInvalidChannelConfig() { createConfig(Map.of( "mp.messaging.outgoing.my-channel.checkpoint.state-store", HIBERNATE_REACTIVE_STATE_STORE, "mp.messaging.incoming.my-channel.state-store", HIBERNATE_ORM_STATE_STORE)); assertFalse(hasStateStoreConfig(HIBERNATE_REACTIVE_STATE_STORE, config)); assertFalse(hasStateStoreConfig(HIBERNATE_ORM_STATE_STORE, config)); } @Test void testHasStateStoreConfigEmptyConfig() { createConfig(Map.of()); assertFalse(hasStateStoreConfig(REDIS_STATE_STORE, config)); } }
CheckpointStateStoreConfigTest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customproviders/NotFoundExeptionMapper.java
{ "start": 238, "end": 443 }
class ____ implements ExceptionMapper<NotFoundException> { @Override public Response toResponse(NotFoundException exception) { return Response.status(404).build(); } }
NotFoundExeptionMapper
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/transaction/queue/GetResult.java
{ "start": 974, "end": 1363 }
class ____ { private MessageExt msg; private PullResult pullResult; public MessageExt getMsg() { return msg; } public void setMsg(MessageExt msg) { this.msg = msg; } public PullResult getPullResult() { return pullResult; } public void setPullResult(PullResult pullResult) { this.pullResult = pullResult; } }
GetResult
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorTests.java
{ "start": 11635, "end": 12011 }
class ____ implements Identifiable { private Long id; private String name; @Override public Long getId() { return id; } @Override public void setId(Long id) { this.id = id; } public String getName() { return name; } @SuppressWarnings("unused") public void setName(String name) { this.name = name; } } private static final
SimpleBean
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/embeddable/OneToManyInEmbeddedQueryTest.java
{ "start": 5062, "end": 5518 }
class ____ implements Serializable { @OneToMany( cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER ) @JoinColumn( name = "entityA_id" ) private List<EntityC> entityCList; public EmbeddedValue() { } public EmbeddedValue(List<EntityC> entityCList) { this.entityCList = entityCList; } public List<EntityC> getEntityCList() { return entityCList; } } @Entity( name = "EntityBToOne" ) public static
EmbeddedValue
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/DefaultLobHandler.java
{ "start": 8809, "end": 13509 }
class ____ implements LobCreator { @Override public void setBlobAsBytes(PreparedStatement ps, int paramIndex, byte @Nullable [] content) throws SQLException { if (streamAsLob) { if (content != null) { ps.setBlob(paramIndex, new ByteArrayInputStream(content), content.length); } else { ps.setBlob(paramIndex, (Blob) null); } } else if (wrapAsLob) { if (content != null) { ps.setBlob(paramIndex, new PassThroughBlob(content)); } else { ps.setBlob(paramIndex, (Blob) null); } } else { ps.setBytes(paramIndex, content); } if (logger.isDebugEnabled()) { logger.debug(content != null ? "Set bytes for BLOB with length " + content.length : "Set BLOB to null"); } } @Override public void setBlobAsBinaryStream( PreparedStatement ps, int paramIndex, @Nullable InputStream binaryStream, int contentLength) throws SQLException { if (streamAsLob) { if (binaryStream != null) { if (contentLength >= 0) { ps.setBlob(paramIndex, binaryStream, contentLength); } else { ps.setBlob(paramIndex, binaryStream); } } else { ps.setBlob(paramIndex, (Blob) null); } } else if (wrapAsLob) { if (binaryStream != null) { ps.setBlob(paramIndex, new PassThroughBlob(binaryStream, contentLength)); } else { ps.setBlob(paramIndex, (Blob) null); } } else if (contentLength >= 0) { ps.setBinaryStream(paramIndex, binaryStream, contentLength); } else { ps.setBinaryStream(paramIndex, binaryStream); } if (logger.isDebugEnabled()) { logger.debug(binaryStream != null ? "Set binary stream for BLOB with length " + contentLength : "Set BLOB to null"); } } @Override public void setClobAsString(PreparedStatement ps, int paramIndex, @Nullable String content) throws SQLException { if (streamAsLob) { if (content != null) { ps.setClob(paramIndex, new StringReader(content), content.length()); } else { ps.setClob(paramIndex, (Clob) null); } } else if (wrapAsLob) { if (content != null) { ps.setClob(paramIndex, new PassThroughClob(content)); } else { ps.setClob(paramIndex, (Clob) null); } } else { ps.setString(paramIndex, content); } if (logger.isDebugEnabled()) { logger.debug(content != null ? "Set string for CLOB with length " + content.length() : "Set CLOB to null"); } } @Override public void setClobAsAsciiStream( PreparedStatement ps, int paramIndex, @Nullable InputStream asciiStream, int contentLength) throws SQLException { if (streamAsLob) { if (asciiStream != null) { Reader reader = new InputStreamReader(asciiStream, StandardCharsets.US_ASCII); if (contentLength >= 0) { ps.setClob(paramIndex, reader, contentLength); } else { ps.setClob(paramIndex, reader); } } else { ps.setClob(paramIndex, (Clob) null); } } else if (wrapAsLob) { if (asciiStream != null) { ps.setClob(paramIndex, new PassThroughClob(asciiStream, contentLength)); } else { ps.setClob(paramIndex, (Clob) null); } } else if (contentLength >= 0) { ps.setAsciiStream(paramIndex, asciiStream, contentLength); } else { ps.setAsciiStream(paramIndex, asciiStream); } if (logger.isDebugEnabled()) { logger.debug(asciiStream != null ? "Set ASCII stream for CLOB with length " + contentLength : "Set CLOB to null"); } } @Override public void setClobAsCharacterStream( PreparedStatement ps, int paramIndex, @Nullable Reader characterStream, int contentLength) throws SQLException { if (streamAsLob) { if (characterStream != null) { if (contentLength >= 0) { ps.setClob(paramIndex, characterStream, contentLength); } else { ps.setClob(paramIndex, characterStream); } } else { ps.setClob(paramIndex, (Clob) null); } } else if (wrapAsLob) { if (characterStream != null) { ps.setClob(paramIndex, new PassThroughClob(characterStream, contentLength)); } else { ps.setClob(paramIndex, (Clob) null); } } else if (contentLength >= 0) { ps.setCharacterStream(paramIndex, characterStream, contentLength); } else { ps.setCharacterStream(paramIndex, characterStream); } if (logger.isDebugEnabled()) { logger.debug(characterStream != null ? "Set character stream for CLOB with length " + contentLength : "Set CLOB to null"); } } @Override public void close() { // nothing to do when not creating temporary LOBs } } }
DefaultLobCreator
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/FluxMergeComparingTest.java
{ "start": 3891, "end": 26276 }
class ____ extends Person { private final String login; User(String name, String login) { super(name); this.login = login; } public String getLogin() { return login; } } @Test void mergeComparingWithCombinesComparators() { Comparator<Person> nameComparator = Comparator.comparing(Person::getName); Comparator<User> loginComparator = Comparator.comparing(User::getLogin).reversed(); Flux<User> a = Flux.just(new User("foo", "A"), new User("bob", "JustBob")); Flux<User> b = Flux.just(new User("foo", "B")); Flux<User> c = Flux.just(new User("foo", "C")); StepVerifier.create(a.mergeComparingWith(b, nameComparator) .mergeComparingWith(c, loginComparator) .map(User::getLogin)) .expectNext("C", "B", "A", "JustBob") .verifyComplete(); } @Test void mergeComparingWithDetectsSameReference() { Comparator<String> comparator = Comparator.comparingInt(String::length); final Flux<String> flux = Flux.just("AAAAA", "BBBB") .mergeComparingWith(Flux.just("DD", "CCC"), comparator) .mergeComparingWith(Flux.just("E"), comparator); assertThat(flux).isInstanceOf(FluxMergeComparing.class); assertThat(((FluxMergeComparing<String>) flux).valueComparator) .as("didn't combine comparator") .isSameAs(comparator); } @Test void mergeComparingWithDoesntCombineNaturalOrder() { final Flux<String> flux = Flux.just("AAAAA", "BBBB") .mergeComparingWith(Flux.just("DD", "CCC"), Comparator.naturalOrder()) .mergeComparingWith(Flux.just("E"), Comparator.naturalOrder()); assertThat(flux).isInstanceOf(FluxMergeComparing.class); assertThat(((FluxMergeComparing<String>) flux).valueComparator) .as("didn't combine naturalOrder()") .isSameAs(Comparator.naturalOrder()); } @Test void considersOnlyLatestElementInEachSource() { final Flux<String> flux = Flux.mergeComparing(Comparator.comparingInt(String::length), Flux.just("AAAAA", "BBBB"), Flux.just("DD", "CCC"), Flux.just("E")); StepVerifier.create(flux) .expectNext("E") // between E, DD and AAAAA => E, 3rd slot done .expectNext("DD") // between DD and AAAAA => DD, replenish 2nd slot to CCC .expectNext("CCC") // between CCC and AAAAA => CCC, 2nd slot done .expectNext("AAAAA", "BBBB") // rest of first flux in 1st slot => AAAAA then BBBB .verifyComplete(); } @Test void reorderingByIndex() { List<Mono<Tuple2<Long, Integer>>> sourceList = Flux.range(1, 10) .index() .map(Mono::just) .collectList() .block(); assertThat(sourceList).isNotNull(); Collections.shuffle(sourceList); @SuppressWarnings("unchecked") Publisher<Tuple2<Long, Integer>>[] sources = sourceList.toArray(new Publisher[sourceList.size()]); Flux<Integer> test = new FluxMergeComparing<>(16, Comparator.comparing(Tuple2::getT1), false, true, sources) .map(Tuple2::getT2); StepVerifier.create(test) .expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .verifyComplete(); } @Test void reorderingByIndexWithDelays() { List<Mono<Tuple2<Long, Integer>>> sourceList = Flux.range(1, 10) .index() .map(t2 -> { if (t2.getT1() < 4) { return Mono.just(t2).delayElement(Duration.ofMillis(500 - t2.getT2() * 100)); } return Mono.just(t2); }) .collectList() .block(); assertThat(sourceList).isNotNull(); Collections.shuffle(sourceList); @SuppressWarnings("unchecked") Publisher<Tuple2<Long, Integer>>[] sources = sourceList.toArray(new Publisher[sourceList.size()]); Flux<Integer> test = new FluxMergeComparing<>(16, Comparator.comparing(Tuple2::getT1), false, true, sources) .map(Tuple2::getT2); StepVerifier.create(test) .expectNext(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .verifyComplete(); } @Test void prefetchZero() { assertThatIllegalArgumentException() .isThrownBy(() -> new FluxMergeComparing<Integer>(0, Comparator.naturalOrder(), false, true)) .withMessage("prefetch > 0 required but it was 0"); } @Test void prefetchNegative() { assertThatIllegalArgumentException() .isThrownBy(() -> new FluxMergeComparing<Integer>(-1, Comparator.naturalOrder(), false, true)) .withMessage("prefetch > 0 required but it was -1"); } @Test void getPrefetch() { FluxMergeComparing<Integer> fmo = new FluxMergeComparing<Integer>(123, Comparator.naturalOrder(), false, true); assertThat(fmo.getPrefetch()).isEqualTo(123); } @Test void nullSources() { assertThatNullPointerException() .isThrownBy(() -> new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, (Publisher<Integer>[]) null)) .withMessage("sources must be non-null"); } @Test void mergeAdditionalSource() { Comparator<Integer> originalComparator = Comparator.naturalOrder(); @SuppressWarnings("unchecked") //safe varargs FluxMergeComparing<Integer> fmo = new FluxMergeComparing<>(2, originalComparator, false, true, Flux.just(1, 2), Flux.just(3, 4)); FluxMergeComparing<Integer> fmo2 = fmo.mergeAdditionalSource(Flux.just(5, 6), Comparator.naturalOrder()); assertThat(fmo2).isNotSameAs(fmo); assertThat(fmo2.sources).startsWith(fmo.sources) .hasSize(3); assertThat(fmo.sources).hasSize(2); assertThat(fmo2.valueComparator) .as("same comparator detected and used") .isSameAs(originalComparator); StepVerifier.create(fmo2) .expectNext(1, 2, 3, 4, 5, 6) .verifyComplete(); } @Test void mergeAdditionalSourcePreservesDelayErrorOfFirst() { Comparator<Integer> originalComparator = Comparator.naturalOrder(); @SuppressWarnings("unchecked") //safe varargs FluxMergeComparing<Integer> fmo = new FluxMergeComparing<>(2, originalComparator, true, true, Flux.just(1, 2), Flux.just(3, 4)); FluxMergeComparing<Integer> fmo2 = fmo.mergeAdditionalSource(Flux.just(5, 6), Comparator.naturalOrder()); assertThat(fmo.delayError).as("delayError fmo").isTrue(); assertThat(fmo2.delayError).as("delayError fmo2").isTrue(); } @Test void scanOperator() { Flux<Integer> source1 = Flux.just(1).map(Function.identity()); //scannable Flux<Integer> source2 = Flux.just(2); @SuppressWarnings("unchecked") //safe varargs FluxMergeComparing<Integer> fmo = new FluxMergeComparing<>(123, Comparator.naturalOrder(), true, true, source1, source2); assertThat(fmo.scan(Scannable.Attr.PARENT)).isSameAs(source1); assertThat(fmo.scan(Scannable.Attr.PREFETCH)).isEqualTo(123); assertThat(fmo.scan(Scannable.Attr.DELAY_ERROR)).isTrue(); //default value assertThat(fmo.scan(Scannable.Attr.BUFFERED)).isEqualTo(0); assertThat(fmo.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); } @Test void scanMain() { CoreSubscriber<? super Integer> actual = new LambdaSubscriber<>(null, null, null, null); FluxMergeComparing.MergeOrderedMainProducer<Integer> test = new FluxMergeComparing.MergeOrderedMainProducer<Integer>(actual, Comparator.naturalOrder(), 123, 4, false, true); assertThat(test.scan(Scannable.Attr.ACTUAL)) .isSameAs(actual) .isSameAs(test.actual()); assertThat(test.scan(Scannable.Attr.DELAY_ERROR)).isFalse(); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); test.emitted = 2; test.requested = 10; assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(8); assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse(); test.cancelled = 2; assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue(); assertThat(test.scan(Scannable.Attr.ERROR)).isNull(); test.error = new IllegalStateException("boom"); assertThat(test.scan(Scannable.Attr.ERROR)).isSameAs(test.error); //default value assertThat(test.scan(Scannable.Attr.NAME)).isNull(); } @Test void scanInner() { CoreSubscriber<? super Integer> actual = new LambdaSubscriber<>(null, null, null, null); FluxMergeComparing.MergeOrderedMainProducer<Integer> main = new FluxMergeComparing.MergeOrderedMainProducer<Integer>(actual, Comparator.naturalOrder(), 123, 4, false, true); FluxMergeComparing.MergeOrderedInnerSubscriber<Integer> test = new FluxMergeComparing.MergeOrderedInnerSubscriber<>( main, 123); Subscription sub = Operators.emptySubscription(); test.onSubscribe(sub); assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(main); assertThat(test.actual()).isSameAs(actual); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(sub); assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(123); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); assertThat(test.scan(Scannable.Attr.DELAY_ERROR)).isFalse(); assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); test.done = true; assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue(); assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(0); test.queue.offer(1); assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(1); //default value assertThat(test.scan(Scannable.Attr.NAME)).isNull(); } @Test void mainSubscribersDifferentCountInners() { CoreSubscriber<? super Integer> actual = new LambdaSubscriber<>(null, null, null, null); FluxMergeComparing.MergeOrderedMainProducer<Integer> test = new FluxMergeComparing.MergeOrderedMainProducer<Integer>(actual, Comparator.naturalOrder(), 123, 4, false, true); assertThatIllegalArgumentException() .isThrownBy(() -> { @SuppressWarnings("unchecked") final Publisher<Integer>[] sources = new Publisher[3]; test.subscribe(sources); }) .withMessage("must subscribe with 4 sources"); } @Test void innerRequestAmountIgnoredAssumedOne() { CoreSubscriber<? super Integer> actual = new LambdaSubscriber<>(null, null, null, null); FluxMergeComparing.MergeOrderedMainProducer<Integer> main = new FluxMergeComparing.MergeOrderedMainProducer<Integer>(actual, Comparator.naturalOrder(), 123, 4, false, true); FluxMergeComparing.MergeOrderedInnerSubscriber<Integer> test = new FluxMergeComparing.MergeOrderedInnerSubscriber<>( main, 4); AtomicLong requested = new AtomicLong(); Subscription sub = new Subscription() { @Override public void request(long n) { requested.addAndGet(n); } @Override public void cancel() { //NO-OP } }; test.onSubscribe(sub); assertThat(requested).as("prefetch").hasValue(test.prefetch); assertThat(test.limit).isEqualTo(3); test.request(1000); assertThat(test.consumed).isEqualTo(1); test.request(1000); assertThat(test.consumed).isEqualTo(2); test.request(Long.MAX_VALUE); assertThat(test.consumed).isEqualTo(0); assertThat(requested).as("prefetch + replenish") .hasValue(test.prefetch + test.limit); } @Test @SuppressWarnings("unchecked") //safe varargs void normal1() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1), Flux.just(2)) .as(StepVerifier::create) .expectNext(1, 2) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void normal2() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1, 3, 5, 7), Flux.just(2, 4, 6, 8)) .as(StepVerifier::create) .expectNext(1, 2, 3, 4, 5, 6, 7, 8) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void normal3() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1, 3, 5, 7), Flux.just(2, 4, 6)) .as(StepVerifier::create) .expectNext(1, 2, 3, 4, 5, 6, 7) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void normal4() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1, 3, 5, 7), Flux.just(1, 3, 5, 7)) .as(StepVerifier::create) .expectNext(1, 1, 3, 3, 5, 5, 7, 7) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void normal1Hidden() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1).hide(), Flux.just(2).hide()) .as(StepVerifier::create) .expectNext(1, 2) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void normal2Hidden() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1, 3, 5, 7).hide(), Flux.just(2, 4, 6, 8).hide()) .as(StepVerifier::create) .expectNext(1, 2, 3, 4, 5, 6, 7, 8) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void normal3Hidden() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1, 3, 5, 7).hide(), Flux.just(2, 4, 6).hide()) .as(StepVerifier::create) .expectNext(1, 2, 3, 4, 5, 6, 7) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void normal4Hidden() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1, 3, 5, 7).hide(), Flux.just(1, 3, 5, 7).hide()) .as(StepVerifier::create) .expectNext(1, 1, 3, 3, 5, 5, 7, 7) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void backpressure1() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1, 3, 5, 7).log("left") , Flux.just(2, 4, 6, 8).log("right")) .limitRate(1) .as(StepVerifier::create) .expectNext(1, 2, 3, 4, 5, 6, 7, 8) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void backpressure2() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1), Flux.just(2)) .limitRate(1) .as(StepVerifier::create) .expectNext(1, 2) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void backpressure3() { new FluxMergeComparing<>(1, Comparator.naturalOrder(), false, true, Flux.just(1, 3, 5, 7), Flux.just(2, 4, 6, 8)) .limitRate(1) .as(StepVerifier::create) .expectNext(1, 2, 3, 4, 5, 6, 7, 8) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void take() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1, 3, 5, 7), Flux.just(2, 4, 6, 8)) .take(5, false) .as(StepVerifier::create) .expectNext(1, 2, 3, 4, 5) .verifyComplete(); } @Test @SuppressWarnings("unchecked") //safe varargs void firstErrorsDelayed() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), true, true, Flux.error(new IOException("boom")), Flux.just(2, 4, 6, 8)) .as(StepVerifier::create) .expectNext(2, 4, 6, 8) .verifyError(IOException.class); } @Test @SuppressWarnings("unchecked") //safe varargs void firstErrorsBackpressuredDelayed() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), true, true, Flux.error(new IOException("boom")), Flux.just(2, 4, 6, 8)) .as(f -> StepVerifier.create(f, 0L)) .thenRequest(4) .expectNext(2, 4, 6, 8) .verifyError(IOException.class); } @Test @SuppressWarnings("unchecked") //safe varargs void secondErrorsDelayed() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), true, true, Flux.just(1, 3, 5, 7), Flux.error(new IOException("boom")) ) .as(StepVerifier::create) .expectNext(1, 3, 5, 7) .verifyError(IOException.class); } @Test @SuppressWarnings("unchecked") //safe varargs void secondErrorsBackpressuredDelayed() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), true, true, Flux.just(1, 3, 5, 7), Flux.error(new IOException("boom")) ) .as(f -> StepVerifier.create(f, 0L)) .thenRequest(4) .expectNext(1, 3, 5, 7) .verifyError(IOException.class); } @Test void bothErrorDelayed() { IOException firstError = new IOException("first"); IOException secondError = new IOException("second"); new FluxMergeComparing<Integer>(2, Comparator.naturalOrder(), true, true, Flux.error(firstError), Flux.error(secondError) ) .as(StepVerifier::create) .consumeErrorWith(e -> assertThat(Exceptions.unwrapMultiple(e)).containsExactly(firstError, secondError)) .verifyThenAssertThat() .hasNotDroppedErrors(); } @Test void never() { new FluxMergeComparing<Integer>(2, Comparator.naturalOrder(), false, true, Flux.never(), Flux.never()) .as(StepVerifier::create) .thenCancel() .verify(); } @Test @SuppressWarnings("unchecked") //safe varargs void fusedThrowsInDrainLoopDelayed() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), true, true, Flux.just(1).map(v -> { throw new IllegalArgumentException("boom"); }), Flux.just(2, 3)) .as(StepVerifier::create) .expectNext(2, 3) .verifyErrorMessage("boom"); } @Test @SuppressWarnings("unchecked") //safe varargs void fusedThrowsInPostEmissionCheckDelayed() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), true, true, Flux.just(1).map(v -> { throw new IllegalArgumentException("boom"); }), Flux.just(2, 3)) .as(f -> StepVerifier.create(f, 0L)) .thenRequest(2) .expectNext(2, 3) .verifyErrorMessage("boom"); } @Test @SuppressWarnings("unchecked") //safe varargs void nullInSourceArray() { assertThatNullPointerException() .isThrownBy(() -> { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1), null); }) .withMessage("sources[1] is null"); } @Test @SuppressWarnings("unchecked") //safe varargs void comparatorThrows() { new FluxMergeComparing<>(2, (a, b) -> { throw new IllegalArgumentException("boom"); }, false, true, Flux.just(1, 3), Flux.just(2, 4)) .as(StepVerifier::create) .verifyErrorMessage("boom"); } @Test @SuppressWarnings("unchecked") //safe varargs void naturalOrder() { new FluxMergeComparing<>(2, Comparator.naturalOrder(), false, true, Flux.just(1), Flux.just(2)) .as(StepVerifier::create) .expectNext(1, 2) .verifyComplete(); } @Test void mergeComparingNoErrorDelay() { Flux.mergeComparing(2, Comparator.naturalOrder(), Flux.error(new RuntimeException("boom")), Flux.<String>never()) .as(StepVerifier::create) .verifyErrorMessage("boom"); } @Test void mergeComparingNoErrorDelay2() { Flux.mergeComparing(1, Integer::compareTo, Flux.range(0, 20), Flux.range(0, 20) .<Integer>handle((v, sink) -> { if (v < 2) { sink.next(v); } else { sink.error(new RuntimeException("boom")); } })) .as(StepVerifier::create) .expectNext(0, 0, 1, 1) .verifyErrorMessage("boom"); } @Test void mergeComparingWithInheritErrorDelay() { Flux<String> fluxNoDelay = Flux.<String>error(new RuntimeException("boom")) .mergeComparingWith(Flux.never(), Comparator.naturalOrder()); FluxMergeComparing<String> fmoNoDelay = (FluxMergeComparing<String>) fluxNoDelay; assertThat(fmoNoDelay.delayError).as("delayError").isFalse(); Flux<String> fluxDelay = Flux.mergeComparingDelayError(2, Comparator.naturalOrder(), Flux.<String>error(new RuntimeException("boom")), Flux.never()) .mergeComparingWith(Flux.never(), Comparator.naturalOrder()); FluxMergeComparing<String> fmoDelay = (FluxMergeComparing<String>) fluxDelay; assertThat(fmoDelay.delayError).as("delayError fmoDelay").isTrue(); } @Test void mergeComparingWithOnNonMergeSourceDefaultsToNoDelay() { Flux<String> flux = Flux.<String>error(new RuntimeException("boom")) .mergeComparingWith(Flux.never(), Comparator.naturalOrder()); FluxMergeComparing<String> fmoNoDelay = (FluxMergeComparing<String>) flux; assertThat(fmoNoDelay.delayError).as("delayError").isFalse(); } @Test void shouldEmitAsyncValuesAsTheyArrive() { StepVerifier.withVirtualTime(() -> { Flux<Tuple2<String, Integer>> catsAreBetterThanDogs = Flux.just( "pickles", // 700 "leela", // 1400 "girl", // 2100 "meatloaf", // 2800 "henry" // 3500 ) .delayElements(Duration.ofMillis(700)) .map(s -> Tuples.of(s, 0)); Flux<Tuple2<String, Integer>> poorDogs = Flux.just( "spot", // 300 "barley", // 600 "goodboy", // 900 "sammy", // 1200 "doug" // 1500 ) .delayElements(Duration.ofMillis(300)) .map(s -> Tuples.of(s, 1)); return Flux.mergePriority(Comparator.comparing(Tuple2::getT2), catsAreBetterThanDogs, poorDogs) .map(Tuple2::getT1); }) .thenAwait(Duration.ofMillis(300))// 300 .expectNext("spot") .thenAwait(Duration.ofMillis(300)) // 600 .expectNext("barley") .thenAwait(Duration.ofMillis(100)) // 700 .expectNext("pickles") .thenAwait(Duration.ofMillis(200)) // 900 .expectNext("goodboy") .thenAwait(Duration.ofMillis(300)) // 1200 .expectNext("sammy") .thenAwait(Duration.ofMillis(200)) // 1400 .expectNext("leela") .thenAwait(Duration.ofMillis(100)) // 1500 .expectNext("doug") .thenAwait(Duration.ofMillis(600)) // 2100 .expectNext("girl") .thenAwait(Duration.ofMillis(700)) // 2800 .expectNext("meatloaf") .thenAwait(Duration.ofMillis(700)) // 3500 .expectNext("henry") .expectComplete() .verify(Duration.ofSeconds(5)); } }
User
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/CancellableTasksTests.java
{ "start": 5018, "end": 6948 }
class ____ extends AbstractTestNodesAction<CancellableNodesRequest, CancellableNodeRequest> { // True if the node operation should get stuck until its cancelled final boolean shouldBlock; final CountDownLatch actionStartedLatch; CancellableTestNodesAction( String actionName, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, boolean shouldBlock, CountDownLatch actionStartedLatch ) { super(actionName, threadPool, clusterService, transportService, CancellableNodeRequest::new); this.shouldBlock = shouldBlock; this.actionStartedLatch = actionStartedLatch; } @Override protected CancellableNodeRequest newNodeRequest(CancellableNodesRequest request) { return new CancellableNodeRequest(request); } @Override protected NodeResponse nodeOperation(CancellableNodeRequest request, Task task) { assert task instanceof CancellableTask; debugDelay("op1"); if (actionStartedLatch != null) { actionStartedLatch.countDown(); } debugDelay("op2"); if (shouldBlock) { // Simulate a job that takes forever to finish // Using periodic checks method to identify that the task was cancelled waitUntil(() -> { ((CancellableTask) task).ensureNotCancelled(); return false; }); fail("It should have thrown an exception"); } debugDelay("op4"); return new NodeResponse(clusterService.localNode()); } } /** * Simulates a cancellation listener and sets a flag to true if the task was cancelled */ static
CancellableTestNodesAction
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/ClientCookieEncoder.java
{ "start": 1375, "end": 2964 }
class ____ { /** * Encodes the specified cookie into a Cookie header value. * * @param name the cookie name * @param value the cookie value * @return a Rfc6265 style Cookie header value */ @Deprecated public static String encode(String name, String value) { return io.netty.handler.codec.http.cookie.ClientCookieEncoder.LAX.encode(name, value); } /** * Encodes the specified cookie into a Cookie header value. * * @param cookie the specified cookie * @return a Rfc6265 style Cookie header value */ @Deprecated public static String encode(Cookie cookie) { return io.netty.handler.codec.http.cookie.ClientCookieEncoder.LAX.encode(cookie); } /** * Encodes the specified cookies into a single Cookie header value. * * @param cookies some cookies * @return a Rfc6265 style Cookie header value, null if no cookies are passed. */ @Deprecated public static String encode(Cookie... cookies) { return io.netty.handler.codec.http.cookie.ClientCookieEncoder.LAX.encode(cookies); } /** * Encodes the specified cookies into a single Cookie header value. * * @param cookies some cookies * @return a Rfc6265 style Cookie header value, null if no cookies are passed. */ @Deprecated public static String encode(Iterable<Cookie> cookies) { return io.netty.handler.codec.http.cookie.ClientCookieEncoder.LAX.encode(cookies); } private ClientCookieEncoder() { // unused } }
ClientCookieEncoder
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/OAuth2TokenEndpointFilterTests.java
{ "start": 4446, "end": 39863 }
class ____ { private static final String DEFAULT_TOKEN_ENDPOINT_URI = "/oauth2/token"; private static final String REMOTE_ADDRESS = "remote-address"; private static final String ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"; private AuthenticationManager authenticationManager; private OAuth2TokenEndpointFilter filter; private final HttpMessageConverter<OAuth2Error> errorHttpResponseConverter = new OAuth2ErrorHttpMessageConverter(); private final HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenHttpResponseConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); @BeforeEach public void setUp() { this.authenticationManager = mock(AuthenticationManager.class); this.filter = new OAuth2TokenEndpointFilter(this.authenticationManager); } @AfterEach public void cleanup() { SecurityContextHolder.clearContext(); } @Test public void constructorWhenAuthenticationManagerNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new OAuth2TokenEndpointFilter(null, "tokenEndpointUri")) .withMessage("authenticationManager cannot be null"); } @Test public void constructorWhenTokenEndpointUriNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new OAuth2TokenEndpointFilter(this.authenticationManager, null)) .withMessage("tokenEndpointUri cannot be empty"); } @Test public void setAuthenticationDetailsSourceWhenNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> this.filter.setAuthenticationDetailsSource(null)) .withMessage("authenticationDetailsSource cannot be null"); } @Test public void setAuthenticationConverterWhenNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> this.filter.setAuthenticationConverter(null)) .withMessage("authenticationConverter cannot be null"); } @Test public void setAuthenticationSuccessHandlerWhenNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> this.filter.setAuthenticationSuccessHandler(null)) .withMessage("authenticationSuccessHandler cannot be null"); } @Test public void setAuthenticationFailureHandlerWhenNullThenThrowIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> this.filter.setAuthenticationFailureHandler(null)) .withMessage("authenticationFailureHandler cannot be null"); } @Test public void doFilterWhenNotTokenRequestThenNotProcessed() throws Exception { String requestUri = "/path"; MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri); request.setServletPath(requestUri); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test public void doFilterWhenTokenRequestGetThenNotProcessed() throws Exception { String requestUri = DEFAULT_TOKEN_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); request.setServletPath(requestUri); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verify(filterChain).doFilter(any(HttpServletRequest.class), any(HttpServletResponse.class)); } @Test public void doFilterWhenTokenRequestMissingGrantTypeThenInvalidRequestError() throws Exception { MockHttpServletRequest request = createAuthorizationCodeTokenRequest( TestRegisteredClients.registeredClient().build()); request.removeParameter(OAuth2ParameterNames.GRANT_TYPE); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2ParameterNames.GRANT_TYPE, OAuth2ErrorCodes.INVALID_REQUEST, request); } @Test public void doFilterWhenTokenRequestMultipleGrantTypeThenInvalidRequestError() throws Exception { MockHttpServletRequest request = createAuthorizationCodeTokenRequest( TestRegisteredClients.registeredClient().build()); request.addParameter(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.AUTHORIZATION_CODE.getValue()); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2ParameterNames.GRANT_TYPE, OAuth2ErrorCodes.INVALID_REQUEST, request); } @Test public void doFilterWhenTokenRequestInvalidGrantTypeThenUnsupportedGrantTypeError() throws Exception { MockHttpServletRequest request = createAuthorizationCodeTokenRequest( TestRegisteredClients.registeredClient().build()); request.setParameter(OAuth2ParameterNames.GRANT_TYPE, "invalid-grant-type"); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2ParameterNames.GRANT_TYPE, OAuth2ErrorCodes.UNSUPPORTED_GRANT_TYPE, request); } @Test public void doFilterWhenTokenRequestMissingCodeThenInvalidRequestError() throws Exception { MockHttpServletRequest request = createAuthorizationCodeTokenRequest( TestRegisteredClients.registeredClient().build()); request.removeParameter(OAuth2ParameterNames.CODE); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2ParameterNames.CODE, OAuth2ErrorCodes.INVALID_REQUEST, request); } @Test public void doFilterWhenTokenRequestMultipleCodeThenInvalidRequestError() throws Exception { MockHttpServletRequest request = createAuthorizationCodeTokenRequest( TestRegisteredClients.registeredClient().build()); request.addParameter(OAuth2ParameterNames.CODE, "code-2"); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2ParameterNames.CODE, OAuth2ErrorCodes.INVALID_REQUEST, request); } @Test public void doFilterWhenTokenRequestMultipleRedirectUriThenInvalidRequestError() throws Exception { MockHttpServletRequest request = createAuthorizationCodeTokenRequest( TestRegisteredClients.registeredClient().build()); request.addParameter(OAuth2ParameterNames.REDIRECT_URI, "https://example2.com"); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2ParameterNames.REDIRECT_URI, OAuth2ErrorCodes.INVALID_REQUEST, request); } @Test public void doFilterWhenTokenRequestMultipleDPoPHeaderThenInvalidRequestError() throws Exception { MockHttpServletRequest request = createAuthorizationCodeTokenRequest( TestRegisteredClients.registeredClient().build()); request.addHeader(OAuth2AccessToken.TokenType.DPOP.getValue(), "dpop-proof-jwt"); request.addHeader(OAuth2AccessToken.TokenType.DPOP.getValue(), "dpop-proof-jwt-2"); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2AccessToken.TokenType.DPOP.getValue(), OAuth2ErrorCodes.INVALID_REQUEST, request); } @Test public void doFilterWhenAuthorizationCodeTokenRequestThenAccessTokenResponse() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); Authentication clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1)), new HashSet<>(Arrays.asList("scope1", "scope2"))); OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", Instant.now(), Instant.now().plus(Duration.ofDays(1))); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken, refreshToken); given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); SecurityContextHolder.setContext(securityContext); MockHttpServletRequest request = createAuthorizationCodeTokenRequest(registeredClient); request.addHeader(OAuth2AccessToken.TokenType.DPOP.getValue(), "dpop-proof-jwt"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verifyNoInteractions(filterChain); ArgumentCaptor<OAuth2AuthorizationCodeAuthenticationToken> authorizationCodeAuthenticationCaptor = ArgumentCaptor .forClass(OAuth2AuthorizationCodeAuthenticationToken.class); verify(this.authenticationManager).authenticate(authorizationCodeAuthenticationCaptor.capture()); OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = authorizationCodeAuthenticationCaptor .getValue(); assertThat(authorizationCodeAuthentication.getCode()) .isEqualTo(request.getParameter(OAuth2ParameterNames.CODE)); assertThat(authorizationCodeAuthentication.getPrincipal()).isEqualTo(clientPrincipal); assertThat(authorizationCodeAuthentication.getRedirectUri()) .isEqualTo(request.getParameter(OAuth2ParameterNames.REDIRECT_URI)); Map<String, Object> expectedAdditionalParameters = new HashMap<>(); expectedAdditionalParameters.put("custom-param-1", "custom-value-1"); expectedAdditionalParameters.put("custom-param-2", new String[] { "custom-value-1", "custom-value-2" }); expectedAdditionalParameters.put("dpop_proof", "dpop-proof-jwt"); expectedAdditionalParameters.put("dpop_method", "POST"); expectedAdditionalParameters.put("dpop_target_uri", "http://localhost/oauth2/token"); assertThat(authorizationCodeAuthentication.getAdditionalParameters()) .containsExactlyInAnyOrderEntriesOf(expectedAdditionalParameters); assertThat(authorizationCodeAuthentication.getDetails()) .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); OAuth2AccessTokenResponse accessTokenResponse = readAccessTokenResponse(response); OAuth2AccessToken accessTokenResult = accessTokenResponse.getAccessToken(); assertThat(accessTokenResult.getTokenType()).isEqualTo(accessToken.getTokenType()); assertThat(accessTokenResult.getTokenValue()).isEqualTo(accessToken.getTokenValue()); assertThat(accessTokenResult.getIssuedAt()).isBetween(accessToken.getIssuedAt().minusSeconds(1), accessToken.getIssuedAt().plusSeconds(1)); assertThat(accessTokenResult.getExpiresAt()).isBetween(accessToken.getExpiresAt().minusSeconds(1), accessToken.getExpiresAt().plusSeconds(1)); assertThat(accessTokenResult.getScopes()).isEqualTo(accessToken.getScopes()); assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo(refreshToken.getTokenValue()); } @Test public void doFilterWhenClientCredentialsTokenRequestMultipleScopeThenInvalidRequestError() throws Exception { MockHttpServletRequest request = createClientCredentialsTokenRequest( TestRegisteredClients.registeredClient2().build()); request.addParameter(OAuth2ParameterNames.SCOPE, "profile"); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2ParameterNames.SCOPE, OAuth2ErrorCodes.INVALID_REQUEST, request); } @Test public void doFilterWhenClientCredentialsTokenRequestThenAccessTokenResponse() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient2().build(); Authentication clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1)), new HashSet<>(Arrays.asList("scope1", "scope2"))); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); SecurityContextHolder.setContext(securityContext); MockHttpServletRequest request = createClientCredentialsTokenRequest(registeredClient); request.addHeader(OAuth2AccessToken.TokenType.DPOP.getValue(), "dpop-proof-jwt"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verifyNoInteractions(filterChain); ArgumentCaptor<OAuth2ClientCredentialsAuthenticationToken> clientCredentialsAuthenticationCaptor = ArgumentCaptor .forClass(OAuth2ClientCredentialsAuthenticationToken.class); verify(this.authenticationManager).authenticate(clientCredentialsAuthenticationCaptor.capture()); OAuth2ClientCredentialsAuthenticationToken clientCredentialsAuthentication = clientCredentialsAuthenticationCaptor .getValue(); assertThat(clientCredentialsAuthentication.getPrincipal()).isEqualTo(clientPrincipal); assertThat(clientCredentialsAuthentication.getScopes()).isEqualTo(registeredClient.getScopes()); Map<String, Object> expectedAdditionalParameters = new HashMap<>(); expectedAdditionalParameters.put("custom-param-1", "custom-value-1"); expectedAdditionalParameters.put("custom-param-2", new String[] { "custom-value-1", "custom-value-2" }); expectedAdditionalParameters.put("dpop_proof", "dpop-proof-jwt"); expectedAdditionalParameters.put("dpop_method", "POST"); expectedAdditionalParameters.put("dpop_target_uri", "http://localhost/oauth2/token"); assertThat(clientCredentialsAuthentication.getAdditionalParameters()) .containsExactlyInAnyOrderEntriesOf(expectedAdditionalParameters); assertThat(clientCredentialsAuthentication.getDetails()) .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); // For gh-281, check that expires_in is a number assertThat(new ObjectMapper().readValue(response.getContentAsByteArray(), Map.class) .get(OAuth2ParameterNames.EXPIRES_IN)).isInstanceOf(Number.class); OAuth2AccessTokenResponse accessTokenResponse = readAccessTokenResponse(response); OAuth2AccessToken accessTokenResult = accessTokenResponse.getAccessToken(); assertThat(accessTokenResult.getTokenType()).isEqualTo(accessToken.getTokenType()); assertThat(accessTokenResult.getTokenValue()).isEqualTo(accessToken.getTokenValue()); assertThat(accessTokenResult.getIssuedAt()).isBetween(accessToken.getIssuedAt().minusSeconds(1), accessToken.getIssuedAt().plusSeconds(1)); assertThat(accessTokenResult.getExpiresAt()).isBetween(accessToken.getExpiresAt().minusSeconds(1), accessToken.getExpiresAt().plusSeconds(1)); assertThat(accessTokenResult.getScopes()).isEqualTo(accessToken.getScopes()); } @Test public void doFilterWhenRefreshTokenRequestMissingRefreshTokenThenInvalidRequestError() throws Exception { MockHttpServletRequest request = createRefreshTokenTokenRequest( TestRegisteredClients.registeredClient().build()); request.removeParameter(OAuth2ParameterNames.REFRESH_TOKEN); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2ParameterNames.REFRESH_TOKEN, OAuth2ErrorCodes.INVALID_REQUEST, request); } @Test public void doFilterWhenRefreshTokenRequestMultipleRefreshTokenThenInvalidRequestError() throws Exception { MockHttpServletRequest request = createRefreshTokenTokenRequest( TestRegisteredClients.registeredClient().build()); request.addParameter(OAuth2ParameterNames.REFRESH_TOKEN, "refresh-token-2"); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2ParameterNames.REFRESH_TOKEN, OAuth2ErrorCodes.INVALID_REQUEST, request); } @Test public void doFilterWhenRefreshTokenRequestMultipleScopeThenInvalidRequestError() throws Exception { MockHttpServletRequest request = createRefreshTokenTokenRequest( TestRegisteredClients.registeredClient().build()); request.addParameter(OAuth2ParameterNames.SCOPE, "profile"); doFilterWhenTokenRequestInvalidParameterThenError(OAuth2ParameterNames.SCOPE, OAuth2ErrorCodes.INVALID_REQUEST, request); } @Test public void doFilterWhenRefreshTokenRequestThenAccessTokenResponse() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); Authentication clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1)), new HashSet<>(Arrays.asList("scope1", "scope2"))); OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", Instant.now()); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken, refreshToken); given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); SecurityContextHolder.setContext(securityContext); MockHttpServletRequest request = createRefreshTokenTokenRequest(registeredClient); request.addHeader(OAuth2AccessToken.TokenType.DPOP.getValue(), "dpop-proof-jwt"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verifyNoInteractions(filterChain); ArgumentCaptor<OAuth2RefreshTokenAuthenticationToken> refreshTokenAuthenticationCaptor = ArgumentCaptor .forClass(OAuth2RefreshTokenAuthenticationToken.class); verify(this.authenticationManager).authenticate(refreshTokenAuthenticationCaptor.capture()); OAuth2RefreshTokenAuthenticationToken refreshTokenAuthenticationToken = refreshTokenAuthenticationCaptor .getValue(); assertThat(refreshTokenAuthenticationToken.getRefreshToken()).isEqualTo(refreshToken.getTokenValue()); assertThat(refreshTokenAuthenticationToken.getPrincipal()).isEqualTo(clientPrincipal); assertThat(refreshTokenAuthenticationToken.getScopes()).isEqualTo(registeredClient.getScopes()); Map<String, Object> expectedAdditionalParameters = new HashMap<>(); expectedAdditionalParameters.put("custom-param-1", "custom-value-1"); expectedAdditionalParameters.put("custom-param-2", new String[] { "custom-value-1", "custom-value-2" }); expectedAdditionalParameters.put("dpop_proof", "dpop-proof-jwt"); expectedAdditionalParameters.put("dpop_method", "POST"); expectedAdditionalParameters.put("dpop_target_uri", "http://localhost/oauth2/token"); assertThat(refreshTokenAuthenticationToken.getAdditionalParameters()) .containsExactlyInAnyOrderEntriesOf(expectedAdditionalParameters); assertThat(refreshTokenAuthenticationToken.getDetails()) .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); OAuth2AccessTokenResponse accessTokenResponse = readAccessTokenResponse(response); OAuth2AccessToken accessTokenResult = accessTokenResponse.getAccessToken(); assertThat(accessTokenResult.getTokenType()).isEqualTo(accessToken.getTokenType()); assertThat(accessTokenResult.getTokenValue()).isEqualTo(accessToken.getTokenValue()); assertThat(accessTokenResult.getIssuedAt()).isBetween(accessToken.getIssuedAt().minusSeconds(1), accessToken.getIssuedAt().plusSeconds(1)); assertThat(accessTokenResult.getExpiresAt()).isBetween(accessToken.getExpiresAt().minusSeconds(1), accessToken.getExpiresAt().plusSeconds(1)); assertThat(accessTokenResult.getScopes()).isEqualTo(accessToken.getScopes()); OAuth2RefreshToken refreshTokenResult = accessTokenResponse.getRefreshToken(); assertThat(refreshTokenResult.getTokenValue()).isEqualTo(refreshToken.getTokenValue()); } @Test public void doFilterWhenTokenExchangeRequestThenAccessTokenResponse() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient() .authorizationGrantType(AuthorizationGrantType.TOKEN_EXCHANGE) .build(); Authentication clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1)), new HashSet<>(Arrays.asList("scope1", "scope2"))); OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", Instant.now()); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken, refreshToken); given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); SecurityContextHolder.setContext(securityContext); MockHttpServletRequest request = createTokenExchangeTokenRequest(registeredClient); request.addHeader(OAuth2AccessToken.TokenType.DPOP.getValue(), "dpop-proof-jwt"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verifyNoInteractions(filterChain); ArgumentCaptor<OAuth2TokenExchangeAuthenticationToken> tokenExchangeAuthenticationCaptor = ArgumentCaptor .forClass(OAuth2TokenExchangeAuthenticationToken.class); verify(this.authenticationManager).authenticate(tokenExchangeAuthenticationCaptor.capture()); OAuth2TokenExchangeAuthenticationToken tokenExchangeAuthenticationToken = tokenExchangeAuthenticationCaptor .getValue(); assertThat(tokenExchangeAuthenticationToken.getSubjectToken()).isEqualTo("subject-token"); assertThat(tokenExchangeAuthenticationToken.getSubjectTokenType()).isEqualTo(ACCESS_TOKEN_TYPE); assertThat(tokenExchangeAuthenticationToken.getPrincipal()).isEqualTo(clientPrincipal); assertThat(tokenExchangeAuthenticationToken.getScopes()).isEqualTo(registeredClient.getScopes()); Map<String, Object> expectedAdditionalParameters = new HashMap<>(); expectedAdditionalParameters.put("custom-param-1", "custom-value-1"); expectedAdditionalParameters.put("custom-param-2", new String[] { "custom-value-1", "custom-value-2" }); expectedAdditionalParameters.put("dpop_proof", "dpop-proof-jwt"); expectedAdditionalParameters.put("dpop_method", "POST"); expectedAdditionalParameters.put("dpop_target_uri", "http://localhost/oauth2/token"); assertThat(tokenExchangeAuthenticationToken.getAdditionalParameters()) .containsExactlyInAnyOrderEntriesOf(expectedAdditionalParameters); assertThat(tokenExchangeAuthenticationToken.getDetails()) .asInstanceOf(InstanceOfAssertFactories.type(WebAuthenticationDetails.class)) .extracting(WebAuthenticationDetails::getRemoteAddress) .isEqualTo(REMOTE_ADDRESS); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); OAuth2AccessTokenResponse accessTokenResponse = readAccessTokenResponse(response); OAuth2AccessToken accessTokenResult = accessTokenResponse.getAccessToken(); assertThat(accessTokenResult.getTokenType()).isEqualTo(accessToken.getTokenType()); assertThat(accessTokenResult.getTokenValue()).isEqualTo(accessToken.getTokenValue()); assertThat(accessTokenResult.getIssuedAt()).isBetween(accessToken.getIssuedAt().minusSeconds(1), accessToken.getIssuedAt().plusSeconds(1)); assertThat(accessTokenResult.getExpiresAt()).isBetween(accessToken.getExpiresAt().minusSeconds(1), accessToken.getExpiresAt().plusSeconds(1)); assertThat(accessTokenResult.getScopes()).isEqualTo(accessToken.getScopes()); OAuth2RefreshToken refreshTokenResult = accessTokenResponse.getRefreshToken(); assertThat(refreshTokenResult.getTokenValue()).isEqualTo(refreshToken.getTokenValue()); } @Test public void doFilterWhenCustomAuthenticationDetailsSourceThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); Authentication clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); MockHttpServletRequest request = createAuthorizationCodeTokenRequest(registeredClient); AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource = mock( AuthenticationDetailsSource.class); WebAuthenticationDetails webAuthenticationDetails = new WebAuthenticationDetails(request); given(authenticationDetailsSource.buildDetails(any())).willReturn(webAuthenticationDetails); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1)), new HashSet<>(Arrays.asList("scope1", "scope2"))); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); SecurityContextHolder.setContext(securityContext); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verify(authenticationDetailsSource).buildDetails(any()); } @Test public void doFilterWhenCustomAuthenticationConverterThenUsed() throws Exception { RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); Authentication clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = new OAuth2AuthorizationCodeAuthenticationToken( "code", clientPrincipal, null, null); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); given(authenticationConverter.convert(any())).willReturn(authorizationCodeAuthentication); this.filter.setAuthenticationConverter(authenticationConverter); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1)), new HashSet<>(Arrays.asList("scope1", "scope2"))); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); SecurityContextHolder.setContext(securityContext); MockHttpServletRequest request = createAuthorizationCodeTokenRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verify(authenticationConverter).convert(any()); } @Test public void doFilterWhenCustomAuthenticationSuccessHandlerThenUsed() throws Exception { AuthenticationSuccessHandler authenticationSuccessHandler = mock(AuthenticationSuccessHandler.class); this.filter.setAuthenticationSuccessHandler(authenticationSuccessHandler); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); Authentication clientPrincipal = new OAuth2ClientAuthenticationToken(registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, registeredClient.getClientSecret()); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plus(Duration.ofHours(1)), new HashSet<>(Arrays.asList("scope1", "scope2"))); OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = new OAuth2AccessTokenAuthenticationToken( registeredClient, clientPrincipal, accessToken); given(this.authenticationManager.authenticate(any())).willReturn(accessTokenAuthentication); SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); securityContext.setAuthentication(clientPrincipal); SecurityContextHolder.setContext(securityContext); MockHttpServletRequest request = createAuthorizationCodeTokenRequest(registeredClient); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verify(authenticationSuccessHandler).onAuthenticationSuccess(any(), any(), any()); } @Test public void doFilterWhenCustomAuthenticationFailureHandlerThenUsed() throws Exception { AuthenticationFailureHandler authenticationFailureHandler = mock(AuthenticationFailureHandler.class); this.filter.setAuthenticationFailureHandler(authenticationFailureHandler); RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); MockHttpServletRequest request = createAuthorizationCodeTokenRequest(registeredClient); request.removeParameter(OAuth2ParameterNames.GRANT_TYPE); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verify(authenticationFailureHandler).onAuthenticationFailure(any(), any(), any()); } private void doFilterWhenTokenRequestInvalidParameterThenError(String parameterName, String errorCode, MockHttpServletRequest request) throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.filter.doFilter(request, response, filterChain); verifyNoInteractions(filterChain); assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); OAuth2Error error = readError(response); assertThat(error.getErrorCode()).isEqualTo(errorCode); assertThat(error.getDescription()).isEqualTo("OAuth 2.0 Parameter: " + parameterName); } private OAuth2Error readError(MockHttpServletResponse response) throws Exception { MockClientHttpResponse httpResponse = new MockClientHttpResponse(response.getContentAsByteArray(), HttpStatus.valueOf(response.getStatus())); return this.errorHttpResponseConverter.read(OAuth2Error.class, httpResponse); } private OAuth2AccessTokenResponse readAccessTokenResponse(MockHttpServletResponse response) throws Exception { MockClientHttpResponse httpResponse = new MockClientHttpResponse(response.getContentAsByteArray(), HttpStatus.valueOf(response.getStatus())); return this.accessTokenHttpResponseConverter.read(OAuth2AccessTokenResponse.class, httpResponse); } private static MockHttpServletRequest createAuthorizationCodeTokenRequest(RegisteredClient registeredClient) { String[] redirectUris = registeredClient.getRedirectUris().toArray(new String[0]); String requestUri = DEFAULT_TOKEN_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri); request.setServletPath(requestUri); request.setRemoteAddr(REMOTE_ADDRESS); request.addParameter(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.AUTHORIZATION_CODE.getValue()); request.addParameter(OAuth2ParameterNames.CODE, "code"); request.addParameter(OAuth2ParameterNames.REDIRECT_URI, redirectUris[0]); // The client does not need to send the client ID param, but we are resilient in // case they do request.addParameter(OAuth2ParameterNames.CLIENT_ID, registeredClient.getClientId()); request.addParameter("custom-param-1", "custom-value-1"); request.addParameter("custom-param-2", "custom-value-1", "custom-value-2"); return request; } private static MockHttpServletRequest createClientCredentialsTokenRequest(RegisteredClient registeredClient) { String requestUri = DEFAULT_TOKEN_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri); request.setServletPath(requestUri); request.setRemoteAddr(REMOTE_ADDRESS); request.addParameter(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()); request.addParameter(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); request.addParameter("custom-param-1", "custom-value-1"); request.addParameter("custom-param-2", "custom-value-1", "custom-value-2"); return request; } private static MockHttpServletRequest createRefreshTokenTokenRequest(RegisteredClient registeredClient) { String requestUri = DEFAULT_TOKEN_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri); request.setServletPath(requestUri); request.setRemoteAddr(REMOTE_ADDRESS); request.addParameter(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue()); request.addParameter(OAuth2ParameterNames.REFRESH_TOKEN, "refresh-token"); request.addParameter(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); request.addParameter("custom-param-1", "custom-value-1"); request.addParameter("custom-param-2", "custom-value-1", "custom-value-2"); return request; } private static MockHttpServletRequest createTokenExchangeTokenRequest(RegisteredClient registeredClient) { String requestUri = DEFAULT_TOKEN_ENDPOINT_URI; MockHttpServletRequest request = new MockHttpServletRequest("POST", requestUri); request.setServletPath(requestUri); request.setRemoteAddr(REMOTE_ADDRESS); request.addParameter(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.TOKEN_EXCHANGE.getValue()); request.addParameter(OAuth2ParameterNames.SUBJECT_TOKEN, "subject-token"); request.addParameter(OAuth2ParameterNames.SUBJECT_TOKEN_TYPE, ACCESS_TOKEN_TYPE); request.addParameter(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(registeredClient.getScopes(), " ")); request.addParameter("custom-param-1", "custom-value-1"); request.addParameter("custom-param-2", "custom-value-1", "custom-value-2"); return request; } }
OAuth2TokenEndpointFilterTests
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CouchDbEndpointBuilderFactory.java
{ "start": 16962, "end": 19536 }
interface ____ extends EndpointProducerBuilder { default CouchDbEndpointProducerBuilder basic() { return (CouchDbEndpointProducerBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedCouchDbEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedCouchDbEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } } /** * Builder for endpoint for the CouchDB component. */ public
AdvancedCouchDbEndpointProducerBuilder
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/subjects/AsyncSubjectTest.java
{ "start": 7931, "end": 15442 }
class ____ extends Thread { private final AsyncSubject<String> subject; private final AtomicReference<String> value = new AtomicReference<>(); SubjectSubscriberThread(AsyncSubject<String> subject) { this.subject = subject; } @Override public void run() { try { // a timeout exception will happen if we don't get a terminal state String v = subject.timeout(2000, TimeUnit.MILLISECONDS).blockingSingle(); value.set(v); } catch (Exception e) { e.printStackTrace(); } } } @Test public void currentStateMethodsNormal() { AsyncSubject<Object> as = AsyncSubject.create(); assertFalse(as.hasValue()); assertFalse(as.hasThrowable()); assertFalse(as.hasComplete()); assertNull(as.getValue()); assertNull(as.getThrowable()); as.onNext(1); assertFalse(as.hasValue()); // AS no longer reports a value until it has completed assertFalse(as.hasThrowable()); assertFalse(as.hasComplete()); assertNull(as.getValue()); // AS no longer reports a value until it has completed assertNull(as.getThrowable()); as.onComplete(); assertTrue(as.hasValue()); assertFalse(as.hasThrowable()); assertTrue(as.hasComplete()); assertEquals(1, as.getValue()); assertNull(as.getThrowable()); } @Test public void currentStateMethodsEmpty() { AsyncSubject<Object> as = AsyncSubject.create(); assertFalse(as.hasValue()); assertFalse(as.hasThrowable()); assertFalse(as.hasComplete()); assertNull(as.getValue()); assertNull(as.getThrowable()); as.onComplete(); assertFalse(as.hasValue()); assertFalse(as.hasThrowable()); assertTrue(as.hasComplete()); assertNull(as.getValue()); assertNull(as.getThrowable()); } @Test public void currentStateMethodsError() { AsyncSubject<Object> as = AsyncSubject.create(); assertFalse(as.hasValue()); assertFalse(as.hasThrowable()); assertFalse(as.hasComplete()); assertNull(as.getValue()); assertNull(as.getThrowable()); as.onError(new TestException()); assertFalse(as.hasValue()); assertTrue(as.hasThrowable()); assertFalse(as.hasComplete()); assertNull(as.getValue()); assertTrue(as.getThrowable() instanceof TestException); } @Test public void fusionLive() { AsyncSubject<Integer> ap = new AsyncSubject<>(); TestObserverEx<Integer> to = ap.to(TestHelper.<Integer>testConsumer(false, QueueFuseable.ANY)); to.assertFuseable() .assertFusionMode(QueueFuseable.ASYNC); to.assertNoValues().assertNoErrors().assertNotComplete(); ap.onNext(1); to.assertNoValues().assertNoErrors().assertNotComplete(); ap.onComplete(); to.assertResult(1); } @Test public void fusionOfflie() { AsyncSubject<Integer> ap = new AsyncSubject<>(); ap.onNext(1); ap.onComplete(); TestObserverEx<Integer> to = ap.to(TestHelper.<Integer>testConsumer(false, QueueFuseable.ANY)); to.assertFuseable() .assertFusionMode(QueueFuseable.ASYNC) .assertResult(1); } @Test public void onSubscribeAfterDone() { AsyncSubject<Object> p = AsyncSubject.create(); Disposable bs = Disposable.empty(); p.onSubscribe(bs); assertFalse(bs.isDisposed()); p.onComplete(); bs = Disposable.empty(); p.onSubscribe(bs); assertTrue(bs.isDisposed()); p.test().assertResult(); } @Test public void cancelUpfront() { AsyncSubject<Object> p = AsyncSubject.create(); assertFalse(p.hasObservers()); p.test().assertEmpty(); p.test().assertEmpty(); p.test(true).assertEmpty(); assertTrue(p.hasObservers()); } @Test public void cancelRace() { AsyncSubject<Object> p = AsyncSubject.create(); for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestObserver<Object> to1 = p.test(); final TestObserver<Object> to2 = p.test(); Runnable r1 = new Runnable() { @Override public void run() { to1.dispose(); } }; Runnable r2 = new Runnable() { @Override public void run() { to2.dispose(); } }; TestHelper.race(r1, r2); } } @Test @SuppressUndeliverable public void onErrorCancelRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AsyncSubject<Object> p = AsyncSubject.create(); final TestObserverEx<Object> to1 = p.to(TestHelper.testConsumer()); Runnable r1 = new Runnable() { @Override public void run() { to1.dispose(); } }; final TestException ex = new TestException(); Runnable r2 = new Runnable() { @Override public void run() { p.onError(ex); } }; TestHelper.race(r1, r2); if (to1.errors().size() != 0) { to1.assertFailure(TestException.class); } else { to1.assertEmpty(); } } } @Test public void onNextCrossCancel() { AsyncSubject<Object> p = AsyncSubject.create(); final TestObserver<Object> to2 = new TestObserver<>(); TestObserver<Object> to1 = new TestObserver<Object>() { @Override public void onNext(Object t) { to2.dispose(); super.onNext(t); } }; p.subscribe(to1); p.subscribe(to2); p.onNext(1); p.onComplete(); to1.assertResult(1); to2.assertEmpty(); } @Test @SuppressUndeliverable public void onErrorCrossCancel() { AsyncSubject<Object> p = AsyncSubject.create(); final TestObserver<Object> to2 = new TestObserver<>(); TestObserver<Object> to1 = new TestObserver<Object>() { @Override public void onError(Throwable t) { to2.dispose(); super.onError(t); } }; p.subscribe(to1); p.subscribe(to2); p.onError(new TestException()); to1.assertFailure(TestException.class); to2.assertEmpty(); } @Test public void onCompleteCrossCancel() { AsyncSubject<Object> p = AsyncSubject.create(); final TestObserver<Object> to2 = new TestObserver<>(); TestObserver<Object> to1 = new TestObserver<Object>() { @Override public void onComplete() { to2.dispose(); super.onComplete(); } }; p.subscribe(to1); p.subscribe(to2); p.onComplete(); to1.assertResult(); to2.assertEmpty(); } @Test public void dispose() { TestHelper.checkDisposed(AsyncSubject.create()); } }
SubjectSubscriberThread
java
apache__camel
components/camel-cxf/camel-cxf-rest/src/test/java/org/apache/camel/component/cxf/jaxrs/simplebinding/testbean/Order.java
{ "start": 1098, "end": 1901 }
class ____ { private long id; private String description; private Map<Long, Product> products = new HashMap<>(); public Order() { init(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescription() { return description; } public void setDescription(String d) { this.description = d; } @GET @Path("products/{productId}/") public Product getProduct(@PathParam("productId") int productId) { Product p = products.get(Long.valueOf(productId)); return p; } final void init() { Product p = new Product(); p.setId(323); p.setDescription("product 323"); products.put(p.getId(), p); } }
Order
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/WatsonLanguageEndpointBuilderFactory.java
{ "start": 1478, "end": 1622 }
interface ____ { /** * Builder for endpoint for the IBM Watson Language component. */ public
WatsonLanguageEndpointBuilderFactory
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ProjectArtifactFactory.java
{ "start": 1306, "end": 1441 }
interface ____ { Set<Artifact> createArtifacts(MavenProject project) throws InvalidDependencyVersionException; }
ProjectArtifactFactory
java
google__guava
android/guava/src/com/google/common/collect/Collections2.java
{ "start": 1965, "end": 4925 }
class ____ { private Collections2() {} /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The returned collection is * a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting collection's iterator does not support {@code remove()}, but all other * collection methods are supported. When given an element that doesn't satisfy the predicate, the * collection's {@code add()} and {@code addAll()} methods throw an {@link * IllegalArgumentException}. When methods such as {@code removeAll()} and {@code clear()} are * called on the filtered collection, only elements that satisfy the filter will be removed from * the underlying collection. * * <p>The returned collection isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered collection's methods, such as {@code size()}, iterate across every * element in the underlying collection and determine which elements satisfy the filter. When a * live view is <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, * predicate)} and use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link * Iterables#filter(Iterable, Class)} for related functionality.) * * <p><b>{@code Stream} equivalent:</b> {@link java.util.stream.Stream#filter Stream.filter}. */ public static <E extends @Nullable Object> Collection<E> filter( Collection<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredCollection) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. return ((FilteredCollection<E>) unfiltered).createCombined(predicate); } return new FilteredCollection<>(checkNotNull(unfiltered), checkNotNull(predicate)); } /** * Delegates to {@link Collection#contains}. Returns {@code false} if the {@code contains} method * throws a {@code ClassCastException} or {@code NullPointerException}. */ static boolean safeContains(Collection<?> collection, @Nullable Object object) { checkNotNull(collection); try { return collection.contains(object); } catch (ClassCastException | NullPointerException e) { return false; } } /** * Delegates to {@link Collection#remove}. Returns {@code false} if the {@code remove} method * throws a {@code ClassCastException} or {@code NullPointerException}. */ static boolean safeRemove(Collection<?> collection, @Nullable Object object) { checkNotNull(collection); try { return collection.remove(object); } catch (ClassCastException | NullPointerException e) { return false; } } static
Collections2
java
apache__camel
components/camel-opentelemetry-metrics/src/test/java/org/apache/camel/opentelemetry/metrics/eventnotifier/OpenTelemetryExchangeEventNotifierDynamicTest.java
{ "start": 2096, "end": 4565 }
class ____ extends AbstractOpenTelemetryTest { @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); OpenTelemetryExchangeEventNotifier eventNotifier = getEventNotifier(); context.getManagementStrategy().addEventNotifier(eventNotifier); eventNotifier.init(); return context; } protected OpenTelemetryExchangeEventNotifier getEventNotifier() { OpenTelemetryExchangeEventNotifier eventNotifier = new OpenTelemetryExchangeEventNotifier(); eventNotifier.setMeter(otelExtension.getOpenTelemetry().getMeter("meterTest")); // create metrics for each dynamic endpoint URI eventNotifier.setBaseEndpointURI(false); return eventNotifier; } @Test public void testEventNotifier() throws Exception { int count = 10; MockEndpoint mock = getMockEndpoint("mock://out"); mock.expectedMessageCount(count); for (int i = 0; i < count; i++) { template.sendBody("direct://in", i); } mock.assertIsSatisfied(); int nameCount = 0; for (PointData pd : getAllPointDataForRouteId(DEFAULT_CAMEL_EXCHANGE_SENT_TIMER, "test")) { String name = pd.getAttributes().get(stringKey(ENDPOINT_NAME_ATTRIBUTE)); // should have recorded metrics for each dynamic endpoint name, e.g. mc://component?clear=val-0&password=xxxxxx if (name != null && name.startsWith("mc://component")) { nameCount++; assertInstanceOf(HistogramPointData.class, pd); HistogramPointData hpd = (HistogramPointData) pd; assertEquals(1, hpd.getCount()); } } assertEquals(count, nameCount, "number of 'mc://component' endpoints should equal the number of exchanges."); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct://in") .routeId("test") .toD("mc:component?clear=val-${body}&password=secret-${body}") .to("mock://out"); } }; } @Override protected void bindToRegistry(Registry registry) { registry.bind("mc", new MyComponent()); } private
OpenTelemetryExchangeEventNotifierDynamicTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClientWithReservation.java
{ "start": 3826, "end": 4112 }
class ____ { protected final static String TEST_DIR = new File(System.getProperty("test.build.data", "/tmp")).getAbsolutePath(); protected final static String FS_ALLOC_FILE = new File(TEST_DIR, "test-fs-queues.xml").getAbsolutePath(); public
TestYarnClientWithReservation
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/AbstractCompositeIdMapper.java
{ "start": 735, "end": 2779 }
class ____ extends AbstractIdMapper implements SimpleIdMapperBuilder { protected final CompositeTypeImplementor compositeType; protected Map<PropertyData, AbstractIdMapper> ids; protected AbstractCompositeIdMapper(Component component) { this( component.getServiceRegistry(), (CompositeTypeImplementor) component.getType() ); } protected AbstractCompositeIdMapper(ServiceRegistry serviceRegistry, CompositeTypeImplementor compositeType) { super( serviceRegistry ); this.compositeType = compositeType; ids = Tools.newLinkedHashMap(); } @Override public void add(PropertyData propertyData) { add( propertyData, new SingleIdMapper( getServiceRegistry(), propertyData ) ); } @Override public void add(PropertyData propertyData, AbstractIdMapper idMapper) { ids.put( propertyData, idMapper ); } @Override public Object mapToIdFromMap(Map data) { if ( data == null ) { return null; } if ( !compositeType.isMutable() ) { return mapToImmutableIdFromMap( data ); } final Object compositeId = instantiateCompositeId( null ); if ( compositeType.isMutable() ) { for ( AbstractIdMapper mapper : ids.values() ) { if ( !mapper.mapToEntityFromMap( compositeId, data ) ) { return null; } } } return compositeId; } protected Object mapToImmutableIdFromMap(Map data) { final var propertyNames = compositeType.getPropertyNames(); final var values = new Object[propertyNames.length]; for ( int i = 0; i < propertyNames.length; i++ ) { values[i] = data.get( propertyNames[i] ); } return instantiateCompositeId( values ); } @Override public void mapToEntityFromEntity(Object objectTo, Object objectFrom) { // no-op; does nothing } protected Object instantiateCompositeId(Object[] values) { try { return compositeType.getMappingModelPart() .getEmbeddableTypeDescriptor() .getRepresentationStrategy() .getInstantiator() .instantiate( () -> values ); } catch ( Exception e ) { throw new AuditException( e ); } } }
AbstractCompositeIdMapper
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedExceptionTest.java
{ "start": 1890, "end": 2335 }
class ____ { void test() { try { } catch (Exception e) { if (equals(this)) { throw new RuntimeException(toString()); } else { throw new RuntimeException(); } } } } """) .addOutputLines( "out/Test.java", """
Test
java
apache__camel
components/camel-cxf/camel-cxf-spring-transport/src/main/java/org/apache/camel/component/cxf/spring/transport/CamelConduitDefinitionParser.java
{ "start": 931, "end": 1113 }
class ____ extends AbstractCamelContextBeanDefinitionParser { public CamelConduitDefinitionParser() { setBeanClass(CamelConduit.class); } }
CamelConduitDefinitionParser
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/records/DeleteSubClusterPoliciesConfigurationsRequest.java
{ "start": 1155, "end": 1277 }
class ____ used to respond to queue deletion requests and contains a list of queues. */ @Private @Unstable public abstract
is
java
apache__camel
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/ExplicitHttpsSslContextParametersRouteTest.java
{ "start": 1324, "end": 3268 }
class ____ extends HttpsRouteTest { // START SNIPPET: e2 private Connector createSslSocketConnector(CamelContext context, int port) { KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource("file://" + this.getClass().getClassLoader().getResource("jsse/localhost.p12").toString()); ksp.setPassword(pwd); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyPassword(pwd); kmp.setKeyStore(ksp); SSLContextParameters sslContextParameters = new SSLContextParameters(); sslContextParameters.setKeyManagers(kmp); return null; } // END SNIPPET: e2 @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: e1 // create SSL select channel connectors for port 9080 and 9090 Map<Integer, Connector> connectors = new HashMap<>(); connectors.put(port1.getPort(), createSslSocketConnector(getContext(), port1.getPort())); connectors.put(port2.getPort(), createSslSocketConnector(getContext(), port2.getPort())); JettyHttpComponent jetty = getContext().getComponent("jetty", JettyHttpComponent.class); jetty.setSslSocketConnectors(connectors); // END SNIPPET: e1 from("jetty:https://localhost:" + port1 + "/test").to("mock:a"); Processor proc = new Processor() { public void process(Exchange exchange) { exchange.getMessage().setBody("<b>Hello World</b>"); } }; from("jetty:https://localhost:" + port1 + "/hello").process(proc); from("jetty:https://localhost:" + port2 + "/test").to("mock:b"); } }; } }
ExplicitHttpsSslContextParametersRouteTest
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/WebApplicationType.java
{ "start": 2428, "end": 3203 }
class ____ implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { for (String servletIndicatorClass : SERVLET_INDICATOR_CLASSES) { registerTypeIfPresent(servletIndicatorClass, classLoader, hints); } registerTypeIfPresent(JERSEY_INDICATOR_CLASS, classLoader, hints); registerTypeIfPresent(WEBFLUX_INDICATOR_CLASS, classLoader, hints); registerTypeIfPresent(WEBMVC_INDICATOR_CLASS, classLoader, hints); } private void registerTypeIfPresent(String typeName, @Nullable ClassLoader classLoader, RuntimeHints hints) { if (ClassUtils.isPresent(typeName, classLoader)) { hints.reflection().registerType(TypeReference.of(typeName)); } } } }
WebApplicationTypeRuntimeHints
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 15445, "end": 15661 }
class ____ { public abstract Object superObject(); public abstract boolean superBoolean(); // The above two are out of alphabetical order to test EclipseHack. } @AutoValue public abstract static
Super
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java
{ "start": 18019, "end": 18091 }
class ____ output the twelve hour field. */ private static final
to
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/stateless/StatelessSessionStatisticsTest.java
{ "start": 1264, "end": 5216 }
class ____ { @Test void test(SessionFactoryScope scope) { final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); final Dialect dialect = scope.fromSession( session -> session.getDialect() ); final boolean isSybaseOrMysql = dialect.getClass().getName().toLowerCase( Locale.ROOT ).split( "sybase|mysql" ).length == 2; int stmtCount = isSybaseOrMysql ? 4 : 3; assertEquals(0, statistics.getEntityInsertCount()); assertEquals(0, statistics.getEntityUpdateCount()); assertEquals(0, statistics.getEntityDeleteCount()); assertEquals(0, statistics.getEntityLoadCount()); assertEquals(0, statistics.getPrepareStatementCount()); Person person = new Person(); person.name = "Gavin"; person.handles.add("@1ovthafew"); scope.inStatelessTransaction(s -> s.insert(person)); assertEquals(1, statistics.getEntityInsertCount()); assertEquals(1, statistics.getCollectionRecreateCount()); assertEquals(stmtCount, statistics.getPrepareStatementCount()); assertEquals(stmtCount, statistics.getCloseStatementCount()); scope.inStatelessSession(s -> s.get(Person.class, person.id)); assertEquals(1, statistics.getEntityLoadCount()); assertEquals(0, statistics.getEntityFetchCount()); assertEquals(1, statistics.getCollectionLoadCount()); assertEquals(0, statistics.getCollectionFetchCount()); assertEquals(++stmtCount, statistics.getPrepareStatementCount()); assertEquals(stmtCount, statistics.getCloseStatementCount()); person.name = "Gavin King"; scope.inStatelessTransaction(s -> s.update(person)); assertEquals(1, statistics.getEntityUpdateCount()); assertEquals(1, statistics.getCollectionUpdateCount()); scope.inStatelessSession(s -> s.get(s.createEntityGraph(Person.class), LOAD, person.id)); assertEquals(2, statistics.getEntityLoadCount()); assertEquals(2, statistics.getCollectionLoadCount()); assertEquals(0, statistics.getCollectionFetchCount()); assertEquals(stmtCount+=4, statistics.getPrepareStatementCount()); assertEquals(stmtCount, statistics.getCloseStatementCount()); scope.inStatelessSession(s -> s.get(s.createEntityGraph(Person.class), FETCH, person.id)); assertEquals(3, statistics.getEntityLoadCount()); assertEquals(2, statistics.getCollectionLoadCount()); assertEquals(0, statistics.getCollectionFetchCount()); assertEquals(++stmtCount, statistics.getPrepareStatementCount()); assertEquals(stmtCount, statistics.getCloseStatementCount()); scope.inStatelessSession(s -> s.fetch(s.get(s.createEntityGraph(Person.class), FETCH, person.id).handles)); assertEquals(4, statistics.getEntityLoadCount()); assertEquals(3, statistics.getCollectionLoadCount()); assertEquals(1, statistics.getCollectionFetchCount()); assertEquals(stmtCount+=2, statistics.getPrepareStatementCount()); assertEquals(stmtCount, statistics.getCloseStatementCount()); scope.inStatelessSession(s -> s.createQuery("from Person", Person.class).getSingleResult()); assertEquals(5, statistics.getEntityLoadCount()); assertEquals(4, statistics.getCollectionLoadCount()); assertEquals(2, statistics.getCollectionFetchCount()); assertEquals(stmtCount+=2, statistics.getPrepareStatementCount()); assertEquals(stmtCount, statistics.getCloseStatementCount()); person.handles.add("hello world"); scope.inStatelessTransaction(s -> s.upsert(person)); assertEquals(2, statistics.getCollectionUpdateCount()); assertEquals(stmtCount+=4, statistics.getPrepareStatementCount()); assertEquals(stmtCount, statistics.getCloseStatementCount()); scope.inStatelessTransaction(s -> s.delete(person)); assertEquals(1, statistics.getEntityDeleteCount()); assertEquals(1, statistics.getCollectionRemoveCount()); assertEquals(4, statistics.getTransactionCount()); assertEquals(stmtCount+=2, statistics.getPrepareStatementCount()); assertEquals(stmtCount, statistics.getCloseStatementCount()); } @Entity(name="Person") static
StatelessSessionStatisticsTest
java
reactor__reactor-core
reactor-core/src/test/java/reactor/util/JdkLoggerTest.java
{ "start": 905, "end": 6035 }
class ____ { @Test public void formatNullFormat() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.FINE); jdkLogger.debug(null, (Object[]) null); assertThat(log.toString()).isEqualTo("null"); } @Test public void nullFormatIsAcceptedByUnderlyingLogger() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.FINEST); jdkLogger.trace(null, null, null); assertThat(log.toString()).isEqualTo("null"); } @Test public void formatNullVararg() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.INFO); jdkLogger.info("test {} is {}", (Object[]) null); assertThat(log.toString()).isEqualTo("test {} is {}"); } @Test public void formatNullParamInVararg() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.FINEST); jdkLogger.trace("test {} is {}", null, null); assertThat(log.toString()).isEqualTo("test null is null"); } @Test public void trace() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.FINEST); jdkLogger.trace("test {} is {}", "foo", "bar"); assertThat(log.toString()).isEqualTo("test foo is bar"); } @Test public void traceWithThrowable() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.FINEST); Throwable t = new IllegalAccessError(); jdkLogger.trace("test {} is {}", "foo", "bar", t); assertThat(log.toString()).startsWith("test foo is bar" + "\njava.lang.IllegalAccessError\n" + "\tat reactor.util.JdkLoggerTest.traceWithThrowable"); } @Test public void debug() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.FINE); jdkLogger.debug("test {} is {}", "foo", "bar"); assertThat(log.toString()).isEqualTo("test foo is bar"); } @Test public void debugWithThrowable() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.FINE); Throwable t = new IllegalAccessError(); jdkLogger.debug("test {} is {}", "foo", "bar", t); assertThat(log.toString()).startsWith("test foo is bar" + "\njava.lang.IllegalAccessError\n" + "\tat reactor.util.JdkLoggerTest.debugWithThrowable"); } @Test public void info() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.FINE); jdkLogger.info("test {} is {}", "foo", "bar"); assertThat(log.toString()).isEqualTo("test foo is bar"); } @Test public void infoWithThrowable() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.FINE); Throwable t = new IllegalAccessError(); jdkLogger.info("test {} is {}", "foo", "bar", t); assertThat(log.toString()).startsWith("test foo is bar" + "\njava.lang.IllegalAccessError\n" + "\tat reactor.util.JdkLoggerTest.infoWithThrowable"); } @Test public void warn() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.WARNING); jdkLogger.warn("test {} is {}", "foo", "bar"); assertThat(log.toString()).isEqualTo("test foo is bar"); } @Test public void warnWithThrowable() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.WARNING); Throwable t = new IllegalAccessError(); jdkLogger.warn("test {} is {}", "foo", "bar", t); assertThat(log.toString()).startsWith("test foo is bar" + "\njava.lang.IllegalAccessError\n" + "\tat reactor.util.JdkLoggerTest.warnWithThrowable"); } @Test public void error() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.SEVERE); jdkLogger.error("test {} is {}", "foo", "bar"); assertThat(log.toString()).isEqualTo("test foo is bar"); } @Test public void errorWithThrowable() { StringBuilder log = new StringBuilder(); Loggers.JdkLogger jdkLogger = getJdkLogger(log, Level.SEVERE); Throwable t = new IllegalAccessError(); jdkLogger.error("test {} is {}", "foo", "bar", t); assertThat(log.toString()).startsWith("test foo is bar" + "\njava.lang.IllegalAccessError\n" + "\tat reactor.util.JdkLoggerTest.errorWithThrowable"); } private Loggers.JdkLogger getJdkLogger(StringBuilder log, Level level) { Logger underlyingLogger = Logger.getAnonymousLogger(); underlyingLogger.setLevel(level); underlyingLogger.addHandler( new Handler() { @Override public void publish(LogRecord record) { log.append(record.getMessage()); if (record.getThrown() != null) { log.append("\n").append(record.getThrown().toString()); for (StackTraceElement element : record.getThrown().getStackTrace()) { log.append("\n\tat ").append(element.toString()); } } } @Override public void flush() { } @Override public void close() throws SecurityException { } }); return new Loggers.JdkLogger(underlyingLogger); } }
JdkLoggerTest
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/rules/logical/AsyncCalcSplitRuleTest.java
{ "start": 12225, "end": 12446 }
class ____ extends AsyncScalarFunction { public void eval(CompletableFuture<Integer> future, Integer param) { future.complete(param + 10); } } /** Test function. */ public static
Func1
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/event/AbstractApplicationEventMulticaster.java
{ "start": 16308, "end": 17621 }
class ____ implements Comparable<ListenerCacheKey> { private final ResolvableType eventType; private final @Nullable Class<?> sourceType; public ListenerCacheKey(ResolvableType eventType, @Nullable Class<?> sourceType) { Assert.notNull(eventType, "Event type must not be null"); this.eventType = eventType; this.sourceType = sourceType; } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof ListenerCacheKey that && this.eventType.equals(that.eventType) && ObjectUtils.nullSafeEquals(this.sourceType, that.sourceType))); } @Override public int hashCode() { return Objects.hash(this.eventType, this.sourceType); } @Override public String toString() { return "ListenerCacheKey [eventType = " + this.eventType + ", sourceType = " + this.sourceType + "]"; } @Override public int compareTo(ListenerCacheKey other) { int result = this.eventType.toString().compareTo(other.eventType.toString()); if (result == 0) { if (this.sourceType == null) { return (other.sourceType == null ? 0 : -1); } if (other.sourceType == null) { return 1; } result = this.sourceType.getName().compareTo(other.sourceType.getName()); } return result; } } /** * Helper
ListenerCacheKey
java
apache__camel
components/camel-spring-parent/camel-spring-ws/src/test/java/net/javacrumbs/springws/test/helper/InMemoryWebServiceMessageSender2.java
{ "start": 1171, "end": 2718 }
class ____ extends InMemoryWebServiceMessageSender { private WebServiceMessageReceiver decorator; @Override public WebServiceMessageReceiver getWebServiceMessageReceiver() { return super.getWebServiceMessageReceiver(); } @Override public void setWebServiceMessageReceiver(WebServiceMessageReceiver webServiceMessageReceiver) { super.setWebServiceMessageReceiver(webServiceMessageReceiver); } public void decorateResponseReceiver() { final WebServiceMessageReceiver original = getWebServiceMessageReceiver(); setWebServiceMessageReceiver(new WebServiceMessageReceiver() { @Override public void receive(MessageContext messageContext) throws Exception { decorator.receive(messageContext); original.receive(messageContext); } }); } /* * (non-Javadoc) * @see net.javacrumbs.springws.test.helper.InMemoryWebServiceMessageSender# * afterPropertiesSet() */ @Override public void afterPropertiesSet() { super.afterPropertiesSet(); if (decorator != null) { decorateResponseReceiver(); } } /** * * @return Returns the decorator. */ public WebServiceMessageReceiver getDecorator() { return decorator; } /** * @param decorator The decorator to set. */ public void setDecorator(WebServiceMessageReceiver decorator) { this.decorator = decorator; } }
InMemoryWebServiceMessageSender2
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/rest/FromRestGetContentTypeTest.java
{ "start": 1209, "end": 2371 }
class ____ extends ContextTestSupport { @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("dummy-rest", new DummyRestConsumerFactory()); return jndi; } @Test public void testFromRestModelContentType() { Exchange out = template.request("seda:get-say-hello", new Processor() { @Override public void process(Exchange exchange) { } }); assertNotNull(out); assertEquals("{ \"name\" : \"Donald\" }", out.getMessage().getBody()); assertEquals("application/json", out.getMessage().getHeader(Exchange.CONTENT_TYPE)); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { restConfiguration().host("localhost"); rest("/say/hello").produces("application/json").get().to("direct:hello"); from("direct:hello").setBody(constant("{ \"name\" : \"Donald\" }")); } }; } }
FromRestGetContentTypeTest
java
apache__hadoop
hadoop-cloud-storage-project/hadoop-cos/src/main/java/org/apache/hadoop/fs/cosn/auth/AbstractCOSCredentialsProvider.java
{ "start": 1135, "end": 1544 }
class ____ implements COSCredentialsProvider { private final URI uri; private final Configuration conf; public AbstractCOSCredentialsProvider(@Nullable URI uri, Configuration conf) { this.uri = uri; this.conf = conf; } public URI getUri() { return uri; } public Configuration getConf() { return conf; } }
AbstractCOSCredentialsProvider
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/mock/http/client/MockClientHttpRequest.java
{ "start": 1316, "end": 4401 }
class ____ extends MockHttpOutputMessage implements ClientHttpRequest { private HttpMethod httpMethod; private URI uri; private @Nullable ClientHttpResponse clientHttpResponse; private boolean executed = false; @Nullable Map<String, Object> attributes; /** * Create a {@code MockClientHttpRequest} with {@link HttpMethod#GET GET} as * the HTTP request method and {@code "/"} as the {@link URI}. */ public MockClientHttpRequest() { this(HttpMethod.GET, URI.create("/")); } /** * Create a {@code MockClientHttpRequest} with the given {@link HttpMethod}, * URI template, and URI template variable values. * @since 6.0.3 */ public MockClientHttpRequest(HttpMethod httpMethod, String uriTemplate, Object... vars) { this(httpMethod, UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(vars).encode().toUri()); } /** * Create a {@code MockClientHttpRequest} with the given {@link HttpMethod} * and {@link URI}. */ public MockClientHttpRequest(HttpMethod httpMethod, URI uri) { this.httpMethod = httpMethod; this.uri = uri; } /** * Set the HTTP method of the request. */ public void setMethod(HttpMethod httpMethod) { this.httpMethod = httpMethod; } @Override public HttpMethod getMethod() { return this.httpMethod; } /** * Set the URI of the request. */ public void setURI(URI uri) { this.uri = uri; } @Override public URI getURI() { return this.uri; } /** * Set the {@link ClientHttpResponse} to be used as the result of executing * this request. * @see #execute() */ public void setResponse(ClientHttpResponse clientHttpResponse) { this.clientHttpResponse = clientHttpResponse; } /** * Get the {@link #isExecuted() executed} flag. * @see #execute() */ public boolean isExecuted() { return this.executed; } @Override public Map<String, Object> getAttributes() { Map<String, Object> attributes = this.attributes; if (attributes == null) { attributes = new ConcurrentHashMap<>(); this.attributes = attributes; } return attributes; } /** * Set the {@link #isExecuted() executed} flag to {@code true} and return the * configured {@link #setResponse(ClientHttpResponse) response}. * @see #executeInternal() */ @Override public final ClientHttpResponse execute() throws IOException { this.executed = true; return executeInternal(); } /** * The default implementation returns the configured * {@link #setResponse(ClientHttpResponse) response}. * <p>Override this method to execute the request and provide a response, * potentially different from the configured response. */ protected ClientHttpResponse executeInternal() throws IOException { Assert.state(this.clientHttpResponse != null, "No ClientHttpResponse"); return this.clientHttpResponse; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.httpMethod).append(' ').append(this.uri); if (!getHeaders().isEmpty()) { sb.append(", headers: ").append(getHeaders()); } return sb.toString(); } }
MockClientHttpRequest
java
apache__kafka
raft/src/test/java/org/apache/kafka/raft/RaftEventSimulationTest.java
{ "start": 40710, "end": 41015 }
class ____ implements NetworkFilter { @Override public boolean acceptInbound(RaftMessage message) { return true; } @Override public boolean acceptOutbound(RaftMessage message) { return true; } } private static
PermitAllTraffic
java
apache__hadoop
hadoop-tools/hadoop-compat-bench/src/main/java/org/apache/hadoop/fs/compat/suites/HdfsCompatSuiteForShell.java
{ "start": 989, "end": 1537 }
class ____ implements HdfsCompatSuite { @Override public String getSuiteName() { return "Shell"; } @Override public Class<? extends AbstractHdfsCompatCase>[] getApiCases() { return new Class[0]; } @Override public String[] getShellCases() { return new String[]{ "directory.t", "fileinfo.t", "read.t", "write.t", "remove.t", "attr.t", "copy.t", "move.t", "concat.t", "snapshot.t", "storagePolicy.t", }; } }
HdfsCompatSuiteForShell
java
apache__camel
components/camel-zeebe/src/test/java/org/apache/camel/component/zeebe/ZeebeConsumerIT.java
{ "start": 2413, "end": 7347 }
class ____ extends CamelTestSupport { public static final String TEST_1_DEFINITION_BPMN = "test1_definition.bpmn"; private ZeebeComponent component; private final ObjectMapper objectMapper = new ObjectMapper(); @BeforeAll void initAll() throws Exception { createComponent(); component.doStart(); DeploymentRequest deployProcessMessage = new DeploymentRequest(); deployProcessMessage.setName(TEST_1_DEFINITION_BPMN); deployProcessMessage .setContent(this.getClass().getClassLoader().getResourceAsStream("data/test1_definition.bpmn").readAllBytes()); DeploymentResponse deploymentResponse = component.getZeebeService().deployResource(deployProcessMessage); ProcessRequest processRequest = new ProcessRequest(); processRequest.setProcessId(((ProcessDeploymentResponse) deploymentResponse).getBpmnProcessId()); ProcessResponse processResponse = component.getZeebeService().startProcess(processRequest); } @Test public void shouldProcessJobWorkerMessage() throws Exception { MockEndpoint workerMock = getMockEndpoint("mock:jobWorker"); workerMock.expectedMinimumMessageCount(1); Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> MockEndpoint.assertIsSatisfied(context)); List<Exchange> exchanges = workerMock.getExchanges(); for (Exchange exchange : exchanges) { JobWorkerMessage jobWorkerMessage = exchange.getMessage().getBody(JobWorkerMessage.class); assertNotNull(jobWorkerMessage); assertTrue(jobWorkerMessage.getKey() > 0); assertTrue(jobWorkerMessage.getProcessInstanceKey() > 0); assertNotNull(jobWorkerMessage.getBpmnProcessId()); assertTrue(jobWorkerMessage.getProcessDefinitionVersion() > 0); assertTrue(jobWorkerMessage.getProcessDefinitionKey() > 0); assertNotNull(jobWorkerMessage.getElementId()); assertTrue(jobWorkerMessage.getProcessInstanceKey() > 0); assertNotNull(jobWorkerMessage.getWorker()); assertTrue(jobWorkerMessage.getRetries() > 0); assertTrue(jobWorkerMessage.getDeadline() > 0); JobRequest jobRequest = new JobRequest(); jobRequest.setJobKey(jobWorkerMessage.getKey()); component.getZeebeService().completeJob(jobRequest); } } @Test public void shouldProcessJobWorkerMessageJSON() throws Exception { MockEndpoint workerMock = getMockEndpoint("mock:jobWorker_JSON"); workerMock.expectedMinimumMessageCount(1); Awaitility.await().atMost(Duration.ofSeconds(30)).untilAsserted(() -> MockEndpoint.assertIsSatisfied(context)); List<Exchange> exchanges = workerMock.getExchanges(); for (Exchange exchange : exchanges) { String jobWorkerMessageString = exchange.getMessage().getBody(String.class); assertNotNull(jobWorkerMessageString); JobWorkerMessage jobWorkerMessage = assertDoesNotThrow(() -> objectMapper.readValue(jobWorkerMessageString, JobWorkerMessage.class)); assertTrue(jobWorkerMessage.getKey() > 0); assertTrue(jobWorkerMessage.getProcessInstanceKey() > 0); assertNotNull(jobWorkerMessage.getBpmnProcessId()); assertTrue(jobWorkerMessage.getProcessDefinitionVersion() > 0); assertTrue(jobWorkerMessage.getProcessDefinitionKey() > 0); assertNotNull(jobWorkerMessage.getElementId()); assertTrue(jobWorkerMessage.getProcessInstanceKey() > 0); assertNotNull(jobWorkerMessage.getWorker()); assertTrue(jobWorkerMessage.getRetries() > 0); assertTrue(jobWorkerMessage.getDeadline() > 0); JobRequest jobRequest = new JobRequest(); jobRequest.setJobKey(jobWorkerMessage.getKey()); component.getZeebeService().completeJob(jobRequest); } } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("zeebe://worker?jobKey=consumerTest&timeOut=3") .to("mock:jobWorker"); from("zeebe://worker?jobKey=consumerTestJSON&timeOut=3&formatJSON=true") .to("mock:jobWorker_JSON"); } }; } protected void createComponent() throws Exception { component = new ZeebeComponent(); component.setGatewayHost(ZeebeConstants.DEFAULT_GATEWAY_HOST); component.setGatewayPort(ZeebeConstants.DEFAULT_GATEWAY_PORT); } @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.addComponent("zeebe", component); return context; } }
ZeebeConsumerIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/orphan/elementcollection/ElementCollectionOrphanTest.java
{ "start": 625, "end": 1624 }
class ____ { @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void setCompositeElementTest(SessionFactoryScope scope) { scope.inTransaction( session -> { EnrollableClass aClass = new EnrollableClass(); aClass.setId( "123" ); aClass.setName( "Math" ); session.persist( aClass ); Student aStudent = new Student(); aStudent.setId( "s1" ); aStudent.setFirstName( "John" ); aStudent.setLastName( "Smith" ); EnrolledClassSeat seat = new EnrolledClassSeat(); seat.setId( "seat1" ); seat.setRow( 10 ); seat.setColumn( 5 ); StudentEnrolledClass enrClass = new StudentEnrolledClass(); enrClass.setEnrolledClass( aClass ); enrClass.setClassStartTime( 130 ); enrClass.setSeat( seat ); aStudent.setEnrolledClasses( Collections.singleton( enrClass ) ); session.persist( aStudent ); } ); } }
ElementCollectionOrphanTest
java
apache__spark
core/src/main/java/org/apache/spark/api/plugin/DriverPlugin.java
{ "start": 1097, "end": 4704 }
interface ____ { /** * Initialize the plugin. * <p> * This method is called early in the initialization of the Spark driver. Explicitly, it is * called before the Spark driver's task scheduler is initialized. This means that a lot * of other Spark subsystems may yet not have been initialized. This call also blocks driver * initialization. * <p> * It's recommended that plugins be careful about what operations are performed in this call, * preferably performing expensive operations in a separate thread, or postponing them until * the application has fully started. * * @param sc The SparkContext loading the plugin. * @param pluginContext Additional plugin-specific about the Spark application where the plugin * is running. * @return A map that will be provided to the {@link ExecutorPlugin#init(PluginContext,Map)} * method. */ default Map<String, String> init(SparkContext sc, PluginContext pluginContext) { return Collections.emptyMap(); } /** * Register metrics published by the plugin with Spark's metrics system. * <p> * This method is called later in the initialization of the Spark application, after most * subsystems are up and the application ID is known. If there are metrics registered in * the registry ({@link PluginContext#metricRegistry()}), then a metrics source with the * plugin name will be created. * <p> * Note that even though the metric registry is still accessible after this method is called, * registering new metrics after this method is called may result in the metrics not being * available. * * @param appId The application ID from the cluster manager. * @param pluginContext Additional plugin-specific about the Spark application where the plugin * is running. */ default void registerMetrics(String appId, PluginContext pluginContext) {} /** * RPC message handler. * <p> * Plugins can use Spark's RPC system to send messages from executors to the driver (but not * the other way around, currently). Messages sent by the executor component of the plugin will * be delivered to this method, and the returned value will be sent back to the executor as * the reply, if the executor has requested one. * <p> * Any exception thrown will be sent back to the executor as an error, in case it is expecting * a reply. In case a reply is not expected, a log message will be written to the driver log. * <p> * The implementation of this handler should be thread-safe. * <p> * Note all plugins share RPC dispatch threads, and this method is called synchronously. So * performing expensive operations in this handler may affect the operation of other active * plugins. Internal Spark endpoints are not directly affected, though, since they use different * threads. * <p> * Spark guarantees that the driver component will be ready to receive messages through this * handler when executors are started. * * @param message The incoming message. * @return Value to be returned to the caller. Ignored if the caller does not expect a reply. */ default Object receive(Object message) throws Exception { throw new UnsupportedOperationException(); } /** * Informs the plugin that the Spark application is shutting down. * <p> * This method is called during the driver shutdown phase. It is recommended that plugins * not use any Spark functions (e.g. send RPC messages) during this call. */ default void shutdown() {} }
DriverPlugin
java
netty__netty
transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollDomainSocketReuseFdTest.java
{ "start": 940, "end": 1346 }
class ____ extends AbstractSocketReuseFdTest { @Override protected SocketAddress newSocketAddress() { return EpollSocketTestPermutation.newDomainSocketAddress(); } @Override protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() { return EpollSocketTestPermutation.INSTANCE.domainSocket(); } }
EpollDomainSocketReuseFdTest
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/rolemapping/TransportDeleteRoleMappingAction.java
{ "start": 1185, "end": 3084 }
class ____ extends HandledTransportAction<DeleteRoleMappingRequest, DeleteRoleMappingResponse> { private final NativeRoleMappingStore roleMappingStore; private final ProjectStateRoleMapper projectStateRoleMapper; @Inject public TransportDeleteRoleMappingAction( ActionFilters actionFilters, TransportService transportService, NativeRoleMappingStore roleMappingStore, ProjectStateRoleMapper projectStateRoleMapper ) { super( DeleteRoleMappingAction.NAME, transportService, actionFilters, DeleteRoleMappingRequest::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.roleMappingStore = roleMappingStore; this.projectStateRoleMapper = projectStateRoleMapper; } @Override protected void doExecute(Task task, DeleteRoleMappingRequest request, ActionListener<DeleteRoleMappingResponse> listener) { roleMappingStore.deleteRoleMapping(request, listener.safeMap(found -> { if (found && projectStateRoleMapper.hasMapping(request.getName())) { // Allow to delete a mapping with the same name in the native role mapping store as the file_settings namespace, but // add a warning header to signal to the caller that this could be a problem. HeaderWarning.addWarning( "A read-only role mapping with the same name [" + request.getName() + "] has previously been defined in a configuration file. " + "The native role mapping was deleted, but the read-only mapping will remain active " + "and will be used to determine role assignments." ); } return new DeleteRoleMappingResponse(found); })); } }
TransportDeleteRoleMappingAction
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_449.java
{ "start": 974, "end": 1946 }
class ____ { @JSONField(name = "Mg2+") private String mg; @JSONField(name = "Na+") private String na; @JSONField(name = "Cl-") private String cl; @JSONField(name = "panellot") private String panellot; public String getMg() { return mg; } public void setMg(String mg) { this.mg = mg; } public String getNa() { return na; } public void setNa(String na) { this.na = na; } public String getCl() { return cl; } public void setCl(String cl) { this.cl = cl; } public String getPanellot() { return panellot; } public void setPanellot(String panellot) { this.panellot = panellot; } } }
ExaminationPojo
java
micronaut-projects__micronaut-core
http-client-core/src/main/java/io/micronaut/http/client/multipart/MultipartBody.java
{ "start": 7436, "end": 8303 }
class ____ * {@link MultipartBody}. * * @param filePart Any file part, such as {@link FilePart}, {@link InputStreamPart}, {@link BytePart} etc * @return A {@link MultipartBody.Builder} to build MultipartBody */ private Builder addFilePart(AbstractFilePart<?> filePart) { parts.add(filePart); return this; } /** * Creates {@link MultipartBody} from the provided parts. * * @return The {@link MultipartBody} * @throws MultipartException If there are no parts */ public MultipartBody build() throws MultipartException { if (parts.isEmpty()) { throw new MultipartException("Cannot create a MultipartBody with no parts"); } return new MultipartBody(parts); } } }
to