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
elastic__elasticsearch
x-pack/plugin/text-structure/src/main/java/org/elasticsearch/xpack/textstructure/structurefinder/TimestampFormatFinder.java
{ "start": 18004, "end": 18454 }
class ____ other classes will update it. */ private final List<String> explanation; private final boolean requireFullMatch; private final boolean errorOnNoTimestamp; private final boolean errorOnMultiplePatterns; private final List<CandidateTimestampFormat> orderedCandidateFormats; private final TimeoutChecker timeoutChecker; private final List<TimestampMatch> matches; // These two are not volatile because the
and
java
apache__flink
flink-filesystems/flink-s3-fs-hadoop/src/main/java/org/apache/flink/fs/s3hadoop/S3AFileSystemFactory.java
{ "start": 942, "end": 1075 }
class ____ extends S3FileSystemFactory { @Override public String getScheme() { return "s3a"; } }
S3AFileSystemFactory
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/alterTable/MySqlAlterTableTest14.java
{ "start": 986, "end": 1965 }
class ____ extends TestCase { public void test_alter_first() throws Exception { String sql = "ALTER TABLE tbl_name IMPORT TABLESPACE;"; MySqlStatementParser parser = new MySqlStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); parser.match(Token.EOF); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); String output = SQLUtils.toMySqlString(stmt); assertEquals("ALTER TABLE tbl_name" + "\n\tIMPORT TABLESPACE;", output); assertEquals(1, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); } }
MySqlAlterTableTest14
java
google__dagger
hilt-android/main/java/dagger/hilt/android/ActivityRetainedLifecycle.java
{ "start": 739, "end": 865 }
class ____ associated with the lifecycle of the {@link * dagger.hilt.android.components.ActivityRetainedComponent}. */ public
is
java
apache__rocketmq
auth/src/main/java/org/apache/rocketmq/auth/authentication/strategy/AuthenticationStrategy.java
{ "start": 947, "end": 1035 }
interface ____ { void evaluate(AuthenticationContext context); }
AuthenticationStrategy
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/builder/ReflectionToStringBuilderMutateInspectConcurrencyTest.java
{ "start": 2435, "end": 3593 }
class ____ { private final LinkedList<Integer> listField = new LinkedList<>(); private final Random random = new Random(); private final int N = 100; TestFixture() { synchronized (this) { for (int i = 0; i < N; i++) { listField.add(Integer.valueOf(i)); } } } public synchronized void add() { listField.add(Integer.valueOf(random.nextInt(N))); } public synchronized void delete() { listField.remove(Integer.valueOf(random.nextInt(N))); } } @Test @Disabled void testConcurrency() { final TestFixture testFixture = new TestFixture(); final int numMutators = 10; final int numIterations = 10; for (int i = 0; i < numIterations; i++) { for (int j = 0; j < numMutators; j++) { final Thread t = new Thread(new MutatingClient(testFixture)); t.start(); final Thread s = new Thread(new InspectingClient(testFixture)); s.start(); } } } }
TestFixture
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/RxReturnValueIgnoredTest.java
{ "start": 11675, "end": 12148 }
class ____ { Flowable getFlowable() { return null; } void f() { // BUG: Diagnostic contains: Rx objects must be checked. getFlowable(); } } """) .doTest(); } @Test public void rx2Maybe() { compilationHelper .addSourceLines( "Test.java", """ import io.reactivex.Maybe;
Test
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/JobConf.java
{ "start": 34637, "end": 36052 }
class ____ be used for grouping keys for the * combiner. It should implement <code>RawComparator</code>. * @see #setOutputKeyComparatorClass(Class) */ public void setCombinerKeyGroupingComparator( Class<? extends RawComparator> theClass) { setClass(JobContext.COMBINER_GROUP_COMPARATOR_CLASS, theClass, RawComparator.class); } /** * Set the user defined {@link RawComparator} comparator for * grouping keys in the input to the reduce. * * <p>This comparator should be provided if the equivalence rules for keys * for sorting the intermediates are different from those for grouping keys * before each call to * {@link Reducer#reduce(Object, java.util.Iterator, OutputCollector, Reporter)}.</p> * * <p>For key-value pairs (K1,V1) and (K2,V2), the values (V1, V2) are passed * in a single call to the reduce function if K1 and K2 compare as equal.</p> * * <p>Since {@link #setOutputKeyComparatorClass(Class)} can be used to control * how keys are sorted, this can be used in conjunction to simulate * <i>secondary sort on values</i>.</p> * * <p><i>Note</i>: This is not a guarantee of the reduce sort being * <i>stable</i> in any sense. (In any case, with the order of available * map-outputs to the reduce being non-deterministic, it wouldn't make * that much sense.)</p> * * @param theClass the comparator
to
java
square__okhttp
samples/guide/src/main/java/okhttp3/recipes/HttpsServer.java
{ "start": 1013, "end": 2158 }
class ____ { public void run() throws Exception { HeldCertificate localhostCertificate = new HeldCertificate.Builder() .addSubjectAlternativeName("localhost") .build(); HandshakeCertificates serverCertificates = new HandshakeCertificates.Builder() .heldCertificate(localhostCertificate) .build(); MockWebServer server = new MockWebServer(); server.useHttps(serverCertificates.sslSocketFactory(), false); server.enqueue(new MockResponse()); HandshakeCertificates clientCertificates = new HandshakeCertificates.Builder() .addTrustedCertificate(localhostCertificate.certificate()) .build(); OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(clientCertificates.sslSocketFactory(), clientCertificates.trustManager()) .build(); Call call = client.newCall(new Request.Builder() .url(server.url("/")) .build()); Response response = call.execute(); System.out.println(response.handshake().tlsVersion()); } public static void main(String... args) throws Exception { new HttpsServer().run(); } }
HttpsServer
java
apache__dubbo
dubbo-remoting/dubbo-remoting-zookeeper-curator5/src/main/java/org/apache/dubbo/remoting/zookeeper/curator5/Curator5ZookeeperClient.java
{ "start": 16290, "end": 17481 }
class ____ implements NodeCacheListener { private CuratorFramework client; private volatile DataListener dataListener; private String path; protected NodeCacheListenerImpl() {} public NodeCacheListenerImpl(CuratorFramework client, DataListener dataListener, String path) { this.client = client; this.dataListener = dataListener; this.path = path; } @Override public void nodeChanged() throws Exception { ChildData childData = nodeCacheMap.get(path).getCurrentData(); String content = null; EventType eventType; if (childData == null) { eventType = EventType.NodeDeleted; } else if (childData.getStat().getVersion() == 0) { content = new String(childData.getData(), CHARSET); eventType = EventType.NodeCreated; } else { content = new String(childData.getData(), CHARSET); eventType = EventType.NodeDataChanged; } dataListener.dataChanged(path, content, eventType); } } static
NodeCacheListenerImpl
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableAllSingle.java
{ "start": 1050, "end": 1712 }
class ____<T> extends Single<Boolean> implements FuseToObservable<Boolean> { final ObservableSource<T> source; final Predicate<? super T> predicate; public ObservableAllSingle(ObservableSource<T> source, Predicate<? super T> predicate) { this.source = source; this.predicate = predicate; } @Override protected void subscribeActual(SingleObserver<? super Boolean> t) { source.subscribe(new AllObserver<>(t, predicate)); } @Override public Observable<Boolean> fuseToObservable() { return RxJavaPlugins.onAssembly(new ObservableAll<>(source, predicate)); } static final
ObservableAllSingle
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/access/NoOpAccessDeniedHandlerTests.java
{ "start": 973, "end": 1472 }
class ____ { private final NoOpAccessDeniedHandler handler = new NoOpAccessDeniedHandler(); @Test void handleWhenInvokedThenDoesNothing() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); AccessDeniedException exception = mock(AccessDeniedException.class); this.handler.handle(request, response, exception); verifyNoInteractions(request, response, exception); } }
NoOpAccessDeniedHandlerTests
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/ReactiveWebApplicationContextRunnerTests.java
{ "start": 1092, "end": 1685 }
class ____ extends AbstractApplicationContextRunnerTests<ReactiveWebApplicationContextRunner, ConfigurableReactiveWebApplicationContext, AssertableReactiveWebApplicationContext> { @Override protected ReactiveWebApplicationContextRunner get() { return new ReactiveWebApplicationContextRunner(); } @Override protected ReactiveWebApplicationContextRunner getWithAdditionalContextInterface() { return new ReactiveWebApplicationContextRunner(TestAnnotationConfigReactiveWebApplicationContext::new, AdditionalContextInterface.class); } static
ReactiveWebApplicationContextRunnerTests
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/DefaultBean.java
{ "start": 900, "end": 1530 }
class ____ { * * &#64;Produces * public MyBean override() { * // create bean * } * } * </pre> * * Then the result of {@code override()} will be used as MyBean in all injection points. * <p> * Default beans can optionally declare {@link jakarta.annotation.Priority}. * In case there is no priority defined, {@code @Priority(0)} is assumed. * Priority value is used for bean ordering and during typesafe resolution to disambiguate multiple matching default beans. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD, ElementType.TYPE, ElementType.FIELD }) public @
SomeOtherConfiguration
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ParameterTest.java
{ "start": 3066, "end": 3544 }
class ____ { void target(Object obj, Integer integer) { // BUG: Diagnostic contains: false target(obj, integer); } } """) .doTest(); } @Test public void isAssignableTo_returnsTrue_assigningIntegerToObject() { CompilationTestHelper.newInstance(IsFirstAssignableToSecond.class, getClass()) .addSourceLines( "Test.java", """ abstract
Test
java
apache__camel
components/camel-salesforce/camel-salesforce-codegen/src/main/java/org/apache/camel/component/salesforce/codegen/GenerateExecution.java
{ "start": 19875, "end": 22977 }
class ____ String queryRecordsOptionalFileName = "QueryRecords" + description.getName() + "Optional" + JAVA_EXT; final File queryRecordsOptionalFile = new File(pkgDir, queryRecordsOptionalFileName); final Template queryRecordsOptionalTemplate = engine.getTemplate(SOBJECT_QUERY_RECORDS_OPTIONAL_VM, UTF_8); try (final Writer writer = new OutputStreamWriter(new FileOutputStream(queryRecordsOptionalFile), StandardCharsets.UTF_8)) { queryRecordsOptionalTemplate.merge(context, writer); } } } @Override protected void executeWithClient() throws Exception { descriptions = new ObjectDescriptions( getRestClient(), getResponseTimeout(), includes, includePattern, excludes, excludePattern, getLog()); // make sure we can load both templates if (!engine.resourceExists(SOBJECT_POJO_VM) || !engine.resourceExists(SOBJECT_QUERY_RECORDS_VM) || !engine.resourceExists(SOBJECT_POJO_OPTIONAL_VM) || !engine.resourceExists(SOBJECT_QUERY_RECORDS_OPTIONAL_VM)) { throw new RuntimeException("Velocity templates not found"); } // create package directory // validate package name if (!packageName.matches(PACKAGE_NAME_PATTERN)) { throw new RuntimeException("Invalid package name " + packageName); } if (outputDirectory.getAbsolutePath().contains("$")) { outputDirectory = new File("generated-sources/camel-salesforce"); } final File pkgDir = new File(outputDirectory, packageName.trim().replace('.', File.separatorChar)); if (!pkgDir.exists()) { if (!pkgDir.mkdirs()) { throw new RuntimeException("Unable to create " + pkgDir); } } getLog().info("Generating Java Classes..."); Set<String> sObjectNames = StreamSupport.stream(descriptions.fetched().spliterator(), false).map(d -> d.getName()) .collect(Collectors.toSet()); // generate POJOs for every object description final GeneratorUtility utility = new GeneratorUtility(); for (final SObjectDescription description : descriptions.fetched()) { if (Defaults.IGNORED_OBJECTS.contains(description.getName())) { continue; } try { processDescription(pkgDir, description, utility, sObjectNames); } catch (final IOException e) { throw new RuntimeException("Unable to generate source files for: " + description.getName(), e); } } getLog().info(String.format("Successfully generated %s Java Classes", descriptions.count() * 2)); } @Override protected Logger getLog() { return LOG; } @Override public void setup() { if (customTypes != null) { types.putAll(customTypes); } } private VelocityEngine createVelocityEngine() { // initialize velocity to load resources from
final
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/SpringApplicationTests.java
{ "start": 77262, "end": 77638 }
class ____ extends AbstractTestRunner implements CommandLineRunner { private final String name; TestCommandLineRunner(String name, int order, String... expectedBefore) { super(order, expectedBefore); this.name = name; } @Override public void run(String... args) { System.out.println(">>> " + this.name); markAsRan(); } } static
TestCommandLineRunner
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/aop/itfce/InterfaceClass.java
{ "start": 755, "end": 2549 }
interface ____<A> { @Mutating("name") String test(String name); @Mutating("age") String test(int age); @Mutating("name") String test(String name, int age); @Mutating("name") String test(); @Mutating("name") void testVoid(String name); @Mutating("name") void testVoid(String name, int age); @Mutating("name") boolean testBoolean(String name); @Mutating("name") boolean testBoolean(String name, int age); @Mutating("name") int testInt(String name); @Mutating("age") int testInt(String name, int age); @Mutating("name") long testLong(String name); @Mutating("age") long testLong(String name, int age); @Mutating("name") short testShort(String name); @Mutating("age") short testShort(String name, int age); @Mutating("name") byte testByte(String name); @Mutating("age") byte testByte(String name, int age); @Mutating("name") double testDouble(String name); @Mutating("age") double testDouble(String name, int age); @Mutating("name") float testFloat(String name); @Mutating("age") float testFloat(String name, int age); @Mutating("name") char testChar(String name); @Mutating("age") char testChar(String name, int age); @Mutating("name") byte[] testByteArray(String name, byte[] data); @Mutating("name") <T extends CharSequence> T testGenericsWithExtends(T name, int age); @Mutating("name") <T> List<? super String> testListWithWildCardSuper(T name, List<? super String> p2); @Mutating("name") <T> List<? extends String> testListWithWildCardExtends(T name, List<? extends String> p2); @Mutating("name") A testGenericsFromType(A name, int age); }
InterfaceClass
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/internals/ReflectiveStrategy.java
{ "start": 1050, "end": 2397 }
class ____ { static Object invoke(Method method, Object obj, Object... args) { try { return method.invoke(obj, args); } catch (IllegalAccessException e) { throw new UnsupportedOperationException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else { throw new RuntimeException(cause); } } } static <T extends Exception> Object invokeChecked(Method method, Class<T> ex, Object obj, Object... args) throws T { try { return method.invoke(obj, args); } catch (IllegalAccessException e) { throw new UnsupportedOperationException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (ex.isInstance(cause)) { throw ex.cast(cause); } else if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else { throw new RuntimeException(cause); } } } /** * Interface to allow mocking out classloading infrastructure. This is used to test reflective operations. */
ReflectiveStrategy
java
apache__camel
components/camel-kubernetes/src/main/java/org/apache/camel/component/kubernetes/events/KubernetesEventsComponent.java
{ "start": 1093, "end": 1370 }
class ____ extends AbstractKubernetesComponent { @Override protected KubernetesEventsEndpoint doCreateEndpoint(String uri, String remaining, KubernetesConfiguration config) { return new KubernetesEventsEndpoint(uri, this, config); } }
KubernetesEventsComponent
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/FenceMethod.java
{ "start": 1407, "end": 1909 }
interface ____ order to achieve fencing. * <p> * Fencing is configured by the operator as an ordered list of methods to * attempt. Each method will be tried in turn, and the next in the list * will only be attempted if the previous one fails. See {@link NodeFencer} * for more information. * <p> * If an implementation also implements {@link Configurable} then its * <code>setConf</code> method will be called upon instantiation. */ @InterfaceAudience.Public @InterfaceStability.Unstable public
in
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/bean/BeanParameterInvalidValueTest.java
{ "start": 4397, "end": 5005 }
class ____ { public String echo(String body, int times) { if (body == null) { // use an empty string for no body return ""; } if (times > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < times; i++) { sb.append(body); } return sb.toString(); } return body; } public String heads(String body, Map<?, ?> headers) { return headers.get("hello") + " " + body; } } }
MyBean
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableSerializeTest.java
{ "start": 10820, "end": 14660 }
class ____ implements ObservableSource<String> { final String[] values; Thread t; AtomicInteger threadsRunning = new AtomicInteger(); AtomicInteger maxConcurrentThreads = new AtomicInteger(); ExecutorService threadPool; TestMultiThreadedObservable(String... values) { this.values = values; this.threadPool = Executors.newCachedThreadPool(); } @Override public void subscribe(final Observer<? super String> observer) { observer.onSubscribe(Disposable.empty()); System.out.println("TestMultiThreadedObservable subscribed to ..."); final NullPointerException npe = new NullPointerException(); t = new Thread(new Runnable() { @Override public void run() { try { System.out.println("running TestMultiThreadedObservable thread"); for (final String s : values) { threadPool.execute(new Runnable() { @Override public void run() { threadsRunning.incrementAndGet(); try { // perform onNext call if (s == null) { System.out.println("TestMultiThreadedObservable onNext: null"); // force an error throw npe; } else { System.out.println("TestMultiThreadedObservable onNext: " + s); } observer.onNext(s); // capture 'maxThreads' int concurrentThreads = threadsRunning.get(); int maxThreads = maxConcurrentThreads.get(); if (concurrentThreads > maxThreads) { maxConcurrentThreads.compareAndSet(maxThreads, concurrentThreads); } } catch (Throwable e) { observer.onError(e); } finally { threadsRunning.decrementAndGet(); } } }); } // we are done spawning threads threadPool.shutdown(); } catch (Throwable e) { throw new RuntimeException(e); } // wait until all threads are done, then mark it as COMPLETED try { // wait for all the threads to finish threadPool.awaitTermination(2, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } observer.onComplete(); } }); System.out.println("starting TestMultiThreadedObservable thread"); t.start(); System.out.println("done starting TestMultiThreadedObservable thread"); } public void waitToFinish() { try { t.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } private static
TestMultiThreadedObservable
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/cluster/routing/allocation/shards/ShardsAvailabilityHealthIndicatorServiceTests.java
{ "start": 123129, "end": 129084 }
enum ____ { UNAVAILABLE, CREATING, AVAILABLE, RESTARTING, INITIALIZING, } private record ShardAllocation(String nodeId, ShardState state, Long unassignedTimeNanos, @Nullable UnassignedInfo unassignedInfo) { ShardAllocation(String nodeId, ShardState state) { this(nodeId, state, null, null); } ShardAllocation(String nodeId, ShardState state, Long unassignedTimeNanos) { this(nodeId, state, unassignedTimeNanos, null); } ShardAllocation(String nodeId, ShardState state, UnassignedInfo unassignedInfo) { this(nodeId, state, null, unassignedInfo); } } private record NodeShutdown(String nodeId, SingleNodeShutdownMetadata.Type type, Integer allocationDelaySeconds) {} private static String randomNodeId() { return UUID.randomUUID().toString(); } private static UnassignedInfo noShardCopy() { return new UnassignedInfo( randomBoolean() ? UnassignedInfo.Reason.NODE_LEFT : UnassignedInfo.Reason.CLUSTER_RECOVERED, null, null, 0, 0, 0, false, UnassignedInfo.AllocationStatus.NO_VALID_SHARD_COPY, Collections.emptySet(), null ); } private static UnassignedInfo nodeLeft() { return new UnassignedInfo( UnassignedInfo.Reason.NODE_LEFT, null, null, 0, 0, 0, false, UnassignedInfo.AllocationStatus.NO_ATTEMPT, Collections.emptySet(), null ); } private static UnassignedInfo unassignedInfoNoFailures(TimeValue unassignedTime) { UnassignedInfo.Reason reason = randomFrom(UnassignedInfo.Reason.NODE_LEFT, UnassignedInfo.Reason.NODE_RESTARTING); return new UnassignedInfo( reason, "message", null, 0, unassignedTime.nanos(), unassignedTime.millis(), randomBoolean(), randomValueOtherThan(UnassignedInfo.AllocationStatus.DECIDERS_NO, () -> randomFrom(UnassignedInfo.AllocationStatus.values())), Set.of(), reason == UnassignedInfo.Reason.NODE_LEFT ? null : randomAlphaOfLength(20) ); } private static UnassignedInfo decidersNo() { return decidersNo(TimeValue.timeValueMillis(0)); } private static UnassignedInfo decidersNo(TimeValue unassignedTime) { return new UnassignedInfo( UnassignedInfo.Reason.ALLOCATION_FAILED, null, null, 1, unassignedTime.nanos(), unassignedTime.millis(), false, UnassignedInfo.AllocationStatus.DECIDERS_NO, Collections.emptySet(), null ); } private record ShardRoutingKey(String index, int shard, boolean primary) {} private static ShardsAvailabilityHealthIndicatorService createShardsAvailabilityIndicatorService(ProjectId projectId) { return createShardsAvailabilityIndicatorService(projectId, ClusterState.EMPTY_STATE, Collections.emptyMap()); } private static ShardsAvailabilityHealthIndicatorService createShardsAvailabilityIndicatorService( ProjectId projectId, ClusterState clusterState ) { return createShardsAvailabilityIndicatorService(projectId, clusterState, Collections.emptyMap()); } private static ShardsAvailabilityHealthIndicatorService createShardsAvailabilityIndicatorService( ProjectId projectId, ClusterState clusterState, final Map<ShardRoutingKey, ShardAllocationDecision> decisions ) { return createAllocationHealthIndicatorService( Settings.EMPTY, clusterState, decisions, new SystemIndices(List.of()), TestProjectResolvers.singleProjectOnly(projectId) ); } private static ShardsAvailabilityHealthIndicatorService createShardsAvailabilityIndicatorService( ProjectId projectId, Settings nodeSettings, ClusterState clusterState, final Map<ShardRoutingKey, ShardAllocationDecision> decisions ) { return createAllocationHealthIndicatorService( nodeSettings, clusterState, decisions, new SystemIndices(List.of()), TestProjectResolvers.singleProjectOnly(projectId) ); } private static ShardsAvailabilityHealthIndicatorService createAllocationHealthIndicatorService( Settings nodeSettings, ClusterState clusterState, final Map<ShardRoutingKey, ShardAllocationDecision> decisions, SystemIndices systemIndices, ProjectResolver projectResolver ) { var clusterService = mock(ClusterService.class); when(clusterService.state()).thenReturn(clusterState); var clusterSettings = new ClusterSettings(nodeSettings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); when(clusterService.getClusterSettings()).thenReturn(clusterSettings); when(clusterService.getSettings()).thenReturn(Settings.EMPTY); var allocationService = mock(AllocationService.class); when(allocationService.explainShardAllocation(any(ShardRouting.class), any(RoutingAllocation.class))).thenAnswer( (Answer<ShardAllocationDecision>) invocation -> { ShardRouting shardRouting = invocation.getArgument(0); var key = new ShardRoutingKey(shardRouting.getIndexName(), shardRouting.getId(), shardRouting.primary()); return decisions.getOrDefault(key, ShardAllocationDecision.NOT_TAKEN); } ); return new ShardsAvailabilityHealthIndicatorService(clusterService, allocationService, systemIndices, projectResolver); } }
ShardState
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/graph/StreamingJobGraphGeneratorNodeHashTest.java
{ "start": 22261, "end": 22540 }
class ____ implements ReduceFunction<String> { private static final long serialVersionUID = -8775747640749256372L; @Override public String reduce(String value1, String value2) throws Exception { return value1; } } }
NoOpReduceFunction
java
apache__maven
compat/maven-artifact/src/main/java/org/apache/maven/artifact/resolver/AbstractArtifactResolutionException.java
{ "start": 1094, "end": 1150 }
class ____ artifact resolution exceptions. * */ public
for
java
elastic__elasticsearch
modules/rank-eval/src/internalClusterTest/java/org/elasticsearch/index/rankeval/RankEvalRequestIT.java
{ "start": 1599, "end": 17416 }
class ____ extends ESIntegTestCase { private static final String TEST_INDEX = "test"; private static final String INDEX_ALIAS = "alias0"; private static final int RELEVANT_RATING_1 = 1; @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList(RankEvalPlugin.class); } @Before public void setup() { createIndex(TEST_INDEX); ensureGreen(); prepareIndex(TEST_INDEX).setId("1").setSource("id", 1, "text", "berlin", "title", "Berlin, Germany", "population", 3670622).get(); prepareIndex(TEST_INDEX).setId("2").setSource("id", 2, "text", "amsterdam", "population", 851573).get(); prepareIndex(TEST_INDEX).setId("3").setSource("id", 3, "text", "amsterdam", "population", 851573).get(); prepareIndex(TEST_INDEX).setId("4").setSource("id", 4, "text", "amsterdam", "population", 851573).get(); prepareIndex(TEST_INDEX).setId("5").setSource("id", 5, "text", "amsterdam", "population", 851573).get(); prepareIndex(TEST_INDEX).setId("6").setSource("id", 6, "text", "amsterdam", "population", 851573).get(); // add another index for testing closed indices etc... prepareIndex("test2").setId("7").setSource("id", 7, "text", "amsterdam", "population", 851573).get(); refresh(); // set up an alias that can also be used in tests assertAcked( indicesAdmin().prepareAliases(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .addAliasAction(AliasActions.add().index(TEST_INDEX).alias(INDEX_ALIAS)) ); } /** * Test cases retrieves all six documents indexed above. The first part checks the Prec@10 calculation where * all unlabeled docs are treated as "unrelevant". We average Prec@ metric across two search use cases, the * first one that labels 4 out of the 6 documents as relevant, the second one with only one relevant document. */ public void testPrecisionAtRequest() { List<RatedRequest> specifications = new ArrayList<>(); SearchSourceBuilder testQuery = new SearchSourceBuilder(); testQuery.query(new MatchAllQueryBuilder()); testQuery.sort("id"); RatedRequest amsterdamRequest = new RatedRequest("amsterdam_query", createRelevant("2", "3", "4", "5"), testQuery); amsterdamRequest.addSummaryFields(Arrays.asList(new String[] { "text", "title" })); specifications.add(amsterdamRequest); RatedRequest berlinRequest = new RatedRequest("berlin_query", createRelevant("1"), testQuery); berlinRequest.addSummaryFields(Arrays.asList(new String[] { "text", "title" })); specifications.add(berlinRequest); PrecisionAtK metric = new PrecisionAtK(1, false, 10); RankEvalSpec task = new RankEvalSpec(specifications, metric); RankEvalRequestBuilder builder = new RankEvalRequestBuilder(client(), new RankEvalRequest()); builder.setRankEvalSpec(task); String indexToUse = randomBoolean() ? TEST_INDEX : INDEX_ALIAS; RankEvalResponse response = client().execute(RankEvalPlugin.ACTION, builder.request().indices(indexToUse)).actionGet(); // the expected Prec@ for the first query is 4/6 and the expected Prec@ for the // second is 1/6, divided by 2 to get the average double expectedPrecision = (1.0 / 6.0 + 4.0 / 6.0) / 2.0; assertEquals(expectedPrecision, response.getMetricScore(), 0.0000000001); Set<Entry<String, EvalQueryQuality>> entrySet = response.getPartialResults().entrySet(); assertEquals(2, entrySet.size()); for (Entry<String, EvalQueryQuality> entry : entrySet) { EvalQueryQuality quality = entry.getValue(); if (entry.getKey() == "amsterdam_query") { assertEquals(2, filterUnratedDocuments(quality.getHitsAndRatings()).size()); List<RatedSearchHit> hitsAndRatings = quality.getHitsAndRatings(); assertEquals(6, hitsAndRatings.size()); for (RatedSearchHit hit : hitsAndRatings) { String id = hit.getSearchHit().getId(); if (id.equals("1") || id.equals("6")) { assertFalse(hit.getRating().isPresent()); } else { assertEquals(RELEVANT_RATING_1, hit.getRating().getAsInt()); } } } if (entry.getKey() == "berlin_query") { assertEquals(5, filterUnratedDocuments(quality.getHitsAndRatings()).size()); List<RatedSearchHit> hitsAndRatings = quality.getHitsAndRatings(); assertEquals(6, hitsAndRatings.size()); for (RatedSearchHit hit : hitsAndRatings) { String id = hit.getSearchHit().getId(); if (id.equals("1")) { assertEquals(RELEVANT_RATING_1, hit.getRating().getAsInt()); } else { assertFalse(hit.getRating().isPresent()); } } } } // test that a different window size k affects the result metric = new PrecisionAtK(1, false, 3); task = new RankEvalSpec(specifications, metric); builder = new RankEvalRequestBuilder(client(), new RankEvalRequest(task, new String[] { TEST_INDEX })); response = client().execute(RankEvalPlugin.ACTION, builder.request()).actionGet(); // if we look only at top 3 documente, the expected P@3 for the first query is // 2/3 and the expected Prec@ for the second is 1/3, divided by 2 to get the average expectedPrecision = (1.0 / 3.0 + 2.0 / 3.0) / 2.0; assertEquals(expectedPrecision, response.getMetricScore(), 0.0000000001); } /** * This test assumes we are using the same ratings as in {@link DiscountedCumulativeGainTests#testDCGAt()}. * See details in that test case for how the expected values are calculated */ public void testDCGRequest() { SearchSourceBuilder testQuery = new SearchSourceBuilder(); testQuery.query(new MatchAllQueryBuilder()); testQuery.sort("id"); List<RatedRequest> specifications = new ArrayList<>(); List<RatedDocument> ratedDocs = Arrays.asList( new RatedDocument(TEST_INDEX, "1", 3), new RatedDocument(TEST_INDEX, "2", 2), new RatedDocument(TEST_INDEX, "3", 3), new RatedDocument(TEST_INDEX, "4", 0), new RatedDocument(TEST_INDEX, "5", 1), new RatedDocument(TEST_INDEX, "6", 2) ); specifications.add(new RatedRequest("amsterdam_query", ratedDocs, testQuery)); DiscountedCumulativeGain metric = new DiscountedCumulativeGain(false, null, 10); RankEvalSpec task = new RankEvalSpec(specifications, metric); RankEvalRequestBuilder builder = new RankEvalRequestBuilder(client(), new RankEvalRequest(task, new String[] { TEST_INDEX })); RankEvalResponse response = client().execute(RankEvalPlugin.ACTION, builder.request()).actionGet(); assertEquals(DiscountedCumulativeGainTests.EXPECTED_DCG, response.getMetricScore(), 10E-14); // test that a different window size k affects the result metric = new DiscountedCumulativeGain(false, null, 3); task = new RankEvalSpec(specifications, metric); builder = new RankEvalRequestBuilder(client(), new RankEvalRequest(task, new String[] { TEST_INDEX })); response = client().execute(RankEvalPlugin.ACTION, builder.request()).actionGet(); assertEquals(12.39278926071437, response.getMetricScore(), 10E-14); } public void testMRRRequest() { SearchSourceBuilder testQuery = new SearchSourceBuilder(); testQuery.query(new MatchAllQueryBuilder()); testQuery.sort("id"); List<RatedRequest> specifications = new ArrayList<>(); specifications.add(new RatedRequest("amsterdam_query", createRelevant("5"), testQuery)); specifications.add(new RatedRequest("berlin_query", createRelevant("1"), testQuery)); MeanReciprocalRank metric = new MeanReciprocalRank(1, 10); RankEvalSpec task = new RankEvalSpec(specifications, metric); RankEvalRequestBuilder builder = new RankEvalRequestBuilder(client(), new RankEvalRequest(task, new String[] { TEST_INDEX })); RankEvalResponse response = client().execute(RankEvalPlugin.ACTION, builder.request()).actionGet(); // the expected reciprocal rank for the amsterdam_query is 1/5 // the expected reciprocal rank for the berlin_query is 1/1 // dividing by 2 to get the average double expectedMRR = (1.0 + 1.0 / 5.0) / 2.0; assertEquals(expectedMRR, response.getMetricScore(), 0.0); // test that a different window size k affects the result metric = new MeanReciprocalRank(1, 3); task = new RankEvalSpec(specifications, metric); builder = new RankEvalRequestBuilder(client(), new RankEvalRequest(task, new String[] { TEST_INDEX })); response = client().execute(RankEvalPlugin.ACTION, builder.request()).actionGet(); // limiting to top 3 results, the amsterdam_query has no relevant document in it // the reciprocal rank for the berlin_query is 1/1 // dividing by 2 to get the average expectedMRR = 1.0 / 2.0; assertEquals(expectedMRR, response.getMetricScore(), 0.0); } /** * test that running a bad query (e.g. one that will target a non existing * field) will produce an error in the response */ public void testBadQuery() { List<RatedRequest> specifications = new ArrayList<>(); SearchSourceBuilder amsterdamQuery = new SearchSourceBuilder(); amsterdamQuery.query(new MatchAllQueryBuilder()); RatedRequest amsterdamRequest = new RatedRequest("amsterdam_query", createRelevant("2", "3", "4", "5"), amsterdamQuery); specifications.add(amsterdamRequest); SearchSourceBuilder brokenQuery = new SearchSourceBuilder(); brokenQuery.query(QueryBuilders.termQuery("population", "noStringOnNumericFields")); RatedRequest brokenRequest = new RatedRequest("broken_query", createRelevant("1"), brokenQuery); specifications.add(brokenRequest); RankEvalSpec task = new RankEvalSpec(specifications, new PrecisionAtK()); RankEvalRequestBuilder builder = new RankEvalRequestBuilder(client(), new RankEvalRequest(task, new String[] { TEST_INDEX })); builder.setRankEvalSpec(task); RankEvalResponse response = client().execute(RankEvalPlugin.ACTION, builder.request()).actionGet(); assertEquals(1, response.getFailures().size()); ElasticsearchException[] rootCauses = ElasticsearchException.guessRootCauses(response.getFailures().get("broken_query")); assertEquals("java.lang.NumberFormatException: For input string: \"noStringOnNumericFields\"", rootCauses[0].getCause().toString()); } /** * test that multiple indices work, setting indices Options is possible and works as expected */ public void testIndicesOptions() { SearchSourceBuilder amsterdamQuery = new SearchSourceBuilder().query(new MatchAllQueryBuilder()); List<RatedDocument> relevantDocs = createRelevant("2", "3", "4", "5", "6"); relevantDocs.add(new RatedDocument("test2", "7", RELEVANT_RATING_1)); List<RatedRequest> specifications = new ArrayList<>(); specifications.add(new RatedRequest("amsterdam_query", relevantDocs, amsterdamQuery)); RankEvalSpec task = new RankEvalSpec(specifications, new PrecisionAtK()); RankEvalRequest request = new RankEvalRequest(task, new String[] { TEST_INDEX, "test2" }); request.setRankEvalSpec(task); RankEvalResponse response = client().execute(RankEvalPlugin.ACTION, request).actionGet(); Detail details = (PrecisionAtK.Detail) response.getPartialResults().get("amsterdam_query").getMetricDetails(); assertEquals(7, details.getRetrieved()); assertEquals(6, details.getRelevantRetrieved()); // test that ignore_unavailable=true works but returns one result less assertTrue(indicesAdmin().prepareClose("test2").get().isAcknowledged()); request.indicesOptions(IndicesOptions.fromParameters(null, "true", null, "false", SearchRequest.DEFAULT_INDICES_OPTIONS)); response = client().execute(RankEvalPlugin.ACTION, request).actionGet(); details = (PrecisionAtK.Detail) response.getPartialResults().get("amsterdam_query").getMetricDetails(); assertEquals(6, details.getRetrieved()); assertEquals(5, details.getRelevantRetrieved()); // test that ignore_unavailable=false or default settings throw an IndexClosedException assertTrue(indicesAdmin().prepareClose("test2").get().isAcknowledged()); request.indicesOptions(IndicesOptions.fromParameters(null, "false", null, "false", SearchRequest.DEFAULT_INDICES_OPTIONS)); response = client().execute(RankEvalPlugin.ACTION, request).actionGet(); assertEquals(1, response.getFailures().size()); assertThat(response.getFailures().get("amsterdam_query"), instanceOf(IndexClosedException.class)); // test expand_wildcards request = new RankEvalRequest(task, new String[] { "tes*" }); request.indicesOptions(IndicesOptions.fromParameters("none", "true", null, "false", SearchRequest.DEFAULT_INDICES_OPTIONS)); response = client().execute(RankEvalPlugin.ACTION, request).actionGet(); details = (PrecisionAtK.Detail) response.getPartialResults().get("amsterdam_query").getMetricDetails(); assertEquals(0, details.getRetrieved()); request.indicesOptions(IndicesOptions.fromParameters("open", null, null, "false", SearchRequest.DEFAULT_INDICES_OPTIONS)); response = client().execute(RankEvalPlugin.ACTION, request).actionGet(); details = (PrecisionAtK.Detail) response.getPartialResults().get("amsterdam_query").getMetricDetails(); assertEquals(6, details.getRetrieved()); assertEquals(5, details.getRelevantRetrieved()); request.indicesOptions(IndicesOptions.fromParameters("closed", null, null, "false", SearchRequest.DEFAULT_INDICES_OPTIONS)); response = client().execute(RankEvalPlugin.ACTION, request).actionGet(); assertEquals(1, response.getFailures().size()); assertThat(response.getFailures().get("amsterdam_query"), instanceOf(IndexClosedException.class)); // test allow_no_indices request = new RankEvalRequest(task, new String[] { "bad*" }); request.indicesOptions(IndicesOptions.fromParameters(null, null, "true", "false", SearchRequest.DEFAULT_INDICES_OPTIONS)); response = client().execute(RankEvalPlugin.ACTION, request).actionGet(); details = (PrecisionAtK.Detail) response.getPartialResults().get("amsterdam_query").getMetricDetails(); assertEquals(0, details.getRetrieved()); request.indicesOptions(IndicesOptions.fromParameters(null, null, "false", "false", SearchRequest.DEFAULT_INDICES_OPTIONS)); response = client().execute(RankEvalPlugin.ACTION, request).actionGet(); assertEquals(1, response.getFailures().size()); assertThat(response.getFailures().get("amsterdam_query"), instanceOf(IndexNotFoundException.class)); } private static List<RatedDocument> createRelevant(String... docs) { List<RatedDocument> relevant = new ArrayList<>(); for (String doc : docs) { relevant.add(new RatedDocument("test", doc, RELEVANT_RATING_1)); } return relevant; } }
RankEvalRequestIT
java
google__guice
core/test/com/google/inject/spi/InjectorSpiTest.java
{ "start": 14418, "end": 14607 }
class ____ { @Inject ClassWithInjectableField(String name) {} @Inject private Integer instanceField; @Inject private static Double staticField; } }
ClassWithInjectableField
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/ValueDeserializerModifier.java
{ "start": 4788, "end": 8365 }
enum ____ deserializer instance. */ public ValueDeserializer<?> modifyEnumDeserializer(DeserializationConfig config, JavaType type, BeanDescription.Supplier beanDescRef, ValueDeserializer<?> deserializer) { return deserializer; } /** * Method called by {@link BeanDeserializerFactory} after constructing default * {@link ReferenceType} deserializer instance. */ public ValueDeserializer<?> modifyReferenceDeserializer(DeserializationConfig config, ReferenceType type, BeanDescription.Supplier beanDescRef, ValueDeserializer<?> deserializer) { return deserializer; } /** * Method called by {@link DeserializerFactory} after it has constructed the * standard deserializer for given * {@link ArrayType} * to make it possible to either replace or augment this deserializer with * additional functionality. * * @param config Configuration in use * @param valueType Type of the value deserializer is used for. * @param beanDescRef Description of the type to deserialize * @param deserializer Default deserializer that would be used. * * @return Deserializer to use; either <code>deserializer</code> that was passed * in, or an instance method constructed. */ public ValueDeserializer<?> modifyArrayDeserializer(DeserializationConfig config, ArrayType valueType, BeanDescription.Supplier beanDescRef, ValueDeserializer<?> deserializer) { return deserializer; } /** * Method called by {@link BeanDeserializerFactory} after constructing default * {@link CollectionType} deserializer instance. */ public ValueDeserializer<?> modifyCollectionDeserializer(DeserializationConfig config, CollectionType type, BeanDescription.Supplier beanDescRef, ValueDeserializer<?> deserializer) { return deserializer; } /** * Method called by {@link BeanDeserializerFactory} after constructing default * {@link CollectionLikeType} deserializer instance. */ public ValueDeserializer<?> modifyCollectionLikeDeserializer(DeserializationConfig config, CollectionLikeType type, BeanDescription.Supplier beanDescRef, ValueDeserializer<?> deserializer) { return deserializer; } /** * Method called by {@link BeanDeserializerFactory} after constructing default * {@link MapType} deserializer instance. */ public ValueDeserializer<?> modifyMapDeserializer(DeserializationConfig config, MapType type, BeanDescription.Supplier beanDescRef, ValueDeserializer<?> deserializer) { return deserializer; } /** * Method called by {@link BeanDeserializerFactory} after constructing default * {@link MapLikeType} deserializer instance. */ public ValueDeserializer<?> modifyMapLikeDeserializer(DeserializationConfig config, MapLikeType type, BeanDescription.Supplier beanDescRef, ValueDeserializer<?> deserializer) { return deserializer; } /** * Method called by {@link DeserializerFactory} after it has constructed the * standard key deserializer for given key type. * This make it possible to replace the default key deserializer, or augment * it somehow (including optional use of default deserializer with occasional * override). */ public KeyDeserializer modifyKeyDeserializer(DeserializationConfig config, JavaType type, KeyDeserializer deserializer) { return deserializer; } }
type
java
quarkusio__quarkus
extensions/hibernate-reactive/deployment/src/test/java/io/quarkus/hibernate/reactive/mapping/timezone/TimezoneDefaultStorageNormalizeTest.java
{ "start": 449, "end": 2210 }
class ____ extends AbstractTimezoneDefaultStorageTest { private static final ZoneId JDBC_TIMEZONE = ZoneId.of("America/Los_Angeles"); @RegisterExtension static QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(EntityWithTimezones.class) .addClasses(SchemaUtil.class)) .withConfigurationResource("application.properties") .overrideConfigKey("quarkus.hibernate-orm.mapping.timezone.default-storage", "normalize") .overrideConfigKey("quarkus.hibernate-orm.jdbc.timezone", JDBC_TIMEZONE.getId()); @Test public void schema() { assertThat(SchemaUtil.getColumnNames(EntityWithTimezones.class, mappingMetamodel())) .doesNotContain("zonedDateTime_tz", "offsetDateTime_tz", "offsetTime_tz"); assertThat(SchemaUtil.getColumnTypeName(EntityWithTimezones.class, "zonedDateTime", mappingMetamodel())) .isEqualTo("TIMESTAMP"); assertThat(SchemaUtil.getColumnTypeName(EntityWithTimezones.class, "offsetDateTime", mappingMetamodel())) .isEqualTo("TIMESTAMP"); } @Test @RunOnVertxContext public void persistAndLoad(UniAsserter asserter) { assertPersistedThenLoadedValues(asserter, PERSISTED_ZONED_DATE_TIME.withZoneSameInstant(ZoneId.systemDefault()), PERSISTED_OFFSET_DATE_TIME.withOffsetSameInstant( ZoneId.systemDefault().getRules().getOffset(PERSISTED_OFFSET_DATE_TIME.toInstant())), PERSISTED_OFFSET_TIME.withOffsetSameInstant( ZoneId.systemDefault().getRules().getOffset(Instant.now()))); } }
TimezoneDefaultStorageNormalizeTest
java
elastic__elasticsearch
libs/entitlement/qa/entitlement-test-plugin/src/main/java/org/elasticsearch/entitlement/qa/test/NioChannelsActions.java
{ "start": 1282, "end": 6200 }
class ____ { @EntitlementTest(expectedAccess = ALWAYS_DENIED) static void createFileChannel() throws IOException { new DummyImplementations.DummyFileChannel().close(); } @EntitlementTest(expectedAccess = PLUGINS) static void fileChannelOpenForWrite() throws IOException { FileChannel.open(FileCheckActions.readWriteFile(), StandardOpenOption.WRITE).close(); } @EntitlementTest(expectedAccess = PLUGINS) static void fileChannelOpenForRead() throws IOException { FileChannel.open(FileCheckActions.readFile()).close(); } @EntitlementTest(expectedAccess = PLUGINS) static void fileChannelOpenForWriteWithOptions() throws IOException { FileChannel.open(FileCheckActions.readWriteFile(), Set.of(StandardOpenOption.WRITE)).close(); } @EntitlementTest(expectedAccess = PLUGINS) static void fileChannelOpenForReadWithOptions() throws IOException { FileChannel.open(FileCheckActions.readFile(), Set.of(StandardOpenOption.READ)).close(); } @EntitlementTest(expectedAccess = ALWAYS_DENIED) static void createAsynchronousFileChannel() { new DummyImplementations.DummyAsynchronousFileChannel().close(); } @EntitlementTest(expectedAccess = PLUGINS) static void asynchronousFileChannelOpenForWrite() throws IOException { var file = EntitledActions.createTempFileForWrite(); AsynchronousFileChannel.open(file, StandardOpenOption.WRITE).close(); } @EntitlementTest(expectedAccess = PLUGINS) static void asynchronousFileChannelOpenForRead() throws IOException { var file = EntitledActions.createTempFileForRead(); AsynchronousFileChannel.open(file).close(); } @EntitlementTest(expectedAccess = PLUGINS) static void asynchronousFileChannelOpenForWriteWithOptions() throws IOException { var file = EntitledActions.createTempFileForWrite(); AsynchronousFileChannel.open(file, Set.of(StandardOpenOption.WRITE), EsExecutors.DIRECT_EXECUTOR_SERVICE).close(); } @EntitlementTest(expectedAccess = PLUGINS) static void asynchronousFileChannelOpenForReadWithOptions() throws IOException { var file = EntitledActions.createTempFileForRead(); AsynchronousFileChannel.open(file, Set.of(StandardOpenOption.READ), EsExecutors.DIRECT_EXECUTOR_SERVICE).close(); } @SuppressForbidden(reason = "specifically testing jdk.nio.Channels") @EntitlementTest(expectedAccess = ALWAYS_DENIED) static void channelsReadWriteSelectableChannel() throws IOException { jdk.nio.Channels.readWriteSelectableChannel(new FileDescriptor(), new DummyImplementations.DummySelectableChannelCloser()).close(); } @EntitlementTest(expectedAccess = PLUGINS) static void selectableChannelRegisterConnect() throws IOException { try (var selectableChannel = new DummyImplementations.DummySelectableChannel(SelectorProvider.provider())) { selectableChannel.configureBlocking(false); selectableChannel.register(new DummyImplementations.DummySelector(SelectorProvider.provider()), SelectionKey.OP_CONNECT); } } @EntitlementTest(expectedAccess = PLUGINS) static void selectableChannelRegisterAccept() throws IOException { try (var selectableChannel = new DummyImplementations.DummySelectableChannel(SelectorProvider.provider())) { selectableChannel.configureBlocking(false); selectableChannel.register(new DummyImplementations.DummySelector(SelectorProvider.provider()), SelectionKey.OP_ACCEPT); } } @EntitlementTest(expectedAccess = PLUGINS) static void selectorProviderOpenSocketChannel() throws IOException { SelectorProvider.provider().openSocketChannel().close(); } @EntitlementTest(expectedAccess = PLUGINS) static void selectorProviderOpenDatagramChannel() throws IOException { SelectorProvider.provider().openDatagramChannel().close(); } @EntitlementTest(expectedAccess = PLUGINS) static void selectorProviderOpenServerSocketChannel() throws IOException { SelectorProvider.provider().openServerSocketChannel().close(); } @EntitlementTest(expectedAccess = PLUGINS) static void selectorProviderOpenSocketChannelWithProtocol() throws IOException { SelectorProvider.provider().openSocketChannel(StandardProtocolFamily.INET).close(); } @EntitlementTest(expectedAccess = PLUGINS) static void selectorProviderOpenDatagramChannelWithProtocol() throws IOException { SelectorProvider.provider().openDatagramChannel(StandardProtocolFamily.INET).close(); } @EntitlementTest(expectedAccess = PLUGINS) static void selectorProviderOpenServerSocketChannelWithProtocol() throws IOException { SelectorProvider.provider().openServerSocketChannel(StandardProtocolFamily.INET).close(); } }
NioChannelsActions
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/naming/NameUtils.java
{ "start": 7385, "end": 27110 }
class ____ as a string. * Shortened name would have package names and owner objects reduced to a single letter. * For example, {@code com.example.Owner$Inner} would become {@code c.e.O$Inner}. * IDEs would still be able to recognize these types, but they would take less space * visually. * * @since 4.8.x * @param typeName The fully-qualified type name * @return The shortened type name */ @Experimental public static @NonNull String getShortenedName(@NonNull String typeName) { int nameStart = typeName.lastIndexOf('$'); if (nameStart < 0) { nameStart = typeName.lastIndexOf('.'); } if (nameStart < 0) { nameStart = 0; } StringBuilder shortened = new StringBuilder(); boolean segmentStart = true; for (int i = 0; i < nameStart; i++) { char c = typeName.charAt(i); if (segmentStart) { shortened.append(c); segmentStart = false; } else if (c == '.' || c == '$') { shortened.append(c); segmentStart = true; } } return shortened.append(typeName.substring(nameStart)).toString(); } /** * Is the given method name a valid setter name. * * @param methodName The method name * @return True if it is a valid setter name */ public static boolean isSetterName(@NonNull String methodName) { return isWriterName(methodName, AccessorsStyle.DEFAULT_WRITE_PREFIX); } /** * Is the given method name a valid writer name for the prefix. * * @param methodName The method name * @param writePrefix The write prefix * @return True if it is a valid writer name * @since 3.3.0 */ public static boolean isWriterName(@NonNull String methodName, @NonNull String writePrefix) { return isWriterName(methodName, new String[]{writePrefix}); } /** * Is the given method name a valid writer name for any of the prefixes. * * @param methodName The method name * @param writePrefixes The write prefixes * @return True if it is a valid writer name * @since 3.3.0 */ public static boolean isWriterName(@NonNull String methodName, @NonNull String[] writePrefixes) { boolean isValid = false; for (String writePrefix : writePrefixes) { if (writePrefix.isEmpty()) { return true; } int len = methodName.length(); int prefixLength = writePrefix.length(); if (len > prefixLength && methodName.startsWith(writePrefix)) { char nextChar = methodName.charAt(prefixLength); isValid = isValidCharacterAfterReaderWriterPrefix(nextChar); } if (isValid) { break; } } return isValid; } /** * Get the equivalent property name for the given setter. * * @param setterName The setter * @return The property name */ public static @NonNull String getPropertyNameForSetter(@NonNull String setterName) { return getPropertyNameForSetter(setterName, AccessorsStyle.DEFAULT_WRITE_PREFIX); } /** * Get the equivalent property name for the given setter and write prefix. * * @param setterName The setter name * @param writePrefix The write prefix * @return The property name * @since 3.3.0 */ public static @NonNull String getPropertyNameForSetter(@NonNull String setterName, @NonNull String writePrefix) { return getPropertyNameForSetter(setterName, new String[]{writePrefix}); } /** * Get the equivalent property name for the given setter and write prefixes. * * @param setterName The setter name * @param writePrefixes The write prefixes * @return The property name * @since 3.3.0 */ public static @NonNull String getPropertyNameForSetter(@NonNull String setterName, @NonNull String[] writePrefixes) { for (String writePrefix : writePrefixes) { if (isWriterName(setterName, writePrefix)) { return decapitalize(setterName.substring(writePrefix.length())); } } return setterName; } /** * Get the equivalent setter name for the given property. * * @param propertyName The property name * @return The setter name */ public static @NonNull String setterNameFor(@NonNull String propertyName) { return setterNameFor(propertyName, PREFIX_SET); } /** * Get the equivalent setter name for the given property and the first prefix. * * @param propertyName The property name * @param prefixes The prefixes * @return The setter name for the first prefix * @since 3.3.0 */ public static @NonNull String setterNameFor(@NonNull String propertyName, @NonNull String[] prefixes) { if (prefixes.length == 0) { return setterNameFor(propertyName, StringUtils.EMPTY_STRING); } else { return setterNameFor(propertyName, prefixes[0]); } } /** * Get the equivalent setter name for the given property and a prefix. * * @param propertyName The property name * @param prefix The prefix * @return The setter name * @since 3.3.0 */ public static @NonNull String setterNameFor(@NonNull String propertyName, @NonNull String prefix) { ArgumentUtils.requireNonNull("propertyName", propertyName); ArgumentUtils.requireNonNull("prefix", prefix); return nameFor(prefix, propertyName); } /** * Is the given method name a valid getter name. * * @param methodName The method name * @return True if it is a valid getter name */ public static boolean isGetterName(@NonNull String methodName) { return isReaderName(methodName, AccessorsStyle.DEFAULT_READ_PREFIX); } /** * Is the given method name a valid reader name. * * @param methodName The method name * @param readPrefix The read prefix * @return True if it is a valid read name * @since 3.3.0 */ public static boolean isReaderName(@NonNull String methodName, @NonNull String readPrefix) { return isReaderName(methodName, new String[]{readPrefix}); } /** * Is the given method name a valid reader name. * * @param methodName The method name * @param readPrefixes The valid read prefixes * @return True if it is a valid reader name * @since 3.3.0 */ public static boolean isReaderName(@NonNull String methodName, @NonNull String[] readPrefixes) { boolean isValid = false; for (String readPrefix : readPrefixes) { int prefixLength = 0; if (readPrefix.isEmpty()) { return true; } else if (methodName.startsWith(readPrefix)) { prefixLength = readPrefix.length(); } else if (methodName.startsWith(PREFIX_IS) && readPrefix.equals(PREFIX_GET)) { prefixLength = IS_LENGTH; } int len = methodName.length(); if (len > prefixLength) { char firstVarNameChar = methodName.charAt(prefixLength); isValid = isValidCharacterAfterReaderWriterPrefix(firstVarNameChar); } if (isValid) { break; } } return isValid; } private static boolean isValidCharacterAfterReaderWriterPrefix(char c) { return c == '_' || c == '$' || Character.isUpperCase(c); } /** * Get the equivalent property name for the given getter. * * @param getterName The getter * @return The property name */ public static @NonNull String getPropertyNameForGetter(@NonNull String getterName) { return getPropertyNameForGetter(getterName, AccessorsStyle.DEFAULT_READ_PREFIX); } /** * Get the equivalent property name for the given getter and read prefix. * * @param getterName The getter * @param readPrefix The read prefix * @return The property name * @since 3.3.0 */ public static @NonNull String getPropertyNameForGetter(@NonNull String getterName, @NonNull String readPrefix) { return getPropertyNameForGetter(getterName, new String[]{readPrefix}); } /** * Get the equivalent property name for the given getter and read prefixes. * * @param getterName The getter * @param readPrefixes The read prefixes * @return The property name * @since 3.3.0 */ public static @NonNull String getPropertyNameForGetter(@NonNull String getterName, @NonNull String[] readPrefixes) { for (String readPrefix: readPrefixes) { if (isReaderName(getterName, readPrefix)) { int prefixLength = 0; if (getterName.startsWith(readPrefix)) { prefixLength = readPrefix.length(); } if (getterName.startsWith(PREFIX_IS) && readPrefix.equals(PREFIX_GET)) { prefixLength = IS_LENGTH; } return decapitalize(getterName.substring(prefixLength)); } } return getterName; } /** * Get the equivalent getter name for the given property. * * @param propertyName The property name * @return The getter name */ public static @NonNull String getterNameFor(@NonNull String propertyName) { return getterNameFor(propertyName, PREFIX_GET); } /** * Get the equivalent getter name for the given property and the first prefix. * * @param propertyName The property name * @param prefixes The prefixes * @return The getter name for the first prefix * @since 3.3.0 */ public static @NonNull String getterNameFor(@NonNull String propertyName, @NonNull String[] prefixes) { if (prefixes.length == 0) { return getterNameFor(propertyName, StringUtils.EMPTY_STRING); } else { return getterNameFor(propertyName, prefixes[0]); } } /** * Get the equivalent getter name for the given property and a prefix. * * @param propertyName The property name * @param prefix The prefix * @return The getter name for the prefix * @since 3.3.0 */ public static @NonNull String getterNameFor(@NonNull String propertyName, @NonNull String prefix) { ArgumentUtils.requireNonNull("propertyName", propertyName); ArgumentUtils.requireNonNull("prefix", prefix); return nameFor(prefix, propertyName); } /** * Get the equivalent getter name for the given property. * * @param propertyName The property name * @param type The type of the property * @return The getter name */ public static @NonNull String getterNameFor(@NonNull String propertyName, @NonNull Class<?> type) { ArgumentUtils.requireNonNull("propertyName", propertyName); final boolean isBoolean = type == boolean.class; return getterNameFor(propertyName, isBoolean); } /** * Get the equivalent getter name for the given property. * * @param propertyName The property name * @param isBoolean Is the property a boolean * @return The getter name */ public static String getterNameFor(@NonNull String propertyName, boolean isBoolean) { return nameFor(isBoolean ? PREFIX_IS : PREFIX_GET, propertyName); } private static @NonNull String nameFor(@Nullable String prefix, @NonNull String propertyName) { if (StringUtils.isEmpty(prefix)) { return propertyName; } final int len = propertyName.length(); switch (len) { case 0: return propertyName; case 1: return prefix + propertyName.toUpperCase(Locale.ENGLISH); default: return prefix + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); } } /** * Decapitalizes a given string according to the rule: * <ul> * <li>If the first or only character is Upper Case, it is made Lower Case * <li>UNLESS the second character is also Upper Case, when the String is * returned unchanged. * </ul> * * @param name The String to decapitalize * @return The decapitalized version of the String */ public static @Nullable String decapitalize(@Nullable String name) { if (name == null) { return null; } int length = name.length(); if (length == 0) { return name; } // Decapitalizes the first character if a lower case // letter is found within 2 characters after the first // Abc -> abc // AB -> AB // ABC -> ABC // ABc -> aBc boolean firstUpper = Character.isUpperCase(name.charAt(0)); if (firstUpper) { if (length == 1) { return Character.toString(Character.toLowerCase(name.charAt(0))); } for (int i = 1; i < Math.min(length, 3); i++) { if (!Character.isUpperCase(name.charAt(i))) { char[] chars = name.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); } } } return name; } static @NonNull String separateCamelCase(@NonNull String name, boolean lowerCase, char separatorChar) { StringBuilder newName = new StringBuilder(name.length() + 4); if (!lowerCase) { boolean first = true; char last = '0'; for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (first) { if (c != separatorChar) { // special case where first char == separatorChar, don't double it // https://github.com/micronaut-projects/micronaut-core/issues/10140 newName.append(c); } first = false; } else { if (Character.isUpperCase(c) && !Character.isUpperCase(last)) { if (c != separatorChar) { newName.append(separatorChar); } newName.append(c); } else { if (c == '.') { first = true; } if (c != separatorChar) { if (last == separatorChar) { newName.append(separatorChar); } newName.append(c); } } } last = c; } } else { boolean first = true; char last = '0'; char secondLast = separatorChar; for (int i = 0; i < name.length(); i++) { char c = name.charAt(i); if (Character.isLowerCase(c) || !Character.isLetter(c)) { first = false; if (c != separatorChar) { if (last == separatorChar) { newName.append(separatorChar); } newName.append(c); } } else { char lowerCaseChar = Character.toLowerCase(c); if (first) { first = false; newName.append(lowerCaseChar); } else if (Character.isUpperCase(last) || last == '.') { newName.append(lowerCaseChar); } else if (Character.isDigit(last) && (Character.isUpperCase(secondLast) || secondLast == separatorChar)) { newName.append(lowerCaseChar); } else { newName.append(separatorChar).append(lowerCaseChar); } } if (i > 1) { secondLast = last; } last = c; } } return newName.toString(); } /** * Retrieves the extension of a file name. * Ex: index.html -&gt; html * * @param filename The name of the file * @return The file extension */ public static @NonNull String extension(@NonNull String filename) { int extensionPos = filename.lastIndexOf('.'); int lastUnixPos = filename.lastIndexOf('/'); int lastWindowsPos = filename.lastIndexOf('\\'); int lastSeparator = Math.max(lastUnixPos, lastWindowsPos); int index = lastSeparator > extensionPos ? -1 : extensionPos; if (index == -1) { return ""; } return filename.substring(index + 1); } /** * The camel case version of the string with the first letter in lower case. * * @param str The string * @return The new string in camel case */ public static @NonNull String camelCase(@NonNull String str) { return camelCase(str, true); } /** * The camel case version of the string with the first letter in lower case. * * @param str The string * @param lowerCaseFirstLetter Whether the first letter is in upper case or lower case * @return The new string in camel case */ public static @NonNull String camelCase(@NonNull String str, boolean lowerCaseFirstLetter) { StringBuilder sb = new StringBuilder(str.length()); for (String s : str.split("[\\s_-]")) { String capitalize = capitalize(s); sb.append(capitalize); } String result = sb.toString(); if (lowerCaseFirstLetter) { return decapitalize(result); } return result; } /** * Retrieves the fileName of a file without extension. * Ex: index.html -&gt; index * * @param path The path of the file * @return The file name without extension */ public static @NonNull String filename(@NonNull String path) { int extensionPos = path.lastIndexOf('.'); int lastUnixPos = path.lastIndexOf('/'); int lastWindowsPos = path.lastIndexOf('\\'); int lastSeparator = Math.max(lastUnixPos, lastWindowsPos); int index = lastSeparator > extensionPos ? path.length() : extensionPos; if (index == -1) { return ""; } return path.substring(lastSeparator + 1, index); } /** * Checks whether the string is a valid hyphenated (kebab-case) property name. * * @param str The string to check * @return Whether is valid kebab-case or not */ public static boolean isValidHyphenatedPropertyName(@NonNull String str) { return KEBAB_CASE_SEQUENCE.matcher(str).matches(); } /** * Checks whether the string is a valid environment-style property name. * * @param str The string to check * @return Whether is valid environment-style property name or not */ public static boolean isEnvironmentName(@NonNull String str) { return ENVIRONMENT_VAR_SEQUENCE.matcher(str).matches(); } }
represented
java
apache__kafka
trogdor/src/test/java/org/apache/kafka/trogdor/basic/BasicPlatformTest.java
{ "start": 1223, "end": 2682 }
class ____ { @Test public void testCreateBasicPlatform() throws Exception { File configFile = TestUtils.tempFile(); try { try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(configFile.toPath()), StandardCharsets.UTF_8)) { writer.write("{\n"); writer.write(" \"platform\": \"org.apache.kafka.trogdor.basic.BasicPlatform\",\n"); writer.write(" \"nodes\": {\n"); writer.write(" \"bob01\": {\n"); writer.write(" \"hostname\": \"localhost\",\n"); writer.write(" \"trogdor.agent.port\": 8888\n"); writer.write(" },\n"); writer.write(" \"bob02\": {\n"); writer.write(" \"hostname\": \"localhost\",\n"); writer.write(" \"trogdor.agent.port\": 8889\n"); writer.write(" }\n"); writer.write(" }\n"); writer.write("}\n"); } Platform platform = Platform.Config.parse("bob01", configFile.getPath()); assertEquals("BasicPlatform", platform.name()); assertEquals(2, platform.topology().nodes().size()); assertEquals("bob01, bob02", String.join(", ", platform.topology().nodes().keySet())); } finally { Files.delete(configFile.toPath()); } } }
BasicPlatformTest
java
netty__netty
transport/src/main/java/io/netty/channel/nio/AbstractNioByteChannel.java
{ "start": 1770, "end": 3625 }
class ____ extends AbstractNioChannel { private static final ChannelMetadata METADATA = new ChannelMetadata(false, 16); private static final String EXPECTED_TYPES = " (expected: " + StringUtil.simpleClassName(ByteBuf.class) + ", " + StringUtil.simpleClassName(FileRegion.class) + ')'; private final Runnable flushTask = new Runnable() { @Override public void run() { // Calling flush0 directly to ensure we not try to flush messages that were added via write(...) in the // meantime. ((AbstractNioUnsafe) unsafe()).flush0(); } }; private boolean inputClosedSeenErrorOnRead; /** * Create a new instance * * @param parent the parent {@link Channel} by which this instance was created. May be {@code null} * @param ch the underlying {@link SelectableChannel} on which it operates */ protected AbstractNioByteChannel(Channel parent, SelectableChannel ch) { super(parent, ch, SelectionKey.OP_READ); } /** * Shutdown the input side of the channel. */ protected abstract ChannelFuture shutdownInput(); protected boolean isInputShutdown0() { return false; } @Override protected AbstractNioUnsafe newUnsafe() { return new NioByteUnsafe(); } @Override public ChannelMetadata metadata() { return METADATA; } final boolean shouldBreakReadReady(ChannelConfig config) { return isInputShutdown0() && (inputClosedSeenErrorOnRead || !isAllowHalfClosure(config)); } private static boolean isAllowHalfClosure(ChannelConfig config) { return config instanceof SocketChannelConfig && ((SocketChannelConfig) config).isAllowHalfClosure(); } protected
AbstractNioByteChannel
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/lucene/index/FilterableTermsEnum.java
{ "start": 1710, "end": 1768 }
class ____ extends TermsEnum { static
FilterableTermsEnum
java
spring-projects__spring-framework
spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java
{ "start": 14613, "end": 16236 }
class ____ { @Test void transactionAttributeDeclaredOnClassMethod() { TransactionAttribute getAgeAttr = getTransactionAttribute(Ejb3AnnotatedBean1.class, ITestBean1.class, "getAge"); assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = getTransactionAttribute(Ejb3AnnotatedBean1.class, ITestBean1.class, "getName"); assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_SUPPORTS); } @Test void transactionAttributeDeclaredOnClass() { TransactionAttribute getAgeAttr = getTransactionAttribute(Ejb3AnnotatedBean2.class, ITestBean1.class, "getAge"); assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = getTransactionAttribute(Ejb3AnnotatedBean2.class, ITestBean1.class, "getName"); assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_SUPPORTS); } @Test void transactionAttributeDeclaredOnInterface() { TransactionAttribute getAgeAttr = getTransactionAttribute(Ejb3AnnotatedBean3.class, ITestEjb.class, "getAge"); assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = getTransactionAttribute(Ejb3AnnotatedBean3.class, ITestEjb.class, "getName"); assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_SUPPORTS); } @jakarta.ejb.TransactionAttribute(TransactionAttributeType.SUPPORTS)
Ejb3AttributeTests
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java
{ "start": 138601, "end": 138959 }
class ____ extends BaseClassWithDestroyMethod { static int closeCount = 0; @SuppressWarnings("unused") private BeanWithDestroyMethod inner; public void setInner(BeanWithDestroyMethod inner) { this.inner = inner; } @Override public BeanWithDestroyMethod close() { closeCount++; return this; } } public static
BeanWithDestroyMethod
java
netty__netty
buffer/src/main/java/io/netty/buffer/ByteBufConvertible.java
{ "start": 672, "end": 864 }
interface ____ can be implemented by any object that know how to turn itself into a {@link ByteBuf}. * All {@link ByteBuf} classes implement this interface, and return themselves. */ public
that
java
junit-team__junit5
platform-tooling-support-tests/src/test/java/platform/tooling/support/tests/GradleModuleFileTests.java
{ "start": 638, "end": 5245 }
class ____ { @Test void jupiterAggregatorGradleModuleMetadataVariants() throws Exception { var expected = List.of(">> HEAD >>", // "{", // " \"formatVersion\": \"1.1\",", // " \"component\": {", // " \"group\": \"org.junit.jupiter\",", // " \"module\": \"junit-jupiter\",", // ">> VERSION >>", // " \"attributes\": {", // ">> STATUS >>", // " }", // " },", // ">> CREATED_BY >>", // " \"variants\": [", // " {", // " \"name\": \"apiElements\",", // " \"attributes\": {", // " \"org.gradle.category\": \"library\",", // " \"org.gradle.dependency.bundling\": \"external\",", // " \"org.gradle.jvm.version\": 17,", // " \"org.gradle.libraryelements\": \"jar\",", // " \"org.gradle.usage\": \"java-api\"", // " },", // " \"dependencies\": [", // " {", // " \"group\": \"org.junit\",", // " \"module\": \"junit-bom\",", // " \"version\": {", // ">> VERSION >>", // " },", // " \"attributes\": {", // " \"org.gradle.category\": \"platform\"", // " },", // " \"endorseStrictVersions\": true", // " },", // " {", // " \"group\": \"org.junit.jupiter\",", // " \"module\": \"junit-jupiter-api\",", // " \"version\": {", // ">> VERSION >>", // " }", // " },", // " {", // " \"group\": \"org.junit.jupiter\",", // " \"module\": \"junit-jupiter-params\",", // " \"version\": {", // ">> VERSION >>", // " }", // " }", // " ],", // " \"files\": [", // " {", // ">> JAR_FILE_DETAILS >>", // " }", // " ]", // " },", // " {", // " \"name\": \"runtimeElements\",", // " \"attributes\": {", // " \"org.gradle.category\": \"library\",", // " \"org.gradle.dependency.bundling\": \"external\",", // " \"org.gradle.jvm.version\": 17,", // " \"org.gradle.libraryelements\": \"jar\",", // " \"org.gradle.usage\": \"java-runtime\"", // " },", // " \"dependencies\": [", // " {", // " \"group\": \"org.junit.jupiter\",", // " \"module\": \"junit-jupiter-engine\",", // " \"version\": {", // ">> VERSION >>", // " }", // " },", // " {", // " \"group\": \"org.junit\",", // " \"module\": \"junit-bom\",", // " \"version\": {", // ">> VERSION >>", // " },", // " \"attributes\": {", // " \"org.gradle.category\": \"platform\"", // " },", // " \"endorseStrictVersions\": true", // " },", // " {", // " \"group\": \"org.junit.jupiter\",", // " \"module\": \"junit-jupiter-api\",", // " \"version\": {", // ">> VERSION >>", // " }", // " },", // " {", // " \"group\": \"org.junit.jupiter\",", // " \"module\": \"junit-jupiter-params\",", // " \"version\": {", // ">> VERSION >>", // " }", // " }", // " ],", // " \"files\": [", // " {", // ">> JAR_FILE_DETAILS >>", // " }", // " ]", // " },", // " {", // " \"name\": \"javadocElements\",", // " \"attributes\": {", // " \"org.gradle.category\": \"documentation\",", // " \"org.gradle.dependency.bundling\": \"external\",", // " \"org.gradle.docstype\": \"javadoc\",", // " \"org.gradle.usage\": \"java-runtime\"", // " },", // " \"files\": [", // " {", // ">> JAR_FILE_DETAILS >>", // " }", // " ]", // " },", // " {", // " \"name\": \"sourcesElements\",", // " \"attributes\": {", // " \"org.gradle.category\": \"documentation\",", // " \"org.gradle.dependency.bundling\": \"external\",", // " \"org.gradle.docstype\": \"sources\",", // " \"org.gradle.usage\": \"java-runtime\"", // " },", // " \"files\": [", // " {", // ">> JAR_FILE_DETAILS >>", // " }", // " ]", // " }", // " ]", // "}"); assertLinesMatch(expected, Files.readAllLines(MavenRepo.gradleModuleMetadata("junit-jupiter"))); } }
GradleModuleFileTests
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/server/i18n/LocaleContextResolver.java
{ "start": 1260, "end": 2571 }
interface ____ { /** * Resolve the current locale context via the given exchange. * <p>The returned context may be a * {@link org.springframework.context.i18n.TimeZoneAwareLocaleContext}, * containing a locale with associated time zone information. * Simply apply an {@code instanceof} check and downcast accordingly. * <p>Custom resolver implementations may also return extra settings in * the returned context, which again can be accessed through downcasting. * @param exchange current server exchange * @return the current locale context (never {@code null}) */ LocaleContext resolveLocaleContext(ServerWebExchange exchange); /** * Set the current locale context to the given one, * potentially including a locale with associated time zone information. * @param exchange current server exchange * @param localeContext the new locale context, or {@code null} to clear the locale * @throws UnsupportedOperationException if the LocaleResolver implementation * does not support dynamic changing of the locale or time zone * @see org.springframework.context.i18n.SimpleLocaleContext * @see org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext */ void setLocaleContext(ServerWebExchange exchange, @Nullable LocaleContext localeContext); }
LocaleContextResolver
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/ProjectBuildFailureException.java
{ "start": 1207, "end": 1725 }
class ____ extends BuildFailureException { private final String projectId; public ProjectBuildFailureException(String projectId, MojoFailureException cause) { super("Build for project: " + projectId + " failed during execution of mojo.", cause); this.projectId = projectId; } public MojoFailureException getMojoFailureException() { return (MojoFailureException) getCause(); } public String getProjectId() { return projectId; } }
ProjectBuildFailureException
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsNodes.java
{ "start": 25997, "end": 27377 }
class ____ implements ToXContentFragment { private final Map<String, AtomicInteger> packagingTypes; PackagingTypes(final List<NodeInfo> nodeInfos) { final var packagingTypes = new HashMap<String, AtomicInteger>(); for (final var nodeInfo : nodeInfos) { final var type = nodeInfo.getBuild().type().displayName(); packagingTypes.computeIfAbsent(type, k -> new AtomicInteger()).incrementAndGet(); } this.packagingTypes = Collections.unmodifiableMap(packagingTypes); } @Override public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { builder.startArray("packaging_types"); { for (final var entry : packagingTypes.entrySet()) { builder.startObject(); { // flavor is no longer used, but we keep it here for backcompat builder.field("flavor", "default"); builder.field("type", entry.getKey()); builder.field("count", entry.getValue().get()); } builder.endObject(); } } builder.endArray(); return builder; } } static
PackagingTypes
java
hibernate__hibernate-orm
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/pagination/TimesTenLimitHandler.java
{ "start": 504, "end": 1942 }
class ____ extends AbstractSimpleLimitHandler { public static final TimesTenLimitHandler INSTANCE = new TimesTenLimitHandler(); public TimesTenLimitHandler(){ } @Override public boolean supportsLimitOffset() { return true; } @Override // TimesTen is 1 based public int convertToFirstRowValue(int zeroBasedFirstResult) { return zeroBasedFirstResult + 1; } @Override public boolean useMaxForLimit() { return true; } @Override public boolean bindLimitParametersFirst() { return true; } @Override protected String limitClause(boolean hasFirstRow) { return hasFirstRow ? " rows ? to ?" : " first ?"; } @Override protected String limitClause(boolean hasFirstRow, int jdbcParameterCount, ParameterMarkerStrategy parameterMarkerStrategy) { final String firstParameter = parameterMarkerStrategy.createMarker( 1, null ); if ( hasFirstRow ) { return " rows " + firstParameter + " to " + parameterMarkerStrategy.createMarker( 2, null ); } else { return " first " + firstParameter; } } @Override protected String offsetOnlyClause(int jdbcParameterCount, ParameterMarkerStrategy parameterMarkerStrategy) { return " rows " + parameterMarkerStrategy.createMarker( 1, null ) + " to " + Integer.MAX_VALUE; } @Override public int getParameterPositionStart(Limit limit) { return hasMaxRows( limit ) ? hasFirstRow( limit ) ? 3 : 2 : hasFirstRow( limit ) ? 2 : 1; } }
TimesTenLimitHandler
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/config/conditional/DisableBuiltInPredicatesTests.java
{ "start": 3765, "end": 3997 }
class ____ { @Autowired(required = false) private List<RoutePredicateFactory<?>> predicates; @Test public void shouldDisableAllBuiltInPredicates() { assertThat(predicates).isNull(); } } }
DisableAllPredicatesByProperty
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/android/FragmentNotInstantiable.java
{ "start": 4053, "end": 4504 }
class ____ (or their stubs). return Description.NO_MATCH; } // The check doesn't apply to abstract classes. if (classTree.getModifiers().getFlags().contains(ABSTRACT)) { return Description.NO_MATCH; } // A fragment must be public. if (!classTree.getModifiers().getFlags().contains(PUBLIC)) { return buildErrorMessage(classTree, "a fragment must be public"); } // A fragment that is an inner
declarations
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/config/ServiceConfigBase.java
{ "start": 2156, "end": 2281 }
interface ____ of the exported service. */ protected Class<?> interfaceClass; /** * The reference to the
class
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/BadInstanceofTest.java
{ "start": 1895, "end": 2087 }
class ____ extends A {} } """) .doTest(); } @Test public void positiveCases() { compilationHelper .addSourceLines( "Test.java", """
C
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/InMemoryOAuth2AuthorizationConsentService.java
{ "start": 1269, "end": 4101 }
class ____ implements OAuth2AuthorizationConsentService { private final Map<Integer, OAuth2AuthorizationConsent> authorizationConsents = new ConcurrentHashMap<>(); /** * Constructs an {@code InMemoryOAuth2AuthorizationConsentService}. */ public InMemoryOAuth2AuthorizationConsentService() { this(Collections.emptyList()); } /** * Constructs an {@code InMemoryOAuth2AuthorizationConsentService} using the provided * parameters. * @param authorizationConsents the authorization consent(s) */ public InMemoryOAuth2AuthorizationConsentService(OAuth2AuthorizationConsent... authorizationConsents) { this(Arrays.asList(authorizationConsents)); } /** * Constructs an {@code InMemoryOAuth2AuthorizationConsentService} using the provided * parameters. * @param authorizationConsents the authorization consent(s) */ public InMemoryOAuth2AuthorizationConsentService(List<OAuth2AuthorizationConsent> authorizationConsents) { Assert.notNull(authorizationConsents, "authorizationConsents cannot be null"); authorizationConsents.forEach((authorizationConsent) -> { Assert.notNull(authorizationConsent, "authorizationConsent cannot be null"); int id = getId(authorizationConsent); Assert.isTrue(!this.authorizationConsents.containsKey(id), "The authorizationConsent must be unique. Found duplicate, with registered client id: [" + authorizationConsent.getRegisteredClientId() + "] and principal name: [" + authorizationConsent.getPrincipalName() + "]"); this.authorizationConsents.put(id, authorizationConsent); }); } @Override public void save(OAuth2AuthorizationConsent authorizationConsent) { Assert.notNull(authorizationConsent, "authorizationConsent cannot be null"); int id = getId(authorizationConsent); this.authorizationConsents.put(id, authorizationConsent); } @Override public void remove(OAuth2AuthorizationConsent authorizationConsent) { Assert.notNull(authorizationConsent, "authorizationConsent cannot be null"); int id = getId(authorizationConsent); this.authorizationConsents.remove(id, authorizationConsent); } @Override @Nullable public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) { Assert.hasText(registeredClientId, "registeredClientId cannot be empty"); Assert.hasText(principalName, "principalName cannot be empty"); int id = getId(registeredClientId, principalName); return this.authorizationConsents.get(id); } private static int getId(String registeredClientId, String principalName) { return Objects.hash(registeredClientId, principalName); } private static int getId(OAuth2AuthorizationConsent authorizationConsent) { return getId(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName()); } }
InMemoryOAuth2AuthorizationConsentService
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/output/EnumSetOutput.java
{ "start": 418, "end": 984 }
class ____<K, V, E extends Enum<E>> extends CommandOutput<K, V, Set<E>> { private boolean initialized; private final Class<E> enumClass; private final UnaryOperator<String> enumValuePreprocessor; private final Function<String, E> onUnknownValue; /** * Create a new {@link EnumSetOutput}. * * @param codec Codec used to encode/decode keys and values, must not be {@code null}. * @param enumClass {@link Enum} type. * @param enumValuePreprocessor pre-processor for {@link String} values before looking up the
EnumSetOutput
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/saml/SamlAuthenticateResponseHandler.java
{ "start": 1574, "end": 1845 }
class ____ implements Factory { @Override public SamlAuthenticateResponseHandler create(Settings settings, TokenService tokenService, Clock clock) { return new DefaultSamlAuthenticateResponseHandler(tokenService); } } }
DefaultFactory
java
bumptech__glide
instrumentation/src/androidTest/java/com/bumptech/glide/RequestTest.java
{ "start": 1327, "end": 9611 }
class ____ { @Rule public TearDownGlide tearDownGlide = new TearDownGlide(); @Mock private RequestListener<Drawable> requestListener; private final ConcurrencyHelper concurrency = new ConcurrencyHelper(); private Context context; private ImageView imageView; @Before public void setUp() { MockitoAnnotations.initMocks(this); context = ApplicationProvider.getApplicationContext(); imageView = new ImageView(context); imageView.measure(100, 100); imageView.layout(0, 0, 100, 100); // Some emulators only have a single resize thread, so waiting on a latch will block them // forever. Glide.init( context, new GlideBuilder().setSourceExecutor(GlideExecutor.newUnlimitedSourceExecutor())); } @Test public void clear_withSingleRequest_nullsOutDrawableInView() { concurrency.loadOnMainThread(GlideApp.with(context).load(ResourceIds.raw.canonical), imageView); assertThat(imageView.getDrawable()).isNotNull(); concurrency.clearOnMainThread(imageView); assertThat(imageView.getDrawable()).isNull(); } @Test public void clear_withRequestWithThumbnail_nullsOutDrawableInView() { concurrency.loadOnMainThread( GlideApp.with(context) .load(ResourceIds.raw.canonical) .thumbnail(GlideApp.with(context).load(ResourceIds.raw.canonical).override(100, 100)), imageView); assertThat(imageView.getDrawable()).isNotNull(); concurrency.clearOnMainThread(imageView); assertThat(imageView.getDrawable()).isNull(); } @Test public void onStop_withSingleRequest_doesNotNullOutDrawableInView() { concurrency.loadOnMainThread(GlideApp.with(context).load(ResourceIds.raw.canonical), imageView); assertThat(imageView.getDrawable()).isNotNull(); concurrency.runOnMainThread( new Runnable() { @Override public void run() { GlideApp.with(context).onStop(); } }); assertThat(imageView.getDrawable()).isNotNull(); } @Test public void onStop_withRequestWithThumbnail_doesNotNullOutDrawableInView() { concurrency.loadOnMainThread( GlideApp.with(context) .load(ResourceIds.raw.canonical) .thumbnail(GlideApp.with(context).load(ResourceIds.raw.canonical).override(100, 100)), imageView); assertThat(imageView.getDrawable()).isNotNull(); concurrency.runOnMainThread( new Runnable() { @Override public void run() { GlideApp.with(context).onStop(); } }); assertThat(imageView.getDrawable()).isNotNull(); } @Test public void onStop_withSingleRequestInProgress_nullsOutDrawableInView() { final WaitModel<Integer> model = WaitModelLoader.waitOn(ResourceIds.raw.canonical); concurrency.runOnMainThread( new Runnable() { @Override public void run() { GlideApp.with(context).load(ResourceIds.raw.canonical).into(imageView); } }); concurrency.runOnMainThread( new Runnable() { @Override public void run() { GlideApp.with(context).onStop(); } }); assertThat(imageView.getDrawable()).isNull(); model.countDown(); } @Test public void onStop_withRequestWithThumbnailBothInProgress_nullsOutDrawableInView() { final WaitModel<Integer> model = WaitModelLoader.waitOn(ResourceIds.raw.canonical); concurrency.runOnMainThread( new Runnable() { @Override public void run() { GlideApp.with(context) .load(model) .thumbnail(GlideApp.with(context).load(model).override(100, 100)) .into(imageView); } }); concurrency.runOnMainThread( new Runnable() { @Override public void run() { GlideApp.with(context).onStop(); } }); assertThat(imageView.getDrawable()).isNull(); model.countDown(); } /** Tests #2555. */ @Test public void clear_withRequestWithOnlyFullInProgress_nullsOutDrawableInView() { final WaitModel<Integer> mainModel = WaitModelLoader.waitOn(ResourceIds.raw.canonical); concurrency.loadUntilFirstFinish( GlideApp.with(context) .load(mainModel) .listener(requestListener) .thumbnail( GlideApp.with(context) .load(ResourceIds.raw.canonical) .listener(requestListener) .override(100, 100)), imageView); concurrency.runOnMainThread( new Runnable() { @Override public void run() { GlideApp.with(context).clear(imageView); } }); verify(requestListener, never()) .onResourceReady( ArgumentMatchers.<Drawable>any(), any(), ArgumentMatchers.<Target<Drawable>>any(), eq(DataSource.DATA_DISK_CACHE), anyBoolean()); verify(requestListener, never()) .onResourceReady( ArgumentMatchers.<Drawable>any(), any(), ArgumentMatchers.<Target<Drawable>>any(), eq(DataSource.RESOURCE_DISK_CACHE), anyBoolean()); assertThat(imageView.getDrawable()).isNull(); mainModel.countDown(); } @Test public void clear_withRequestWithOnlyFullInProgress_doesNotNullOutDrawableInView() { final WaitModel<Integer> mainModel = WaitModelLoader.waitOn(ResourceIds.raw.canonical); concurrency.loadUntilFirstFinish( GlideApp.with(context) .load(mainModel) .listener(requestListener) .thumbnail( GlideApp.with(context) .load(ResourceIds.raw.canonical) .listener(requestListener) .override(100, 100)), imageView); concurrency.runOnMainThread( new Runnable() { @Override public void run() { GlideApp.with(context).onStop(); } }); verify(requestListener, never()) .onResourceReady( ArgumentMatchers.<Drawable>any(), any(), ArgumentMatchers.<Target<Drawable>>any(), eq(DataSource.DATA_DISK_CACHE), anyBoolean()); verify(requestListener, never()) .onResourceReady( ArgumentMatchers.<Drawable>any(), any(), ArgumentMatchers.<Target<Drawable>>any(), eq(DataSource.RESOURCE_DISK_CACHE), anyBoolean()); assertThat(imageView.getDrawable()).isNotNull(); mainModel.countDown(); } @Test public void onStop_withRequestWithOnlyThumbnailInProgress_doesNotNullOutDrawableInView() { final WaitModel<Integer> thumbModel = WaitModelLoader.waitOn(ResourceIds.raw.canonical); concurrency.loadUntilFirstFinish( GlideApp.with(context) .load(ResourceIds.raw.canonical) .listener(requestListener) .thumbnail( GlideApp.with(context) .load(thumbModel) .listener(requestListener) .override(100, 100)), imageView); concurrency.runOnMainThread( new Runnable() { @Override public void run() { GlideApp.with(context).onStop(); } }); verify(requestListener, never()) .onResourceReady( ArgumentMatchers.<Drawable>any(), any(), ArgumentMatchers.<Target<Drawable>>any(), eq(DataSource.DATA_DISK_CACHE), anyBoolean()); verify(requestListener, never()) .onResourceReady( ArgumentMatchers.<Drawable>any(), any(), ArgumentMatchers.<Target<Drawable>>any(), eq(DataSource.RESOURCE_DISK_CACHE), anyBoolean()); // Only requests that are running are paused in onStop. The full request should take priority // over the thumbnail request. Therefore, if the full request is finished in onStop, it should // not be cleared, even if the thumbnail request is still running. assertThat(imageView.getDrawable()).isNotNull(); thumbModel.countDown(); } }
RequestTest
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/impl/SetterlessProperty.java
{ "start": 835, "end": 5726 }
class ____ extends SettableBeanProperty { protected final AnnotatedMethod _annotated; /** * Get method for accessing property value used to access property * (of Collection or Map type) to modify. */ protected final Method _getter; public SetterlessProperty(BeanPropertyDefinition propDef, JavaType type, TypeDeserializer typeDeser, Annotations contextAnnotations, AnnotatedMethod method) { super(propDef, type, typeDeser, contextAnnotations); _annotated = method; _getter = method.getAnnotated(); } protected SetterlessProperty(SetterlessProperty src, ValueDeserializer<?> deser, NullValueProvider nva) { super(src, deser, nva); _annotated = src._annotated; _getter = src._getter; } protected SetterlessProperty(SetterlessProperty src, PropertyName newName) { super(src, newName); _annotated = src._annotated; _getter = src._getter; } @Override public SettableBeanProperty withName(PropertyName newName) { return new SetterlessProperty(this, newName); } @Override public SettableBeanProperty withValueDeserializer(ValueDeserializer<?> deser) { if (_valueDeserializer == deser) { return this; } // 07-May-2019, tatu: As per [databind#2303], must keep VD/NVP in-sync if they were NullValueProvider nvp = (_valueDeserializer == _nullProvider) ? deser : _nullProvider; return new SetterlessProperty(this, deser, nvp); } @Override public SettableBeanProperty withNullProvider(NullValueProvider nva) { return new SetterlessProperty(this, _valueDeserializer, nva); } @Override public void fixAccess(DeserializationConfig config) { _annotated.fixAccess( config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS)); } @Override // since 2.20 public boolean isMerging() { return true; } /* /********************************************************** /* BeanProperty impl /********************************************************** */ @Override public <A extends Annotation> A getAnnotation(Class<A> acls) { return _annotated.getAnnotation(acls); } @Override public AnnotatedMember getMember() { return _annotated; } /* /********************************************************** /* Overridden methods /********************************************************** */ @Override public final void deserializeAndSet(JsonParser p, DeserializationContext ctxt, Object instance) throws JacksonException { JsonToken t = p.currentToken(); if (t == JsonToken.VALUE_NULL) { // Hmmh. Is this a problem? We won't be setting anything, so it's // equivalent of empty Collection/Map in this case return; } // For [databind#501] fix we need to implement this but: if (_valueTypeDeserializer != null) { ctxt.reportBadDefinition(getType(), String.format( "Problem deserializing 'setterless' property (\"%s\"): no way to handle typed deser with setterless yet", getName())); // return _valueDeserializer.deserializeWithType(p, ctxt, _valueTypeDeserializer); } // Ok: then, need to fetch Collection/Map to modify: Object toModify; try { toModify = _getter.invoke(instance, (Object[]) null); } catch (Exception e) { _throwAsJacksonE(p, e); return; // never gets here } // Note: null won't work, since we can't then inject anything in. At least // that's not good in common case. However, theoretically the case where // we get JSON null might be compatible. If so, implementation could be changed. if (toModify == null) { ctxt.reportBadDefinition(getType(), String.format( "Problem deserializing 'setterless' property '%s': get method returned null", getName())); } _valueDeserializer.deserialize(p, ctxt, toModify); } @Override public Object deserializeSetAndReturn(JsonParser p, DeserializationContext ctxt, Object instance) throws JacksonException { deserializeAndSet(p, ctxt, instance); return instance; } @Override public final void set(DeserializationContext ctxt, Object instance, Object value) { throw new UnsupportedOperationException("Should never call `set()` on setterless property ('"+getName()+"')"); } @Override public Object setAndReturn(DeserializationContext ctxt, Object instance, Object value) { set(ctxt, instance, value); return instance; } }
SetterlessProperty
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/Mapper.java
{ "start": 4427, "end": 4907 }
interface ____ { Mapper.Builder parse(String name, Map<String, Object> node, MappingParserContext parserContext) throws MapperParsingException; /** * Whether we can parse this type on indices with the given index created version. */ default boolean supportsVersion(IndexVersion indexCreatedVersion) { return indexCreatedVersion.onOrAfter(IndexVersions.MINIMUM_READONLY_COMPATIBLE); } } /** * This
TypeParser
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/CheckpointCoordinatorMasterHooksTest.java
{ "start": 3126, "end": 22742 }
class ____ { @RegisterExtension static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE = TestingUtils.defaultExecutorExtension(); // ------------------------------------------------------------------------ // hook registration // ------------------------------------------------------------------------ /** This method tests that hooks with the same identifier are not registered multiple times. */ @Test void testDeduplicateOnRegister() throws Exception { ExecutionGraph graph = new CheckpointCoordinatorTestingUtils.CheckpointExecutionGraphBuilder() .addJobVertex(new JobVertexID()) .build(EXECUTOR_RESOURCE.getExecutor()); final CheckpointCoordinator cc = instantiateCheckpointCoordinator(graph); MasterTriggerRestoreHook<?> hook1 = mock(MasterTriggerRestoreHook.class); when(hook1.getIdentifier()).thenReturn("test id"); MasterTriggerRestoreHook<?> hook2 = mock(MasterTriggerRestoreHook.class); when(hook2.getIdentifier()).thenReturn("test id"); MasterTriggerRestoreHook<?> hook3 = mock(MasterTriggerRestoreHook.class); when(hook3.getIdentifier()).thenReturn("anotherId"); assertThat(cc.addMasterHook(hook1)).isTrue(); assertThat(cc.addMasterHook(hook2)).isFalse(); assertThat(cc.addMasterHook(hook3)).isTrue(); } /** Test that validates correct exceptions when supplying hooks with invalid IDs. */ @Test void testNullOrInvalidId() throws Exception { ExecutionGraph graph = new CheckpointCoordinatorTestingUtils.CheckpointExecutionGraphBuilder() .addJobVertex(new JobVertexID()) .build(EXECUTOR_RESOURCE.getExecutor()); final CheckpointCoordinator cc = instantiateCheckpointCoordinator(graph); try { cc.addMasterHook(null); fail("expected an exception"); } catch (NullPointerException ignored) { } try { cc.addMasterHook(mock(MasterTriggerRestoreHook.class)); fail("expected an exception"); } catch (IllegalArgumentException ignored) { } try { MasterTriggerRestoreHook<?> hook = mock(MasterTriggerRestoreHook.class); when(hook.getIdentifier()).thenReturn(" "); cc.addMasterHook(hook); fail("expected an exception"); } catch (IllegalArgumentException ignored) { } } @Test void testHookReset() throws Exception { final String id1 = "id1"; final String id2 = "id2"; final MasterTriggerRestoreHook<String> hook1 = mockGeneric(MasterTriggerRestoreHook.class); when(hook1.getIdentifier()).thenReturn(id1); final MasterTriggerRestoreHook<String> hook2 = mockGeneric(MasterTriggerRestoreHook.class); when(hook2.getIdentifier()).thenReturn(id2); // create the checkpoint coordinator ExecutionGraph graph = new CheckpointCoordinatorTestingUtils.CheckpointExecutionGraphBuilder() .addJobVertex(new JobVertexID()) .build(EXECUTOR_RESOURCE.getExecutor()); CheckpointCoordinator cc = instantiateCheckpointCoordinator(graph); cc.addMasterHook(hook1); cc.addMasterHook(hook2); // initialize the hooks cc.restoreLatestCheckpointedStateToAll(Collections.emptySet(), false); verify(hook1, times(1)).reset(); verify(hook2, times(1)).reset(); // shutdown cc.shutdown(); verify(hook1, times(1)).close(); verify(hook2, times(1)).close(); } // ------------------------------------------------------------------------ // trigger / restore behavior // ------------------------------------------------------------------------ @Test void testHooksAreCalledOnTrigger() throws Exception { final String id1 = "id1"; final String id2 = "id2"; final String state1 = "the-test-string-state"; final byte[] state1serialized = new StringSerializer().serialize(state1); final long state2 = 987654321L; final byte[] state2serialized = new LongSerializer().serialize(state2); final MasterTriggerRestoreHook<String> statefulHook1 = mockGeneric(MasterTriggerRestoreHook.class); when(statefulHook1.getIdentifier()).thenReturn(id1); when(statefulHook1.createCheckpointDataSerializer()).thenReturn(new StringSerializer()); when(statefulHook1.triggerCheckpoint(anyLong(), anyLong(), any(Executor.class))) .thenReturn(CompletableFuture.completedFuture(state1)); final MasterTriggerRestoreHook<Long> statefulHook2 = mockGeneric(MasterTriggerRestoreHook.class); when(statefulHook2.getIdentifier()).thenReturn(id2); when(statefulHook2.createCheckpointDataSerializer()).thenReturn(new LongSerializer()); when(statefulHook2.triggerCheckpoint(anyLong(), anyLong(), any(Executor.class))) .thenReturn(CompletableFuture.completedFuture(state2)); final MasterTriggerRestoreHook<Void> statelessHook = mockGeneric(MasterTriggerRestoreHook.class); when(statelessHook.getIdentifier()).thenReturn("some-id"); // create the checkpoint coordinator JobVertexID jobVertexId = new JobVertexID(); final ExecutionGraph graph = new CheckpointCoordinatorTestingUtils.CheckpointExecutionGraphBuilder() .addJobVertex(jobVertexId) .build(EXECUTOR_RESOURCE.getExecutor()); final ManuallyTriggeredScheduledExecutor manuallyTriggeredScheduledExecutor = new ManuallyTriggeredScheduledExecutor(); final CheckpointCoordinator cc = instantiateCheckpointCoordinator(graph, manuallyTriggeredScheduledExecutor); cc.addMasterHook(statefulHook1); cc.addMasterHook(statelessHook); cc.addMasterHook(statefulHook2); // trigger a checkpoint final CompletableFuture<CompletedCheckpoint> checkpointFuture = cc.triggerCheckpoint(false); manuallyTriggeredScheduledExecutor.triggerAll(); assertThat(checkpointFuture).isNotCompletedExceptionally(); assertThat(cc.getNumberOfPendingCheckpoints()).isOne(); verify(statefulHook1, times(1)) .triggerCheckpoint(anyLong(), anyLong(), any(Executor.class)); verify(statefulHook2, times(1)) .triggerCheckpoint(anyLong(), anyLong(), any(Executor.class)); verify(statelessHook, times(1)) .triggerCheckpoint(anyLong(), anyLong(), any(Executor.class)); ExecutionAttemptID attemptID = graph.getJobVertex(jobVertexId) .getTaskVertices()[0] .getCurrentExecutionAttempt() .getAttemptId(); final long checkpointId = cc.getPendingCheckpoints().values().iterator().next().getCheckpointID(); cc.receiveAcknowledgeMessage( new AcknowledgeCheckpoint(graph.getJobID(), attemptID, checkpointId), "Unknown location"); assertThat(cc.getNumberOfPendingCheckpoints()).isZero(); assertThat(cc.getNumberOfRetainedSuccessfulCheckpoints()).isOne(); final CompletedCheckpoint chk = cc.getCheckpointStore().getLatestCheckpoint(); final Collection<MasterState> masterStates = chk.getMasterHookStates(); assertThat(masterStates.size()).isEqualTo(2); for (MasterState ms : masterStates) { if (ms.name().equals(id1)) { assertThat(ms.bytes()).isEqualTo(state1serialized); assertThat(ms.version()).isEqualTo(StringSerializer.VERSION); } else if (ms.name().equals(id2)) { assertThat(ms.bytes()).isEqualTo(state2serialized); assertThat(ms.version()).isEqualTo(LongSerializer.VERSION); } else { fail("unrecognized state name: " + ms.name()); } } } @Test void testHooksAreCalledOnRestore() throws Exception { final String id1 = "id1"; final String id2 = "id2"; final String state1 = "the-test-string-state"; final byte[] state1serialized = new StringSerializer().serialize(state1); final long state2 = 987654321L; final byte[] state2serialized = new LongSerializer().serialize(state2); final List<MasterState> masterHookStates = Arrays.asList( new MasterState(id1, state1serialized, StringSerializer.VERSION), new MasterState(id2, state2serialized, LongSerializer.VERSION)); final MasterTriggerRestoreHook<String> statefulHook1 = mockGeneric(MasterTriggerRestoreHook.class); when(statefulHook1.getIdentifier()).thenReturn(id1); when(statefulHook1.createCheckpointDataSerializer()).thenReturn(new StringSerializer()); when(statefulHook1.triggerCheckpoint(anyLong(), anyLong(), any(Executor.class))) .thenThrow(new Exception("not expected")); final MasterTriggerRestoreHook<Long> statefulHook2 = mockGeneric(MasterTriggerRestoreHook.class); when(statefulHook2.getIdentifier()).thenReturn(id2); when(statefulHook2.createCheckpointDataSerializer()).thenReturn(new LongSerializer()); when(statefulHook2.triggerCheckpoint(anyLong(), anyLong(), any(Executor.class))) .thenThrow(new Exception("not expected")); final MasterTriggerRestoreHook<Void> statelessHook = mockGeneric(MasterTriggerRestoreHook.class); when(statelessHook.getIdentifier()).thenReturn("some-id"); final JobID jid = new JobID(); final long checkpointId = 13L; final CompletedCheckpoint checkpoint = new CompletedCheckpoint( jid, checkpointId, 123L, 125L, Collections.<OperatorID, OperatorState>emptyMap(), masterHookStates, CheckpointProperties.forCheckpoint( CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION), new TestCompletedCheckpointStorageLocation(), null); ExecutionGraph graph = new CheckpointCoordinatorTestingUtils.CheckpointExecutionGraphBuilder() .addJobVertex(new JobVertexID()) .build(EXECUTOR_RESOURCE.getExecutor()); CheckpointCoordinator cc = instantiateCheckpointCoordinator(graph); cc.addMasterHook(statefulHook1); cc.addMasterHook(statelessHook); cc.addMasterHook(statefulHook2); cc.getCheckpointStore() .addCheckpointAndSubsumeOldestOne(checkpoint, new CheckpointsCleaner(), () -> {}); cc.restoreLatestCheckpointedStateToAll(Collections.emptySet(), false); verify(statefulHook1, times(1)).restoreCheckpoint(eq(checkpointId), eq(state1)); verify(statefulHook2, times(1)).restoreCheckpoint(eq(checkpointId), eq(state2)); verify(statelessHook, times(1)).restoreCheckpoint(eq(checkpointId), isNull(Void.class)); } @Test void checkUnMatchedStateOnRestore() throws Exception { final String id1 = "id1"; final String id2 = "id2"; final String state1 = "the-test-string-state"; final byte[] state1serialized = new StringSerializer().serialize(state1); final long state2 = 987654321L; final byte[] state2serialized = new LongSerializer().serialize(state2); final List<MasterState> masterHookStates = Arrays.asList( new MasterState(id1, state1serialized, StringSerializer.VERSION), new MasterState(id2, state2serialized, LongSerializer.VERSION)); final MasterTriggerRestoreHook<String> statefulHook = mockGeneric(MasterTriggerRestoreHook.class); when(statefulHook.getIdentifier()).thenReturn(id1); when(statefulHook.createCheckpointDataSerializer()).thenReturn(new StringSerializer()); when(statefulHook.triggerCheckpoint(anyLong(), anyLong(), any(Executor.class))) .thenThrow(new Exception("not expected")); final MasterTriggerRestoreHook<Void> statelessHook = mockGeneric(MasterTriggerRestoreHook.class); when(statelessHook.getIdentifier()).thenReturn("some-id"); final JobID jid = new JobID(); final long checkpointId = 44L; final CompletedCheckpoint checkpoint = new CompletedCheckpoint( jid, checkpointId, 123L, 125L, Collections.<OperatorID, OperatorState>emptyMap(), masterHookStates, CheckpointProperties.forCheckpoint( CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION), new TestCompletedCheckpointStorageLocation(), null); ExecutionGraph graph = new CheckpointCoordinatorTestingUtils.CheckpointExecutionGraphBuilder() .addJobVertex(new JobVertexID()) .build(EXECUTOR_RESOURCE.getExecutor()); CheckpointCoordinator cc = instantiateCheckpointCoordinator(graph); cc.addMasterHook(statefulHook); cc.addMasterHook(statelessHook); cc.getCheckpointStore() .addCheckpointAndSubsumeOldestOne(checkpoint, new CheckpointsCleaner(), () -> {}); // since we have unmatched state, this should fail try { cc.restoreLatestCheckpointedStateToAll(Collections.emptySet(), false); fail("exception expected"); } catch (IllegalStateException ignored) { } // permitting unmatched state should succeed cc.restoreLatestCheckpointedStateToAll(Collections.emptySet(), true); verify(statefulHook, times(1)).restoreCheckpoint(eq(checkpointId), eq(state1)); verify(statelessHook, times(1)).restoreCheckpoint(eq(checkpointId), isNull(Void.class)); } // ------------------------------------------------------------------------ // failure scenarios // ------------------------------------------------------------------------ /** * This test makes sure that the checkpoint is already registered by the time. that the hooks * are called */ @Test void ensureRegisteredAtHookTime() throws Exception { final String id = "id"; // create the checkpoint coordinator ExecutionGraph graph = new CheckpointCoordinatorTestingUtils.CheckpointExecutionGraphBuilder() .addJobVertex(new JobVertexID()) .build(EXECUTOR_RESOURCE.getExecutor()); final ManuallyTriggeredScheduledExecutor manuallyTriggeredScheduledExecutor = new ManuallyTriggeredScheduledExecutor(); CheckpointCoordinator cc = instantiateCheckpointCoordinator(graph, manuallyTriggeredScheduledExecutor); final MasterTriggerRestoreHook<Void> hook = mockGeneric(MasterTriggerRestoreHook.class); when(hook.getIdentifier()).thenReturn(id); when(hook.triggerCheckpoint(anyLong(), anyLong(), any(Executor.class))) .thenAnswer( new Answer<CompletableFuture<Void>>() { @Override public CompletableFuture<Void> answer(InvocationOnMock invocation) throws Throwable { assertThat(cc.getNumberOfPendingCheckpoints()).isOne(); long checkpointId = (Long) invocation.getArguments()[0]; assertThat(cc.getPendingCheckpoints()).containsKey(checkpointId); return null; } }); cc.addMasterHook(hook); // trigger a checkpoint final CompletableFuture<CompletedCheckpoint> checkpointFuture = cc.triggerCheckpoint(false); manuallyTriggeredScheduledExecutor.triggerAll(); assertThat(checkpointFuture).isNotCompletedExceptionally(); } // ------------------------------------------------------------------------ // failure scenarios // ------------------------------------------------------------------------ @Test void testSerializationFailsOnTrigger() {} @Test void testHookCallFailsOnTrigger() {} @Test void testDeserializationFailsOnRestore() {} @Test void testHookCallFailsOnRestore() {} @Test void testTypeIncompatibleWithSerializerOnStore() {} @Test void testTypeIncompatibleWithHookOnRestore() {} // ------------------------------------------------------------------------ // utilities // ------------------------------------------------------------------------ private CheckpointCoordinator instantiateCheckpointCoordinator(ExecutionGraph executionGraph) { return instantiateCheckpointCoordinator( executionGraph, new ManuallyTriggeredScheduledExecutor()); } private CheckpointCoordinator instantiateCheckpointCoordinator( ExecutionGraph graph, ScheduledExecutor testingScheduledExecutor) { CheckpointCoordinatorConfiguration chkConfig = new CheckpointCoordinatorConfiguration( 10000000L, 600000L, 0L, 1, CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION, true, false, 0, 0); Executor executor = Executors.directExecutor(); return new CheckpointCoordinator( graph.getJobID(), chkConfig, Collections.emptyList(), new StandaloneCheckpointIDCounter(), new StandaloneCompletedCheckpointStore(10), new JobManagerCheckpointStorage(), executor, new CheckpointsCleaner(), testingScheduledExecutor, new CheckpointFailureManager(0, NoOpFailJobCall.INSTANCE), new DefaultCheckpointPlanCalculator( graph.getJobID(), new ExecutionGraphCheckpointPlanCalculatorContext(graph), graph.getVerticesTopologically(), false), new DefaultCheckpointStatsTracker( 1, UnregisteredMetricGroups.createUnregisteredJobManagerJobMetricGroup())); } private static <T> T mockGeneric(Class<?> clazz) { @SuppressWarnings("unchecked") Class<T> typedClass = (Class<T>) clazz; return mock(typedClass); } // ------------------------------------------------------------------------ private static final
CheckpointCoordinatorMasterHooksTest
java
spring-projects__spring-security
oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/SpringReactiveOpaqueTokenIntrospector.java
{ "start": 10747, "end": 12358 }
class ____ { private final String introspectionUri; private String clientId; private String clientSecret; private Builder(String introspectionUri) { this.introspectionUri = introspectionUri; } /** * The builder will {@link URLEncoder encode} the client id that you provide, so * please give the unencoded value. * @param clientId The unencoded client id * @return the {@link SpringReactiveOpaqueTokenIntrospector.Builder} * @since 6.5 */ public Builder clientId(String clientId) { Assert.notNull(clientId, "clientId cannot be null"); this.clientId = URLEncoder.encode(clientId, StandardCharsets.UTF_8); return this; } /** * The builder will {@link URLEncoder encode} the client secret that you provide, * so please give the unencoded value. * @param clientSecret The unencoded client secret * @return the {@link SpringReactiveOpaqueTokenIntrospector.Builder} * @since 6.5 */ public Builder clientSecret(String clientSecret) { Assert.notNull(clientSecret, "clientSecret cannot be null"); this.clientSecret = URLEncoder.encode(clientSecret, StandardCharsets.UTF_8); return this; } /** * Creates a {@code SpringReactiveOpaqueTokenIntrospector} * @return the {@link SpringReactiveOpaqueTokenIntrospector} * @since 6.5 */ public SpringReactiveOpaqueTokenIntrospector build() { WebClient webClient = WebClient.builder() .defaultHeaders((h) -> h.setBasicAuth(this.clientId, this.clientSecret)) .build(); return new SpringReactiveOpaqueTokenIntrospector(this.introspectionUri, webClient); } } }
Builder
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/factories/TestCatalogFactory.java
{ "start": 2773, "end": 3708 }
class ____ implements CatalogFactory { public static final String IDENTIFIER = "test-catalog"; public static final ConfigOption<String> DEFAULT_DATABASE = ConfigOptions.key(CommonCatalogOptions.DEFAULT_DATABASE_KEY) .stringType() .noDefaultValue(); @Override public String factoryIdentifier() { return IDENTIFIER; } @Override public Set<ConfigOption<?>> requiredOptions() { return Collections.emptySet(); } @Override public Set<ConfigOption<?>> optionalOptions() { final Set<ConfigOption<?>> options = new HashSet<>(); options.add(DEFAULT_DATABASE); return options; } @Override public Catalog createCatalog(Context context) { return new TestCatalog(context.getName(), context.getOptions()); } /** Test catalog for discovery testing. */ public static
TestCatalogFactory
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java
{ "start": 3898, "end": 4618 }
class ____ { public String[] getFoo() { return null; } public C setFoo(int i, String foo) { return this; } } BeanInfo bi = Introspector.getBeanInfo(C.class); assertThat(hasReadMethodForProperty(bi, "foo")).isTrue(); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); assertThat(hasIndexedWriteMethodForProperty(bi, "foo")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(bi); assertThat(hasReadMethodForProperty(ebi, "foo")).isTrue(); assertThat(hasWriteMethodForProperty(ebi, "foo")).isFalse(); assertThat(hasIndexedWriteMethodForProperty(ebi, "foo")).isTrue(); } @Test void standardReadMethodsAndOverloadedNonStandardWriteMethods() throws Exception { @SuppressWarnings("unused")
C
java
apache__hadoop
hadoop-tools/hadoop-fs2img/src/main/java/org/apache/hadoop/hdfs/server/namenode/ImageWriter.java
{ "start": 8603, "end": 15904 }
class ____ extends LinkedHashMap<Long, DirEntry.Builder> { // should cache path to root, not evict LRCached private final int nEntries; DirEntryCache(int nEntries) { this.nEntries = nEntries; } @Override public DirEntry.Builder put(Long p, DirEntry.Builder b) { DirEntry.Builder e = get(p); if (null == e) { return super.put(p, b); } // merge e.addAllChildren(b.getChildrenList()); // not strictly conforming return e; } @Override protected boolean removeEldestEntry(Entry<Long, DirEntry.Builder> be) { if (size() > nEntries) { DirEntry d = be.getValue().build(); try { writeDirEntry(d); } catch (IOException e) { throw new RuntimeException(e); } return true; } return false; } } synchronized void writeInode(INode n) throws IOException { n.writeDelimitedTo(inodes); } synchronized void writeDirEntry(DirEntry e) throws IOException { e.writeDelimitedTo(dirs); } private static int getOndiskSize(GeneratedMessageV3 s) { return CodedOutputStream.computeUInt32SizeNoTag(s.getSerializedSize()) + s.getSerializedSize(); } @Override public synchronized void close() throws IOException { if (closed) { return; } for (DirEntry.Builder b : dircache.values()) { DirEntry e = b.build(); writeDirEntry(e); } dircache.clear(); // close side files IOUtils.cleanupWithLogger(null, dirs, inodes, blocks); if (null == dirs || null == inodes) { // init failed if (raw != null) { raw.close(); } return; } try { writeNameSystemSection(); writeINodeSection(); writeDirSection(); writeStringTableSection(); // write summary directly to raw FileSummary s = summary.build(); s.writeDelimitedTo(raw); int length = getOndiskSize(s); byte[] lengthBytes = new byte[4]; ByteBuffer.wrap(lengthBytes).asIntBuffer().put(length); raw.write(lengthBytes); } finally { raw.close(); } writeMD5("fsimage_0000000000000000000"); closed = true; } /** * Write checksum for image file. Pulled from MD5Utils/internals. Awkward to * reuse existing tools/utils. */ void writeMD5(String imagename) throws IOException { if (null == outdir) { return; } MD5Hash md5 = new MD5Hash(digest.digest()); String digestString = StringUtils.byteToHexString(md5.getDigest()); Path chk = new Path(outdir, imagename + ".md5"); try (OutputStream out = outfs.create(chk)) { String md5Line = digestString + " *" + imagename + "\n"; out.write(md5Line.getBytes(StandardCharsets.UTF_8)); } } OutputStream beginSection(OutputStream out) throws IOException { CompressionCodec codec = compress.getImageCodec(); if (null == codec) { return out; } return codec.createOutputStream(out); } void endSection(OutputStream out, SectionName name) throws IOException { CompressionCodec codec = compress.getImageCodec(); if (codec != null) { ((CompressorStream)out).finish(); } out.flush(); long length = raw.pos - curSec; summary.addSections(FileSummary.Section.newBuilder() .setName(name.toString()) // not strictly correct, but name not visible .setOffset(curSec).setLength(length)); curSec += length; } void writeNameSystemSection() throws IOException { NameSystemSection.Builder b = NameSystemSection.newBuilder() .setGenstampV1(1000) .setGenstampV1Limit(0) .setGenstampV2(1001) .setLastAllocatedBlockId(blockIds.lastId()) .setTransactionId(0); NameSystemSection s = b.build(); OutputStream sec = beginSection(raw); s.writeDelimitedTo(sec); endSection(sec, SectionName.NS_INFO); } void writeINodeSection() throws IOException { // could reset dict to avoid compression cost in close INodeSection.Builder b = INodeSection.newBuilder() .setNumInodes(curInode.get() - startInode) .setLastInodeId(curInode.get()); INodeSection s = b.build(); OutputStream sec = beginSection(raw); s.writeDelimitedTo(sec); // copy inodes try (FileInputStream in = new FileInputStream(inodesTmp)) { IOUtils.copyBytes(in, sec, 4096, false); } endSection(sec, SectionName.INODE); } void writeDirSection() throws IOException { // No header, so dirs can be written/compressed independently OutputStream sec = raw; // copy dirs try (FileInputStream in = new FileInputStream(dirsTmp)) { IOUtils.copyBytes(in, sec, 4096, false); } endSection(sec, SectionName.INODE_DIR); } void writeFilesUCSection() throws IOException { FilesUnderConstructionSection.Builder b = FilesUnderConstructionSection.newBuilder(); FilesUnderConstructionSection s = b.build(); OutputStream sec = beginSection(raw); s.writeDelimitedTo(sec); endSection(sec, SectionName.FILES_UNDERCONSTRUCTION); } void writeSnapshotDiffSection() throws IOException { SnapshotDiffSection.Builder b = SnapshotDiffSection.newBuilder(); SnapshotDiffSection s = b.build(); OutputStream sec = beginSection(raw); s.writeDelimitedTo(sec); endSection(sec, SectionName.SNAPSHOT_DIFF); } void writeSecretManagerSection() throws IOException { SecretManagerSection.Builder b = SecretManagerSection.newBuilder() .setCurrentId(0) .setTokenSequenceNumber(0); SecretManagerSection s = b.build(); OutputStream sec = beginSection(raw); s.writeDelimitedTo(sec); endSection(sec, SectionName.SECRET_MANAGER); } void writeCacheManagerSection() throws IOException { CacheManagerSection.Builder b = CacheManagerSection.newBuilder() .setNumPools(0) .setNumDirectives(0) .setNextDirectiveId(1); CacheManagerSection s = b.build(); OutputStream sec = beginSection(raw); s.writeDelimitedTo(sec); endSection(sec, SectionName.CACHE_MANAGER); } void writeStringTableSection() throws IOException { StringTableSection.Builder b = StringTableSection.newBuilder(); Map<Integer, String> u = ugis.ugiMap(); b.setNumEntry(u.size()); StringTableSection s = b.build(); OutputStream sec = beginSection(raw); s.writeDelimitedTo(sec); for (Map.Entry<Integer, String> e : u.entrySet()) { StringTableSection.Entry.Builder x = StringTableSection.Entry.newBuilder() .setId(e.getKey()) .setStr(e.getValue()); x.build().writeDelimitedTo(sec); } endSection(sec, SectionName.STRING_TABLE); } @Override public synchronized String toString() { StringBuilder sb = new StringBuilder(); sb.append("{ codec=\"").append(compress.getImageCodec()); sb.append("\", startBlock=").append(startBlock); sb.append(", curBlock=").append(curBlock); sb.append(", startInode=").append(startInode); sb.append(", curInode=").append(curInode); sb.append(", ugi=").append(ugis); sb.append(", blockIds=").append(blockIds); sb.append(", offset=").append(raw.pos); sb.append(" }"); return sb.toString(); } static
DirEntryCache
java
elastic__elasticsearch
x-pack/plugin/security/qa/security-trial/src/javaRestTest/java/org/elasticsearch/xpack/security/apikey/GetApiKeysRestIT.java
{ "start": 1764, "end": 15451 }
class ____ extends SecurityOnTrialLicenseRestTestCase { private static final SecureString END_USER_PASSWORD = new SecureString("end-user-password".toCharArray()); private static final String MANAGE_OWN_API_KEY_USER = "manage_own_api_key_user"; private static final String MANAGE_SECURITY_USER = "manage_security_user"; @Before public void createUsers() throws IOException { createUser(MANAGE_OWN_API_KEY_USER, END_USER_PASSWORD, List.of("manage_own_api_key_role")); createRole("manage_own_api_key_role", Set.of("manage_own_api_key")); createUser(MANAGE_SECURITY_USER, END_USER_PASSWORD, List.of("manage_security_role")); createRole("manage_security_role", Set.of("manage_security")); } public void testGetApiKeysWithActiveOnlyFlag() throws Exception { final String apiKeyId0 = createApiKey(MANAGE_SECURITY_USER, "key-0"); final String apiKeyId1 = createApiKey(MANAGE_SECURITY_USER, "key-1"); // Set short enough expiration for the API key to be expired by the time we query for it final String apiKeyId2 = createApiKey(MANAGE_SECURITY_USER, "key-2", TimeValue.timeValueNanos(1)); // All API keys returned when flag false (implicitly or explicitly) { final Map<String, String> parameters = new HashMap<>(); if (randomBoolean()) { parameters.put("active_only", "false"); } assertResponseContainsApiKeyIds(getApiKeysWithRequestParams(parameters), apiKeyId0, apiKeyId1, apiKeyId2); } // Only active keys returned when flag true assertResponseContainsApiKeyIds(getApiKeysWithRequestParams(Map.of("active_only", "true")), apiKeyId0, apiKeyId1); // Also works with `name` filter assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(Map.of("active_only", "true", "name", randomFrom("*", "key-*"))), apiKeyId0, apiKeyId1 ); // Also works with `realm_name` filter assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(Map.of("active_only", "true", "realm_name", "default_native")), apiKeyId0, apiKeyId1 ); // Same applies to invalidated key getSecurityClient().invalidateApiKeys(apiKeyId0); { final Map<String, String> parameters = new HashMap<>(); if (randomBoolean()) { parameters.put("active_only", "false"); } assertResponseContainsApiKeyIds(getApiKeysWithRequestParams(parameters), apiKeyId0, apiKeyId1, apiKeyId2); } assertResponseContainsApiKeyIds(getApiKeysWithRequestParams(Map.of("active_only", "true")), apiKeyId1); // also works with name filter assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(Map.of("active_only", "true", "name", randomFrom("*", "key-*", "key-1"))), apiKeyId1 ); // We get an empty result when no API keys active getSecurityClient().invalidateApiKeys(apiKeyId1); assertThat(getApiKeysWithRequestParams(Map.of("active_only", "true")).getApiKeyInfoList(), emptyIterable()); { // Using together with id parameter, returns 404 for inactive key var ex = expectThrows( ResponseException.class, () -> getApiKeysWithRequestParams(Map.of("active_only", "true", "id", randomFrom(apiKeyId0, apiKeyId1, apiKeyId2))) ); assertThat(ex.getResponse().getStatusLine().getStatusCode(), equalTo(404)); } { // manage_own_api_key prohibits owner=false, even if active_only is set var ex = expectThrows( ResponseException.class, () -> getApiKeysWithRequestParams(MANAGE_OWN_API_KEY_USER, Map.of("active_only", "true", "owner", "false")) ); assertThat(ex.getResponse().getStatusLine().getStatusCode(), equalTo(403)); } } public void testGetApiKeysWithActiveOnlyFlagAndMultipleUsers() throws Exception { final String manageOwnApiKeyUserApiKeyId = createApiKey(MANAGE_OWN_API_KEY_USER, "key-0"); final String manageApiKeyUserApiKeyId = createApiKey(MANAGE_SECURITY_USER, "key-1"); // Both users' API keys are returned assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(Map.of("active_only", Boolean.toString(randomBoolean()))), manageOwnApiKeyUserApiKeyId, manageApiKeyUserApiKeyId ); // Filtering by username works (also via owner flag) assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(Map.of("active_only", Boolean.toString(randomBoolean()), "username", MANAGE_SECURITY_USER)), manageApiKeyUserApiKeyId ); assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(Map.of("active_only", Boolean.toString(randomBoolean()), "username", MANAGE_OWN_API_KEY_USER)), manageOwnApiKeyUserApiKeyId ); assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(MANAGE_SECURITY_USER, Map.of("active_only", Boolean.toString(randomBoolean()), "owner", "true")), manageApiKeyUserApiKeyId ); assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(MANAGE_OWN_API_KEY_USER, Map.of("active_only", Boolean.toString(randomBoolean()), "owner", "true")), manageOwnApiKeyUserApiKeyId ); // One user's API key is active invalidateApiKeysForUser(MANAGE_OWN_API_KEY_USER); // Filtering by username still works (also via owner flag) assertResponseContainsApiKeyIds(getApiKeysWithRequestParams(Map.of("active_only", "true")), manageApiKeyUserApiKeyId); assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(Map.of("active_only", "true", "username", MANAGE_SECURITY_USER)), manageApiKeyUserApiKeyId ); assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(MANAGE_SECURITY_USER, Map.of("active_only", "true", "owner", "true")), manageApiKeyUserApiKeyId ); assertThat( getApiKeysWithRequestParams(Map.of("active_only", "true", "username", MANAGE_OWN_API_KEY_USER)).getApiKeyInfoList(), emptyIterable() ); assertThat( getApiKeysWithRequestParams(MANAGE_OWN_API_KEY_USER, Map.of("active_only", "true", "owner", "true")).getApiKeyInfoList(), emptyIterable() ); // No more active API keys invalidateApiKeysForUser(MANAGE_SECURITY_USER); assertThat( getApiKeysWithRequestParams( Map.of("active_only", "true", "username", randomFrom(MANAGE_SECURITY_USER, MANAGE_OWN_API_KEY_USER)) ).getApiKeyInfoList(), emptyIterable() ); assertThat( getApiKeysWithRequestParams( randomFrom(MANAGE_SECURITY_USER, MANAGE_OWN_API_KEY_USER), Map.of("active_only", "true", "owner", "true") ).getApiKeyInfoList(), emptyIterable() ); // With flag set to false, we get both inactive keys assertResponseContainsApiKeyIds( getApiKeysWithRequestParams(randomBoolean() ? Map.of() : Map.of("active_only", "false")), manageOwnApiKeyUserApiKeyId, manageApiKeyUserApiKeyId ); } public void testInvalidateApiKey() throws Exception { final String apiKeyId0 = createApiKey(MANAGE_SECURITY_USER, "key-2"); Request request = new Request(HttpGet.METHOD_NAME, "/_security/api_key/"); setUserForRequest(request, MANAGE_SECURITY_USER); GetApiKeyResponse getApiKeyResponse = GetApiKeyResponse.fromXContent(getParser(client().performRequest(request))); assertThat(getApiKeyResponse.getApiKeyInfoList(), iterableWithSize(1)); ApiKey apiKey = getApiKeyResponse.getApiKeyInfoList().get(0).apiKeyInfo(); assertThat(apiKey.isInvalidated(), equalTo(false)); assertThat(apiKey.getInvalidation(), nullValue()); assertThat(apiKey.getId(), equalTo(apiKeyId0)); request = new Request(HttpDelete.METHOD_NAME, "/_security/api_key/"); setUserForRequest(request, MANAGE_SECURITY_USER); request.setJsonEntity(XContentTestUtils.convertToXContent(Map.of("ids", List.of(apiKeyId0)), XContentType.JSON).utf8ToString()); InvalidateApiKeyResponse invalidateApiKeyResponse = InvalidateApiKeyResponse.fromXContent( getParser(client().performRequest(request)) ); assertThat(invalidateApiKeyResponse.getInvalidatedApiKeys().size(), equalTo(1)); assertThat(invalidateApiKeyResponse.getInvalidatedApiKeys().get(0), equalTo(apiKey.getId())); request = new Request(HttpGet.METHOD_NAME, "/_security/api_key/"); setUserForRequest(request, MANAGE_SECURITY_USER); getApiKeyResponse = GetApiKeyResponse.fromXContent(getParser(client().performRequest(request))); assertThat(getApiKeyResponse.getApiKeyInfoList(), iterableWithSize(1)); apiKey = getApiKeyResponse.getApiKeyInfoList().get(0).apiKeyInfo(); assertThat(apiKey.isInvalidated(), equalTo(true)); assertThat(apiKey.getInvalidation(), notNullValue()); assertThat(apiKey.getId(), equalTo(apiKeyId0)); } private GetApiKeyResponse getApiKeysWithRequestParams(Map<String, String> requestParams) throws IOException { return getApiKeysWithRequestParams(MANAGE_SECURITY_USER, requestParams); } private GetApiKeyResponse getApiKeysWithRequestParams(String userOnRequest, Map<String, String> requestParams) throws IOException { final var request = new Request(HttpGet.METHOD_NAME, "/_security/api_key/"); request.addParameters(requestParams); setUserForRequest(request, userOnRequest); return GetApiKeyResponse.fromXContent(getParser(client().performRequest(request))); } private static void assertResponseContainsApiKeyIds(GetApiKeyResponse response, String... ids) { assertThat( response.getApiKeyInfoList().stream().map(GetApiKeyResponse.Item::apiKeyInfo).map(ApiKey::getId).toList(), containsInAnyOrder(ids) ); } private static XContentParser getParser(Response response) throws IOException { final byte[] responseBody = EntityUtils.toByteArray(response.getEntity()); return XContentType.JSON.xContent().createParser(XContentParserConfiguration.EMPTY, responseBody); } private String createApiKey(String creatorUser, String apiKeyName) throws IOException { return createApiKey(creatorUser, apiKeyName, null); } /** * Returns id of created API key. */ private String createApiKey(String creatorUser, String apiKeyName, @Nullable TimeValue expiration) throws IOException { // Sanity check to ensure API key name and creator name aren't flipped assert creatorUser.equals(MANAGE_OWN_API_KEY_USER) || creatorUser.equals(MANAGE_SECURITY_USER); // Exercise cross cluster keys, if viable (i.e., creator has enough privileges and feature flag is enabled) final boolean createCrossClusterKey = creatorUser.equals(MANAGE_SECURITY_USER) && randomBoolean(); if (createCrossClusterKey) { final Map<String, Object> createApiKeyRequestBody = expiration == null ? Map.of("name", apiKeyName, "access", Map.of("search", List.of(Map.of("names", List.of("*"))))) : Map.of("name", apiKeyName, "expiration", expiration, "access", Map.of("search", List.of(Map.of("names", List.of("*"))))); final var createApiKeyRequest = new Request("POST", "/_security/cross_cluster/api_key"); createApiKeyRequest.setJsonEntity( XContentTestUtils.convertToXContent(createApiKeyRequestBody, XContentType.JSON).utf8ToString() ); setUserForRequest(createApiKeyRequest, creatorUser); final Response createApiKeyResponse = client().performRequest(createApiKeyRequest); assertOK(createApiKeyResponse); final Map<String, Object> createApiKeyResponseMap = responseAsMap(createApiKeyResponse); return (String) createApiKeyResponseMap.get("id"); } else { final Map<String, Object> createApiKeyRequestBody = expiration == null ? Map.of("name", apiKeyName) : Map.of("name", apiKeyName, "expiration", expiration); final var createApiKeyRequest = new Request("POST", "/_security/api_key"); createApiKeyRequest.setJsonEntity( XContentTestUtils.convertToXContent(createApiKeyRequestBody, XContentType.JSON).utf8ToString() ); setUserForRequest(createApiKeyRequest, creatorUser); final Response createApiKeyResponse = client().performRequest(createApiKeyRequest); assertOK(createApiKeyResponse); final Map<String, Object> createApiKeyResponseMap = responseAsMap(createApiKeyResponse); return (String) createApiKeyResponseMap.get("id"); } } private void setUserForRequest(Request request, String username) { request.setOptions( request.getOptions() .toBuilder() .removeHeader("Authorization") .addHeader("Authorization", UsernamePasswordToken.basicAuthHeaderValue(username, END_USER_PASSWORD)) ); } }
GetApiKeysRestIT
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/fs/contract/router/RouterHDFSContract.java
{ "start": 1409, "end": 3762 }
class ____ extends HDFSContract { public static final int BLOCK_SIZE = AbstractFSContractTestBase.TEST_FILE_LEN; private static MiniRouterDFSCluster cluster; public RouterHDFSContract(Configuration conf) { super(conf); } public static void createCluster() throws IOException { createCluster(false); } public static void createCluster(boolean security) throws IOException { createCluster(true, 2, security); } public static void createCluster( boolean ha, int numNameServices, boolean security) throws IOException { try { Configuration conf = null; if (security) { conf = SecurityConfUtil.initSecurity(); } cluster = new MiniRouterDFSCluster(ha, numNameServices, conf); // Start NNs and DNs and wait until ready cluster.startCluster(conf); // Start routers with only an RPC service cluster.startRouters(); // Register and verify all NNs with all routers cluster.registerNamenodes(); cluster.waitNamenodeRegistration(); // Setup the mount table cluster.installMockLocations(); // Making one Namenodes active per nameservice if (cluster.isHighAvailability()) { for (String ns : cluster.getNameservices()) { cluster.switchToActive(ns, NAMENODES[0]); cluster.switchToStandby(ns, NAMENODES[1]); } } cluster.waitActiveNamespaces(); } catch (Exception e) { destroyCluster(); throw new IOException("Cannot start federated cluster", e); } } public static void destroyCluster() throws IOException { if (cluster != null) { cluster.shutdown(); cluster = null; } try { SecurityConfUtil.destroy(); } catch (Exception e) { throw new IOException("Cannot destroy security context", e); } } public static MiniDFSCluster getCluster() { return cluster.getCluster(); } public static MiniRouterDFSCluster getRouterCluster() { return cluster; } public static FileSystem getFileSystem() throws IOException { //assumes cluster is not null Assertions.assertNotNull(cluster, "cluster not created"); return cluster.getRandomRouter().getFileSystem(); } @Override public FileSystem getTestFileSystem() throws IOException { return getFileSystem(); } }
RouterHDFSContract
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/state/internals/FilteredCacheIteratorTest.java
{ "start": 1614, "end": 4907 }
class ____ { private static final CacheFunction IDENTITY_FUNCTION = new CacheFunction() { @Override public Bytes key(final Bytes cacheKey) { return cacheKey; } @Override public Bytes cacheKey(final Bytes key) { return key; } }; private final KeyValueStore<Bytes, LRUCacheEntry> store = new GenericInMemoryKeyValueStore<>("my-store"); private final KeyValue<Bytes, LRUCacheEntry> firstEntry = KeyValue.pair(Bytes.wrap("a".getBytes()), new LRUCacheEntry("1".getBytes())); private final List<KeyValue<Bytes, LRUCacheEntry>> entries = asList( firstEntry, KeyValue.pair(Bytes.wrap("b".getBytes()), new LRUCacheEntry("2".getBytes())), KeyValue.pair(Bytes.wrap("c".getBytes()), new LRUCacheEntry("3".getBytes()))); private FilteredCacheIterator allIterator; private FilteredCacheIterator firstEntryIterator; @BeforeEach public void before() { store.putAll(entries); final HasNextCondition allCondition = Iterator::hasNext; allIterator = new FilteredCacheIterator( new DelegatingPeekingKeyValueIterator<>("", store.all()), allCondition, IDENTITY_FUNCTION); final HasNextCondition firstEntryCondition = iterator -> iterator.hasNext() && iterator.peekNextKey().equals(firstEntry.key); firstEntryIterator = new FilteredCacheIterator( new DelegatingPeekingKeyValueIterator<>("", store.all()), firstEntryCondition, IDENTITY_FUNCTION); } @Test public void shouldAllowEntryMatchingHasNextCondition() { final List<KeyValue<Bytes, LRUCacheEntry>> keyValues = toListAndCloseIterator(allIterator); assertThat(keyValues, equalTo(entries)); } @Test public void shouldPeekNextKey() { while (allIterator.hasNext()) { final Bytes nextKey = allIterator.peekNextKey(); final KeyValue<Bytes, LRUCacheEntry> next = allIterator.next(); assertThat(next.key, equalTo(nextKey)); } } @Test public void shouldPeekNext() { while (allIterator.hasNext()) { final KeyValue<Bytes, LRUCacheEntry> peeked = allIterator.peekNext(); final KeyValue<Bytes, LRUCacheEntry> next = allIterator.next(); assertThat(peeked, equalTo(next)); } } @Test public void shouldNotHaveNextIfHasNextConditionNotMet() { assertTrue(firstEntryIterator.hasNext()); firstEntryIterator.next(); assertFalse(firstEntryIterator.hasNext()); } @Test public void shouldFilterEntriesNotMatchingHasNextCondition() { final List<KeyValue<Bytes, LRUCacheEntry>> keyValues = toListAndCloseIterator(firstEntryIterator); assertThat(keyValues, equalTo(Collections.singletonList(firstEntry))); } @Test public void shouldThrowUnsupportedOperationExceptionOnRemove() { assertThrows(UnsupportedOperationException.class, () -> allIterator.remove()); } }
FilteredCacheIteratorTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/collectionelement/flush/ElementCollectionFlushAfterQueryTest.java
{ "start": 1066, "end": 2059 }
class ____ { private static final Long MY_ENTITY_ID = 1l; @Test public void testAutoFlush(SessionFactoryScope scope) { scope.inTransaction( session -> { MyEntity myEntity = new MyEntity( MY_ENTITY_ID, "my entity" ); myEntity.addRedirectUris( "1" ); session.persist( myEntity ); } ); scope.inTransaction( session -> { MyEntity myEntity = session.find( MyEntity.class, MY_ENTITY_ID ); Set<String> set = new HashSet<>(); set.add( "3" ); myEntity.setRedirectUris( set ); session.createQuery( "from MyOtherEntity ", MyOtherEntity.class ).getResultList(); } ); scope.inTransaction( session -> { MyEntity myEntity = session.find( MyEntity.class, MY_ENTITY_ID ); Set<String> redirectUris = myEntity.getRedirectUris(); assertThat( redirectUris.size() ).isEqualTo( 1 ); assertThat( redirectUris.contains( "3" ) ); } ); } @Entity(name = "MyEntity") public static
ElementCollectionFlushAfterQueryTest
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractAssertWithComparator.java
{ "start": 1341, "end": 2505 }
class ____<SELF extends AbstractAssertWithComparator<SELF, ACTUAL>, ACTUAL> extends AbstractAssert<SELF, ACTUAL> implements AssertWithComparator<SELF, ACTUAL> { // we prefer not to use Class<? extends S> selfType because it would force inherited // constructor to cast with a compiler warning // let's keep compiler warning internal (when we can) and not expose them to our end users. protected AbstractAssertWithComparator(ACTUAL actual, Class<?> selfType) { super(actual, selfType); } /** * {@inheritDoc} */ @Override @CheckReturnValue public SELF usingComparator(Comparator<? super ACTUAL> customComparator, String customComparatorDescription) { // using a specific strategy to compare actual with other objects. this.objects = new Objects(new ComparatorBasedComparisonStrategy(customComparator, customComparatorDescription)); return myself; } /** * {@inheritDoc} */ @Override @CheckReturnValue public SELF usingDefaultComparator() { // fall back to default strategy to compare actual with other objects. this.objects = Objects.instance(); return myself; } }
AbstractAssertWithComparator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryLongToIntConversionTest.java
{ "start": 1986, "end": 4204 }
class ____ { static void acceptsLong(long value) {} static void acceptsMultipleParams(int intValue, long longValue) {} public void longToIntForLongParam() { long x = 1; // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong((int) x); } public void longObjectToIntForLongParam() { Long x = Long.valueOf(1); // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(x.intValue()); } public void convertMultipleArgs() { long x = 1; // The method expects an int for the first parameter and a long for the second parameter. // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsMultipleParams(Ints.checkedCast(x), Ints.checkedCast(x)); } // The following test cases test various conversion methods, including an unchecked cast. public void castToInt() { long x = 1; // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong((int) x); } public void checkedCast() { long x = 1; // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(Ints.checkedCast(x)); } public void saturatedCast() { long x = 1; // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(Ints.saturatedCast(x)); } public void toIntExact() { long x = 1; // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(Math.toIntExact(x)); } public void toIntExactWithLongObject() { Long x = Long.valueOf(1); // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(Math.toIntExact(x)); } public void intValue() { Long x = Long.valueOf(1); // BUG: Diagnostic contains: UnnecessaryLongToIntConversion acceptsLong(x.intValue()); } }\ """) .doTest(); } @Test public void longParameterLongToIntNegativeCases() { compilationHelper .addSourceLines( "UnnecessaryLongToIntConversionNegativeCases.java", """ package com.google.errorprone.bugpatterns.testdata; import com.google.common.primitives.Ints; /** Negative cases for {@link com.google.errorprone.bugpatterns.UnnecessaryLongToIntConversion}. */ public
UnnecessaryLongToIntConversionPositiveCases
java
google__guava
guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
{ "start": 17857, "end": 19756 }
class ____ extends SomeClassThatDoesNotUseNullable { @Keep public static void doThrow(Object arg) { if (arg == null) { throw new FooException(); } } @Keep public void noArg() {} @Keep public void oneArg(String s) { checkNotNull(s); } void packagePrivateOneArg(String s) { checkNotNull(s); } @Keep protected void protectedOneArg(String s) { checkNotNull(s); } @Keep public void oneNullableArg(@Nullable String s) {} @Keep public void oneNullableArgThrows(@Nullable String s) { doThrow(s); } @Keep public void twoArg(String s, Integer i) { checkNotNull(s); i.intValue(); } @Keep public void twoMixedArgs(String s, @Nullable Integer i) { checkNotNull(s); } @Keep public void twoMixedArgs(@Nullable Integer i, String s) { checkNotNull(s); } @Keep public void twoMixedArgsThrows(String s, @Nullable Integer i) { checkNotNull(s); doThrow(i); } @Keep public void twoMixedArgsThrows(@Nullable Integer i, String s) { checkNotNull(s); doThrow(i); } @Keep public void twoNullableArgs(@Nullable String s, @javax.annotation.Nullable Integer i) {} @Keep public void twoNullableArgsThrowsFirstArg(@Nullable String s, @Nullable Integer i) { doThrow(s); } @Keep public void twoNullableArgsThrowsSecondArg(@Nullable String s, @Nullable Integer i) { doThrow(i); } @Keep public static void staticOneArg(String s) { checkNotNull(s); } @Keep public static void staticOneNullableArg(@Nullable String s) {} @Keep public static void staticOneNullableArgThrows(@Nullable String s) { doThrow(s); } } public void testGoodClass() { shouldPass(new PassObject()); } private static
PassObject
java
quarkusio__quarkus
extensions/tls-registry/runtime/src/main/java/io/quarkus/tls/runtime/keystores/PemKeyStores.java
{ "start": 479, "end": 554 }
class ____ validate PEM key store and trust store configurations. */ public
to
java
elastic__elasticsearch
client/rest/src/test/java/org/elasticsearch/client/RestClientMultipleHostsIntegTests.java
{ "start": 6734, "end": 15357 }
class ____ implements HttpHandler { @Override public void handle(HttpExchange httpExchange) throws IOException { byte[] body = "01234567890123456789".getBytes(StandardCharsets.UTF_8); httpExchange.sendResponseHeaders(200, body.length); try (OutputStream out = httpExchange.getResponseBody()) { out.write(body); } httpExchange.close(); } } @AfterClass public static void stopHttpServers() throws IOException { restClient.close(); restClient = null; for (HttpServer httpServer : httpServers) { httpServer.stop(0); } httpServers = null; } @Before public void stopRandomHost() { // verify that shutting down some hosts doesn't matter as long as one working host is left behind if (httpServers.length > 1 && randomBoolean()) { List<HttpServer> updatedHttpServers = new ArrayList<>(httpServers.length - 1); int nodeIndex = randomIntBetween(0, httpServers.length - 1); if (0 == nodeIndex) { stoppedFirstHost = true; } for (int i = 0; i < httpServers.length; i++) { HttpServer httpServer = httpServers[i]; if (i == nodeIndex) { httpServer.stop(0); } else { updatedHttpServers.add(httpServer); } } httpServers = updatedHttpServers.toArray(new HttpServer[0]); } } public void testSyncRequests() throws IOException { int numRequests = randomIntBetween(5, 20); for (int i = 0; i < numRequests; i++) { final String method = RestClientTestUtil.randomHttpMethod(getRandom()); // we don't test status codes that are subject to retries as they interfere with hosts being stopped final int statusCode = randomBoolean() ? randomOkStatusCode(getRandom()) : randomErrorNoRetryStatusCode(getRandom()); Response response; try { response = restClient.performRequest(new Request(method, "/" + statusCode)); } catch (ResponseException responseException) { response = responseException.getResponse(); } assertEquals(method, response.getRequestLine().getMethod()); assertEquals(statusCode, response.getStatusLine().getStatusCode()); assertEquals((pathPrefix.length() > 0 ? pathPrefix : "") + "/" + statusCode, response.getRequestLine().getUri()); } } public void testAsyncRequests() throws Exception { int numRequests = randomIntBetween(5, 20); final CountDownLatch latch = new CountDownLatch(numRequests); final List<TestResponse> responses = new CopyOnWriteArrayList<>(); for (int i = 0; i < numRequests; i++) { final String method = RestClientTestUtil.randomHttpMethod(getRandom()); // we don't test status codes that are subject to retries as they interfere with hosts being stopped final int statusCode = randomBoolean() ? randomOkStatusCode(getRandom()) : randomErrorNoRetryStatusCode(getRandom()); restClient.performRequestAsync(new Request(method, "/" + statusCode), new ResponseListener() { @Override public void onSuccess(Response response) { responses.add(new TestResponse(method, statusCode, response)); latch.countDown(); } @Override public void onFailure(Exception exception) { responses.add(new TestResponse(method, statusCode, exception)); latch.countDown(); } }); } assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(numRequests, responses.size()); for (TestResponse testResponse : responses) { Response response = testResponse.getResponse(); assertEquals(testResponse.method, response.getRequestLine().getMethod()); assertEquals(testResponse.statusCode, response.getStatusLine().getStatusCode()); assertEquals((pathPrefix.length() > 0 ? pathPrefix : "") + "/" + testResponse.statusCode, response.getRequestLine().getUri()); } } public void testCancelAsyncRequests() throws Exception { int numRequests = randomIntBetween(5, 20); final List<Response> responses = new CopyOnWriteArrayList<>(); final List<Exception> exceptions = new CopyOnWriteArrayList<>(); for (int i = 0; i < numRequests; i++) { CountDownLatch latch = new CountDownLatch(1); waitForCancelHandler = resetWaitHandlers(); Cancellable cancellable = restClient.performRequestAsync(new Request("GET", "/wait"), new ResponseListener() { @Override public void onSuccess(Response response) { responses.add(response); latch.countDown(); } @Override public void onFailure(Exception exception) { exceptions.add(exception); latch.countDown(); } }); if (randomBoolean()) { // we wait for the request to get to the server-side otherwise we almost always cancel // the request artificially on the client-side before even sending it waitForCancelHandler.awaitRequest(); } cancellable.cancel(); waitForCancelHandler.cancelDone(); assertTrue(latch.await(5, TimeUnit.SECONDS)); } assertEquals(0, responses.size()); assertEquals(numRequests, exceptions.size()); for (Exception exception : exceptions) { assertThat(exception, instanceOf(CancellationException.class)); } } /** * Test host selector against a real server <strong>and</strong> * test what happens after calling */ public void testNodeSelector() throws Exception { try (RestClient restClient = buildRestClient(firstPositionNodeSelector())) { Request request = new Request("GET", "/200"); int rounds = between(1, 10); for (int i = 0; i < rounds; i++) { /* * Run the request more than once to verify that the * NodeSelector overrides the round robin behavior. */ if (stoppedFirstHost) { try { RestClientSingleHostTests.performRequestSyncOrAsync(restClient, request); fail("expected to fail to connect"); } catch (ConnectException e) { // Windows isn't consistent here. Sometimes the message is even null! if (false == System.getProperty("os.name").startsWith("Windows")) { assertThat(e.getMessage(), startsWith("Connection refused")); } } } else { Response response = RestClientSingleHostTests.performRequestSyncOrAsync(restClient, request); assertEquals(httpHosts[0], response.getHost()); } } } } @Ignore("https://github.com/elastic/elasticsearch/issues/87314") public void testNonRetryableException() throws Exception { RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder(); options.setHttpAsyncResponseConsumerFactory( // Limit to very short responses to trigger a ContentTooLongException () -> new HeapBufferedAsyncResponseConsumer(10) ); AtomicInteger failureCount = new AtomicInteger(); RestClient client = buildRestClient(NodeSelector.ANY, new RestClient.FailureListener() { @Override public void onFailure(Node node) { failureCount.incrementAndGet(); } }); failureCount.set(0); Request request = new Request("POST", "/20bytes"); request.setOptions(options); try { RestClientSingleHostTests.performRequestSyncOrAsync(client, request); fail("Request should not succeed"); } catch (IOException e) { assertEquals(stoppedFirstHost ? 2 : 1, failureCount.intValue()); } client.close(); } private static
ResponseHandlerWithContent
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/test/resources/Hey.java
{ "start": 941, "end": 1292 }
class ____ extends org.apache.camel.builder.RouteBuilder { @Override public void configure() throws Exception { // Write your routes here, for example: from("timer:java?period={{period}}") .routeId("java") .process(e -> { e.getMessage().setBody("Hello from Camel"); }) .log("${body}"); } }
Hey
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToStringErrorTests.java
{ "start": 800, "end": 1983 }
class ____ extends ErrorsForCasesWithoutExamplesTestCase { @Override protected List<TestCaseSupplier> cases() { return paramsToSuppliers(ToStringTests.parameters()); } @Override protected Expression build(Source source, List<Expression> args) { return new ToString(source, args.get(0)); } @Override protected Matcher<String> expectedTypeErrorMatcher(List<Set<DataType>> validPerPosition, List<DataType> signature) { return equalTo(typeErrorMessage(false, validPerPosition, signature, (v, p) -> { /* * In general ToString should support all signatures. While building a * new type you may we to temporarily remove this. */ throw new UnsupportedOperationException("all signatures should be supported"); })); } @Override protected void assertNumberOfCheckedSignatures(int checked) { /* * In general ToString should support all signatures. While building a * new type you may we to temporarily relax this. */ assertThat("all signatures should be supported", checked, equalTo(0)); } }
ToStringErrorTests
java
apache__spark
core/src/main/java/org/apache/spark/unsafe/map/HashMapGrowthStrategy.java
{ "start": 1197, "end": 1622 }
class ____ implements HashMapGrowthStrategy { private static final int ARRAY_MAX = ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH; @Override public int nextCapacity(int currentCapacity) { assert (currentCapacity > 0); int doubleCapacity = currentCapacity * 2; // Guard against overflow return (doubleCapacity > 0 && doubleCapacity <= ARRAY_MAX) ? doubleCapacity : ARRAY_MAX; } } }
Doubling
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/validation/SpiModelBindingGraphConverter.java
{ "start": 21247, "end": 22308 }
class ____ extends DaggerExecutableElement { public static DaggerExecutableElement from(XExecutableElement executableElement) { return new AutoValue_SpiModelBindingGraphConverter_DaggerExecutableElementImpl( executableElement); } abstract XExecutableElement executableElement(); @Override public ExecutableElement javac() { checkIsJavac(backend()); return toJavac(executableElement()); } @Override public KSDeclaration ksp() { checkIsKsp(backend()); return isMethod(executableElement()) && XElements.asMethod(executableElement()).isKotlinPropertyMethod() ? (KSPropertyDeclaration) toKS((XElement) executableElement()) : toKS(executableElement()); } @Override public DaggerProcessingEnv.Backend backend() { return getBackend(getProcessingEnv(executableElement())); } @Override public final String toString() { return XElements.toStableString(executableElement()); } } private static
DaggerExecutableElementImpl
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/config/InstantiationAwareBeanPostProcessor.java
{ "start": 1780, "end": 2661 }
interface ____ extends BeanPostProcessor { /** * Apply this BeanPostProcessor <i>before the target bean gets instantiated</i>. * The returned bean object may be a proxy to use instead of the target bean, * effectively suppressing default instantiation of the target bean. * <p>If a non-null object is returned by this method, the bean creation process * will be short-circuited. The only further processing applied is the * {@link #postProcessAfterInitialization} callback from the configured * {@link BeanPostProcessor BeanPostProcessors}. * <p>This callback will be applied to bean definitions with their bean class, * as well as to factory-method definitions in which case the returned bean type * will be passed in here. * <p>Post-processors may implement the extended * {@link SmartInstantiationAwareBeanPostProcessor}
InstantiationAwareBeanPostProcessor
java
elastic__elasticsearch
x-pack/qa/src/main/java/org/elasticsearch/xpack/test/rest/IndexMappingTemplateAsserter.java
{ "start": 1509, "end": 16531 }
class ____ { /** * Assert that the mappings of the ml indices are the same as in the * templates. If different this is either a consequence of an unintended * write (dynamic update) or the mappings have not been updated after * upgrade. * * A failure here will be very difficult to reproduce as it may be a side * effect of a different test running in the cluster. * * @param client The rest client */ public static void assertMlMappingsMatchTemplates(RestClient client) throws Exception { // Excluding those from stats index as some have been renamed and other removed. // These exceptions are necessary for Full Cluster Restart tests where the upgrade version is < 7.x Set<String> statsIndexException = new HashSet<>(); statsIndexException.add("properties.hyperparameters.properties.regularization_depth_penalty_multiplier.type"); statsIndexException.add("properties.hyperparameters.properties.regularization_leaf_weight_penalty_multiplier.type"); statsIndexException.add("properties.hyperparameters.properties.regularization_soft_tree_depth_limit.type"); statsIndexException.add("properties.hyperparameters.properties.regularization_soft_tree_depth_tolerance.type"); statsIndexException.add("properties.hyperparameters.properties.regularization_tree_size_penalty_multiplier.type"); // Excluding this from notifications index as `ignore_above` has been added to the `message.raw` field. // The exception is necessary for Full Cluster Restart tests. Set<String> notificationsIndexExceptions = new HashSet<>(); notificationsIndexExceptions.add("properties.message.fields.raw.ignore_above"); assertComposableTemplateMatchesIndexMappings(client, ".ml-stats", ".ml-stats-000001", true, statsIndexException, false); assertComposableTemplateMatchesIndexMappings(client, ".ml-state", ".ml-state-000001", true, Collections.emptySet(), false); // Depending on the order Full Cluster restart tests are run there may not be an notifications index yet assertComposableTemplateMatchesIndexMappings( client, ".ml-notifications-000002", ".ml-notifications-000002", true, notificationsIndexExceptions, false ); // .ml-annotations-6 does not use a template // .ml-anomalies-shared uses a template but will have dynamically updated mappings as new jobs are opened // Dynamic mappings updates are banned for system indices. // The .ml-config and .ml-meta indices have mappings that allow dynamic updates. // The effect is instant error if a document containing an unknown field is added // to one of these indices. Assuming we have some sort of test coverage somewhere // for new fields, we will very quickly catch any failures to add new fields to // the mappings for the .ml-config and .ml-meta indices. So there is no need to // test again here. } /** * * @param client The Rest client * @param templateName Template * @param version Expected template version * @param indexPatterns Expected index patterns * @throws Exception Assertion */ @SuppressWarnings("unchecked") public static void assertTemplateVersionAndPattern(RestClient client, String templateName, int version, List<String> indexPatterns) throws Exception { AtomicReference<Response> templateResponse = new AtomicReference<>(); ESRestTestCase.assertBusy(() -> { Request getTemplate = new Request("GET", "_index_template/" + templateName); templateResponse.set(client.performRequest(getTemplate)); assertEquals("missing template [" + templateName + "]", 200, templateResponse.get().getStatusLine().getStatusCode()); }); var responseMap = ESRestTestCase.entityAsMap(templateResponse.get()); Integer templateVersion = ((List<Integer>) XContentMapValues.extractValue( responseMap, "index_templates", "index_template", "version" )).getFirst(); assertEquals(version, templateVersion.intValue()); var templateIndexPatterns = ((List<String>) XContentMapValues.extractValue( responseMap, "index_templates", "index_template", "index_patterns" )); assertEquals(responseMap.toString(), templateIndexPatterns, indexPatterns); } /** * Compares the mappings from the composable template and the index and asserts * they are the same. The assertion error message details the differences in * the mappings. * * The Mappings, which are maps of maps, are flattened with the keys built * from the keys of the sub-maps appended to the parent key. * This makes diffing the 2 maps easier and diffs more comprehensible. * * The _meta field is not compared as it contains version numbers that * change even when the mappings don't. * * Mistakes happen and some indices may be stuck with the incorrect mappings * that cannot be fixed without re-index. In this case use the {@code exceptions} * parameter to filter out fields in the index mapping that are not in the * template. Each exception should be a '.' separated path to the value * e.g. {@code properties.analysis.analysis_field.type}. * * @param client The rest client to use * @param templateName The template * @param indexName The index * @param notAnErrorIfIndexDoesNotExist The index may or may not have been created from * the template. If {@code true} then the missing * index does not cause an error * @param exceptions List of keys to ignore in the index mappings. * Each key is a '.' separated path. * @param allowSystemIndexWarnings Whether deprecation warnings for system index access should be allowed/expected. */ @SuppressWarnings("unchecked") public static void assertComposableTemplateMatchesIndexMappings( RestClient client, String templateName, String indexName, boolean notAnErrorIfIndexDoesNotExist, Set<String> exceptions, boolean allowSystemIndexWarnings ) throws Exception { AtomicReference<Response> templateResponse = new AtomicReference<>(); ESRestTestCase.assertBusy(() -> { Request getTemplate = new Request("GET", "_index_template/" + templateName); templateResponse.set(client.performRequest(getTemplate)); assertEquals("missing template [" + templateName + "]", 200, templateResponse.get().getStatusLine().getStatusCode()); }); Map<String, Object> templateMappings = ((List<Map<String, Object>>) XContentMapValues.extractValue( ESRestTestCase.entityAsMap(templateResponse.get()), "index_templates", "index_template", "template", "mappings" )).get(0); assertNotNull(templateMappings); assertTemplateMatchesIndexMappingsCommon( client, templateName, templateMappings, indexName, notAnErrorIfIndexDoesNotExist, exceptions, allowSystemIndexWarnings ); } @SuppressWarnings("unchecked") private static void assertTemplateMatchesIndexMappingsCommon( RestClient client, String templateName, Map<String, Object> templateMappings, String indexName, boolean notAnErrorIfIndexDoesNotExist, Set<String> exceptions, boolean allowSystemIndexWarnings ) throws IOException { Request getIndexMapping = new Request("GET", indexName + "/_mapping"); if (allowSystemIndexWarnings) { final String systemIndexWarning = "this request accesses system indices: [" + indexName + "], but in a future major version, " + "direct access to system indices will be prevented by default"; getIndexMapping.setOptions(ESRestTestCase.expectVersionSpecificWarnings(v -> { v.current(systemIndexWarning); v.compatible(systemIndexWarning); })); } Response indexMappingResponse; try { indexMappingResponse = client.performRequest(getIndexMapping); } catch (ResponseException e) { if (e.getResponse().getStatusLine().getStatusCode() == 404 && notAnErrorIfIndexDoesNotExist) { return; } else { throw e; } } assertEquals("error getting mappings for index [" + indexName + "]", 200, indexMappingResponse.getStatusLine().getStatusCode()); Map<String, Object> indexMappings = (Map<String, Object>) XContentMapValues.extractValue( ESRestTestCase.entityAsMap(indexMappingResponse), indexName, "mappings" ); assertNotNull(indexMappings); // ignore the _meta field indexMappings.remove("_meta"); templateMappings.remove("_meta"); // We cannot do a simple comparison of mappings e.g // Objects.equals(indexMappings, templateMappings) because some // templates use strings for the boolean values - "true" and "false" // which are automatically converted to Booleans causing the equality // to fail. boolean mappingsAreTheSame = true; // flatten the map of maps Map<String, Object> flatTemplateMap = flattenMap(templateMappings); Map<String, Object> flatIndexMap = flattenMap(indexMappings); SortedSet<String> keysInTemplateMissingFromIndex = new TreeSet<>(flatTemplateMap.keySet()); keysInTemplateMissingFromIndex.removeAll(flatIndexMap.keySet()); keysInTemplateMissingFromIndex.removeAll(exceptions); SortedSet<String> keysInIndexMissingFromTemplate = new TreeSet<>(flatIndexMap.keySet()); keysInIndexMissingFromTemplate.removeAll(flatTemplateMap.keySet()); // In the case of object fields the 'type: object' mapping is set by default. // If this does not explicitly appear in the template it is not an error // as ES has added the default to the index mappings keysInIndexMissingFromTemplate.removeIf(key -> key.endsWith("type") && "object".equals(flatIndexMap.get(key))); // Remove the exceptions keysInIndexMissingFromTemplate.removeAll(exceptions); StringBuilder errorMesssage = new StringBuilder("Error the template mappings [").append(templateName) .append("] and index mappings [") .append(indexName) .append("] are not the same") .append(System.lineSeparator()); if (keysInTemplateMissingFromIndex.isEmpty() == false) { mappingsAreTheSame = false; errorMesssage.append("Keys in the template missing from the index mapping: ") .append(keysInTemplateMissingFromIndex) .append(System.lineSeparator()); } if (keysInIndexMissingFromTemplate.isEmpty() == false) { mappingsAreTheSame = false; errorMesssage.append("Keys in the index missing from the template mapping: ") .append(keysInIndexMissingFromTemplate) .append(System.lineSeparator()); } // find values that are different for the same key Set<String> commonKeys = new TreeSet<>(flatIndexMap.keySet()); commonKeys.retainAll(flatTemplateMap.keySet()); for (String key : commonKeys) { Object template = flatTemplateMap.get(key); Object index = flatIndexMap.get(key); if (Objects.equals(template, index) == false) { // Both maybe be booleans but different representations if (areBooleanObjectsAndEqual(index, template)) { continue; } mappingsAreTheSame = false; errorMesssage.append("Values for key [").append(key).append("] are different").append(System.lineSeparator()); errorMesssage.append(" template value [") .append(template) .append("] ") .append(template.getClass().getSimpleName()) .append(System.lineSeparator()); errorMesssage.append(" index value [") .append(index) .append("] ") .append(index.getClass().getSimpleName()) .append(System.lineSeparator()); } } if (mappingsAreTheSame == false) { fail(errorMesssage.toString()); } } private static boolean areBooleanObjectsAndEqual(Object a, Object b) { Boolean left; Boolean right; if (a instanceof Boolean) { left = (Boolean) a; } else if (a instanceof String && isBooleanValueString((String) a)) { left = Boolean.parseBoolean((String) a); } else { return false; } if (b instanceof Boolean) { right = (Boolean) b; } else if (b instanceof String && isBooleanValueString((String) b)) { right = Boolean.parseBoolean((String) b); } else { return false; } return left.equals(right); } /* Boolean.parseBoolean is not strict. Anything that isn't * "true" is returned as false. Here we want to know if * the string is a boolean value. */ private static boolean isBooleanValueString(String s) { return s.equalsIgnoreCase("true") || s.equalsIgnoreCase("false"); } private static Map<String, Object> flattenMap(Map<String, Object> map) { return new TreeMap<>(flatten("", map).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); } private static Stream<Map.Entry<String, Object>> flatten(String path, Map<String, Object> map) { return map.entrySet().stream().flatMap((e) -> extractValue(path, e)); } @SuppressWarnings("unchecked") private static Stream<Map.Entry<String, Object>> extractValue(String path, Map.Entry<String, Object> entry) { String nextPath = path.isEmpty() ? entry.getKey() : path + "." + entry.getKey(); if (entry.getValue() instanceof Map<?, ?>) { return flatten(nextPath, (Map<String, Object>) entry.getValue()); } else { return Stream.of(new AbstractMap.SimpleEntry<>(nextPath, entry.getValue())); } } }
IndexMappingTemplateAsserter
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/rollup/action/StopRollupJobAction.java
{ "start": 1762, "end": 4334 }
class ____ extends BaseTasksRequest<Request> implements ToXContentObject { private String id; private boolean waitForCompletion = false; private TimeValue timeout = null; public Request(String id) { this(id, false, null); } public Request(String id, boolean waitForCompletion, @Nullable TimeValue timeout) { this.id = ExceptionsHelper.requireNonNull(id, RollupField.ID.getPreferredName()); this.timeout = timeout == null ? DEFAULT_TIMEOUT : timeout; this.waitForCompletion = waitForCompletion; } public Request() {} public Request(StreamInput in) throws IOException { super(in); id = in.readString(); waitForCompletion = in.readBoolean(); timeout = in.readTimeValue(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(id); out.writeBoolean(waitForCompletion); out.writeTimeValue(timeout); } public String getId() { return id; } public TimeValue timeout() { return timeout; } public boolean waitForCompletion() { return waitForCompletion; } @Override public ActionRequestValidationException validate() { return null; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(RollupField.ID.getPreferredName(), id); builder.field(WAIT_FOR_COMPLETION.getPreferredName(), waitForCompletion); if (timeout != null) { builder.field(TIMEOUT.getPreferredName(), timeout); } builder.endObject(); return builder; } @Override public int hashCode() { return Objects.hash(id, waitForCompletion, timeout); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Request other = (Request) obj; return Objects.equals(id, other.id) && Objects.equals(waitForCompletion, other.waitForCompletion) && Objects.equals(timeout, other.timeout); } } public static
Request
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/operators/drivers/AllReduceDriverTest.java
{ "start": 12902, "end": 13307 }
class ____ extends RichReduceFunction<Tuple2<String, Integer>> { @Override public Tuple2<String, Integer> reduce( Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) { value2.f0 = value1.f0 + value2.f0; value2.f1 = value1.f1 + value2.f1; return value2; } } public static final
ConcatSumSecondReducer
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/AbstractWebSocketHandlerRegistration.java
{ "start": 1543, "end": 1865 }
class ____ {@link WebSocketHandlerRegistration WebSocketHandlerRegistrations} that gathers all the configuration * options but allows subclasses to put together the actual HTTP request mappings. * * @author Rossen Stoyanchev * @author Sebastien Deleuze * @since 4.0 * @param <M> the mappings type */ public abstract
for
java
apache__flink
flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/history/HistoryServerStaticFileServerHandlerTest.java
{ "start": 1440, "end": 4224 }
class ____ { @Test void testRespondWithFile(@TempDir Path tmpDir) throws Exception { final Path webDir = Files.createDirectory(tmpDir.resolve("webDir")); final Path uploadDir = Files.createDirectory(tmpDir.resolve("uploadDir")); Router router = new Router() .addGet("/:*", new HistoryServerStaticFileServerHandler(webDir.toFile())); WebFrontendBootstrap webUI = new WebFrontendBootstrap( router, LoggerFactory.getLogger(HistoryServerStaticFileServerHandlerTest.class), uploadDir.toFile(), null, "localhost", 0, new Configuration()); int port = webUI.getServerPort(); try { // verify that 404 message is returned when requesting a non-existent file Tuple2<Integer, String> notFound404 = HttpUtils.getFromHTTP("http://localhost:" + port + "/hello"); assertThat(notFound404.f0).isEqualTo(404); assertThat(notFound404.f1).contains("not found"); // verify that a) a file can be loaded using the ClassLoader and b) that the // HistoryServer // index_hs.html is injected Tuple2<Integer, String> index = HttpUtils.getFromHTTP("http://localhost:" + port + "/index.html"); assertThat(index.f0).isEqualTo(200); assertThat(index.f1).contains("Apache Flink Web Dashboard"); // verify that index.html is appended if the request path ends on '/' Tuple2<Integer, String> index2 = HttpUtils.getFromHTTP("http://localhost:" + port + "/"); assertThat(index2).isEqualTo(index); // verify that a 405 message is returned when requesting a directory Files.createDirectory(webDir.resolve("dir.json")); Tuple2<Integer, String> dirNotFound = HttpUtils.getFromHTTP("http://localhost:" + port + "/dir"); assertThat(dirNotFound.f0).isEqualTo(405); assertThat(dirNotFound.f1).contains("not found"); // verify that a 403 message is returned when requesting a file outside the webDir Files.createFile(tmpDir.resolve("secret")); Tuple2<Integer, String> dirOutsideDirectory = HttpUtils.getFromHTTP("http://localhost:" + port + "/../secret"); assertThat(dirOutsideDirectory.f0).isEqualTo(403); assertThat(dirOutsideDirectory.f1).contains("Forbidden"); } finally { webUI.shutdown(); } } }
HistoryServerStaticFileServerHandlerTest
java
resilience4j__resilience4j
resilience4j-micronaut/src/main/java/io/github/resilience4j/micronaut/bulkhead/ThreadPoolBulkheadProperties.java
{ "start": 2446, "end": 2815 }
class ____ extends CommonThreadPoolBulkheadConfigurationProperties.InstanceProperties implements Named { private final String name; public InstancePropertiesInstances(@Parameter String name) { this.name = name; } @Override public String getName() { return name; } } }
InstancePropertiesInstances
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/support/descriptor/FileSystemSource.java
{ "start": 785, "end": 966 }
interface ____ extends UriSource { /** * Get the source file or directory. * * @return the source file or directory; never {@code null} */ File getFile(); }
FileSystemSource
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/main/java/org/springframework/cloud/gateway/route/RouteDefinition.java
{ "start": 1326, "end": 4050 }
class ____ { private @Nullable String id; @NotEmpty @Valid private List<PredicateDefinition> predicates = new ArrayList<>(); @Valid private List<FilterDefinition> filters = new ArrayList<>(); private @Nullable URI uri; private Map<String, Object> metadata = new HashMap<>(); private int order = 0; private boolean enabled = true; public RouteDefinition() { } public RouteDefinition(String text) { int eqIdx = text.indexOf('='); if (eqIdx <= 0) { throw new ValidationException( "Unable to parse RouteDefinition text '" + text + "'" + ", must be of the form name=value"); } setId(text.substring(0, eqIdx)); String[] args = tokenizeToStringArray(text.substring(eqIdx + 1), ","); setUri(URI.create(args[0])); for (int i = 1; i < args.length; i++) { this.predicates.add(new PredicateDefinition(args[i])); } } public @Nullable String getId() { return id; } public void setId(String id) { this.id = id; } public List<PredicateDefinition> getPredicates() { return predicates; } public void setPredicates(List<PredicateDefinition> predicates) { this.predicates = predicates; } public List<FilterDefinition> getFilters() { return filters; } public void setFilters(List<FilterDefinition> filters) { this.filters = filters; } public @Nullable URI getUri() { return uri; } public void setUri(URI uri) { this.uri = uri; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RouteDefinition that = (RouteDefinition) o; return this.order == that.order && Objects.equals(this.id, that.id) && Objects.equals(this.predicates, that.predicates) && Objects.equals(this.filters, that.filters) && Objects.equals(this.uri, that.uri) && Objects.equals(this.metadata, that.metadata) && Objects.equals(this.enabled, that.enabled); } @Override public int hashCode() { return Objects.hash(this.id, this.predicates, this.filters, this.uri, this.metadata, this.order, this.enabled); } @Override public String toString() { return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters + ", uri=" + uri + ", order=" + order + ", metadata=" + metadata + ", enabled=" + enabled + '}'; } }
RouteDefinition
java
elastic__elasticsearch
x-pack/plugin/voting-only-node/src/test/java/org/elasticsearch/cluster/coordination/votingonly/VotingOnlyNodeCoordinatorTests.java
{ "start": 829, "end": 2899 }
class ____ extends AbstractCoordinatorTestCase { @Override protected TransportInterceptor getTransportInterceptor(DiscoveryNode localNode, ThreadPool threadPool) { if (VotingOnlyNodePlugin.isVotingOnlyNode(localNode)) { return new TransportInterceptor() { @Override public AsyncSender interceptSender(AsyncSender sender) { return new VotingOnlyNodePlugin.VotingOnlyNodeAsyncSender(sender, () -> threadPool); } }; } else { return super.getTransportInterceptor(localNode, threadPool); } } @Override protected CoordinatorStrategy createCoordinatorStrategy() { return new DefaultCoordinatorStrategy(new VotingOnlyNodePlugin.VotingOnlyNodeElectionStrategy()); } public void testDoesNotElectVotingOnlyMasterNode() { try (Cluster cluster = new Cluster(randomIntBetween(1, 5), false, Settings.EMPTY)) { cluster.runRandomly(); cluster.stabilise(); final Cluster.ClusterNode leader = cluster.getAnyLeader(); assertTrue(leader.getLocalNode().isMasterNode()); assertFalse(leader.getLocalNode().toString(), VotingOnlyNodePlugin.isVotingOnlyNode(leader.getLocalNode())); } } @Override protected DiscoveryNode createDiscoveryNode(int nodeIndex, boolean masterEligible) { return DiscoveryNodeUtils.builder("node" + nodeIndex) .ephemeralId(UUIDs.randomBase64UUID(random())) // generated deterministically for repeatable tests .roles( masterEligible ? ALL_ROLES_EXCEPT_VOTING_ONLY : randomBoolean() ? emptySet() : Set.of( DiscoveryNodeRole.DATA_ROLE, DiscoveryNodeRole.INGEST_ROLE, DiscoveryNodeRole.MASTER_ROLE, DiscoveryNodeRole.VOTING_ONLY_NODE_ROLE ) ) .build(); } }
VotingOnlyNodeCoordinatorTests
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/planner/QueryTranslator.java
{ "start": 25318, "end": 25614 }
class ____<F extends Function> extends AggTranslator<F> { @Override protected final LeafAgg asAgg(String id, F function) { return toAgg(id, function); } protected abstract LeafAgg toAgg(String id, F f); } abstract static
SingleValueAggTranslator
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/AbstractDataBoundFormElementTag.java
{ "start": 1723, "end": 8295 }
class ____ extends AbstractFormTag implements EditorAwareTag { /** * Name of the exposed path variable within the scope of this tag: "nestedPath". * Same value as {@link org.springframework.web.servlet.tags.NestedPathTag#NESTED_PATH_VARIABLE_NAME}. */ protected static final String NESTED_PATH_VARIABLE_NAME = NestedPathTag.NESTED_PATH_VARIABLE_NAME; /** * The property path from the {@link FormTag#setModelAttribute form object}. */ private @Nullable String path; /** * The value of the '{@code id}' attribute. */ private @Nullable String id; /** * The {@link BindStatus} of this tag. */ private @Nullable BindStatus bindStatus; /** * Set the property path from the {@link FormTag#setModelAttribute form object}. * May be a runtime expression. */ public void setPath(String path) { this.path = path; } /** * Get the {@link #evaluate resolved} property path for the * {@link FormTag#setModelAttribute form object}. */ protected final String getPath() throws JspException { String resolvedPath = (String) evaluate("path", this.path); return (resolvedPath != null ? resolvedPath : ""); } /** * Set the value of the '{@code id}' attribute. * <p>May be a runtime expression; defaults to the value of {@link #getName()}. * Note that the default value may not be valid for certain tags. */ @Override public void setId(@Nullable String id) { this.id = id; } /** * Get the value of the '{@code id}' attribute. */ @Override public @Nullable String getId() { return this.id; } /** * Writes the default set of attributes to the supplied {@link TagWriter}. * Further, abstract subclasses should override this method to add in * any additional default attributes but <strong>must</strong> remember * to call the {@code super} method. * <p>Concrete subclasses should call this method when/if they want * to render default attributes. * @param tagWriter the {@link TagWriter} to which any attributes are to be written */ protected void writeDefaultAttributes(TagWriter tagWriter) throws JspException { writeOptionalAttribute(tagWriter, "id", resolveId()); writeOptionalAttribute(tagWriter, "name", getName()); } /** * Determine the '{@code id}' attribute value for this tag, * autogenerating one if none specified. * @see #getId() * @see #autogenerateId() */ protected @Nullable String resolveId() throws JspException { Object id = evaluate("id", getId()); if (id != null) { String idString = id.toString(); return (StringUtils.hasText(idString) ? idString : null); } return autogenerateId(); } /** * Autogenerate the '{@code id}' attribute value for this tag. * <p>The default implementation simply delegates to {@link #getName()}, * deleting invalid characters (such as "[" or "]"). */ protected @Nullable String autogenerateId() throws JspException { String name = getName(); return (name != null ? StringUtils.deleteAny(name, "[]") : null); } /** * Get the value for the HTML '{@code name}' attribute. * <p>The default implementation simply delegates to * {@link #getPropertyPath()} to use the property path as the name. * For the most part this is desirable as it links with the server-side * expectation for data binding. However, some subclasses may wish to change * the value of the '{@code name}' attribute without changing the bind path. * @return the value for the HTML '{@code name}' attribute */ protected @Nullable String getName() throws JspException { return getPropertyPath(); } /** * Get the {@link BindStatus} for this tag. */ protected BindStatus getBindStatus() throws JspException { if (this.bindStatus == null) { // HTML escaping in tags is performed by the ValueFormatter class. String nestedPath = getNestedPath(); String pathToUse = (nestedPath != null ? nestedPath + getPath() : getPath()); if (pathToUse.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) { pathToUse = pathToUse.substring(0, pathToUse.length() - 1); } this.bindStatus = new BindStatus(getRequestContext(), pathToUse, false); } return this.bindStatus; } /** * Get the value of the nested path that may have been exposed by the * {@link NestedPathTag}. */ protected @Nullable String getNestedPath() { return (String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE); } /** * Build the property path for this tag, including the nested path * but <i>not</i> prefixed with the name of the form attribute. * @see #getNestedPath() * @see #getPath() */ protected String getPropertyPath() throws JspException { String expression = getBindStatus().getExpression(); return (expression != null ? expression : ""); } /** * Get the bound value. * @see #getBindStatus() */ protected final @Nullable Object getBoundValue() throws JspException { return getBindStatus().getValue(); } /** * Get the {@link PropertyEditor}, if any, in use for value bound to this tag. */ protected @Nullable PropertyEditor getPropertyEditor() throws JspException { return getBindStatus().getEditor(); } /** * Exposes the {@link PropertyEditor} for {@link EditorAwareTag}. * <p>Use {@link #getPropertyEditor()} for internal rendering purposes. */ @Override public final @Nullable PropertyEditor getEditor() throws JspException { return getPropertyEditor(); } /** * Get a display String for the given value, converted by a PropertyEditor * that the BindStatus may have registered for the value's Class. */ protected String convertToDisplayString(@Nullable Object value) throws JspException { PropertyEditor editor = (value != null ? getBindStatus().findEditor(value.getClass()) : null); return getDisplayString(value, editor); } /** * Process the given form field through a {@link RequestDataValueProcessor} * instance if one is configured or otherwise returns the same value. */ protected final String processFieldValue(@Nullable String name, String value, String type) { RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor(); ServletRequest request = this.pageContext.getRequest(); if (processor != null && request instanceof HttpServletRequest httpServletRequest) { value = processor.processFormFieldValue(httpServletRequest, name, value, type); } return value; } /** * Disposes of the {@link BindStatus} instance. */ @Override public void doFinally() { super.doFinally(); this.bindStatus = null; } }
AbstractDataBoundFormElementTag
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/MongoDbEndpointBuilderFactory.java
{ "start": 109615, "end": 121147 }
interface ____ extends MongoDbEndpointConsumerBuilder, MongoDbEndpointProducerBuilder { default AdvancedMongoDbEndpointBuilder advanced() { return (AdvancedMongoDbEndpointBuilder) this; } /** * Sets the name of the MongoDB collection to bind to this endpoint. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param collection the value to set * @return the dsl builder */ default MongoDbEndpointBuilder collection(String collection) { doSetProperty("collection", collection); return this; } /** * Sets the collection index (JSON FORMAT : { field1 : order1, field2 : * order2}). * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param collectionIndex the value to set * @return the dsl builder */ default MongoDbEndpointBuilder collectionIndex(String collectionIndex) { doSetProperty("collectionIndex", collectionIndex); return this; } /** * Set the whole Connection String/Uri for mongodb endpoint. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param connectionUriString the value to set * @return the dsl builder */ default MongoDbEndpointBuilder connectionUriString(String connectionUriString) { doSetProperty("connectionUriString", connectionUriString); return this; } /** * Create the collection during initialisation if it doesn't exist. * Default is true. * * The option is a: <code>boolean</code> type. * * Default: true * Group: common * * @param createCollection the value to set * @return the dsl builder */ default MongoDbEndpointBuilder createCollection(boolean createCollection) { doSetProperty("createCollection", createCollection); return this; } /** * Create the collection during initialisation if it doesn't exist. * Default is true. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: common * * @param createCollection the value to set * @return the dsl builder */ default MongoDbEndpointBuilder createCollection(String createCollection) { doSetProperty("createCollection", createCollection); return this; } /** * Sets the name of the MongoDB database to target. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param database the value to set * @return the dsl builder */ default MongoDbEndpointBuilder database(String database) { doSetProperty("database", database); return this; } /** * Host address of mongodb server in host:port format. It's possible to * also use more than one address, as a comma separated list of hosts: * host1:port1,host2:port2. If this parameter is specified, the provided * connectionBean is ignored. * * The option is a: <code>java.lang.String</code> type. * * Group: common * * @param hosts the value to set * @return the dsl builder */ default MongoDbEndpointBuilder hosts(String hosts) { doSetProperty("hosts", hosts); return this; } /** * Sets the connection bean used as a client for connecting to a * database. * * The option is a: <code>com.mongodb.client.MongoClient</code> type. * * Group: common * * @param mongoConnection the value to set * @return the dsl builder */ default MongoDbEndpointBuilder mongoConnection(com.mongodb.client.MongoClient mongoConnection) { doSetProperty("mongoConnection", mongoConnection); return this; } /** * Sets the connection bean used as a client for connecting to a * database. * * The option will be converted to a * <code>com.mongodb.client.MongoClient</code> type. * * Group: common * * @param mongoConnection the value to set * @return the dsl builder */ default MongoDbEndpointBuilder mongoConnection(String mongoConnection) { doSetProperty("mongoConnection", mongoConnection); return this; } /** * Sets the operation this endpoint will execute against MongoDB. * * The option is a: * <code>org.apache.camel.component.mongodb.MongoDbOperation</code> * type. * * Group: common * * @param operation the value to set * @return the dsl builder */ default MongoDbEndpointBuilder operation(org.apache.camel.component.mongodb.MongoDbOperation operation) { doSetProperty("operation", operation); return this; } /** * Sets the operation this endpoint will execute against MongoDB. * * The option will be converted to a * <code>org.apache.camel.component.mongodb.MongoDbOperation</code> * type. * * Group: common * * @param operation the value to set * @return the dsl builder */ default MongoDbEndpointBuilder operation(String operation) { doSetProperty("operation", operation); return this; } /** * Convert the output of the producer to the selected type: DocumentList * Document or MongoIterable. DocumentList or MongoIterable applies to * findAll and aggregate. Document applies to all other operations. * * The option is a: * <code>org.apache.camel.component.mongodb.MongoDbOutputType</code> * type. * * Group: common * * @param outputType the value to set * @return the dsl builder */ default MongoDbEndpointBuilder outputType(org.apache.camel.component.mongodb.MongoDbOutputType outputType) { doSetProperty("outputType", outputType); return this; } /** * Convert the output of the producer to the selected type: DocumentList * Document or MongoIterable. DocumentList or MongoIterable applies to * findAll and aggregate. Document applies to all other operations. * * The option will be converted to a * <code>org.apache.camel.component.mongodb.MongoDbOutputType</code> * type. * * Group: common * * @param outputType the value to set * @return the dsl builder */ default MongoDbEndpointBuilder outputType(String outputType) { doSetProperty("outputType", outputType); return this; } /** * The database name associated with the user's credentials. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param authSource the value to set * @return the dsl builder */ default MongoDbEndpointBuilder authSource(String authSource) { doSetProperty("authSource", authSource); return this; } /** * User password for mongodb connection. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param password the value to set * @return the dsl builder */ default MongoDbEndpointBuilder password(String password) { doSetProperty("password", password); return this; } /** * Specifies that all communication with MongoDB instances should use * TLS. Supersedes the ssl option. Default: false. * * The option is a: <code>boolean</code> type. * * Default: false * Group: security * * @param tls the value to set * @return the dsl builder */ default MongoDbEndpointBuilder tls(boolean tls) { doSetProperty("tls", tls); return this; } /** * Specifies that all communication with MongoDB instances should use * TLS. Supersedes the ssl option. Default: false. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: security * * @param tls the value to set * @return the dsl builder */ default MongoDbEndpointBuilder tls(String tls) { doSetProperty("tls", tls); return this; } /** * Specifies that the driver should allow invalid hostnames in the * certificate for TLS connections. Supersedes * sslInvalidHostNameAllowed. Has the same effect as tlsInsecure by * setting tlsAllowInvalidHostnames to true. Default: false. * * The option is a: <code>boolean</code> type. * * Default: false * Group: security * * @param tlsAllowInvalidHostnames the value to set * @return the dsl builder */ default MongoDbEndpointBuilder tlsAllowInvalidHostnames(boolean tlsAllowInvalidHostnames) { doSetProperty("tlsAllowInvalidHostnames", tlsAllowInvalidHostnames); return this; } /** * Specifies that the driver should allow invalid hostnames in the * certificate for TLS connections. Supersedes * sslInvalidHostNameAllowed. Has the same effect as tlsInsecure by * setting tlsAllowInvalidHostnames to true. Default: false. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: security * * @param tlsAllowInvalidHostnames the value to set * @return the dsl builder */ default MongoDbEndpointBuilder tlsAllowInvalidHostnames(String tlsAllowInvalidHostnames) { doSetProperty("tlsAllowInvalidHostnames", tlsAllowInvalidHostnames); return this; } /** * Username for mongodb connection. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param username the value to set * @return the dsl builder */ default MongoDbEndpointBuilder username(String username) { doSetProperty("username", username); return this; } } /** * Advanced builder for endpoint for the MongoDB component. */ public
MongoDbEndpointBuilder
java
mapstruct__mapstruct
processor/src/test/resources/fixtures/org/mapstruct/ap/test/collection/adder/SourceTargetMapperStrategyDefaultImpl.java
{ "start": 559, "end": 1121 }
class ____ implements SourceTargetMapperStrategyDefault { private final PetMapper petMapper = new PetMapper(); @Override public Target shouldFallBackToAdder(Source source) throws DogException { if ( source == null ) { return null; } Target target = new Target(); try { target.setPets( petMapper.toPets( source.getPets() ) ); } catch ( CatException e ) { throw new RuntimeException( e ); } return target; } }
SourceTargetMapperStrategyDefaultImpl
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/reactive/ServerHttpSecurityConfigurationTests.java
{ "start": 4762, "end": 13772 }
class ____ { public final SpringTestContext spring = new SpringTestContext(this); WebTestClient webClient; @Autowired void setup(ApplicationContext context) { if (!context.containsBean(WebHttpHandlerBuilder.WEB_HANDLER_BEAN_NAME)) { return; } this.webClient = WebTestClient.bindToApplicationContext(context) .apply(springSecurity()) .configureClient() .build(); } @Test public void loadConfigWhenReactiveUserDetailsServiceConfiguredThenServerHttpSecurityExists() { this.spring .register(ServerHttpSecurityConfiguration.class, ReactiveAuthenticationTestConfiguration.class, WebFluxSecurityConfiguration.class) .autowire(); ServerHttpSecurity serverHttpSecurity = this.spring.getContext().getBean(ServerHttpSecurity.class); assertThat(serverHttpSecurity).isNotNull(); } @Test public void loadConfigWhenProxyingEnabledAndSubclassThenServerHttpSecurityExists() { this.spring .register(SubclassConfig.class, ReactiveAuthenticationTestConfiguration.class, WebFluxSecurityConfiguration.class) .autowire(); ServerHttpSecurity serverHttpSecurity = this.spring.getContext().getBean(ServerHttpSecurity.class); assertThat(serverHttpSecurity).isNotNull(); } @Test void loginWhenCompromisePasswordCheckerConfiguredAndPasswordCompromisedThenUnauthorized() { this.spring.register(FormLoginConfig.class, UserDetailsConfig.class, CompromisedPasswordCheckerConfig.class) .autowire(); MultiValueMap<String, String> data = new LinkedMultiValueMap<>(); data.add("username", "user"); data.add("password", "password"); // @formatter:off this.webClient.mutateWith(csrf()) .post() .uri("/login") .body(BodyInserters.fromFormData(data)) .exchange() .expectStatus().is3xxRedirection() .expectHeader().location("/login?error"); // @formatter:on } @Test void loginWhenCompromisePasswordCheckerConfiguredAndPasswordNotCompromisedThenUnauthorized() { this.spring.register(FormLoginConfig.class, UserDetailsConfig.class, CompromisedPasswordCheckerConfig.class) .autowire(); MultiValueMap<String, String> data = new LinkedMultiValueMap<>(); data.add("username", "admin"); data.add("password", "password2"); // @formatter:off this.webClient.mutateWith(csrf()) .post() .uri("/login") .body(BodyInserters.fromFormData(data)) .exchange() .expectStatus().is3xxRedirection() .expectHeader().location("/"); // @formatter:on } @Test void loginWhenCompromisedPasswordAndRedirectIfPasswordExceptionThenRedirectedToResetPassword() { this.spring .register(FormLoginRedirectToResetPasswordConfig.class, UserDetailsConfig.class, CompromisedPasswordCheckerConfig.class) .autowire(); MultiValueMap<String, String> data = new LinkedMultiValueMap<>(); data.add("username", "user"); data.add("password", "password"); // @formatter:off this.webClient.mutateWith(csrf()) .post() .uri("/login") .body(BodyInserters.fromFormData(data)) .exchange() .expectStatus().is3xxRedirection() .expectHeader().location("/reset-password"); // @formatter:on } @Test public void metaAnnotationWhenTemplateDefaultsBeanThenResolvesExpression() throws Exception { this.spring.register(MetaAnnotationPlaceholderConfig.class).autowire(); Authentication user = new TestingAuthenticationToken("user", "password", "ROLE_USER"); this.webClient.mutateWith(mockAuthentication(user)) .get() .uri("/hi") .exchange() .expectStatus() .isOk() .expectBody(String.class) .isEqualTo("Hi, Stranger!"); Authentication harold = new TestingAuthenticationToken("harold", "password", "ROLE_USER"); this.webClient.mutateWith(mockAuthentication(harold)) .get() .uri("/hi") .exchange() .expectBody(String.class) .isEqualTo("Hi, Harold!"); } @Test public void resoleMetaAnnotationWhenTemplateDefaultsBeanThenResolvesExpression() throws Exception { this.spring.register(MetaAnnotationPlaceholderConfig.class).autowire(); Authentication user = new TestingAuthenticationToken("user", "password", "ROLE_USER"); this.webClient.mutateWith(mockAuthentication(user)) .get() .uri("/hello") .exchange() .expectStatus() .isOk() .expectBody(String.class) .isEqualTo("user"); Authentication harold = new TestingAuthenticationToken("harold", "password", "ROLE_USER"); this.webClient.mutateWith(mockAuthentication(harold)) .get() .uri("/hello") .exchange() .expectBody(String.class) .isEqualTo("harold"); } @Test public void getWhenUsingObservationRegistryThenObservesRequest() { this.spring.register(ObservationRegistryConfig.class).autowire(); // @formatter:off this.webClient .get() .uri("/hello") .headers((headers) -> headers.setBasicAuth("user", "password")) .exchange() .expectStatus() .isNotFound(); // @formatter:on ObservationHandler<Observation.Context> handler = this.spring.getContext().getBean(ObservationHandler.class); ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, times(6)).onStart(captor.capture()); Iterator<Observation.Context> contexts = captor.getAllValues().iterator(); assertThat(contexts.next().getContextualName()).isEqualTo("http get"); assertThat(contexts.next().getContextualName()).isEqualTo("security filterchain before"); assertThat(contexts.next().getName()).isEqualTo("spring.security.authentications"); assertThat(contexts.next().getName()).isEqualTo("spring.security.authorizations"); assertThat(contexts.next().getName()).isEqualTo("spring.security.http.secured.requests"); assertThat(contexts.next().getContextualName()).isEqualTo("security filterchain after"); } // gh-16161 @Test public void getWhenUsingRSocketThenObservesRequest() { this.spring.register(ObservationRegistryConfig.class, RSocketSecurityConfig.class).autowire(); // @formatter:off this.webClient .get() .uri("/hello") .headers((headers) -> headers.setBasicAuth("user", "password")) .exchange() .expectStatus() .isNotFound(); // @formatter:on ObservationHandler<Observation.Context> handler = this.spring.getContext().getBean(ObservationHandler.class); ArgumentCaptor<Observation.Context> captor = ArgumentCaptor.forClass(Observation.Context.class); verify(handler, times(6)).onStart(captor.capture()); Iterator<Observation.Context> contexts = captor.getAllValues().iterator(); assertThat(contexts.next().getContextualName()).isEqualTo("http get"); assertThat(contexts.next().getContextualName()).isEqualTo("security filterchain before"); assertThat(contexts.next().getName()).isEqualTo("spring.security.authentications"); assertThat(contexts.next().getName()).isEqualTo("spring.security.authorizations"); assertThat(contexts.next().getName()).isEqualTo("spring.security.http.secured.requests"); assertThat(contexts.next().getContextualName()).isEqualTo("security filterchain after"); } @Test void authorizeExchangeCustomizerBean() { this.spring.register(AuthorizeExchangeCustomizerBeanConfig.class).autowire(); Customizer<AuthorizeExchangeSpec> authzCustomizer = this.spring.getContext().getBean("authz", Customizer.class); ArgumentCaptor<AuthorizeExchangeSpec> arg0 = ArgumentCaptor.forClass(AuthorizeExchangeSpec.class); verify(authzCustomizer).customize(arg0.capture()); } @Test void multiAuthorizeExchangeCustomizerBean() { this.spring.register(MultiAuthorizeExchangeCustomizerBeanConfig.class).autowire(); Customizer<AuthorizeExchangeSpec> authzCustomizer = this.spring.getContext().getBean("authz", Customizer.class); ArgumentCaptor<AuthorizeExchangeSpec> arg0 = ArgumentCaptor.forClass(AuthorizeExchangeSpec.class); verify(authzCustomizer).customize(arg0.capture()); } @Test void serverHttpSecurityCustomizerBean() { this.spring.register(ServerHttpSecurityCustomizerConfig.class).autowire(); Customizer<ServerHttpSecurity> httpSecurityCustomizer = this.spring.getContext() .getBean("httpSecurityCustomizer", Customizer.class); ArgumentCaptor<ServerHttpSecurity> arg0 = ArgumentCaptor.forClass(ServerHttpSecurity.class); verify(httpSecurityCustomizer).customize(arg0.capture()); } @Test void multiServerHttpSecurityCustomizerBean() { this.spring.register(MultiServerHttpSecurityCustomizerConfig.class).autowire(); Customizer<ServerHttpSecurity> httpSecurityCustomizer = this.spring.getContext() .getBean("httpSecurityCustomizer", Customizer.class); Customizer<ServerHttpSecurity> httpSecurityCustomizer0 = this.spring.getContext() .getBean("httpSecurityCustomizer0", Customizer.class); InOrder inOrder = Mockito.inOrder(httpSecurityCustomizer0, httpSecurityCustomizer); ArgumentCaptor<ServerHttpSecurity> arg0 = ArgumentCaptor.forClass(ServerHttpSecurity.class); inOrder.verify(httpSecurityCustomizer0).customize(arg0.capture()); inOrder.verify(httpSecurityCustomizer).customize(arg0.capture()); } @Configuration static
ServerHttpSecurityConfigurationTests
java
apache__camel
core/camel-management/src/test/java/org/apache/camel/management/ManagedCustomBeanTest.java
{ "start": 1482, "end": 2879 }
class ____ extends ManagementTestSupport { @Test public void testManageCustomBean() throws Exception { MBeanServer mbeanServer = getMBeanServer(); ObjectName on = getCamelObjectName(TYPE_PROCESSOR, "custom"); getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:result").expectedHeaderReceived("foo", "hey"); template.sendBody("direct:start", "World"); assertMockEndpointsSatisfied(); String foo = (String) mbeanServer.getAttribute(on, "Foo"); assertEquals("hey", foo); // change foo mbeanServer.setAttribute(on, new Attribute("Foo", "changed")); resetMocks(); getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:result").expectedHeaderReceived("foo", "changed"); template.sendBody("direct:start", "Camel"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").routeId("foo") .bean(new MyCustomBean()).id("custom") .to("mock:result"); } }; } // START SNIPPET: e1 @ManagedResource(description = "My Managed Bean") public static
ManagedCustomBeanTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2253/TestMapper.java
{ "start": 845, "end": 1042 }
class ____ { private final int age; public PersonDto(int age) { this.age = age; } public int getAge() { return age; } } }
PersonDto
java
apache__camel
components/camel-telegram/src/main/java/org/apache/camel/component/telegram/service/TelegramServiceRestBotAPIAdapter.java
{ "start": 15061, "end": 15827 }
class ____ extends OutgoingMessageHandler<OutgoingStickerMessage> { public OutgoingStickerMessageHandler(HttpClient client, ObjectMapper mapper, String baseUri, int bufferSize) { super(client, mapper, baseUri + "/sendSticker", null, MessageResult.class, bufferSize); } @Override protected void addBody(OutgoingStickerMessage message) { fillCommonMediaParts(message); if (message.getSticker() != null) { buildTextPart("sticker", message.getSticker()); } else { buildMediaPart("sticker", message.getFilenameWithExtension(), message.getStickerImage()); } } } }
OutgoingStickerMessageHandler
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/inheritance/joined/ChildAuditing.java
{ "start": 702, "end": 2392 }
class ____ { private Integer id1; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { id1 = 1; // Rev 1 scope.inTransaction( em -> { ChildEntity ce = new ChildEntity( id1, "x", 1l ); em.persist( ce ); } ); // Rev 2 scope.inTransaction( em -> { ChildEntity ce = em.find( ChildEntity.class, id1 ); ce.setData( "y" ); ce.setNumVal( 2l ); } ); } @Test public void testRevisionsCounts(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { assertEquals( Arrays.asList( 1, 2 ), AuditReaderFactory.get( em ).getRevisions( ChildEntity.class, id1 ) ); } ); } @Test public void testHistoryOfChildId1(EntityManagerFactoryScope scope) { ChildEntity ver1 = new ChildEntity( id1, "x", 1l ); ChildEntity ver2 = new ChildEntity( id1, "y", 2l ); scope.inEntityManager( em -> { var auditReader = AuditReaderFactory.get( em ); assertEquals( ver1, auditReader.find( ChildEntity.class, id1, 1 ) ); assertEquals( ver2, auditReader.find( ChildEntity.class, id1, 2 ) ); assertEquals( ver1, auditReader.find( ParentEntity.class, id1, 1 ) ); assertEquals( ver2, auditReader.find( ParentEntity.class, id1, 2 ) ); } ); } @Test public void testPolymorphicQuery(EntityManagerFactoryScope scope) { ChildEntity childVer1 = new ChildEntity( id1, "x", 1l ); scope.inEntityManager( em -> { var auditReader = AuditReaderFactory.get( em ); assertEquals( childVer1, auditReader.createQuery().forEntitiesAtRevision( ChildEntity.class, 1 ).getSingleResult() ); assertEquals( childVer1, auditReader.createQuery().forEntitiesAtRevision( ParentEntity.class, 1 ).getSingleResult() ); } ); } }
ChildAuditing
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/dispatcher/UnavailableDispatcherOperationException.java
{ "start": 944, "end": 1192 }
class ____ extends DispatcherException { private static final long serialVersionUID = -45499335133622792L; public UnavailableDispatcherOperationException(String message) { super(message); } }
UnavailableDispatcherOperationException
java
mapstruct__mapstruct
core/src/main/java/org/mapstruct/DecoratedWith.java
{ "start": 4457, "end": 4694 }
class ____ of the mapper implementation ends with an underscore). To inject that bean in your * decorator, add the same annotation to the delegate field (e.g. by copy/pasting it from the generated class): * * <pre> * public abstract
name
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ZookeeperComponentBuilderFactory.java
{ "start": 1360, "end": 1836 }
interface ____ { /** * ZooKeeper (camel-zookeeper) * Manage ZooKeeper clusters. * * Category: clustering,management,bigdata * Since: 2.9 * Maven coordinates: org.apache.camel:camel-zookeeper * * @return the dsl builder */ static ZookeeperComponentBuilder zookeeper() { return new ZookeeperComponentBuilderImpl(); } /** * Builder for the ZooKeeper component. */
ZookeeperComponentBuilderFactory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/ops/replicate/ReplicateTest.java
{ "start": 1096, "end": 1614 }
class ____ { @Test public void refreshTest(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { City city = new City(); city.setId( 100L ); city.setName( "Cluj-Napoca" ); entityManager.unwrap( Session.class ).replicate( city, ReplicationMode.OVERWRITE ); } ); scope.inTransaction( entityManager -> { City city = entityManager.find( City.class, 100L ); assertThat( city.getName() ).isEqualTo( "Cluj-Napoca" ); } ); } @Entity(name = "City") public static
ReplicateTest
java
spring-projects__spring-boot
module/spring-boot-transaction/src/test/java/org/springframework/boot/transaction/autoconfigure/TransactionAutoConfigurationTests.java
{ "start": 8830, "end": 9189 }
class ____ { @Bean ReactiveTransactionManager reactiveTransactionManager1() { return mock(ReactiveTransactionManager.class); } @Bean ReactiveTransactionManager reactiveTransactionManager2() { return mock(ReactiveTransactionManager.class); } } @Configuration(proxyBeanMethods = false) static
SeveralReactiveTransactionManagersConfiguration
java
elastic__elasticsearch
modules/lang-painless/spi/src/main/java/org/elasticsearch/painless/spi/WhitelistLoader.java
{ "start": 6292, "end": 6637 }
class ____ the same, all * specified constructors, methods, and fields will be merged into a single Painless type. The * Painless dynamic type, 'def', used as part of constructor, method, and field definitions will * be appropriately parsed and handled. Painless complex types must be specified with the * fully-qualified Java
is
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/i18n/DefaultLocaleMissingMessageTemplateTest.java
{ "start": 1695, "end": 1800 }
interface ____ extends Messages { @Message("Goodbye") String goodbye(); } }
EnMessages
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/ThreadMetadataImpl.java
{ "start": 1183, "end": 5085 }
class ____ implements ThreadMetadata { private final String threadName; private final String threadState; private final Set<TaskMetadata> activeTasks; private final Set<TaskMetadata> standbyTasks; private final String mainConsumerClientId; private final String restoreConsumerClientId; private final Set<String> producerClientIds; // the admin client should be shared among all threads, so the client id should be the same; // we keep it at the thread-level for user's convenience and possible extensions in the future private final String adminClientId; public ThreadMetadataImpl(final String threadName, final String threadState, final String mainConsumerClientId, final String restoreConsumerClientId, final String producerClientIds, final String adminClientId, final Set<TaskMetadata> activeTasks, final Set<TaskMetadata> standbyTasks) { this.mainConsumerClientId = mainConsumerClientId; this.restoreConsumerClientId = restoreConsumerClientId; this.producerClientIds = Collections.singleton(producerClientIds); this.adminClientId = adminClientId; this.threadName = threadName; this.threadState = threadState; this.activeTasks = Collections.unmodifiableSet(activeTasks); this.standbyTasks = Collections.unmodifiableSet(standbyTasks); } public String threadState() { return threadState; } public String threadName() { return threadName; } public Set<TaskMetadata> activeTasks() { return activeTasks; } public Set<TaskMetadata> standbyTasks() { return standbyTasks; } public String consumerClientId() { return mainConsumerClientId; } public String restoreConsumerClientId() { return restoreConsumerClientId; } public Set<String> producerClientIds() { return producerClientIds; } public String adminClientId() { return adminClientId; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final ThreadMetadataImpl that = (ThreadMetadataImpl) o; return Objects.equals(threadName, that.threadName) && Objects.equals(threadState, that.threadState) && Objects.equals(activeTasks, that.activeTasks) && Objects.equals(standbyTasks, that.standbyTasks) && mainConsumerClientId.equals(that.mainConsumerClientId) && restoreConsumerClientId.equals(that.restoreConsumerClientId) && Objects.equals(producerClientIds, that.producerClientIds) && adminClientId.equals(that.adminClientId); } @Override public int hashCode() { return Objects.hash( threadName, threadState, activeTasks, standbyTasks, mainConsumerClientId, restoreConsumerClientId, producerClientIds, adminClientId); } @Override public String toString() { return "ThreadMetadata{" + "threadName=" + threadName + ", threadState=" + threadState + ", activeTasks=" + activeTasks + ", standbyTasks=" + standbyTasks + ", consumerClientId=" + mainConsumerClientId + ", restoreConsumerClientId=" + restoreConsumerClientId + ", producerClientIds=" + producerClientIds + ", adminClientId=" + adminClientId + '}'; } }
ThreadMetadataImpl
java
google__guava
android/guava/src/com/google/common/base/Splitter.java
{ "start": 21180, "end": 21304 }
interface ____ { Iterator<String> iterator(Splitter splitter, CharSequence toSplit); } private abstract static
Strategy
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/long_/LongAssert_isOdd_Test.java
{ "start": 869, "end": 1158 }
class ____ extends LongAssertBaseTest { @Override protected LongAssert invoke_api_method() { return assertions.isOdd(); } @Override protected void verify_internal_effects() { verify(longs).assertIsOdd(getInfo(assertions), getActual(assertions)); } }
LongAssert_isOdd_Test