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
apache__camel
components/camel-braintree/src/generated/java/org/apache/camel/component/braintree/PaymentMethodGatewayEndpointConfiguration.java
{ "start": 1885, "end": 3638 }
class ____ extends BraintreeConfiguration { @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "delete")}) private com.braintreegateway.PaymentMethodDeleteRequest deleteRequest; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "grant")}) private com.braintreegateway.PaymentMethodGrantRequest grantRequest; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "create"), @ApiMethod(methodName = "update")}) private com.braintreegateway.PaymentMethodRequest request; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "delete"), @ApiMethod(methodName = "find"), @ApiMethod(methodName = "grant"), @ApiMethod(methodName = "revoke"), @ApiMethod(methodName = "update")}) private String token; public com.braintreegateway.PaymentMethodDeleteRequest getDeleteRequest() { return deleteRequest; } public void setDeleteRequest(com.braintreegateway.PaymentMethodDeleteRequest deleteRequest) { this.deleteRequest = deleteRequest; } public com.braintreegateway.PaymentMethodGrantRequest getGrantRequest() { return grantRequest; } public void setGrantRequest(com.braintreegateway.PaymentMethodGrantRequest grantRequest) { this.grantRequest = grantRequest; } public com.braintreegateway.PaymentMethodRequest getRequest() { return request; } public void setRequest(com.braintreegateway.PaymentMethodRequest request) { this.request = request; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
PaymentMethodGatewayEndpointConfiguration
java
google__guava
android/guava/src/com/google/common/collect/Multimaps.java
{ "start": 9568, "end": 13412 }
class ____<K extends @Nullable Object, V extends @Nullable Object> extends AbstractMapBasedMultimap<K, V> { transient Supplier<? extends Collection<V>> factory; CustomMultimap(Map<K, Collection<V>> map, Supplier<? extends Collection<V>> factory) { super(map); this.factory = checkNotNull(factory); } @Override Set<K> createKeySet() { return createMaybeNavigableKeySet(); } @Override Map<K, Collection<V>> createAsMap() { return createMaybeNavigableAsMap(); } @Override protected Collection<V> createCollection() { return factory.get(); } @Override <E extends @Nullable Object> Collection<E> unmodifiableCollectionSubclass( Collection<E> collection) { if (collection instanceof NavigableSet) { return Sets.unmodifiableNavigableSet((NavigableSet<E>) collection); } else if (collection instanceof SortedSet) { return Collections.unmodifiableSortedSet((SortedSet<E>) collection); } else if (collection instanceof Set) { return Collections.unmodifiableSet((Set<E>) collection); } else if (collection instanceof List) { return Collections.unmodifiableList((List<E>) collection); } else { return Collections.unmodifiableCollection(collection); } } @Override Collection<V> wrapCollection(@ParametricNullness K key, Collection<V> collection) { if (collection instanceof List) { return wrapList(key, (List<V>) collection, null); } else if (collection instanceof NavigableSet) { return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null); } else if (collection instanceof SortedSet) { return new WrappedSortedSet(key, (SortedSet<V>) collection, null); } else if (collection instanceof Set) { return new WrappedSet(key, (Set<V>) collection); } else { return new WrappedCollection(key, collection, null); } } // can't use Serialization writeMultimap and populateMultimap methods since // there's no way to generate the empty backing map. /** * @serialData the factory and the backing map */ @GwtIncompatible @J2ktIncompatible private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(factory); stream.writeObject(backingMap()); } @GwtIncompatible @J2ktIncompatible @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); factory = (Supplier<? extends Collection<V>>) requireNonNull(stream.readObject()); Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject()); setMap(map); } @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; } /** * Creates a new {@code ListMultimap} that uses the provided map and factory. It can generate a * multimap based on arbitrary {@link Map} and {@link List} classes. Most users should prefer * {@link MultimapBuilder}, though a small number of users will need this method to cover map or * collection types that {@link MultimapBuilder} does not support. * * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code * toString} methods for the multimap and its returned views. The multimap's {@code get}, {@code * removeAll}, and {@code replaceValues} methods return {@code RandomAccess} lists if the factory * does. However, the multimap's {@code get} method returns instances of a different
CustomMultimap
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/exchange/ExchangeSink.java
{ "start": 532, "end": 1114 }
interface ____ { /** * adds a new page to this sink */ void addPage(Page page); /** * called once all pages have been added (see {@link #addPage(Page)}). */ void finish(); /** * Whether the sink has received all pages */ boolean isFinished(); /** * Adds a listener that will be notified when this exchange sink is finished. */ void addCompletionListener(ActionListener<Void> listener); /** * Whether the sink is blocked on adding more pages */ IsBlockedResult waitForWriting(); }
ExchangeSink
java
junit-team__junit5
documentation/src/test/java/example/ParameterizedClassDemo.java
{ "start": 1664, "end": 2022 }
class ____ { final String fruit; final int quantity; FruitTests(String fruit, int quantity) { this.fruit = fruit; this.quantity = quantity; } @Test void test() { assertFruit(fruit); assertQuantity(quantity); } @Test void anotherTest() { // ... } } // end::constructor_injection[] } @Nested
FruitTests
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/OperatorStateOutputCheckpointStreamTest.java
{ "start": 1274, "end": 4653 }
class ____ { private static final int STREAM_CAPACITY = 128; private static OperatorStateCheckpointOutputStream createStream() throws IOException { CheckpointStateOutputStream checkStream = new TestMemoryCheckpointOutputStream(STREAM_CAPACITY); return new OperatorStateCheckpointOutputStream(checkStream); } private OperatorStateHandle writeAllTestKeyGroups( OperatorStateCheckpointOutputStream stream, int numPartitions) throws Exception { DataOutputView dov = new DataOutputViewStreamWrapper(stream); for (int i = 0; i < numPartitions; ++i) { assertThat(stream.getNumberOfPartitions()).isEqualTo(i); stream.startNewPartition(); dov.writeInt(i); } return stream.closeAndGetHandle(); } @Test void testCloseNotPropagated() throws Exception { OperatorStateCheckpointOutputStream stream = createStream(); TestMemoryCheckpointOutputStream innerStream = (TestMemoryCheckpointOutputStream) stream.getDelegate(); stream.close(); assertThat(innerStream.isClosed()).isFalse(); innerStream.close(); } @Test void testEmptyOperatorStream() throws Exception { OperatorStateCheckpointOutputStream stream = createStream(); TestMemoryCheckpointOutputStream innerStream = (TestMemoryCheckpointOutputStream) stream.getDelegate(); OperatorStateHandle emptyHandle = stream.closeAndGetHandle(); assertThat(innerStream.isClosed()).isTrue(); assertThat(stream.getNumberOfPartitions()).isZero(); assertThat(emptyHandle).isNull(); } @Test void testWriteReadRoundtrip() throws Exception { int numPartitions = 3; OperatorStateCheckpointOutputStream stream = createStream(); OperatorStateHandle fullHandle = writeAllTestKeyGroups(stream, numPartitions); assertThat(fullHandle).isNotNull(); Map<String, OperatorStateHandle.StateMetaInfo> stateNameToPartitionOffsets = fullHandle.getStateNameToPartitionOffsets(); for (Map.Entry<String, OperatorStateHandle.StateMetaInfo> entry : stateNameToPartitionOffsets.entrySet()) { assertThat(entry.getValue().getDistributionMode()) .isEqualTo(OperatorStateHandle.Mode.SPLIT_DISTRIBUTE); } verifyRead(fullHandle, numPartitions); } private static void verifyRead(OperatorStateHandle fullHandle, int numPartitions) throws IOException { int count = 0; try (FSDataInputStream in = fullHandle.openInputStream()) { OperatorStateHandle.StateMetaInfo metaInfo = fullHandle .getStateNameToPartitionOffsets() .get(DefaultOperatorStateBackend.DEFAULT_OPERATOR_STATE_NAME); long[] offsets = metaInfo.getOffsets(); assertThat(offsets).isNotNull(); DataInputView div = new DataInputViewStreamWrapper(in); for (int i = 0; i < numPartitions; ++i) { in.seek(offsets[i]); assertThat(div.readInt()).isEqualTo(i); ++count; } } assertThat(count).isEqualTo(numPartitions); } }
OperatorStateOutputCheckpointStreamTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/ApplicationHistoryProtocolPB.java
{ "start": 1267, "end": 1373 }
interface ____ extends ApplicationHistoryProtocolService.BlockingInterface { }
ApplicationHistoryProtocolPB
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 95035, "end": 95297 }
class ____<K, V> { abstract MyMap<K, V> map(); abstract Builder<K, V> toBuilder(); static <K, V> Builder<K, V> builder() { return new AutoValue_AutoValueTest_BuildMyMap.Builder<K, V>(); } @AutoValue.Builder abstract static
BuildMyMap
java
google__guava
android/guava-tests/test/com/google/common/collect/FauxveridesTest.java
{ "start": 1724, "end": 5867 }
class ____ extends TestCase { public void testImmutableBiMap() { doHasAllFauxveridesTest(ImmutableBiMap.class, ImmutableMap.class); } public void testImmutableListMultimap() { doHasAllFauxveridesTest(ImmutableListMultimap.class, ImmutableMultimap.class); } public void testImmutableSetMultimap() { doHasAllFauxveridesTest(ImmutableSetMultimap.class, ImmutableMultimap.class); } public void testImmutableSortedMap() { doHasAllFauxveridesTest(ImmutableSortedMap.class, ImmutableMap.class); } public void testImmutableSortedSet() { doHasAllFauxveridesTest(ImmutableSortedSet.class, ImmutableSet.class); } public void testImmutableSortedMultiset() { doHasAllFauxveridesTest(ImmutableSortedMultiset.class, ImmutableMultiset.class); } /* * Demonstrate that ClassCastException is possible when calling * ImmutableSorted{Set,Map}.copyOf(), whose type parameters we are unable to * restrict (see ImmutableSortedSetFauxverideShim). */ public void testImmutableSortedMapCopyOfMap() { Map<Object, Object> original = ImmutableMap.of(new Object(), new Object(), new Object(), new Object()); assertThrows(ClassCastException.class, () -> ImmutableSortedMap.copyOf(original)); } public void testImmutableSortedSetCopyOfIterable() { // false positive: `new Object()` is not equal to `new Object()` @SuppressWarnings("DistinctVarargsChecker") Set<Object> original = ImmutableSet.of(new Object(), new Object()); assertThrows(ClassCastException.class, () -> ImmutableSortedSet.copyOf(original)); } public void testImmutableSortedSetCopyOfIterator() { // false positive: `new Object()` is not equal to `new Object()` @SuppressWarnings("DistinctVarargsChecker") Set<Object> original = ImmutableSet.of(new Object(), new Object()); assertThrows(ClassCastException.class, () -> ImmutableSortedSet.copyOf(original.iterator())); } private void doHasAllFauxveridesTest(Class<?> descendant, Class<?> ancestor) { Set<MethodSignature> required = getAllRequiredToFauxveride(ancestor); Set<MethodSignature> found = getAllFauxveridden(descendant, ancestor); Set<MethodSignature> missing = ImmutableSortedSet.copyOf(difference(required, found)); if (!missing.isEmpty()) { fail( rootLocaleFormat( "%s should hide the public static methods declared in %s: %s", descendant.getSimpleName(), ancestor.getSimpleName(), missing)); } } private static Set<MethodSignature> getAllRequiredToFauxveride(Class<?> ancestor) { return getPublicStaticMethodsBetween(ancestor, Object.class); } private static Set<MethodSignature> getAllFauxveridden(Class<?> descendant, Class<?> ancestor) { return getPublicStaticMethodsBetween(descendant, ancestor); } private static Set<MethodSignature> getPublicStaticMethodsBetween( Class<?> descendant, Class<?> ancestor) { Set<MethodSignature> methods = new HashSet<>(); for (Class<?> clazz : getClassesBetween(descendant, ancestor)) { methods.addAll(getPublicStaticMethods(clazz)); } return methods; } private static Set<MethodSignature> getPublicStaticMethods(Class<?> clazz) { Set<MethodSignature> publicStaticMethods = new HashSet<>(); for (Method method : clazz.getDeclaredMethods()) { int modifiers = method.getModifiers(); if (isPublic(modifiers) && isStatic(modifiers)) { publicStaticMethods.add(new MethodSignature(method)); } } return publicStaticMethods; } /** [descendant, ancestor) */ private static Set<Class<?>> getClassesBetween(Class<?> descendant, Class<?> ancestor) { Set<Class<?>> classes = new HashSet<>(); while (!descendant.equals(ancestor)) { classes.add(descendant); descendant = descendant.getSuperclass(); } return classes; } /** * Not really a signature -- just the parts that affect whether one method is a fauxveride of a * method from an ancestor class. * * <p>See JLS 8.4.2 for the definition of the related "override-equivalent." */ private static final
FauxveridesTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskManagerRunnerTest.java
{ "start": 2558, "end": 12670 }
class ____ { @TempDir private Path temporaryFolder; private TaskManagerRunner taskManagerRunner; @AfterEach void after() throws Exception { if (taskManagerRunner != null) { taskManagerRunner.close(); } } @Test void testShouldShutdownOnFatalError() throws Exception { Configuration configuration = createConfiguration(); // very high timeout, to ensure that we don't fail because of registration timeouts configuration.set(TaskManagerOptions.REGISTRATION_TIMEOUT, TimeUtils.parseDuration("42 h")); taskManagerRunner = createTaskManagerRunner(configuration); taskManagerRunner.onFatalError(new RuntimeException()); assertThatFuture(taskManagerRunner.getTerminationFuture()) .eventuallySucceeds() .isEqualTo(TaskManagerRunner.Result.FAILURE); } @Test void testShouldShutdownIfRegistrationWithJobManagerFails() throws Exception { Configuration configuration = createConfiguration(); configuration.set( TaskManagerOptions.REGISTRATION_TIMEOUT, TimeUtils.parseDuration("10 ms")); taskManagerRunner = createTaskManagerRunner(configuration); assertThatFuture(taskManagerRunner.getTerminationFuture()) .eventuallySucceeds() .isEqualTo(TaskManagerRunner.Result.FAILURE); } @Test void testGenerateTaskManagerResourceIDWithMetaData() throws Exception { final Configuration configuration = createConfiguration(); final String metadata = "test"; configuration.set(TaskManagerOptionsInternal.TASK_MANAGER_RESOURCE_ID_METADATA, metadata); final ResourceID taskManagerResourceID = TaskManagerRunner.getTaskManagerResourceID(configuration, "", -1).unwrap(); assertThat(taskManagerResourceID.getMetadata()).isEqualTo(metadata); } @Test void testGenerateTaskManagerResourceIDWithoutMetaData() throws Exception { final Configuration configuration = createConfiguration(); final String resourceID = "test"; configuration.set(TaskManagerOptions.TASK_MANAGER_RESOURCE_ID, resourceID); final ResourceID taskManagerResourceID = TaskManagerRunner.getTaskManagerResourceID(configuration, "", -1).unwrap(); assertThat(taskManagerResourceID.getMetadata()).isEmpty(); assertThat(taskManagerResourceID.getStringWithMetadata()).isEqualTo("test"); } @Test void testGenerateTaskManagerResourceIDWithConfig() throws Exception { final Configuration configuration = createConfiguration(); final String resourceID = "test"; configuration.set(TaskManagerOptions.TASK_MANAGER_RESOURCE_ID, resourceID); final ResourceID taskManagerResourceID = TaskManagerRunner.getTaskManagerResourceID(configuration, "", -1).unwrap(); assertThat(taskManagerResourceID.getResourceIdString()).isEqualTo(resourceID); } @Test void testGenerateTaskManagerResourceIDWithRemoteRpcService() throws Exception { final Configuration configuration = createConfiguration(); final String rpcAddress = "flink"; final int rpcPort = 9090; final ResourceID taskManagerResourceID = TaskManagerRunner.getTaskManagerResourceID(configuration, rpcAddress, rpcPort) .unwrap(); assertThat(taskManagerResourceID).isNotNull(); assertThat(taskManagerResourceID.getResourceIdString()) .contains(rpcAddress + ":" + rpcPort); } @Test void testGenerateTaskManagerResourceIDWithLocalRpcService() throws Exception { final Configuration configuration = createConfiguration(); final String rpcAddress = ""; final int rpcPort = -1; final ResourceID taskManagerResourceID = TaskManagerRunner.getTaskManagerResourceID(configuration, rpcAddress, rpcPort) .unwrap(); assertThat(taskManagerResourceID).isNotNull(); assertThat(taskManagerResourceID.getResourceIdString()) .contains(InetAddress.getLocalHost().getHostName()); } @Test void testUnexpectedTaskManagerTerminationFailsRunnerFatally() throws Exception { final CompletableFuture<Void> terminationFuture = new CompletableFuture<>(); final TestingTaskExecutorService taskExecutorService = TestingTaskExecutorService.newBuilder() .setTerminationFuture(terminationFuture) .build(); final TaskManagerRunner taskManagerRunner = createTaskManagerRunner( createConfiguration(), createTaskExecutorServiceFactory(taskExecutorService)); terminationFuture.complete(null); assertThatFuture(taskManagerRunner.getTerminationFuture()) .eventuallySucceeds() .isEqualTo(TaskManagerRunner.Result.FAILURE); } @Test void testUnexpectedTaskManagerTerminationAfterRunnerCloseWillBeIgnored() throws Exception { final CompletableFuture<Void> terminationFuture = new CompletableFuture<>(); final TestingTaskExecutorService taskExecutorService = TestingTaskExecutorService.newBuilder() .setTerminationFuture(terminationFuture) .withManualTerminationFutureCompletion() .build(); final TaskManagerRunner taskManagerRunner = createTaskManagerRunner( createConfiguration(), createTaskExecutorServiceFactory(taskExecutorService)); taskManagerRunner.closeAsync(); terminationFuture.complete(null); assertThatFuture(taskManagerRunner.getTerminationFuture()) .eventuallySucceeds() .isEqualTo(TaskManagerRunner.Result.SUCCESS); } @Test void testWorkingDirIsSetupWhenStartingTaskManagerRunner() throws Exception { final File workingDirBase = TempDirUtils.newFolder(temporaryFolder); final ResourceID taskManagerResourceId = new ResourceID("foobar"); final Configuration configuration = createConfigurationWithWorkingDirectory(workingDirBase, taskManagerResourceId); final File workingDir = ClusterEntrypointUtils.generateTaskManagerWorkingDirectoryFile( configuration, taskManagerResourceId); final TaskManagerRunner taskManagerRunner = createTaskManagerRunner(configuration); try { assertThat(workingDir).exists(); } finally { taskManagerRunner.close(); } assertThat(workingDir) .withFailMessage( "The working dir should be cleaned up when stopping the TaskManager process gracefully.") .doesNotExist(); } @Nonnull private Configuration createConfigurationWithWorkingDirectory( File workingDirBase, ResourceID taskManagerResourceId) { final Configuration configuration = createConfiguration(); configuration.set( ClusterOptions.PROCESS_WORKING_DIR_BASE, workingDirBase.getAbsolutePath()); configuration.set( TaskManagerOptions.TASK_MANAGER_RESOURCE_ID, taskManagerResourceId.toString()); return configuration; } @Test void testWorkingDirIsNotDeletedInCaseOfFailure() throws Exception { final File workingDirBase = TempDirUtils.newFolder(temporaryFolder); final ResourceID resourceId = ResourceID.generate(); final Configuration configuration = createConfigurationWithWorkingDirectory(workingDirBase, resourceId); final TaskManagerRunner taskManagerRunner = createTaskManagerRunner( configuration, new TestingFailingTaskExecutorServiceFactory()); taskManagerRunner.getTerminationFuture().join(); assertThat( ClusterEntrypointUtils.generateTaskManagerWorkingDirectoryFile( configuration, resourceId)) .exists(); } @Nonnull private TaskManagerRunner.TaskExecutorServiceFactory createTaskExecutorServiceFactory( TestingTaskExecutorService taskExecutorService) { return (configuration, resourceID, rpcService, highAvailabilityServices, heartbeatServices, metricRegistry, blobCacheService, localCommunicationOnly, externalResourceInfoProvider, workingDirectory, fatalErrorHandler, delegationTokenReceiverRepository) -> taskExecutorService; } private static Configuration createConfiguration() { final Configuration configuration = new Configuration(); configuration.set(JobManagerOptions.ADDRESS, "localhost"); configuration.set(TaskManagerOptions.HOST, "localhost"); return TaskExecutorResourceUtils.adjustForLocalExecution(configuration); } private static TaskManagerRunner createTaskManagerRunner(final Configuration configuration) throws Exception { return createTaskManagerRunner(configuration, TaskManagerRunner::createTaskExecutorService); } private static TaskManagerRunner createTaskManagerRunner( final Configuration configuration, TaskManagerRunner.TaskExecutorServiceFactory taskExecutorServiceFactory) throws Exception { final PluginManager pluginManager = PluginUtils.createPluginManagerFromRootFolder(configuration); TaskManagerRunner taskManagerRunner = new TaskManagerRunner(configuration, pluginManager, taskExecutorServiceFactory); taskManagerRunner.start(); return taskManagerRunner; } private static
TaskManagerRunnerTest
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/instrument/classloading/WeavingTransformer.java
{ "start": 1928, "end": 2179 }
class ____ transformer to register */ public void addTransformer(ClassFileTransformer transformer) { Assert.notNull(transformer, "Transformer must not be null"); this.transformers.add(transformer); } /** * Apply transformation on a given
file
java
apache__kafka
metadata/src/test/java/org/apache/kafka/metadata/KafkaConfigSchemaTest.java
{ "start": 1751, "end": 10273 }
class ____ { public static final Map<ConfigResource.Type, ConfigDef> CONFIGS = new HashMap<>(); static { CONFIGS.put(BROKER, new ConfigDef(). define("foo.bar", ConfigDef.Type.LIST, "1", ConfigDef.Importance.HIGH, "foo bar doc"). define("baz", ConfigDef.Type.STRING, ConfigDef.Importance.HIGH, "baz doc"). define("quux", ConfigDef.Type.INT, ConfigDef.Importance.HIGH, "quux doc"). define("quuux", ConfigDef.Type.PASSWORD, ConfigDef.Importance.HIGH, "quuux doc"). define("quuux2", ConfigDef.Type.PASSWORD, ConfigDef.Importance.HIGH, "quuux2 doc")); CONFIGS.put(TOPIC, new ConfigDef(). define("abc", ConfigDef.Type.LIST, ConfigDef.Importance.HIGH, "abc doc"). define("def", ConfigDef.Type.LONG, ConfigDef.Importance.HIGH, "def doc"). define("ghi", ConfigDef.Type.BOOLEAN, true, ConfigDef.Importance.HIGH, "ghi doc"). define("xyz", ConfigDef.Type.PASSWORD, "thedefault", ConfigDef.Importance.HIGH, "xyz doc"). defineInternal("internal", ConfigDef.Type.STRING, "internalValue", null, ConfigDef.Importance.HIGH, "internal doc")); } public static final Map<String, List<ConfigSynonym>> SYNONYMS = new HashMap<>(); static { SYNONYMS.put("abc", List.of(new ConfigSynonym("foo.bar"))); SYNONYMS.put("def", List.of(new ConfigSynonym("quux", HOURS_TO_MILLISECONDS))); SYNONYMS.put("ghi", List.of(new ConfigSynonym("ghi"))); SYNONYMS.put("xyz", List.of(new ConfigSynonym("quuux"), new ConfigSynonym("quuux2"))); } private static final KafkaConfigSchema SCHEMA = new KafkaConfigSchema(CONFIGS, SYNONYMS); @Test public void testTranslateConfigTypes() { testTranslateConfigType(ConfigDef.Type.BOOLEAN, ConfigEntry.ConfigType.BOOLEAN); testTranslateConfigType(ConfigDef.Type.STRING, ConfigEntry.ConfigType.STRING); testTranslateConfigType(ConfigDef.Type.INT, ConfigEntry.ConfigType.INT); testTranslateConfigType(ConfigDef.Type.SHORT, ConfigEntry.ConfigType.SHORT); testTranslateConfigType(ConfigDef.Type.LONG, ConfigEntry.ConfigType.LONG); testTranslateConfigType(ConfigDef.Type.DOUBLE, ConfigEntry.ConfigType.DOUBLE); testTranslateConfigType(ConfigDef.Type.LIST, ConfigEntry.ConfigType.LIST); testTranslateConfigType(ConfigDef.Type.CLASS, ConfigEntry.ConfigType.CLASS); testTranslateConfigType(ConfigDef.Type.PASSWORD, ConfigEntry.ConfigType.PASSWORD); } private static void testTranslateConfigType(ConfigDef.Type a, ConfigEntry.ConfigType b) { assertEquals(b, KafkaConfigSchema.translateConfigType(a)); } @Test public void testTranslateConfigSources() { testTranslateConfigSource(ConfigEntry.ConfigSource.DYNAMIC_TOPIC_CONFIG, DescribeConfigsResponse.ConfigSource.TOPIC_CONFIG); testTranslateConfigSource(ConfigEntry.ConfigSource.DYNAMIC_BROKER_LOGGER_CONFIG, DescribeConfigsResponse.ConfigSource.DYNAMIC_BROKER_LOGGER_CONFIG); testTranslateConfigSource(ConfigEntry.ConfigSource.DYNAMIC_BROKER_CONFIG, DescribeConfigsResponse.ConfigSource.DYNAMIC_BROKER_CONFIG); testTranslateConfigSource(ConfigEntry.ConfigSource.DYNAMIC_DEFAULT_BROKER_CONFIG, DescribeConfigsResponse.ConfigSource.DYNAMIC_DEFAULT_BROKER_CONFIG); testTranslateConfigSource(ConfigEntry.ConfigSource.STATIC_BROKER_CONFIG, DescribeConfigsResponse.ConfigSource.STATIC_BROKER_CONFIG); testTranslateConfigSource(ConfigEntry.ConfigSource.DYNAMIC_CLIENT_METRICS_CONFIG, DescribeConfigsResponse.ConfigSource.CLIENT_METRICS_CONFIG); testTranslateConfigSource(ConfigEntry.ConfigSource.DYNAMIC_GROUP_CONFIG, DescribeConfigsResponse.ConfigSource.GROUP_CONFIG); testTranslateConfigSource(ConfigEntry.ConfigSource.DEFAULT_CONFIG, DescribeConfigsResponse.ConfigSource.DEFAULT_CONFIG); } private static void testTranslateConfigSource(ConfigEntry.ConfigSource a, DescribeConfigsResponse.ConfigSource b) { assertEquals(b, KafkaConfigSchema.translateConfigSource(a)); } @Test public void testIsSplittable() { assertTrue(SCHEMA.isSplittable(BROKER, "foo.bar")); assertFalse(SCHEMA.isSplittable(BROKER, "baz")); assertFalse(SCHEMA.isSplittable(BROKER, "foo.baz.quux")); assertFalse(SCHEMA.isSplittable(TOPIC, "baz")); assertTrue(SCHEMA.isSplittable(TOPIC, "abc")); } @Test public void testGetConfigValueDefault() { assertEquals("1", SCHEMA.getDefault(BROKER, "foo.bar")); assertNull(SCHEMA.getDefault(BROKER, "foo.baz.quux")); assertNull(SCHEMA.getDefault(TOPIC, "abc")); assertEquals("true", SCHEMA.getDefault(TOPIC, "ghi")); } @Test public void testIsSensitive() { assertFalse(SCHEMA.isSensitive(BROKER, "foo.bar")); assertTrue(SCHEMA.isSensitive(BROKER, "quuux")); assertTrue(SCHEMA.isSensitive(BROKER, "quuux2")); assertTrue(SCHEMA.isSensitive(BROKER, "unknown.config.key")); assertFalse(SCHEMA.isSensitive(TOPIC, "abc")); } @Test public void testResolveEffectiveTopicConfig() { Map<String, String> staticNodeConfig = new HashMap<>(); staticNodeConfig.put("foo.bar", "the,static,value"); staticNodeConfig.put("quux", "123"); staticNodeConfig.put("ghi", "false"); Map<String, String> dynamicClusterConfigs = new HashMap<>(); dynamicClusterConfigs.put("foo.bar", "the,dynamic,cluster,config,value"); dynamicClusterConfigs.put("quux", "456"); Map<String, String> dynamicNodeConfigs = new HashMap<>(); dynamicNodeConfigs.put("quux", "789"); Map<String, String> dynamicTopicConfigs = new HashMap<>(); dynamicTopicConfigs.put("ghi", "true"); Map<String, ConfigEntry> expected = new HashMap<>(); expected.put("abc", new ConfigEntry("abc", "the,dynamic,cluster,config,value", ConfigEntry.ConfigSource.DYNAMIC_DEFAULT_BROKER_CONFIG, false, false, List.of(), ConfigEntry.ConfigType.LIST, "abc doc")); expected.put("def", new ConfigEntry("def", "2840400000", ConfigEntry.ConfigSource.DYNAMIC_BROKER_CONFIG, false, false, List.of(), ConfigEntry.ConfigType.LONG, "def doc")); expected.put("ghi", new ConfigEntry("ghi", "true", ConfigEntry.ConfigSource.DYNAMIC_TOPIC_CONFIG, false, false, List.of(), ConfigEntry.ConfigType.BOOLEAN, "ghi doc")); expected.put("xyz", new ConfigEntry("xyz", "thedefault", ConfigEntry.ConfigSource.DEFAULT_CONFIG, true, false, List.of(), ConfigEntry.ConfigType.PASSWORD, "xyz doc")); assertEquals(expected, SCHEMA.resolveEffectiveTopicConfigs(staticNodeConfig, dynamicClusterConfigs, dynamicNodeConfigs, dynamicTopicConfigs)); } @Test public void testResolveEffectiveDynamicInternalTopicConfig() { Map<String, String> dynamicTopicConfigs = Map.of( "ghi", "true", "internal", "internal,change" ); Map<String, ConfigEntry> expected = Map.of( "abc", new ConfigEntry("abc", null, ConfigEntry.ConfigSource.DEFAULT_CONFIG, false, false, List.of(), ConfigEntry.ConfigType.LIST, "abc doc"), "def", new ConfigEntry("def", null, ConfigEntry.ConfigSource.DEFAULT_CONFIG, false, false, List.of(), ConfigEntry.ConfigType.LONG, "def doc"), "ghi", new ConfigEntry("ghi", "true", ConfigEntry.ConfigSource.DYNAMIC_TOPIC_CONFIG, false, false, List.of(), ConfigEntry.ConfigType.BOOLEAN, "ghi doc"), "xyz", new ConfigEntry("xyz", "thedefault", ConfigEntry.ConfigSource.DEFAULT_CONFIG, true, false, List.of(), ConfigEntry.ConfigType.PASSWORD, "xyz doc"), "internal", new ConfigEntry("internal", "internal,change", ConfigEntry.ConfigSource.DYNAMIC_TOPIC_CONFIG, false, false, List.of(), ConfigEntry.ConfigType.STRING, "internal doc") ); assertEquals(expected, SCHEMA.resolveEffectiveTopicConfigs(Map.of(), Map.of(), Map.of(), dynamicTopicConfigs)); } }
KafkaConfigSchemaTest
java
quarkusio__quarkus
independent-projects/qute/core/src/main/java/io/quarkus/qute/ValueResolvers.java
{ "start": 5127, "end": 6181 }
class ____ extends AbstractValueResolver { public OrResolver() { super(Set.of(ELVIS, OR, COLON), Collections.emptySet()); } public boolean appliesTo(EvalContext context) { if (context.getParams().size() != 1) { return false; } String name = context.getName(); return name.equals(ELVIS) || name.equals(OR) || name.equals(COLON); } @Override public CompletionStage<Object> resolve(EvalContext context) { Object base = context.getBase(); if (base == null || Results.isNotFound(base) || (base instanceof Optional && ((Optional<?>) base).isEmpty())) { return asLiteralOrEvaluate(context, 0); } return CompletedStage.of(base); } } /** * Return an empty list if the base object is null or not found. */ public static ValueResolver orEmpty() { return new OrEmptyResolver(); } public static final
OrResolver
java
quarkusio__quarkus
extensions/qute/runtime/src/main/java/io/quarkus/qute/runtime/extensions/CollectionTemplateExtensions.java
{ "start": 394, "end": 2258 }
class ____ { static <T> T get(List<T> list, int index) { return list.get(index); } @TemplateExtension(matchRegex = "\\d{1,10}") static <T> T getByIndex(List<T> list, String index) { return list.get(Integer.parseInt(index)); } static <T> Iterator<T> reversed(List<T> list) { ListIterator<T> it = list.listIterator(list.size()); return new Iterator<T>() { @Override public boolean hasNext() { return it.hasPrevious(); } @Override public T next() { return it.previous(); } }; } static <T> List<T> take(List<T> list, int n) { if (n < 1 || n > list.size()) { throw new IndexOutOfBoundsException(n); } if (list.isEmpty()) { return list; } return list.subList(0, n); } static <T> List<T> takeLast(List<T> list, int n) { if (n < 1 || n > list.size()) { throw new IndexOutOfBoundsException(n); } if (list.isEmpty()) { return list; } return list.subList(list.size() - n, list.size()); } // This extension method has higher priority than ValueResolvers.orEmpty() // and makes it possible to validate expressions derived from {list.orEmpty} static <T> Collection<T> orEmpty(Collection<T> iterable) { return iterable != null ? iterable : Collections.emptyList(); } static <T> T first(List<T> list) { if (list.isEmpty()) { throw new NoSuchElementException(); } return list.get(0); } static <T> T last(List<T> list) { if (list.isEmpty()) { throw new NoSuchElementException(); } return list.get(list.size() - 1); } }
CollectionTemplateExtensions
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticEntityLockException.java
{ "start": 358, "end": 767 }
class ____ extends LockingStrategyException { /** * Constructs a PessimisticEntityLockException * * @param entity The entity we were trying to lock * @param message Message explaining the condition * @param cause The underlying cause */ public PessimisticEntityLockException(Object entity, String message, JDBCException cause) { super( entity, message, cause ); } }
PessimisticEntityLockException
java
apache__maven
compat/maven-compat/src/test/java/org/apache/maven/repository/legacy/resolver/conflict/AbstractConflictResolverTest.java
{ "start": 1590, "end": 4441 }
class ____ { // constants -------------------------------------------------------------- private static final String GROUP_ID = "test"; // fields ----------------------------------------------------------------- protected Artifact a1; protected Artifact a2; protected Artifact b1; private final String roleHint; @Inject private ArtifactFactory artifactFactory; private ConflictResolver conflictResolver; @Inject protected PlexusContainer container; // constructors ----------------------------------------------------------- public AbstractConflictResolverTest(String roleHint) throws Exception { this.roleHint = roleHint; } // TestCase methods ------------------------------------------------------- /* * @see junit.framework.TestCase#setUp() */ @BeforeEach public void setUp() throws Exception { conflictResolver = (ConflictResolver) container.lookup(ConflictResolver.ROLE, roleHint); a1 = createArtifact("a", "1.0"); a2 = createArtifact("a", "2.0"); b1 = createArtifact("b", "1.0"); } // protected methods ------------------------------------------------------ protected ConflictResolver getConflictResolver() { return conflictResolver; } protected void assertResolveConflict( ResolutionNode expectedNode, ResolutionNode actualNode1, ResolutionNode actualNode2) { ResolutionNode resolvedNode = getConflictResolver().resolveConflict(actualNode1, actualNode2); assertNotNull(resolvedNode, "Expected resolvable"); assertEquals(expectedNode, resolvedNode, "Resolution node"); } protected Artifact createArtifact(String id, String version) throws InvalidVersionSpecificationException { return createArtifact(id, version, Artifact.SCOPE_COMPILE); } protected Artifact createArtifact(String id, String version, String scope) throws InvalidVersionSpecificationException { return createArtifact(id, version, scope, null, false); } protected Artifact createArtifact(String id, String version, String scope, String inheritedScope, boolean optional) throws InvalidVersionSpecificationException { VersionRange versionRange = VersionRange.createFromVersionSpec(version); return artifactFactory.createDependencyArtifact( GROUP_ID, id, versionRange, "jar", null, scope, inheritedScope, optional); } protected ResolutionNode createResolutionNode(Artifact artifact) { return new ResolutionNode(artifact, Collections.emptyList()); } protected ResolutionNode createResolutionNode(Artifact artifact, ResolutionNode parent) { return new ResolutionNode(artifact, Collections.emptyList(), parent); } }
AbstractConflictResolverTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/AllocationDecider.java
{ "start": 1132, "end": 7141 }
class ____ { /** * Returns a {@link Decision} whether the given shard routing can be * re-balanced to the given allocation. The default is * {@link Decision#ALWAYS}. */ public Decision canRebalance(ShardRouting shardRouting, RoutingAllocation allocation) { return Decision.ALWAYS; } /** * Returns a {@link Decision} whether the given shard routing can be * allocated on the given node. The default is {@link Decision#ALWAYS}. */ public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { return Decision.ALWAYS; } /** * Returns a {@link Decision} whether the given shard routing can be remain * on the given node. The default is {@link Decision#ALWAYS}. */ public Decision canRemain(IndexMetadata indexMetadata, ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { return Decision.ALWAYS; } /** * Returns a {@link Decision} whether the given shard routing can be allocated at all at this state of the * {@link RoutingAllocation}. The default is {@link Decision#ALWAYS}. */ public Decision canAllocate(ShardRouting shardRouting, RoutingAllocation allocation) { return Decision.ALWAYS; } /** * Returns a {@link Decision} whether the given shard routing can be allocated at all at this state of the * {@link RoutingAllocation}. The default is {@link Decision#ALWAYS}. */ public Decision canAllocate(IndexMetadata indexMetadata, RoutingNode node, RoutingAllocation allocation) { return Decision.ALWAYS; } /** * Returns a {@link Decision} whether shards of the given index should be auto-expanded to this node at this state of the * {@link RoutingAllocation}. The default is {@link Decision#ALWAYS}. */ public Decision shouldAutoExpandToNode(IndexMetadata indexMetadata, DiscoveryNode node, RoutingAllocation allocation) { return Decision.ALWAYS; } /** * Returns a {@link Decision} on whether the cluster is allowed to rebalance shards to improve relative node shard weights and * performance. * @return {@link Decision#ALWAYS} is returned by default if not overridden. */ public Decision canRebalance(RoutingAllocation allocation) { return Decision.ALWAYS; } /** * Returns a {@link Decision} whether the given primary shard can be * forcibly allocated on the given node. This method should only be called * for unassigned primary shards where the node has a shard copy on disk. * * Note: all implementations that override this behavior should take into account * the results of {@link #canAllocate(ShardRouting, RoutingNode, RoutingAllocation)} * before making a decision on force allocation, because force allocation should only * be considered if all deciders return {@link Decision#NO}. */ public Decision canForceAllocatePrimary(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { assert shardRouting.primary() : "must not call canForceAllocatePrimary on a non-primary shard " + shardRouting; assert shardRouting.unassigned() : "must not call canForceAllocatePrimary on an assigned shard " + shardRouting; Decision decision = canAllocate(shardRouting, node, allocation); if (decision.type() == Type.NO) { // On a NO decision, by default, we allow force allocating the primary. return allocation.decision( Decision.YES, decision.label(), "primary shard [%s] allowed to force allocate on node [%s]", shardRouting.shardId(), node.nodeId() ); } else { // On a THROTTLE/YES decision, we use the same decision instead of forcing allocation return decision; } } /** * Returns a {@link Decision} whether the given shard can be forced to the * given node in the event that the shard's source node is being replaced. * This allows nodes using a replace-type node shutdown to * override certain deciders in the interest of moving the shard away from * a node that *must* be removed. * * It defaults to returning "YES" and must be overridden by deciders that * opt-out to having their other NO decisions *not* overridden while vacating. * * The caller is responsible for first checking: * - that a replacement is ongoing * - the shard routing's current node is the source of the replacement */ public Decision canForceAllocateDuringReplace(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { return Decision.YES; } /** * Returns a {@link Decision} whether the given replica shard can be * allocated to the given node when there is an existing retention lease * already existing on the node (meaning it has been allocated there previously) * * This method does not actually check whether there is a retention lease, * that is the responsibility of the caller. * * It defaults to the same value as {@code canAllocate}. */ public Decision canAllocateReplicaWhenThereIsRetentionLease(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) { return canAllocate(shardRouting, node, allocation); } /** * Returns a {@code empty()} if shard could be initially allocated anywhere or {@code Optional.of(Set.of(nodeIds))} if shard could be * initially allocated only on subset of a nodes. * * This might be required for splitting or shrinking index as resulting shards have to be on the same node as a source shard. */ public Optional<Set<String>> getForcedInitialShardAllocationToNodes(ShardRouting shardRouting, RoutingAllocation allocation) { return Optional.empty(); } }
AllocationDecider
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/client/reactive/JdkClientHttpConnector.java
{ "start": 1745, "end": 4994 }
class ____ implements ClientHttpConnector { private final HttpClient httpClient; private DataBufferFactory bufferFactory = DefaultDataBufferFactory.sharedInstance; private @Nullable Duration readTimeout; private ResponseCookie.Parser cookieParser = new JdkResponseCookieParser(); /** * Default constructor that uses {@link HttpClient#newHttpClient()}. */ public JdkClientHttpConnector() { this(HttpClient.newHttpClient()); } /** * Constructor with an initialized {@link HttpClient} and a {@link DataBufferFactory}. */ public JdkClientHttpConnector(HttpClient httpClient) { this.httpClient = httpClient; } /** * Constructor with a {@link JdkHttpClientResourceFactory} that provides * shared resources. * @param clientBuilder a pre-initialized builder for the client that will * be further initialized with the shared resources to use * @param resourceFactory the {@link JdkHttpClientResourceFactory} to use */ public JdkClientHttpConnector( HttpClient.Builder clientBuilder, @Nullable JdkHttpClientResourceFactory resourceFactory) { if (resourceFactory != null) { Executor executor = resourceFactory.getExecutor(); clientBuilder.executor(executor); } this.httpClient = clientBuilder.build(); } /** * Set the buffer factory to use. * <p>By default, this is {@link DefaultDataBufferFactory#sharedInstance}. */ public void setBufferFactory(DataBufferFactory bufferFactory) { Assert.notNull(bufferFactory, "DataBufferFactory is required"); this.bufferFactory = bufferFactory; } /** * Set the underlying {@code HttpClient} read timeout as a {@code Duration}. * <p>Default is the system's default timeout. * @since 6.2 * @see java.net.http.HttpRequest.Builder#timeout */ public void setReadTimeout(Duration readTimeout) { Assert.notNull(readTimeout, "readTimeout is required"); this.readTimeout = readTimeout; } /** * Customize the parsing of response cookies. * <p>By default, {@link java.net.HttpCookie#parse(String)} is used, and * additionally the sameSite attribute is parsed and set. * @param parser the parser to use * @since 7.0 */ public void setCookieParser(ResponseCookie.Parser parser) { Assert.notNull(parser, "ResponseCookie parser is required"); this.cookieParser = parser; } @Override public Mono<ClientHttpResponse> connect( HttpMethod method, URI uri, Function<? super ClientHttpRequest, Mono<Void>> requestCallback) { JdkClientHttpRequest request = new JdkClientHttpRequest(method, uri, this.bufferFactory, this.readTimeout); return requestCallback.apply(request).then(Mono.defer(() -> { HttpRequest nativeRequest = request.getNativeRequest(); CompletableFuture<HttpResponse<Flow.Publisher<List<ByteBuffer>>>> future = this.httpClient.sendAsync(nativeRequest, HttpResponse.BodyHandlers.ofPublisher()); return Mono.fromCompletionStage(future).map(response -> new JdkClientHttpResponse(response, this.bufferFactory, parseCookies(response))); })); } private MultiValueMap<String, ResponseCookie> parseCookies(HttpResponse<?> response) { List<String> headers = response.headers().allValues(HttpHeaders.SET_COOKIE); return this.cookieParser.parse(headers); } }
JdkClientHttpConnector
java
qos-ch__slf4j
slf4j-api/src/main/java/org/slf4j/spi/MDCAdapter.java
{ "start": 1424, "end": 4431 }
interface ____ { /** * Put a context value (the <code>val</code> parameter) as identified with * the <code>key</code> parameter into the current thread's context map. * The <code>key</code> parameter cannot be null. The <code>val</code> parameter * can be null only if the underlying implementation supports it. * * <p>If the current thread does not have a context map it is created as a side * effect of this call. */ public void put(String key, String val); /** * Get the context identified by the <code>key</code> parameter. * The <code>key</code> parameter cannot be null. * * @return the string value identified by the <code>key</code> parameter. */ public String get(String key); /** * Remove the context identified by the <code>key</code> parameter. * The <code>key</code> parameter cannot be null. * * <p> * This method does nothing if there is no previous value * associated with <code>key</code>. */ public void remove(String key); /** * Clear all entries in the MDC. */ public void clear(); /** * Return a copy of the current thread's context map, with keys and * values of type String. Returned value may be null. * * @return A copy of the current thread's context map. May be null. * @since 1.5.1 */ public Map<String, String> getCopyOfContextMap(); /** * Set the current thread's context map by first clearing any existing * map and then copying the map passed as parameter. The context map * parameter must only contain keys and values of type String. * * Implementations must support null valued map passed as parameter. * * @param contextMap must contain only keys and values of type String * * @since 1.5.1 */ public void setContextMap(Map<String, String> contextMap); /** * Push a value into the <b>deque(stack)</b> referenced by 'key'. * * @param key identifies the appropriate stack * @param value the value to push into the stack * @since 2.0.0 */ public void pushByKey(String key, String value); /** * Pop the <b>stack</b> referenced by 'key' and return the value possibly null. * * @param key identifies the deque(stack) * @return the value just popped. May be null/ * @since 2.0.0 */ public String popByKey(String key); /** * Returns a copy of the <b>deque(stack)</b> referenced by 'key'. May be null. * * @param key identifies the stack * @return copy of stack referenced by 'key'. May be null. * * @since 2.0.0 */ public Deque<String> getCopyOfDequeByKey(String key); /** * Clear the <b>deque(stack)</b> referenced by 'key'. * * @param key identifies the stack * * @since 2.0.0 */ public void clearDequeByKey(String key); }
MDCAdapter
java
spring-projects__spring-security
webauthn/src/main/java/org/springframework/security/web/webauthn/management/RelyingPartyPublicKey.java
{ "start": 1014, "end": 1757 }
class ____ { private final PublicKeyCredential<AuthenticatorAttestationResponse> credential; private final String label; /** * Creates a new instance. * @param credential the credential * @param label a human readable label that will be associated to the credential */ public RelyingPartyPublicKey(PublicKeyCredential<AuthenticatorAttestationResponse> credential, String label) { Assert.notNull(credential, "credential cannot be null"); Assert.notNull(label, "label cannot be null"); this.credential = credential; this.label = label; } public PublicKeyCredential<AuthenticatorAttestationResponse> getCredential() { return this.credential; } public String getLabel() { return this.label; } }
RelyingPartyPublicKey
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/launcher/TestContainerLaunchParameterized.java
{ "start": 1242, "end": 6935 }
class ____ { private static Stream<Arguments> inputForGetEnvDependenciesLinux() { return Stream.of( Arguments.of(null, asSet()), Arguments.of("", asSet()), Arguments.of("A", asSet()), Arguments.of("\\$A", asSet()), Arguments.of("$$", asSet()), Arguments.of("$1", asSet()), Arguments.of("handle \"'$A'\" simple quotes", asSet()), Arguments.of("handle \" escaped \\\" '${A}'\" simple quotes", asSet()), Arguments .of("$ crash test for StringArrayOutOfBoundException", asSet()), Arguments.of("${ crash test for StringArrayOutOfBoundException", asSet()), Arguments.of("${# crash test for StringArrayOutOfBoundException", asSet()), Arguments .of("crash test for StringArrayOutOfBoundException $", asSet()), Arguments.of("crash test for StringArrayOutOfBoundException ${", asSet()), Arguments.of("crash test for StringArrayOutOfBoundException ${#", asSet()), Arguments.of("$A", asSet("A")), Arguments.of("${A}", asSet("A")), Arguments.of("${#A[*]}", asSet("A")), Arguments.of("in the $A midlle", asSet("A")), Arguments.of("${A:-$B} var in var", asSet("A", "B")), Arguments.of("${A}$B var outside var", asSet("A", "B")), Arguments.of("$A:$B:$C:pathlist var", asSet("A", "B", "C")), Arguments .of("${A}/foo/bar:$B:${C}:pathlist var", asSet("A", "B", "C")), // https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html Arguments.of("${parameter:-word}", asSet("parameter")), Arguments.of("${parameter:=word}", asSet("parameter")), Arguments.of("${parameter:?word}", asSet("parameter")), Arguments.of("${parameter:+word}", asSet("parameter")), Arguments.of("${parameter:71}", asSet("parameter")), Arguments.of("${parameter:71:30}", asSet("parameter")), Arguments.of("!{prefix*}", asSet()), Arguments.of("${!prefix@}", asSet()), Arguments.of("${!name[@]}", asSet()), Arguments.of("${!name[*]}", asSet()), Arguments.of("${#parameter}", asSet("parameter")), Arguments.of("${parameter#word}", asSet("parameter")), Arguments.of("${parameter##word}", asSet("parameter")), Arguments.of("${parameter%word}", asSet("parameter")), Arguments.of("${parameter/pattern/string}", asSet("parameter")), Arguments.of("${parameter^pattern}", asSet("parameter")), Arguments.of("${parameter^^pattern}", asSet("parameter")), Arguments.of("${parameter,pattern}", asSet("parameter")), Arguments.of("${parameter,,pattern}", asSet("parameter")), Arguments.of("${parameter@o}", asSet("parameter")), Arguments.of("${parameter:-${another}}", asSet("parameter", "another")), Arguments .of("${FILES:-$(git diff --name-only \"${GIT_REVISION}..HEAD\"" + " | grep \"java$\" | grep -iv \"test\")}", asSet("FILES", "GIT_REVISION")), Arguments.of("handle '${A}' simple quotes", asSet("A")), Arguments.of("handle '${A} $B ${C:-$D}' simple quotes", asSet("A", "B", "C", "D")), Arguments.of("handle \"'${A}'\" double and single quotes", asSet()), Arguments.of("handle \"'\\${A}'\" double and single quotes", asSet()), Arguments.of("handle '\\${A} \\$B \\${C:-D}' single quotes", asSet()), Arguments.of("handle \"${A}\" double quotes", asSet("A")), Arguments.of("handle \"${A} $B ${C:-$D}\" double quotes", asSet("A", "B", "C", "D")) ); } @ParameterizedTest @MethodSource("inputForGetEnvDependenciesLinux") void testGetEnvDependenciesLinux(String input, Set<String> expected) { ContainerLaunch.ShellScriptBuilder bash = ContainerLaunch.ShellScriptBuilder.create(Shell.OSType.OS_TYPE_LINUX); assertEquals(expected, bash.getEnvDependencies(input), "Failed to parse " + input); } private static Stream<Arguments> inputForGetEnvDependenciesWin() { return Stream.of( Arguments.of(null, asSet()), Arguments.of("", asSet()), Arguments.of("A", asSet()), Arguments.of("%%%%%%", asSet()), Arguments.of("%%A%", asSet()), Arguments.of("%A", asSet()), Arguments.of("%A:", asSet()), Arguments.of("%A%", asSet("A")), Arguments.of("%:%", asSet(":")), Arguments.of("%:A%", asSet()), Arguments.of("%%%A%", asSet("A")), Arguments.of("%%C%A%", asSet("A")), Arguments.of("%A:~-1%", asSet("A")), Arguments.of("%A:%", asSet("A")), Arguments.of("%A:whatever:a:b:%", asSet("A")), Arguments.of("%A%B%", asSet("A")), Arguments.of("%A%%%%%B%", asSet("A")), Arguments.of("%A%%B%", asSet("A", "B")), Arguments.of("%A%%%%B%", asSet("A", "B")), Arguments.of("%A%:%B%:%C%:pathlist var", asSet("A", "B", "C")), Arguments.of("%A%\\\\foo\\\\bar:%B%:%C%:pathlist var", asSet("A", "B", "C")) ); } @ParameterizedTest @MethodSource("inputForGetEnvDependenciesWin") void testGetEnvDependenciesWin(String input, Set<String> expected) { ContainerLaunch.ShellScriptBuilder win = ContainerLaunch.ShellScriptBuilder.create(Shell.OSType.OS_TYPE_WIN); assertEquals(expected, win.getEnvDependencies(input), "Failed to parse " + input); } private static Set<String> asSet(String... str) { return Sets.newHashSet(str); } }
TestContainerLaunchParameterized
java
redisson__redisson
redisson/src/main/java/org/redisson/api/queue/QueuePollParams.java
{ "start": 764, "end": 2083 }
class ____ extends BaseSyncParams<QueuePollArgs> implements QueuePollArgs { private AcknowledgeMode acknowledgeMode = AcknowledgeMode.MANUAL; private Duration timeout; private Duration visibility = Duration.ofSeconds(30); private int count = 1; private Codec headersCodec; @Override public QueuePollArgs acknowledgeMode(AcknowledgeMode mode) { this.acknowledgeMode = mode; return this; } @Override public QueuePollArgs headersCodec(Codec codec) { this.headersCodec = codec; return this; } @Override public QueuePollArgs timeout(Duration timeout) { this.timeout = timeout; return this; } @Override public QueuePollArgs visibility(Duration visibility) { this.visibility = visibility; return this; } @Override public QueuePollArgs count(int value) { this.count = value; return this; } public Duration getTimeout() { return timeout; } public Duration getVisibility() { return visibility; } public int getCount() { return count; } public Codec getHeadersCodec() { return headersCodec; } public AcknowledgeMode getAcknowledgeMode() { return acknowledgeMode; } }
QueuePollParams
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/util/CancellableSingleObjectCacheTests.java
{ "start": 21003, "end": 23156 }
class ____ extends CancellableSingleObjectCache<String, String, Integer> { private final LinkedList<ListenableFuture<Function<String, Integer>>> pendingRefreshes = new LinkedList<>(); private TestCache() { super(testThreadContext); } @Override protected void refresh( String input, Runnable ensureNotCancelled, BooleanSupplier supersedeIfStale, ActionListener<Integer> listener ) { final ListenableFuture<Function<String, Integer>> stepListener = new ListenableFuture<>(); pendingRefreshes.offer(stepListener); stepListener.addListener(listener.delegateFailureAndWrap((l, f) -> { if (supersedeIfStale.getAsBoolean()) { return; } ActionListener.completeWith(l, () -> { ensureNotCancelled.run(); return f.apply(input); }); })); } @Override protected String getKey(String s) { return s; } void assertPendingRefreshes(int expected) { assertThat(pendingRefreshes.size(), equalTo(expected)); } void assertNoPendingRefreshes() { assertThat(pendingRefreshes, empty()); } void completeNextRefresh(String key, int value) { nextRefresh().onResponse(k -> { assertThat(k, equalTo(key)); return value; }); } void completeNextRefresh(Exception e) { nextRefresh().onFailure(e); } void assertNextRefreshCancelled() { nextRefresh().onResponse(k -> { throw new AssertionError("should not be called"); }); } private ListenableFuture<Function<String, Integer>> nextRefresh() { assertThat(pendingRefreshes, not(empty())); final ListenableFuture<Function<String, Integer>> nextRefresh = pendingRefreshes.poll(); assertNotNull(nextRefresh); return nextRefresh; } } private static
TestCache
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/multiplerelations/Address.java
{ "start": 643, "end": 2138 }
class ____ implements Serializable { @Id @GeneratedValue private long id; private String city; @ManyToMany(cascade = {CascadeType.PERSIST}) private Set<Person> tenants = new HashSet<Person>(); @ManyToOne @JoinColumn(nullable = false) Person landlord; public Address() { } public Address(String city) { this.city = city; } public Address(String city, long id) { this.id = id; this.city = city; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( !(o instanceof Address) ) { return false; } Address address = (Address) o; if ( id != address.id ) { return false; } if ( city != null ? !city.equals( address.city ) : address.city != null ) { return false; } return true; } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (city != null ? city.hashCode() : 0); return result; } @Override public String toString() { return "Address(id = " + id + ", city = " + city + ")"; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Set<Person> getTenants() { return tenants; } public void setTenants(Set<Person> tenants) { this.tenants = tenants; } public Person getLandlord() { return landlord; } public void setLandlord(Person landlord) { this.landlord = landlord; } }
Address
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/benchmark/failover/RegionToRestartInStreamingJobBenchmarkTest.java
{ "start": 1268, "end": 1648 }
class ____ { @Test void calculateRegionToRestart() throws Exception { RegionToRestartInStreamingJobBenchmark benchmark = new RegionToRestartInStreamingJobBenchmark(); benchmark.setup(JobConfiguration.STREAMING_TEST); benchmark.calculateRegionToRestart(); benchmark.teardown(); } }
RegionToRestartInStreamingJobBenchmarkTest
java
apache__camel
test-infra/camel-test-infra-messaging-common/src/main/java/org/apache/camel/test/infra/messaging/services/MessagingInfraService.java
{ "start": 943, "end": 1258 }
interface ____ extends InfrastructureService { /** * Gets the default endpoint for the messaging service (ie.: amqp://host:port, or tcp://host:port, etc) * * @return the endpoint URL as a string in the specific format used by the service */ String defaultEndpoint(); }
MessagingInfraService
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/jobmaster/slotpool/PhysicalSlotRequestBulkCheckerImplTest.java
{ "start": 2605, "end": 13056 }
class ____ { private static final Duration TIMEOUT = Duration.ofMillis(50L); private static ScheduledExecutorService singleThreadScheduledExecutorService; private static ComponentMainThreadExecutor mainThreadExecutor; private final ManualClock clock = new ManualClock(); private PhysicalSlotRequestBulkCheckerImpl bulkChecker; private Set<PhysicalSlot> slots; private Supplier<Set<SlotInfo>> slotsRetriever; @BeforeAll private static void setupClass() { singleThreadScheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); mainThreadExecutor = ComponentMainThreadExecutorServiceAdapter.forSingleThreadExecutor( singleThreadScheduledExecutorService); } @AfterAll private static void teardownClass() { if (singleThreadScheduledExecutorService != null) { singleThreadScheduledExecutorService.shutdownNow(); } } @BeforeEach private void setup() { slots = new HashSet<>(); slotsRetriever = () -> new HashSet<>(slots); bulkChecker = new PhysicalSlotRequestBulkCheckerImpl(slotsRetriever, clock); bulkChecker.start(mainThreadExecutor); } @Test void testPendingBulkIsNotCancelled() throws InterruptedException, ExecutionException { final CompletableFuture<ExecutionVertexID> cancellationFuture = new CompletableFuture<>(); final PhysicalSlotRequestBulk bulk = createPhysicalSlotRequestBulkWithCancellationFuture( cancellationFuture, new ExecutionVertexID(new JobVertexID(), 0)); bulkChecker.schedulePendingRequestBulkTimeoutCheck(bulk, TIMEOUT); checkNotCancelledAfter(cancellationFuture, 2 * TIMEOUT.toMillis()); } @Test void testFulfilledBulkIsNotCancelled() throws InterruptedException, ExecutionException { final CompletableFuture<ExecutionVertexID> cancellationFuture = new CompletableFuture<>(); final PhysicalSlotRequestBulk bulk = createPhysicalSlotRequestBulkWithCancellationFuture( cancellationFuture, new ExecutionVertexID(new JobVertexID(), 0)); bulkChecker.schedulePendingRequestBulkTimeoutCheck(bulk, TIMEOUT); checkNotCancelledAfter(cancellationFuture, 2 * TIMEOUT.toMillis()); } private static void checkNotCancelledAfter(CompletableFuture<?> cancellationFuture, long milli) throws ExecutionException, InterruptedException { mainThreadExecutor.schedule(() -> {}, milli, TimeUnit.MILLISECONDS).get(); assertThatThrownBy( () -> { assertThatFuture(cancellationFuture).isNotDone(); cancellationFuture.get(milli, TimeUnit.MILLISECONDS); }) .withFailMessage("The future must not have been cancelled") .isInstanceOf(TimeoutException.class); assertThatFuture(cancellationFuture).isNotDone(); } @Test void testUnfulfillableBulkIsCancelled() { final CompletableFuture<ExecutionVertexID> cancellationFuture = new CompletableFuture<>(); final ExecutionVertexID executionVertexID = new ExecutionVertexID(new JobVertexID(), 0); final PhysicalSlotRequestBulk bulk = createPhysicalSlotRequestBulkWithCancellationFuture( cancellationFuture, executionVertexID); bulkChecker.schedulePendingRequestBulkTimeoutCheck(bulk, TIMEOUT); clock.advanceTime(TIMEOUT.toMillis() + 1L, TimeUnit.MILLISECONDS); assertThat(cancellationFuture.join()).isEqualTo(executionVertexID); } @Test void testBulkFulfilledOnCheck() { final ExecutionSlotSharingGroup executionSlotSharingGroup = new ExecutionSlotSharingGroup(new SlotSharingGroup()); final SharingPhysicalSlotRequestBulk bulk = createPhysicalSlotRequestBulk(executionSlotSharingGroup); bulk.markFulfilled(executionSlotSharingGroup, new AllocationID()); final PhysicalSlotRequestBulkWithTimestamp bulkWithTimestamp = new PhysicalSlotRequestBulkWithTimestamp(bulk); assertThat(checkBulkTimeout(bulkWithTimestamp)) .isEqualTo(PhysicalSlotRequestBulkCheckerImpl.TimeoutCheckResult.FULFILLED); } @Test void testBulkTimeoutOnCheck() { final PhysicalSlotRequestBulkWithTimestamp bulk = createPhysicalSlotRequestBulkWithTimestamp( new ExecutionSlotSharingGroup(new SlotSharingGroup())); clock.advanceTime(TIMEOUT.toMillis() + 1L, TimeUnit.MILLISECONDS); assertThat(checkBulkTimeout(bulk)) .isEqualTo(PhysicalSlotRequestBulkCheckerImpl.TimeoutCheckResult.TIMEOUT); } @Test void testBulkPendingOnCheckIfFulfillable() { final PhysicalSlotRequestBulkWithTimestamp bulk = createPhysicalSlotRequestBulkWithTimestamp( new ExecutionSlotSharingGroup(new SlotSharingGroup())); final PhysicalSlot slot = addOneSlot(); occupyPhysicalSlot(slot, false); assertThat(checkBulkTimeout(bulk)) .isEqualTo(PhysicalSlotRequestBulkCheckerImpl.TimeoutCheckResult.PENDING); } @Test void testBulkPendingOnCheckIfUnfulfillableButNotTimedOut() { final PhysicalSlotRequestBulkWithTimestamp bulk = createPhysicalSlotRequestBulkWithTimestamp( new ExecutionSlotSharingGroup(new SlotSharingGroup())); assertThat(checkBulkTimeout(bulk)) .isEqualTo(PhysicalSlotRequestBulkCheckerImpl.TimeoutCheckResult.PENDING); } @Test void testBulkFulfillable() { final PhysicalSlotRequestBulk bulk = createPhysicalSlotRequestBulk( new ExecutionSlotSharingGroup(new SlotSharingGroup())); addOneSlot(); assertThat(isFulfillable(bulk)).isTrue(); } @Test void testBulkUnfulfillableWithInsufficientSlots() { final PhysicalSlotRequestBulk bulk = createPhysicalSlotRequestBulk( new ExecutionSlotSharingGroup(new SlotSharingGroup()), new ExecutionSlotSharingGroup(new SlotSharingGroup())); addOneSlot(); assertThat(isFulfillable(bulk)).isFalse(); } @Test void testBulkUnfulfillableWithSlotAlreadyAssignedToBulk() { final ExecutionSlotSharingGroup executionSlotSharingGroup = new ExecutionSlotSharingGroup(new SlotSharingGroup()); final SharingPhysicalSlotRequestBulk bulk = createPhysicalSlotRequestBulk( executionSlotSharingGroup, new ExecutionSlotSharingGroup(new SlotSharingGroup())); final PhysicalSlot slot = addOneSlot(); bulk.markFulfilled(executionSlotSharingGroup, slot.getAllocationId()); assertThat(isFulfillable(bulk)).isFalse(); } @Test void testBulkUnfulfillableWithSlotOccupiedIndefinitely() { final PhysicalSlotRequestBulk bulk = createPhysicalSlotRequestBulk( new ExecutionSlotSharingGroup(new SlotSharingGroup()), new ExecutionSlotSharingGroup(new SlotSharingGroup())); final PhysicalSlot slot1 = addOneSlot(); addOneSlot(); occupyPhysicalSlot(slot1, true); assertThat(isFulfillable(bulk)).isFalse(); } @Test void testBulkFulfillableWithSlotOccupiedTemporarily() { final PhysicalSlotRequestBulk bulk = createPhysicalSlotRequestBulk( new ExecutionSlotSharingGroup(new SlotSharingGroup()), new ExecutionSlotSharingGroup(new SlotSharingGroup())); final PhysicalSlot slot1 = addOneSlot(); addOneSlot(); occupyPhysicalSlot(slot1, false); assertThat(isFulfillable(bulk)).isTrue(); } private PhysicalSlotRequestBulkWithTimestamp createPhysicalSlotRequestBulkWithTimestamp( ExecutionSlotSharingGroup... executionSlotSharingGroups) { final PhysicalSlotRequestBulkWithTimestamp bulk = new PhysicalSlotRequestBulkWithTimestamp( createPhysicalSlotRequestBulk(executionSlotSharingGroups)); bulk.markUnfulfillable(clock.relativeTimeMillis()); return bulk; } private static SharingPhysicalSlotRequestBulk createPhysicalSlotRequestBulk( ExecutionSlotSharingGroup... executionSlotSharingGroups) { final TestingPhysicalSlotRequestBulkBuilder builder = TestingPhysicalSlotRequestBulkBuilder.newBuilder(); for (ExecutionSlotSharingGroup executionSlotSharingGroup : executionSlotSharingGroups) { builder.addPendingRequest(executionSlotSharingGroup, ResourceProfile.UNKNOWN); } return builder.buildSharingPhysicalSlotRequestBulk(); } private PhysicalSlotRequestBulk createPhysicalSlotRequestBulkWithCancellationFuture( CompletableFuture<ExecutionVertexID> cancellationFuture, ExecutionVertexID executionVertexID) { ExecutionSlotSharingGroup executionSlotSharingGroup = new ExecutionSlotSharingGroup(new SlotSharingGroup()); executionSlotSharingGroup.addVertex(executionVertexID); return TestingPhysicalSlotRequestBulkBuilder.newBuilder() .addPendingRequest(executionSlotSharingGroup, ResourceProfile.UNKNOWN) .setCanceller((id, t) -> cancellationFuture.complete(id)) .buildSharingPhysicalSlotRequestBulk(); } private PhysicalSlot addOneSlot() { final PhysicalSlot slot = createPhysicalSlot(); CompletableFuture.runAsync(() -> slots.add(slot), mainThreadExecutor).join(); return slot; } private PhysicalSlotRequestBulkCheckerImpl.TimeoutCheckResult checkBulkTimeout( final PhysicalSlotRequestBulkWithTimestamp bulk) { return bulkChecker.checkPhysicalSlotRequestBulkTimeout(bulk, TIMEOUT); } private boolean isFulfillable(final PhysicalSlotRequestBulk bulk) { return PhysicalSlotRequestBulkCheckerImpl.isSlotRequestBulkFulfillable( bulk, slotsRetriever); } }
PhysicalSlotRequestBulkCheckerImplTest
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/model/source/DefaultOptions.java
{ "start": 1063, "end": 6711 }
class ____ extends DelegatingOptions { private final MapperGem mapper; private final Options options; DefaultOptions(MapperGem mapper, Options options) { super( null ); this.mapper = mapper; this.options = options; } @Override public String implementationName() { return mapper.implementationName().getDefaultValue(); } @Override public String implementationPackage() { return mapper.implementationPackage().getDefaultValue(); } @Override public Set<DeclaredType> uses() { return Collections.emptySet(); } @Override public Set<DeclaredType> imports() { return Collections.emptySet(); } @Override public ReportingPolicyGem unmappedTargetPolicy() { ReportingPolicyGem unmappedTargetPolicy = options.getUnmappedTargetPolicy(); if ( unmappedTargetPolicy != null ) { return unmappedTargetPolicy; } return ReportingPolicyGem.valueOf( mapper.unmappedTargetPolicy().getDefaultValue() ); } @Override public ReportingPolicyGem unmappedSourcePolicy() { ReportingPolicyGem unmappedSourcePolicy = options.getUnmappedSourcePolicy(); if ( unmappedSourcePolicy != null ) { return unmappedSourcePolicy; } return ReportingPolicyGem.valueOf( mapper.unmappedSourcePolicy().getDefaultValue() ); } @Override public ReportingPolicyGem typeConversionPolicy() { return ReportingPolicyGem.valueOf( mapper.typeConversionPolicy().getDefaultValue() ); } @Override public String componentModel() { String defaultComponentModel = options.getDefaultComponentModel(); if ( defaultComponentModel != null ) { return defaultComponentModel; } return mapper.componentModel().getDefaultValue(); } public boolean suppressTimestampInGenerated() { if ( mapper.suppressTimestampInGenerated().hasValue() ) { return mapper.suppressTimestampInGenerated().getValue(); } return options.isSuppressGeneratorTimestamp(); } @Override public MappingInheritanceStrategyGem getMappingInheritanceStrategy() { return MappingInheritanceStrategyGem.valueOf( mapper.mappingInheritanceStrategy().getDefaultValue() ); } @Override public InjectionStrategyGem getInjectionStrategy() { String defaultInjectionStrategy = options.getDefaultInjectionStrategy(); if ( defaultInjectionStrategy != null ) { return InjectionStrategyGem.valueOf( defaultInjectionStrategy.toUpperCase() ); } return InjectionStrategyGem.valueOf( mapper.injectionStrategy().getDefaultValue() ); } @Override public Boolean isDisableSubMappingMethodsGeneration() { return mapper.disableSubMappingMethodsGeneration().getDefaultValue(); } // BeanMapping and Mapping public CollectionMappingStrategyGem getCollectionMappingStrategy() { return CollectionMappingStrategyGem.valueOf( mapper.collectionMappingStrategy().getDefaultValue() ); } public NullValueCheckStrategyGem getNullValueCheckStrategy() { return NullValueCheckStrategyGem.valueOf( mapper.nullValueCheckStrategy().getDefaultValue() ); } public NullValuePropertyMappingStrategyGem getNullValuePropertyMappingStrategy() { return NullValuePropertyMappingStrategyGem.valueOf( mapper.nullValuePropertyMappingStrategy().getDefaultValue() ); } public NullValueMappingStrategyGem getNullValueMappingStrategy() { return NullValueMappingStrategyGem.valueOf( mapper.nullValueMappingStrategy().getDefaultValue() ); } public SubclassExhaustiveStrategyGem getSubclassExhaustiveStrategy() { return SubclassExhaustiveStrategyGem.valueOf( mapper.subclassExhaustiveStrategy().getDefaultValue() ); } public TypeMirror getSubclassExhaustiveException() { return mapper.subclassExhaustiveException().getDefaultValue(); } public NullValueMappingStrategyGem getNullValueIterableMappingStrategy() { NullValueMappingStrategyGem nullValueIterableMappingStrategy = options.getNullValueIterableMappingStrategy(); if ( nullValueIterableMappingStrategy != null ) { return nullValueIterableMappingStrategy; } return NullValueMappingStrategyGem.valueOf( mapper.nullValueIterableMappingStrategy().getDefaultValue() ); } public NullValueMappingStrategyGem getNullValueMapMappingStrategy() { NullValueMappingStrategyGem nullValueMapMappingStrategy = options.getNullValueMapMappingStrategy(); if ( nullValueMapMappingStrategy != null ) { return nullValueMapMappingStrategy; } return NullValueMappingStrategyGem.valueOf( mapper.nullValueMapMappingStrategy().getDefaultValue() ); } public BuilderGem getBuilder() { // TODO: I realized this is not correct, however it needs to be null in order to keep downward compatibility // but assuming a default @Builder will make testcases fail. Not having a default means that you need to // specify this mandatory on @MapperConfig and @Mapper. return null; } @Override public MappingControl getMappingControl(ElementUtils elementUtils) { return MappingControl.fromTypeMirror( mapper.mappingControl().getDefaultValue(), elementUtils ); } @Override public TypeMirror getUnexpectedValueMappingException() { return null; } @Override public boolean hasAnnotation() { return false; } }
DefaultOptions
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/ClientAttributes.java
{ "start": 1820, "end": 3090 }
class ____ { private static final String CLIENT_REGISTRATION_ID_ATTR_NAME = ClientRegistration.class.getName() .concat(".CLIENT_REGISTRATION_ID"); /** * Resolves the {@link ClientRegistration#getRegistrationId() clientRegistrationId} to * be used to look up the {@link OAuth2AuthorizedClient}. * @param attributes the to search * @return the registration id to use. */ public static String resolveClientRegistrationId(Map<String, Object> attributes) { return (String) attributes.get(CLIENT_REGISTRATION_ID_ATTR_NAME); } /** * Produces a Consumer that adds the {@link ClientRegistration#getRegistrationId() * clientRegistrationId} to be used to look up the {@link OAuth2AuthorizedClient}. * @param clientRegistrationId the {@link ClientRegistration#getRegistrationId() * clientRegistrationId} to be used to look up the {@link OAuth2AuthorizedClient} * @return the {@link Consumer} to populate the attributes */ public static Consumer<Map<String, Object>> clientRegistrationId(String clientRegistrationId) { Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty"); return (attributes) -> attributes.put(CLIENT_REGISTRATION_ID_ATTR_NAME, clientRegistrationId); } private ClientAttributes() { } }
ClientAttributes
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/internal/security/certprovider/SystemRootCertificateProvider.java
{ "start": 1226, "end": 2607 }
class ____ extends CertificateProvider { public SystemRootCertificateProvider(CertificateProvider.Watcher watcher) { super(new DistributorWatcher(), false); getWatcher().addWatcher(watcher); } @Override public void start() { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); List<TrustManager> trustManagers = Arrays.asList(trustManagerFactory.getTrustManagers()); List<X509Certificate> rootCerts = trustManagers.stream() .filter(X509TrustManager.class::isInstance) .map(X509TrustManager.class::cast) .map(trustManager -> Arrays.asList(trustManager.getAcceptedIssuers())) .flatMap(Collection::stream) .collect(Collectors.toList()); getWatcher().updateTrustedRoots(rootCerts); } catch (KeyStoreException | NoSuchAlgorithmException ex) { getWatcher().onError(Status.UNAVAILABLE .withDescription("Could not load system root certs") .withCause(ex)); } } @Override public void close() { // Unnecessary because there's no more callbacks, but do it for good measure for (Watcher watcher : getWatcher().getDownstreamWatchers()) { getWatcher().removeWatcher(watcher); } } }
SystemRootCertificateProvider
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/spi/ClassTransformer.java
{ "start": 344, "end": 603 }
interface ____ the * {@link jakarta.persistence.spi.PersistenceUnitInfo#addTransformer} method. * The supplied transformer instance will get called to transform entity class * files when they are loaded and redefined. The transformation occurs before * the
to
java
google__gson
gson/src/main/java/com/google/gson/JsonElement.java
{ "start": 1029, "end": 2647 }
class ____ multiple {@code getAs} methods which allow * * <ul> * <li>obtaining the represented primitive value, for example {@link #getAsString()} * <li>casting to the {@code JsonElement} subclasses in a convenient way, for example {@link * #getAsJsonObject()} * </ul> * * <h2>Converting {@code JsonElement} from / to JSON</h2> * * There are two ways to parse JSON data as a {@link JsonElement}: * * <ul> * <li>{@link JsonParser}, for example: * <pre> * JsonObject jsonObject = JsonParser.parseString("{}").getAsJsonObject(); * </pre> * <li>{@link Gson#fromJson(java.io.Reader, Class) Gson.fromJson(..., JsonElement.class)}<br> * It is possible to directly specify a {@code JsonElement} subclass, for example: * <pre> * JsonObject jsonObject = gson.fromJson("{}", JsonObject.class); * </pre> * </ul> * * To convert a {@code JsonElement} to JSON either {@link #toString() JsonElement.toString()} or the * method {@link Gson#toJson(JsonElement)} and its overloads can be used. * * <p>It is also possible to obtain the {@link TypeAdapter} for {@code JsonElement} from a {@link * Gson} instance and then use it for conversion from and to JSON: * * <pre>{@code * TypeAdapter<JsonElement> adapter = gson.getAdapter(JsonElement.class); * * JsonElement value = adapter.fromJson("{}"); * String json = adapter.toJson(value); * }</pre> * * <h2>{@code JsonElement} as JSON data</h2> * * {@code JsonElement} can also be treated as JSON data, allowing to deserialize from a {@code * JsonElement} and serializing to a {@code JsonElement}. The {@link Gson}
provides
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/sequencedmultisetstate/SequencedMultiSetStateTest.java
{ "start": 24960, "end": 25371 }
class ____ extends GeneratedRecordEqualiser { private final int keyPos; public MyGeneratedEqualiser(int keyPos) { super("", "", new Object[0]); this.keyPos = keyPos; } @Override public RecordEqualiser newInstance(ClassLoader classLoader) { return new TestRecordEqualiser(keyPos); } } private static
MyGeneratedEqualiser
java
spring-projects__spring-boot
module/spring-boot-hibernate/src/main/java/org/springframework/boot/hibernate/autoconfigure/HibernateJpaConfiguration.java
{ "start": 3595, "end": 10366 }
class ____ extends JpaBaseConfiguration { private static final Log logger = LogFactory.getLog(HibernateJpaConfiguration.class); private static final String JTA_PLATFORM = "hibernate.transaction.jta.platform"; private static final String PROVIDER_DISABLES_AUTOCOMMIT = "hibernate.connection.provider_disables_autocommit"; /** * {@code NoJtaPlatform} implementations for various Hibernate versions. */ private static final String[] NO_JTA_PLATFORM_CLASSES = { "org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform", "org.hibernate.service.jta.platform.internal.NoJtaPlatform" }; private final HibernateProperties hibernateProperties; private final HibernateDefaultDdlAutoProvider defaultDdlAutoProvider; private final DataSourcePoolMetadataProvider poolMetadataProvider; private final ObjectProvider<SQLExceptionTranslator> sqlExceptionTranslator; private final List<HibernatePropertiesCustomizer> hibernatePropertiesCustomizers; HibernateJpaConfiguration(DataSource dataSource, JpaProperties jpaProperties, ConfigurableListableBeanFactory beanFactory, ObjectProvider<JtaTransactionManager> jtaTransactionManager, HibernateProperties hibernateProperties, ObjectProvider<Collection<DataSourcePoolMetadataProvider>> metadataProviders, ObjectProvider<SchemaManagementProvider> providers, ObjectProvider<PhysicalNamingStrategy> physicalNamingStrategy, ObjectProvider<ImplicitNamingStrategy> implicitNamingStrategy, ObjectProvider<SQLExceptionTranslator> sqlExceptionTranslator, ObjectProvider<HibernatePropertiesCustomizer> hibernatePropertiesCustomizers) { super(dataSource, jpaProperties, jtaTransactionManager); this.hibernateProperties = hibernateProperties; this.defaultDdlAutoProvider = new HibernateDefaultDdlAutoProvider(providers); this.poolMetadataProvider = new CompositeDataSourcePoolMetadataProvider(metadataProviders.getIfAvailable()); this.sqlExceptionTranslator = sqlExceptionTranslator; this.hibernatePropertiesCustomizers = determineHibernatePropertiesCustomizers( physicalNamingStrategy.getIfAvailable(), implicitNamingStrategy.getIfAvailable(), beanFactory, hibernatePropertiesCustomizers.orderedStream().toList()); } private List<HibernatePropertiesCustomizer> determineHibernatePropertiesCustomizers( @Nullable PhysicalNamingStrategy physicalNamingStrategy, @Nullable ImplicitNamingStrategy implicitNamingStrategy, ConfigurableListableBeanFactory beanFactory, List<HibernatePropertiesCustomizer> hibernatePropertiesCustomizers) { List<HibernatePropertiesCustomizer> customizers = new ArrayList<>(); if (ClassUtils.isPresent("org.hibernate.resource.beans.container.spi.BeanContainer", getClass().getClassLoader())) { customizers.add((properties) -> properties.put(ManagedBeanSettings.BEAN_CONTAINER, new SpringBeanContainer(beanFactory))); } if (physicalNamingStrategy != null || implicitNamingStrategy != null) { customizers .add(new NamingStrategiesHibernatePropertiesCustomizer(physicalNamingStrategy, implicitNamingStrategy)); } customizers.addAll(hibernatePropertiesCustomizers); return customizers; } @Override protected AbstractJpaVendorAdapter createJpaVendorAdapter() { HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); this.sqlExceptionTranslator.ifUnique(adapter.getJpaDialect()::setJdbcExceptionTranslator); return adapter; } @Override protected Map<String, Object> getVendorProperties(DataSource dataSource) { Supplier<String> defaultDdlMode = () -> this.defaultDdlAutoProvider.getDefaultDdlAuto(dataSource); return new LinkedHashMap<>(this.hibernateProperties.determineHibernateProperties( getProperties().getProperties(), new HibernateSettings().ddlAuto(defaultDdlMode) .hibernatePropertiesCustomizers(this.hibernatePropertiesCustomizers))); } @Override protected void customizeVendorProperties(Map<String, Object> vendorProperties) { super.customizeVendorProperties(vendorProperties); if (!vendorProperties.containsKey(JTA_PLATFORM)) { configureJtaPlatform(vendorProperties); } if (!vendorProperties.containsKey(PROVIDER_DISABLES_AUTOCOMMIT)) { configureProviderDisablesAutocommit(vendorProperties); } } private void configureJtaPlatform(Map<String, Object> vendorProperties) throws LinkageError { JtaTransactionManager jtaTransactionManager = getJtaTransactionManager(); // Make sure Hibernate doesn't attempt to auto-detect a JTA platform if (jtaTransactionManager == null) { vendorProperties.put(JTA_PLATFORM, getNoJtaPlatformManager()); } // As of Hibernate 5.2, Hibernate can fully integrate with the WebSphere // transaction manager on its own. else if (!runningOnWebSphere()) { configureSpringJtaPlatform(vendorProperties, jtaTransactionManager); } } private void configureProviderDisablesAutocommit(Map<String, Object> vendorProperties) { if (isDataSourceAutoCommitDisabled() && !isJta()) { vendorProperties.put(PROVIDER_DISABLES_AUTOCOMMIT, "true"); } } private boolean isDataSourceAutoCommitDisabled() { DataSourcePoolMetadata poolMetadata = this.poolMetadataProvider.getDataSourcePoolMetadata(getDataSource()); return poolMetadata != null && Boolean.FALSE.equals(poolMetadata.getDefaultAutoCommit()); } private boolean runningOnWebSphere() { return ClassUtils.isPresent("com.ibm.websphere.jtaextensions.ExtendedJTATransaction", getClass().getClassLoader()); } private void configureSpringJtaPlatform(Map<String, Object> vendorProperties, JtaTransactionManager jtaTransactionManager) { try { vendorProperties.put(JTA_PLATFORM, new SpringJtaPlatform(jtaTransactionManager)); } catch (LinkageError ex) { // NoClassDefFoundError can happen if Hibernate 4.2 is used and some // containers (e.g. JBoss EAP 6) wrap it in the superclass LinkageError if (!isUsingJndi()) { throw new IllegalStateException( "Unable to set Hibernate JTA platform, are you using the correct version of Hibernate?", ex); } // Assume that Hibernate will use JNDI if (logger.isDebugEnabled()) { logger.debug("Unable to set Hibernate JTA platform : " + ex.getMessage()); } } } private boolean isUsingJndi() { try { return JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable(); } catch (Error ex) { return false; } } private Object getNoJtaPlatformManager() { for (String candidate : NO_JTA_PLATFORM_CLASSES) { try { return Class.forName(candidate).getDeclaredConstructor().newInstance(); } catch (Exception ex) { // Continue searching } } throw new IllegalStateException( "No available JtaPlatform candidates amongst " + Arrays.toString(NO_JTA_PLATFORM_CLASSES)); } private static
HibernateJpaConfiguration
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/search/SimpleQueryStringQueryParser.java
{ "start": 12055, "end": 17258 }
class ____ { /** Specifies whether lenient query parsing should be used. */ private boolean lenient = SimpleQueryStringBuilder.DEFAULT_LENIENT; /** Specifies whether wildcards should be analyzed. */ private boolean analyzeWildcard = SimpleQueryStringBuilder.DEFAULT_ANALYZE_WILDCARD; /** Specifies a suffix, if any, to apply to field names for phrase matching. */ private String quoteFieldSuffix = null; /** Whether phrase queries should be automatically generated for multi terms synonyms. */ private boolean autoGenerateSynonymsPhraseQuery = true; /** Prefix length in fuzzy queries.*/ private int fuzzyPrefixLength = SimpleQueryStringBuilder.DEFAULT_FUZZY_PREFIX_LENGTH; /** The number of terms fuzzy queries will expand to.*/ private int fuzzyMaxExpansions = SimpleQueryStringBuilder.DEFAULT_FUZZY_MAX_EXPANSIONS; /** Whether transpositions are supported in fuzzy queries.*/ private boolean fuzzyTranspositions = SimpleQueryStringBuilder.DEFAULT_FUZZY_TRANSPOSITIONS; /** * Generates default {@link Settings} object (uses ROOT locale, does * lowercase terms, no lenient parsing, no wildcard analysis). * */ public Settings() {} public Settings(Settings other) { this.lenient = other.lenient; this.analyzeWildcard = other.analyzeWildcard; this.quoteFieldSuffix = other.quoteFieldSuffix; this.autoGenerateSynonymsPhraseQuery = other.autoGenerateSynonymsPhraseQuery; this.fuzzyPrefixLength = other.fuzzyPrefixLength; this.fuzzyMaxExpansions = other.fuzzyMaxExpansions; this.fuzzyTranspositions = other.fuzzyTranspositions; } /** Specifies whether to use lenient parsing, defaults to false. */ public void lenient(boolean lenient) { this.lenient = lenient; } /** Returns whether to use lenient parsing. */ public boolean lenient() { return this.lenient; } /** Specifies whether to analyze wildcards. Defaults to false if unset. */ public void analyzeWildcard(boolean analyzeWildcard) { this.analyzeWildcard = analyzeWildcard; } /** Returns whether to analyze wildcards. */ public boolean analyzeWildcard() { return analyzeWildcard; } /** * Set the suffix to append to field names for phrase matching. */ public void quoteFieldSuffix(String suffix) { this.quoteFieldSuffix = suffix; } /** * Return the suffix to append for phrase matching, or {@code null} if * no suffix should be appended. */ public String quoteFieldSuffix() { return quoteFieldSuffix; } public void autoGenerateSynonymsPhraseQuery(boolean value) { this.autoGenerateSynonymsPhraseQuery = value; } /** * Whether phrase queries should be automatically generated for multi terms synonyms. * Defaults to {@code true}. */ public boolean autoGenerateSynonymsPhraseQuery() { return autoGenerateSynonymsPhraseQuery; } public int fuzzyPrefixLength() { return fuzzyPrefixLength; } public void fuzzyPrefixLength(int fuzzyPrefixLength) { this.fuzzyPrefixLength = fuzzyPrefixLength; } public int fuzzyMaxExpansions() { return fuzzyMaxExpansions; } public void fuzzyMaxExpansions(int fuzzyMaxExpansions) { this.fuzzyMaxExpansions = fuzzyMaxExpansions; } public boolean fuzzyTranspositions() { return fuzzyTranspositions; } public void fuzzyTranspositions(boolean fuzzyTranspositions) { this.fuzzyTranspositions = fuzzyTranspositions; } @Override public int hashCode() { return Objects.hash( lenient, analyzeWildcard, quoteFieldSuffix, autoGenerateSynonymsPhraseQuery, fuzzyPrefixLength, fuzzyMaxExpansions, fuzzyTranspositions ); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } Settings other = (Settings) obj; return Objects.equals(lenient, other.lenient) && Objects.equals(analyzeWildcard, other.analyzeWildcard) && Objects.equals(quoteFieldSuffix, other.quoteFieldSuffix) && Objects.equals(autoGenerateSynonymsPhraseQuery, other.autoGenerateSynonymsPhraseQuery) && Objects.equals(fuzzyPrefixLength, other.fuzzyPrefixLength) && Objects.equals(fuzzyMaxExpansions, other.fuzzyMaxExpansions) && Objects.equals(fuzzyTranspositions, other.fuzzyTranspositions); } } }
Settings
java
apache__flink
flink-state-backends/flink-statebackend-forst/src/main/java/org/apache/flink/state/forst/ConfigurableForStOptionsFactory.java
{ "start": 1064, "end": 1710 }
interface ____ extends ForStOptionsFactory { /** * Creates a variant of the options factory that applies additional configuration parameters. * * <p>If no configuration is applied, or if the method directly applies configuration values to * the (mutable) options factory object, this method may return the original options factory * object. Otherwise it typically returns a modified copy. * * @param configuration The configuration to pick the values from. * @return A reconfigured options factory. */ ForStOptionsFactory configure(ReadableConfig configuration); }
ConfigurableForStOptionsFactory
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/aot/nativex/FileNativeConfigurationWriter.java
{ "start": 1192, "end": 2774 }
class ____ extends NativeConfigurationWriter { private final Path basePath; private final @Nullable String groupId; private final @Nullable String artifactId; public FileNativeConfigurationWriter(Path basePath) { this(basePath, null, null); } public FileNativeConfigurationWriter(Path basePath, @Nullable String groupId, @Nullable String artifactId) { this.basePath = basePath; if ((groupId == null && artifactId != null) || (groupId != null && artifactId == null)) { throw new IllegalArgumentException("groupId and artifactId must be both null or both non-null"); } this.groupId = groupId; this.artifactId = artifactId; } @Override protected void writeTo(String fileName, Consumer<BasicJsonWriter> writer) { try { File file = createIfNecessary(fileName); try (FileWriter out = new FileWriter(file)) { writer.accept(createJsonWriter(out)); } } catch (IOException ex) { throw new IllegalStateException("Failed to write native configuration for " + fileName, ex); } } private File createIfNecessary(String filename) throws IOException { Path outputDirectory = this.basePath.resolve("META-INF").resolve("native-image"); if (this.groupId != null && this.artifactId != null) { outputDirectory = outputDirectory.resolve(this.groupId).resolve(this.artifactId); } outputDirectory.toFile().mkdirs(); File file = outputDirectory.resolve(filename).toFile(); file.createNewFile(); return file; } private BasicJsonWriter createJsonWriter(Writer out) { return new BasicJsonWriter(out); } }
FileNativeConfigurationWriter
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/observer/SyntheticObserverTest.java
{ "start": 989, "end": 3132 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(MyObserver.class)) .addBuildChainCustomizer(buildCustomizer()); static Consumer<BuildChainBuilder> buildCustomizer() { return new Consumer<BuildChainBuilder>() { @Override public void accept(BuildChainBuilder builder) { builder.addBuildStep(new BuildStep() { @Override public void execute(BuildContext context) { ObserverRegistrationPhaseBuildItem observerRegistrationPhase = context .consume(ObserverRegistrationPhaseBuildItem.class); context.produce(new ObserverConfiguratorBuildItem( observerRegistrationPhase.getContext().configure() .beanClass(DotName.createSimple(SyntheticObserverTest.class.getName())) .observedType(String.class) .notify(ng -> { BlockCreator bc = ng.notifyMethod(); bc.withList(Expr.staticField(FieldDesc.of(MyObserver.class, "EVENTS"))) .add(Const.of("synthetic")); bc.return_(); }))); } }).consumes(ObserverRegistrationPhaseBuildItem.class).produces(ObserverConfiguratorBuildItem.class).build(); } }; } @Test public void testSyntheticObserver() { MyObserver.EVENTS.clear(); Arc.container().beanManager().getEvent().fire("foo"); assertEquals(2, MyObserver.EVENTS.size(), "Events: " + MyObserver.EVENTS); assertTrue(MyObserver.EVENTS.contains("synthetic")); assertTrue(MyObserver.EVENTS.contains("foo_MyObserver")); } @Singleton static
SyntheticObserverTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/charsequence/CharSequenceAssert_hasSameSizeAs_with_Array_Test.java
{ "start": 967, "end": 1445 }
class ____ extends CharSequenceAssertBaseTest { private static Object[] other; @BeforeAll static void setUpOnce() { other = new Object[] { "Luke" }; } @Override protected CharSequenceAssert invoke_api_method() { return assertions.hasSameSizeAs(other); } @Override protected void verify_internal_effects() { verify(strings).assertHasSameSizeAs(getInfo(assertions), getActual(assertions), other); } }
CharSequenceAssert_hasSameSizeAs_with_Array_Test
java
spring-projects__spring-security
oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationTokenTests.java
{ "start": 1403, "end": 5698 }
class ____ { @Test public void getNameWhenJwtHasSubjectThenReturnsSubject() { Jwt jwt = builder().subject("Carl").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt); assertThat(token.getName()).isEqualTo("Carl"); } @Test public void getNameWhenJwtHasNoSubjectThenReturnsNull() { Jwt jwt = builder().claim("claim", "value").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt); assertThat(token.getName()).isNull(); } @Test public void constructorWhenJwtIsNullThenThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new JwtAuthenticationToken((Jwt) null)) .withMessageContaining("token cannot be null"); } @Test public void constructorWhenUsingCorrectParametersThenConstructedCorrectly() { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test"); Jwt jwt = builder().claim("claim", "value").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities); assertThat(token.getAuthorities()).isEqualTo(authorities); assertThat(token.getPrincipal()).isEqualTo(jwt); assertThat(token.getCredentials()).isEqualTo(jwt); assertThat(token.getToken()).isEqualTo(jwt); assertThat(token.getTokenAttributes()).isEqualTo(jwt.getClaims()); assertThat(token.isAuthenticated()).isTrue(); } @Test public void constructorWhenUsingOnlyJwtThenConstructedCorrectly() { Jwt jwt = builder().claim("claim", "value").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt); assertThat(token.getAuthorities()).isEmpty(); assertThat(token.getPrincipal()).isEqualTo(jwt); assertThat(token.getCredentials()).isEqualTo(jwt); assertThat(token.getToken()).isEqualTo(jwt); assertThat(token.getTokenAttributes()).isEqualTo(jwt.getClaims()); assertThat(token.isAuthenticated()).isFalse(); } @Test public void getNameWhenConstructedWithJwtThenReturnsSubject() { Jwt jwt = builder().subject("Hayden").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt); assertThat(token.getName()).isEqualTo("Hayden"); } @Test public void getNameWhenConstructedWithJwtAndAuthoritiesThenReturnsSubject() { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test"); Jwt jwt = builder().subject("Hayden").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities); assertThat(token.getName()).isEqualTo("Hayden"); } @Test public void getNameWhenConstructedWithNameThenReturnsProvidedName() { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test"); Jwt jwt = builder().claim("claim", "value").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities, "Hayden"); assertThat(token.getName()).isEqualTo("Hayden"); } @Test public void getNameWhenConstructedWithNoSubjectThenReturnsNull() { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test"); Jwt jwt = builder().claim("claim", "value").build(); assertThat(new JwtAuthenticationToken(jwt, authorities, null).getName()).isNull(); assertThat(new JwtAuthenticationToken(jwt, authorities).getName()).isNull(); assertThat(new JwtAuthenticationToken(jwt).getName()).isNull(); } @Test public void toBuilderWhenApplyThenCopies() { JwtAuthenticationToken factorOne = new JwtAuthenticationToken(builder().claim("c", "v").build(), AuthorityUtils.createAuthorityList("FACTOR_ONE"), "alice"); JwtAuthenticationToken factorTwo = new JwtAuthenticationToken(builder().claim("d", "w").build(), AuthorityUtils.createAuthorityList("FACTOR_TWO"), "bob"); JwtAuthenticationToken result = factorOne.toBuilder() .authorities((a) -> a.addAll(factorTwo.getAuthorities())) .principal(factorTwo.getPrincipal()) .name(factorTwo.getName()) .build(); Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities()); assertThat(result.getPrincipal()).isSameAs(factorTwo.getPrincipal()); assertThat(result.getName()).isSameAs(factorTwo.getName()); assertThat(authorities).containsExactlyInAnyOrder("FACTOR_ONE", "FACTOR_TWO"); } private Jwt.Builder builder() { return Jwt.withTokenValue("token").header("alg", JwsAlgorithms.RS256); } }
JwtAuthenticationTokenTests
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/config/conditional/DisableBuiltInGlobalFiltersTests.java
{ "start": 3796, "end": 4022 }
class ____ { @Autowired(required = false) private List<GlobalFilter> globalFilters; @Test public void shouldDisableAllBuiltInFilters() { assertThat(globalFilters).isNull(); } } }
DisableAllGlobalFiltersByProperty
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/DefaultAuditTest.java
{ "start": 915, "end": 3814 }
class ____ { @Test public void test(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { //tag::envers-audited-insert-example[] Customer customer = new Customer(); customer.setId(1L); customer.setFirstName("John"); customer.setLastName("Doe"); entityManager.persist(customer); //end::envers-audited-insert-example[] }); scope.inTransaction( entityManager -> { //tag::envers-audited-update-example[] Customer customer = entityManager.find(Customer.class, 1L); customer.setLastName("Doe Jr."); //end::envers-audited-update-example[] }); scope.inTransaction( entityManager -> { //tag::envers-audited-delete-example[] Customer customer = entityManager.getReference(Customer.class, 1L); entityManager.remove(customer); //end::envers-audited-delete-example[] }); //tag::envers-audited-revisions-example[] List<Number> revisions = scope.fromTransaction( entityManager -> { return AuditReaderFactory.get(entityManager).getRevisions( Customer.class, 1L ); }); //end::envers-audited-revisions-example[] scope.inTransaction( entityManager -> { //tag::envers-audited-rev1-example[] Customer customer = (Customer) AuditReaderFactory .get(entityManager) .createQuery() .forEntitiesAtRevision(Customer.class, revisions.get(0)) .getSingleResult(); assertEquals("Doe", customer.getLastName()); //end::envers-audited-rev1-example[] }); scope.inTransaction( entityManager -> { //tag::envers-audited-rev2-example[] Customer customer = (Customer) AuditReaderFactory .get(entityManager) .createQuery() .forEntitiesAtRevision(Customer.class, revisions.get(1)) .getSingleResult(); assertEquals("Doe Jr.", customer.getLastName()); //end::envers-audited-rev2-example[] }); scope.inTransaction( entityManager -> { //tag::envers-audited-rev3-example[] try { Customer customer = (Customer) AuditReaderFactory .get(entityManager) .createQuery() .forEntitiesAtRevision(Customer.class, revisions.get(2)) .getSingleResult(); fail("The Customer was deleted at this revision: " + revisions.get(2)); } catch (NoResultException expected) { } //end::envers-audited-rev3-example[] }); scope.inTransaction( entityManager -> { //tag::envers-audited-rev4-example[] Customer customer = (Customer) AuditReaderFactory .get(entityManager) .createQuery() .forEntitiesAtRevision( Customer.class, Customer.class.getName(), revisions.get(2), true) .getSingleResult(); assertEquals(Long.valueOf(1L), customer.getId()); assertNull(customer.getFirstName()); assertNull(customer.getLastName()); assertNull(customer.getCreatedOn()); //end::envers-audited-rev4-example[] }); } //tag::envers-audited-mapping-example[] @Audited @Entity(name = "Customer") public static
DefaultAuditTest
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/support/rowset/ResultSetWrappingSqlRowSet.java
{ "start": 2493, "end": 3017 }
class ____ the {@code java.io.Serializable} marker interface * through the SqlRowSet interface, but is only actually serializable if the disconnected * ResultSet/RowSet contained in it is serializable. Most CachedRowSet implementations * are actually serializable, so serialization should usually work. * * @author Thomas Risberg * @author Juergen Hoeller * @since 1.2 * @see java.sql.ResultSet * @see javax.sql.rowset.CachedRowSet * @see org.springframework.jdbc.core.JdbcTemplate#queryForRowSet */ public
implements
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/diversification/ResultDiversification.java
{ "start": 775, "end": 1627 }
class ____<C extends ResultDiversificationContext> { protected final C context; protected ResultDiversification(C context) { this.context = context; } public abstract RankDoc[] diversify(RankDoc[] docs) throws IOException; protected float getFloatVectorComparisonScore( VectorSimilarityFunction similarityFunction, VectorData thisDocVector, VectorData comparisonVector ) { return similarityFunction.compare(thisDocVector.floatVector(), comparisonVector.floatVector()); } protected float getByteVectorComparisonScore( VectorSimilarityFunction similarityFunction, VectorData thisDocVector, VectorData comparisonVector ) { return similarityFunction.compare(thisDocVector.byteVector(), comparisonVector.byteVector()); } }
ResultDiversification
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/iterables/Iterables_assertHave_Test.java
{ "start": 1493, "end": 2571 }
class ____ extends IterablesWithConditionsBaseTest { @Test void should_pass_if_each_element_satisfies_condition() { actual = newArrayList("Yoda", "Luke"); iterables.assertHave(someInfo(), actual, jediPower); verify(conditions).assertIsNotNull(jediPower); } @Test void should_throw_error_if_condition_is_null() { assertThatNullPointerException().isThrownBy(() -> { actual = newArrayList("Yoda", "Luke"); iterables.assertHave(someInfo(), actual, null); }).withMessage("The condition to evaluate should not be null"); } @Test void should_fail_if_condition_is_not_met() { testCondition.shouldMatch(false); AssertionInfo info = someInfo(); actual = newArrayList("Yoda", "Luke", "Leia"); Throwable error = catchThrowable(() -> iterables.assertHave(someInfo(), actual, jediPower)); assertThat(error).isInstanceOf(AssertionError.class); verify(conditions).assertIsNotNull(jediPower); verify(failures).failure(info, elementsShouldHave(actual, newArrayList("Leia"), jediPower)); } }
Iterables_assertHave_Test
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2437/Phone.java
{ "start": 232, "end": 415 }
class ____ { private final String number; public Phone(String number) { this.number = number; } public String getNumber() { return number; } }
Phone
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/filter/CustomNullSerializationTest.java
{ "start": 2210, "end": 2912 }
class ____ extends SerializationContextExt { public MyNullSerializerSerializationContext(TokenStreamFactory streamFactory, SerializerCache cache, SerializationConfig config, GeneratorSettings genSettings, SerializerFactory f) { super(streamFactory, config, genSettings, f, cache); } @Override public ValueSerializer<Object> findNullValueSerializer(BeanProperty property) { if ("name".equals(property.getName())) { return new NullAsFoobarSerializer(); } return super.findNullValueSerializer(property); } } static
MyNullSerializerSerializationContext
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSDirErasureCodingOp.java
{ "start": 2258, "end": 18700 }
class ____ { /** * Private constructor for preventing FSDirErasureCodingOp object * creation. Static-only class. */ private FSDirErasureCodingOp() {} /** * Check if the ecPolicyName is valid and enabled, return the corresponding * EC policy if is, including the REPLICATION EC policy. * @param fsn namespace * @param ecPolicyName name of EC policy to be checked * @return an erasure coding policy if ecPolicyName is valid and enabled * @throws IOException */ static ErasureCodingPolicy getEnabledErasureCodingPolicyByName( final FSNamesystem fsn, final String ecPolicyName) throws IOException { assert fsn.hasReadLock(RwLockMode.FS); ErasureCodingPolicy ecPolicy = fsn.getErasureCodingPolicyManager() .getEnabledPolicyByName(ecPolicyName); if (ecPolicy == null) { final String sysPolicies = Arrays.asList( fsn.getErasureCodingPolicyManager().getEnabledPolicies()) .stream() .map(ErasureCodingPolicy::getName) .collect(Collectors.joining(", ")); final String message = String.format("Policy '%s' does not match any " + "enabled erasure" + " coding policies: [%s]. An erasure coding policy can be" + " enabled by enableErasureCodingPolicy API.", ecPolicyName, sysPolicies ); throw new HadoopIllegalArgumentException(message); } return ecPolicy; } /** * Check if the ecPolicyName is valid, return the corresponding * EC policy if is, including the REPLICATION EC policy. * @param fsn namespace * @param ecPolicyName name of EC policy to be checked * @return an erasure coding policy if ecPolicyName is valid * @throws IOException */ static ErasureCodingPolicy getErasureCodingPolicyByName( final FSNamesystem fsn, final String ecPolicyName) throws IOException { assert fsn.hasReadLock(RwLockMode.FS); ErasureCodingPolicy ecPolicy = fsn.getErasureCodingPolicyManager() .getErasureCodingPolicyByName(ecPolicyName); if (ecPolicy == null) { throw new HadoopIllegalArgumentException( "The given erasure coding " + "policy " + ecPolicyName + " does not exist."); } return ecPolicy; } /** * Set an erasure coding policy on the given path. * * @param fsn The namespace * @param srcArg The path of the target directory. * @param ecPolicyName The erasure coding policy name to set on the target * directory. * @param logRetryCache whether to record RPC ids in editlog for retry * cache rebuilding * @return {@link FileStatus} * @throws IOException * @throws HadoopIllegalArgumentException if the policy is not enabled * @throws AccessControlException if the user does not have write access */ static FileStatus setErasureCodingPolicy(final FSNamesystem fsn, final String srcArg, final String ecPolicyName, final FSPermissionChecker pc, final boolean logRetryCache) throws IOException, AccessControlException { assert fsn.hasWriteLock(RwLockMode.FS); String src = srcArg; FSDirectory fsd = fsn.getFSDirectory(); final INodesInPath iip; List<XAttr> xAttrs; fsd.writeLock(); try { ErasureCodingPolicy ecPolicy = getEnabledErasureCodingPolicyByName(fsn, ecPolicyName); iip = fsd.resolvePath(pc, src, DirOp.WRITE_LINK); // Write access is required to set erasure coding policy if (fsd.isPermissionEnabled()) { fsd.checkPathAccess(pc, iip, FsAction.WRITE); } src = iip.getPath(); xAttrs = setErasureCodingPolicyXAttr(fsn, iip, ecPolicy); } finally { fsd.writeUnlock(); } fsn.getEditLog().logSetXAttrs(src, xAttrs, logRetryCache); return fsd.getAuditFileInfo(iip); } private static List<XAttr> setErasureCodingPolicyXAttr(final FSNamesystem fsn, final INodesInPath srcIIP, ErasureCodingPolicy ecPolicy) throws IOException { FSDirectory fsd = fsn.getFSDirectory(); assert fsd.hasWriteLock(); Preconditions.checkNotNull(srcIIP, "INodes cannot be null"); Preconditions.checkNotNull(ecPolicy, "EC policy cannot be null"); String src = srcIIP.getPath(); final INode inode = srcIIP.getLastINode(); if (inode == null) { throw new FileNotFoundException("Path not found: " + srcIIP.getPath()); } if (!inode.isDirectory()) { throw new IOException("Attempt to set an erasure coding policy " + "for a file " + src); } final XAttr ecXAttr; DataOutputStream dOut = null; try { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); dOut = new DataOutputStream(bOut); WritableUtils.writeString(dOut, ecPolicy.getName()); ecXAttr = XAttrHelper.buildXAttr(XATTR_ERASURECODING_POLICY, bOut.toByteArray()); } finally { IOUtils.closeStream(dOut); } // check whether the directory already has an erasure coding policy // directly on itself. final Boolean hasEcXAttr = getErasureCodingPolicyXAttrForINode(fsn, inode) == null ? false : true; final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1); xattrs.add(ecXAttr); final EnumSet<XAttrSetFlag> flag = hasEcXAttr ? EnumSet.of(XAttrSetFlag.REPLACE) : EnumSet.of(XAttrSetFlag.CREATE); FSDirXAttrOp.unprotectedSetXAttrs(fsd, srcIIP, xattrs, flag); return xattrs; } /** * Unset erasure coding policy from the given directory. * * @param fsn The namespace * @param srcArg The path of the target directory. * @param logRetryCache whether to record RPC ids in editlog for retry * cache rebuilding * @return {@link FileStatus} * @throws IOException * @throws AccessControlException if the user does not have write access */ static FileStatus unsetErasureCodingPolicy(final FSNamesystem fsn, final String srcArg, final FSPermissionChecker pc, final boolean logRetryCache) throws IOException { assert fsn.hasWriteLock(RwLockMode.FS); String src = srcArg; FSDirectory fsd = fsn.getFSDirectory(); final INodesInPath iip; List<XAttr> xAttrs; fsd.writeLock(); try { iip = fsd.resolvePath(pc, src, DirOp.WRITE_LINK); // Write access is required to unset erasure coding policy if (fsd.isPermissionEnabled()) { fsd.checkPathAccess(pc, iip, FsAction.WRITE); } src = iip.getPath(); xAttrs = removeErasureCodingPolicyXAttr(fsn, iip); } finally { fsd.writeUnlock(); } if (xAttrs != null) { fsn.getEditLog().logRemoveXAttrs(src, xAttrs, logRetryCache); } else { throw new NoECPolicySetException( "No erasure coding policy explicitly set on " + src); } return fsd.getAuditFileInfo(iip); } /** * Add an erasure coding policy. * * @param fsn namespace * @param policy the new policy to be added into system * @param logRetryCache whether to record RPC ids in editlog for retry cache * rebuilding * @throws IOException */ static ErasureCodingPolicy addErasureCodingPolicy(final FSNamesystem fsn, ErasureCodingPolicy policy, final boolean logRetryCache) { Preconditions.checkNotNull(policy); ErasureCodingPolicy retPolicy = fsn.getErasureCodingPolicyManager().addPolicy(policy); fsn.getEditLog().logAddErasureCodingPolicy(policy, logRetryCache); return retPolicy; } /** * Remove an erasure coding policy. * * @param fsn namespace * @param ecPolicyName the name of the policy to be removed * @param logRetryCache whether to record RPC ids in editlog for retry cache * rebuilding * @throws IOException */ static void removeErasureCodingPolicy(final FSNamesystem fsn, String ecPolicyName, final boolean logRetryCache) throws IOException { Preconditions.checkNotNull(ecPolicyName); fsn.getErasureCodingPolicyManager().removePolicy(ecPolicyName); fsn.getEditLog().logRemoveErasureCodingPolicy(ecPolicyName, logRetryCache); } /** * Enable an erasure coding policy. * * @param fsn namespace * @param ecPolicyName the name of the policy to be enabled * @param logRetryCache whether to record RPC ids in editlog for retry cache * rebuilding * @throws IOException */ static boolean enableErasureCodingPolicy(final FSNamesystem fsn, String ecPolicyName, final boolean logRetryCache) throws IOException { Preconditions.checkNotNull(ecPolicyName); boolean success = fsn.getErasureCodingPolicyManager().enablePolicy(ecPolicyName); if (success) { fsn.getEditLog().logEnableErasureCodingPolicy(ecPolicyName, logRetryCache); } return success; } /** * Disable an erasure coding policy. * * @param fsn namespace * @param ecPolicyName the name of the policy to be disabled * @param logRetryCache whether to record RPC ids in editlog for retry cache * rebuilding * @throws IOException */ static boolean disableErasureCodingPolicy(final FSNamesystem fsn, String ecPolicyName, final boolean logRetryCache) throws IOException { Preconditions.checkNotNull(ecPolicyName); boolean success = fsn.getErasureCodingPolicyManager().disablePolicy(ecPolicyName); if (success) { fsn.getEditLog().logDisableErasureCodingPolicy(ecPolicyName, logRetryCache); } return success; } private static List<XAttr> removeErasureCodingPolicyXAttr( final FSNamesystem fsn, final INodesInPath srcIIP) throws IOException { FSDirectory fsd = fsn.getFSDirectory(); assert fsd.hasWriteLock(); Preconditions.checkNotNull(srcIIP, "INodes cannot be null"); String src = srcIIP.getPath(); final INode inode = srcIIP.getLastINode(); if (inode == null) { throw new FileNotFoundException("Path not found: " + srcIIP.getPath()); } if (!inode.isDirectory()) { throw new IOException("Cannot unset an erasure coding policy " + "on a file " + src); } // Check whether the directory has a specific erasure coding policy // directly on itself. final XAttr ecXAttr = getErasureCodingPolicyXAttrForINode(fsn, inode); if (ecXAttr == null) { return null; } final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1); xattrs.add(ecXAttr); return FSDirXAttrOp.unprotectedRemoveXAttrs(fsd, srcIIP, xattrs); } /** * Get the erasure coding policy information for specified path. * * @param fsn namespace * @param src path * @return {@link ErasureCodingPolicy}, or null if no policy has * been set or the policy is REPLICATION * @throws IOException * @throws FileNotFoundException if the path does not exist. * @throws AccessControlException if no read access */ static ErasureCodingPolicy getErasureCodingPolicy(final FSNamesystem fsn, final String src, FSPermissionChecker pc) throws IOException, AccessControlException { assert fsn.hasReadLock(RwLockMode.FS); if (FSDirectory.isExactReservedName(src)) { return null; } FSDirectory fsd = fsn.getFSDirectory(); final INodesInPath iip = fsd.resolvePath(pc, src, DirOp.READ); if (fsn.isPermissionEnabled()) { fsn.getFSDirectory().checkPathAccess(pc, iip, FsAction.READ); } ErasureCodingPolicy ecPolicy; if (iip.isDotSnapshotDir()) { ecPolicy = null; } else if (iip.getLastINode() == null) { throw new FileNotFoundException("Path not found: " + src); } else { ecPolicy = getErasureCodingPolicyForPath(fsd, iip); } if (ecPolicy != null && ecPolicy.isReplicationPolicy()) { ecPolicy = null; } return ecPolicy; } /** * Get the erasure coding policy information for specified path and policy * name. If ec policy name is given, it will be parsed and the corresponding * policy will be returned. Otherwise, get the policy from the parents of the * iip. * * @param fsn namespace * @param ecPolicyName the ec policy name * @param iip inodes in the path containing the file * @return {@link ErasureCodingPolicy}, or null if no policy is found * @throws IOException */ static ErasureCodingPolicy getErasureCodingPolicy(FSNamesystem fsn, String ecPolicyName, INodesInPath iip) throws IOException { ErasureCodingPolicy ecPolicy; if (!StringUtils.isEmpty(ecPolicyName)) { ecPolicy = FSDirErasureCodingOp.getEnabledErasureCodingPolicyByName( fsn, ecPolicyName); } else { ecPolicy = FSDirErasureCodingOp.unprotectedGetErasureCodingPolicy( fsn, iip); } return ecPolicy; } /** * Get the erasure coding policy, including the REPLICATION policy. This does * not do any permission checking. * * @param fsn namespace * @param iip inodes in the path containing the file * @return {@link ErasureCodingPolicy} * @throws IOException */ static ErasureCodingPolicy unprotectedGetErasureCodingPolicy( final FSNamesystem fsn, final INodesInPath iip) throws IOException { assert fsn.hasReadLock(RwLockMode.FS); return getErasureCodingPolicyForPath(fsn.getFSDirectory(), iip); } /** * Get available erasure coding polices. * * @param fsn namespace * @return {@link ErasureCodingPolicyInfo} array */ static ErasureCodingPolicyInfo[] getErasureCodingPolicies( final FSNamesystem fsn) throws IOException { assert fsn.hasReadLock(RwLockMode.FS); return fsn.getErasureCodingPolicyManager().getPolicies(); } /** * Get available erasure coding codecs and coders. * * @param fsn namespace * @return {@link java.util.HashMap} array */ static Map<String, String> getErasureCodingCodecs(final FSNamesystem fsn) throws IOException { assert fsn.hasReadLock(RwLockMode.FS); return CodecRegistry.getInstance().getCodec2CoderCompactMap(); } //return erasure coding policy for path, including REPLICATION policy private static ErasureCodingPolicy getErasureCodingPolicyForPath( FSDirectory fsd, INodesInPath iip) throws IOException { Preconditions.checkNotNull(iip, "INodes cannot be null"); fsd.readLock(); try { for (int i = iip.length() - 1; i >= 0; i--) { final INode inode = iip.getINode(i); if (inode == null) { continue; } if (inode.isFile()) { byte id = inode.asFile().getErasureCodingPolicyID(); return id < 0 ? null : fsd.getFSNamesystem().getErasureCodingPolicyManager().getByID(id); } // We don't allow setting EC policies on paths with a symlink. Thus // if a symlink is encountered, the dir shouldn't have EC policy. // TODO: properly support symlinks if (inode.isSymlink()) { return null; } final XAttrFeature xaf = inode.getXAttrFeature(iip.getPathSnapshotId()); if (xaf != null) { XAttr xattr = xaf.getXAttr(XATTR_ERASURECODING_POLICY); if (xattr != null) { ByteArrayInputStream bIn = new ByteArrayInputStream(xattr.getValue()); DataInputStream dIn = new DataInputStream(bIn); String ecPolicyName = WritableUtils.readString(dIn); return fsd.getFSNamesystem().getErasureCodingPolicyManager() .getByName(ecPolicyName); } } } } finally { fsd.readUnlock(); } return null; } private static XAttr getErasureCodingPolicyXAttrForINode( FSNamesystem fsn, INode inode) throws IOException { // INode can be null if (inode == null) { return null; } FSDirectory fsd = fsn.getFSDirectory(); fsd.readLock(); try { // We don't allow setting EC policies on paths with a symlink. Thus // if a symlink is encountered, the dir shouldn't have EC policy. // TODO: properly support symlinks if (inode.isSymlink()) { return null; } final XAttrFeature xaf = inode.getXAttrFeature(); if (xaf != null) { XAttr xattr = xaf.getXAttr(XATTR_ERASURECODING_POLICY); if (xattr != null) { return xattr; } } } finally { fsd.readUnlock(); } return null; } }
FSDirErasureCodingOp
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/classrealm/DefaultClassRealmManager.java
{ "start": 2033, "end": 2122 }
class ____ be changed or deleted * without prior notice. * */ @Named @Singleton public
can
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/validation/ComponentValidator.java
{ "start": 7686, "end": 9156 }
interface ____ the rest of the checks since // the remaining checks will likely just output unhelpful noise in such cases. return report.addError(invalidTypeError(), component).build(); } superficialValidation.validateTypeOf(component); validateUseOfCancellationPolicy(); validateIsAbstractType(); validateCreators(); validateNoReusableAnnotation(); validateComponentMethods(); validateNoConflictingEntryPoints(); validateSubcomponentReferences(); validateComponentDependencies(); validateReferencedModules(); validateSubcomponents(); return report.build(); } private String moreThanOneComponentAnnotationError() { return String.format( "Components may not be annotated with more than one component annotation: found %s", annotationsFor(componentKinds)); } private void validateUseOfCancellationPolicy() { if (component.hasAnnotation(XTypeNames.CANCELLATION_POLICY) && !componentKind().isProducer()) { report.addError( "@CancellationPolicy may only be applied to production components and subcomponents", component); } } private void validateIsAbstractType() { if (!component.isAbstract()) { report.addError(invalidTypeError(), component); } } private String invalidTypeError() { return String.format( "@%s may only be applied to an
skip
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/mixins/TestMixinInheritance.java
{ "start": 1021, "end": 2292 }
class ____ extends BeanoMixinSuper2 { @Override @JsonProperty("id") public abstract int getIdo(); } /* /********************************************************** /* Unit tests /********************************************************** */ @Test public void testMixinFieldInheritance() throws IOException { ObjectMapper mapper = jsonMapperBuilder() .addMixIn(Beano.class, BeanoMixinSub.class) .build(); Map<String,Object> result; result = writeAndMap(mapper, new Beano()); assertEquals(2, result.size()); if (!result.containsKey("id") || !result.containsKey("name")) { fail("Should have both 'id' and 'name', but content = "+result); } } @Test public void testMixinMethodInheritance() throws IOException { ObjectMapper mapper = jsonMapperBuilder() .addMixIn(Beano2.class, BeanoMixinSub2.class) .build(); Map<String,Object> result; result = writeAndMap(mapper, new Beano2()); assertEquals(2, result.size()); assertTrue(result.containsKey("id")); assertTrue(result.containsKey("name")); } }
BeanoMixinSub2
java
apache__camel
components/camel-disruptor/src/test/java/org/apache/camel/component/disruptor/DisruptorConcurrentConsumersNPEIssueTest.java
{ "start": 1267, "end": 3377 }
class ____ extends CamelTestSupport { @Test void testSendToDisruptor() throws Exception { final MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); template.sendBody("disruptor:foo", "Hello World"); MockEndpoint.assertIsSatisfied(context); RouteController routeController = context.getRouteController(); Exception ex = assertThrows(FailedToStartRouteException.class, () -> routeController.startRoute("first")); assertEquals("Failed to start route: first because: Multiple consumers for the same endpoint is not " + "allowed: disruptor://foo?concurrentConsumers=5", ex.getMessage()); } @Test void testStartThird() throws Exception { final MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World"); template.sendBody("disruptor:foo", "Hello World"); MockEndpoint.assertIsSatisfied(context); // this should be okay context.getRouteController().startRoute("third"); RouteController routeController = context.getRouteController(); Exception ex = assertThrows(FailedToStartRouteException.class, () -> routeController.startRoute("first")); assertEquals("Failed to start route: first because: Multiple consumers for the same endpoint is not allowed:" + " disruptor://foo?concurrentConsumers=5", ex.getMessage()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("disruptor:foo?concurrentConsumers=5").routeId("first").noAutoStartup() .to("mock:result"); from("disruptor:foo?concurrentConsumers=5").routeId("second").to("mock:result"); from("direct:foo").routeId("third").noAutoStartup().to("mock:result"); } }; } }
DisruptorConcurrentConsumersNPEIssueTest
java
apache__rocketmq
common/src/test/java/org/apache/rocketmq/common/CountDownLatch2Test.java
{ "start": 1257, "end": 3851 }
class ____ { /** * test constructor with invalid init param * * @see CountDownLatch2#CountDownLatch2(int) */ @Test public void testConstructorError() { int count = -1; try { CountDownLatch2 latch = new CountDownLatch2(count); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("count < 0")); } } /** * test constructor with valid init param * * @see CountDownLatch2#CountDownLatch2(int) */ @Test public void testConstructor() { int count = 10; CountDownLatch2 latch = new CountDownLatch2(count); assertEquals("Expected equal", count, latch.getCount()); assertThat("Expected contain", latch.toString(), containsString("[Count = " + count + "]")); } /** * test await timeout * * @see CountDownLatch2#await(long, TimeUnit) */ @Test public void testAwaitTimeout() throws InterruptedException { int count = 1; CountDownLatch2 latch = new CountDownLatch2(count); boolean await = latch.await(10, TimeUnit.MILLISECONDS); assertFalse("Expected false", await); latch.countDown(); boolean await2 = latch.await(10, TimeUnit.MILLISECONDS); assertTrue("Expected true", await2); } /** * test reset * * @see CountDownLatch2#countDown() */ @Test(timeout = 1000) public void testCountDownAndGetCount() throws InterruptedException { int count = 2; CountDownLatch2 latch = new CountDownLatch2(count); assertEquals("Expected equal", count, latch.getCount()); latch.countDown(); assertEquals("Expected equal", count - 1, latch.getCount()); latch.countDown(); latch.await(); assertEquals("Expected equal", 0, latch.getCount()); } /** * test reset * * @see CountDownLatch2#reset() */ @Test public void testReset() throws InterruptedException { int count = 2; CountDownLatch2 latch = new CountDownLatch2(count); latch.countDown(); assertEquals("Expected equal", count - 1, latch.getCount()); latch.reset(); assertEquals("Expected equal", count, latch.getCount()); latch.countDown(); latch.countDown(); latch.await(); assertEquals("Expected equal", 0, latch.getCount()); // coverage Sync#tryReleaseShared, c==0 latch.countDown(); assertEquals("Expected equal", 0, latch.getCount()); } }
CountDownLatch2Test
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/dataview/DataViewUtils.java
{ "start": 2740, "end": 7532 }
class ____ { /** Returns whether the given {@link LogicalType} qualifies as a {@link DataView}. */ public static boolean isDataView(LogicalType viewType, Class<? extends DataView> viewClass) { final boolean isDataView = viewType.is(STRUCTURED_TYPE) && ((StructuredType) viewType) .getImplementationClass() .map(viewClass::isAssignableFrom) .orElse(false); if (!isDataView) { return false; } viewType.getChildren().forEach(DataViewUtils::checkForInvalidDataViews); return true; } /** Checks that the given type and its children do not contain data views. */ public static void checkForInvalidDataViews(LogicalType type) { if (hasNested(type, t -> isDataView(t, DataView.class))) { throw new ValidationException( "Data views are not supported at the declared location. Given type: " + type); } } /** Searches for data views in the data type of an accumulator and extracts them. */ public static List<DataViewSpec> extractDataViews(int aggIndex, DataType accumulatorDataType) { final LogicalType accumulatorType = accumulatorDataType.getLogicalType(); if (!accumulatorType.is(ROW) && !accumulatorType.is(STRUCTURED_TYPE)) { return Collections.emptyList(); } final List<String> fieldNames = getFieldNames(accumulatorType); final List<DataType> fieldDataTypes = accumulatorDataType.getChildren(); final List<DataViewSpec> specs = new ArrayList<>(); for (int fieldIndex = 0; fieldIndex < fieldDataTypes.size(); fieldIndex++) { final DataType fieldDataType = fieldDataTypes.get(fieldIndex); final LogicalType fieldType = fieldDataType.getLogicalType(); if (isDataView(fieldType, ListView.class)) { specs.add( new ListViewSpec( createStateId(aggIndex, fieldNames.get(fieldIndex)), fieldIndex, fieldDataType.getChildren().get(0))); } else if (isDataView(fieldType, MapView.class)) { specs.add( new MapViewSpec( createStateId(aggIndex, fieldNames.get(fieldIndex)), fieldIndex, fieldDataType.getChildren().get(0), false)); } } return specs; } /** * Modifies the data type of an accumulator regarding data views. * * <p>For performance reasons, each data view is wrapped into a RAW type which gives it {@link * LazyBinaryFormat} semantics and avoids multiple deserialization steps during access. * Furthermore, a data view will not be serialized if a state backend is used (the serializer of * the RAW type will be a {@link NullSerializer} in this case). */ public static DataType adjustDataViews( DataType accumulatorDataType, boolean hasStateBackedDataViews) { final Function<DataType, TypeSerializer<?>> serializer; if (hasStateBackedDataViews) { serializer = dataType -> NullSerializer.INSTANCE; } else { serializer = ExternalSerializer::of; } return DataTypeUtils.transform( accumulatorDataType, new DataViewsTransformation(serializer)); } /** Creates a special {@link DataType} for DISTINCT aggregates. */ public static DataType createDistinctViewDataType( DataType keyDataType, int filterArgs, int filterArgsLimit) { final DataType valueDataType; if (filterArgs <= filterArgsLimit) { valueDataType = DataTypes.BIGINT().notNull(); } else { valueDataType = DataTypes.ARRAY(DataTypes.BIGINT().notNull()).bridgedTo(long[].class); } return MapView.newMapViewDataType(keyDataType, valueDataType); } /** Creates a special {@link DistinctViewSpec} for DISTINCT aggregates. */ public static DistinctViewSpec createDistinctViewSpec( int index, DataType distinctViewDataType) { return new DistinctViewSpec("distinctAcc_" + index, distinctViewDataType); } // -------------------------------------------------------------------------------------------- private static String createStateId(int fieldIndex, String fieldName) { return "agg" + fieldIndex + "$" + fieldName; } // -------------------------------------------------------------------------------------------- private static
DataViewUtils
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/nullness/NullablePrimitiveArray.java
{ "start": 2620, "end": 5986 }
class ____ extends BugChecker implements VariableTreeMatcher, MethodTreeMatcher { @Override public Description matchMethod(MethodTree tree, VisitorState state) { return check(tree.getReturnType(), tree.getModifiers().getAnnotations(), state); } @Override public Description matchVariable(VariableTree tree, VisitorState state) { return check(tree.getType(), tree.getModifiers().getAnnotations(), state); } // other cases of `@Nullable int[]` are covered by the existing NullablePrimitive private Description check( Tree typeTree, List<? extends AnnotationTree> allTreeAnnos, VisitorState state) { Type type = getType(typeTree); if (type == null) { return NO_MATCH; } if (!type.getKind().equals(TypeKind.ARRAY)) { return NO_MATCH; } while (type.getKind().equals(TypeKind.ARRAY)) { type = state.getTypes().elemtype(type); } if (!type.isPrimitive()) { return NO_MATCH; } ImmutableList<AnnotationTree> treeNullnessAnnos = NullnessAnnotations.annotationsRelevantToNullness(allTreeAnnos); if (treeNullnessAnnos.isEmpty()) { return NO_MATCH; } Symbol target = state.getSymtab().annotationTargetType.tsym; ImmutableList<AnnotationTree> typeNullnessAnnos = treeNullnessAnnos.stream() .filter(annotation -> isTypeAnnotation(getSymbol(annotation).attribute(target))) .collect(toImmutableList()); if (typeNullnessAnnos.isEmpty()) { return NO_MATCH; } Tree dims = typeTree; while (dims instanceof ArrayTypeTree) { dims = ((ArrayTypeTree) dims).getType(); } SuggestedFix.Builder fix = SuggestedFix.builder(); typeNullnessAnnos.forEach(fix::delete); boolean hasDeclarationNullnessAnno = typeNullnessAnnos.size() < treeNullnessAnnos.size(); boolean hasTypeNullnessAnnoOnArray = dims instanceof AnnotatedTypeTree annotatedTypeTree && !NullnessAnnotations.annotationsRelevantToNullness( annotatedTypeTree.getAnnotations()) .isEmpty(); if (!hasDeclarationNullnessAnno && !hasTypeNullnessAnnoOnArray) { fix.postfixWith( dims, typeNullnessAnnos.stream().map(state::getSourceForNode).collect(joining(" ", " ", " "))); } return describeMatch(typeNullnessAnnos.getFirst(), fix.build()); } private static boolean isTypeAnnotation(Attribute.Compound attribute) { if (attribute == null) { return false; } Set<String> targets = new HashSet<>(); Optional<Attribute> value = MoreAnnotations.getValue(attribute, "value"); if (value.isEmpty()) { return false; } new SimpleAnnotationValueVisitor8<Void, Void>() { @Override public Void visitEnumConstant(VariableElement c, Void unused) { targets.add(c.getSimpleName().toString()); return null; } @Override public Void visitArray(List<? extends AnnotationValue> list, Void unused) { list.forEach(x -> x.accept(this, null)); return null; } }.visit(value.get(), null); for (String target : targets) { switch (target) { case "METHOD", "FIELD", "LOCAL_VARIABLE", "PARAMETER" -> { return false; } default -> {} } } return targets.contains("TYPE_USE"); } }
NullablePrimitiveArray
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/filter/ManyToManyWithDynamicFilterTest.java
{ "start": 1383, "end": 2592 }
class ____ { @BeforeEach void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { final Role r1 = new Role( 1, "R1", false ); final Role r2 = new Role( 2, "R2", false ); session.persist( r1 ); session.persist( r2 ); final User user = new User( 1, "A", true, r1, r2 ); session.persist( user ); } ); } @AfterEach void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test @JiraKey(value = "HHH-11410") void testManyToManyCollectionWithActiveFilterOnJoin(SessionFactoryScope scope) { scope.inTransaction( session -> { session.enableFilter( "activeUserFilter" ); session.enableFilter( "activeRoleFilter" ); final User user = session.find( User.class, 1 ); assertNotNull( user ); assertTrue( user.getRoles().isEmpty() ); } ); } @Test @JiraKey(value = "HHH-11410") void testManyToManyCollectionWithNoFilterOnJoin(SessionFactoryScope scope) { scope.inTransaction( session -> { final User user = session.find( User.class, 1 ); assertNotNull( user ); assertThat( user.getRoles().size(), is( 2 ) ); } ); } @MappedSuperclass public static abstract
ManyToManyWithDynamicFilterTest
java
google__error-prone
check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java
{ "start": 23286, "end": 24014 }
class ____<R, P> extends TreePathScanner<R, P> { protected final VisitorState state; public SuppressibleTreePathScanner(VisitorState state) { this.state = state; } @Override public R scan(Tree tree, P param) { return suppressed(tree) ? null : super.scan(tree, param); } @Override public R scan(TreePath treePath, P param) { return suppressed(treePath.getLeaf()) ? null : super.scan(treePath, param); } private boolean suppressed(Tree tree) { boolean isSuppressible = tree instanceof ClassTree || tree instanceof MethodTree || tree instanceof VariableTree; return isSuppressible && isSuppressed(tree, state); } } }
SuppressibleTreePathScanner
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/contextual/ContextualSerializationTest.java
{ "start": 2524, "end": 2825 }
class ____ { @Prefix("list->") public final List<String> beans = new ArrayList<String>(); public ContextualListBean(String... strings) { for (String string : strings) { beans.add(string); } } } static
ContextualListBean
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/Television.java
{ "start": 542, "end": 1352 }
class ____ extends VideoSystem { private Integer id; private RemoteControl control; private String name; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @OneToOne(cascade = CascadeType.ALL) public RemoteControl getControl() { return control; } public void setControl(RemoteControl control) { this.control = control; } public String getName() { return name; } public void setName(String name) { this.name = name; } @PreUpdate public void isLast() { if ( isLast ) throw new IllegalStateException(); isFirst = false; isLast = true; communication++; } @PrePersist public void prepareEntity() { //override a super method annotated with the same // event for it not to be called counter++; } }
Television
java
apache__camel
components/camel-quickfix/src/main/java/org/apache/camel/component/quickfixj/QuickfixjEngine.java
{ "start": 17873, "end": 21551 }
class ____ implements Application { @Override public void fromAdmin(Message message, SessionID sessionID) throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, RejectLogon { try { dispatch(QuickfixjEventCategory.AdminMessageReceived, sessionID, message); } catch (RuntimeException e) { throw e; } catch (Exception e) { rethrowIfType(e, FieldNotFound.class); rethrowIfType(e, IncorrectDataFormat.class); rethrowIfType(e, IncorrectTagValue.class); rethrowIfType(e, RejectLogon.class); throw new DispatcherException(e); } } @Override public void fromApp(Message message, SessionID sessionID) throws FieldNotFound, IncorrectDataFormat, IncorrectTagValue, UnsupportedMessageType { try { dispatch(QuickfixjEventCategory.AppMessageReceived, sessionID, message); } catch (RuntimeException e) { throw e; } catch (Exception e) { rethrowIfType(e, FieldNotFound.class); rethrowIfType(e, IncorrectDataFormat.class); rethrowIfType(e, IncorrectTagValue.class); rethrowIfType(e, UnsupportedMessageType.class); throw new DispatcherException(e); } } @Override public void onCreate(SessionID sessionID) { try { dispatch(QuickfixjEventCategory.SessionCreated, sessionID, null); } catch (Exception e) { throw new DispatcherException(e); } } @Override public void onLogon(SessionID sessionID) { try { dispatch(QuickfixjEventCategory.SessionLogon, sessionID, null); } catch (Exception e) { throw new DispatcherException(e); } } @Override public void onLogout(SessionID sessionID) { try { dispatch(QuickfixjEventCategory.SessionLogoff, sessionID, null); } catch (Exception e) { throw new DispatcherException(e); } } @Override public void toAdmin(Message message, SessionID sessionID) { try { dispatch(QuickfixjEventCategory.AdminMessageSent, sessionID, message); } catch (Exception e) { throw new DispatcherException(e); } } @Override public void toApp(Message message, SessionID sessionID) throws DoNotSend { try { dispatch(QuickfixjEventCategory.AppMessageSent, sessionID, message); } catch (Exception e) { throw new DispatcherException(e); } } private <T extends Exception> void rethrowIfType(Exception e, Class<T> exceptionClass) throws T { if (e.getClass() == exceptionClass) { throw exceptionClass.cast(e); } } private void dispatch(QuickfixjEventCategory quickfixjEventCategory, SessionID sessionID, Message message) throws Exception { LOG.debug("FIX event dispatched: {} {}", quickfixjEventCategory, message != null ? message : ""); for (QuickfixjEventListener listener : eventListeners) { // Exceptions propagate back to the FIX engine so sequence numbers can be adjusted listener.onEvent(quickfixjEventCategory, sessionID, message); } } private
Dispatcher
java
spring-projects__spring-framework
spring-messaging/src/test/java/org/springframework/messaging/support/ErrorMessageTests.java
{ "start": 816, "end": 1258 }
class ____ { @Test void testToString() { ErrorMessage em = new ErrorMessage(new RuntimeException("foo")); String emString = em.toString(); assertThat(emString).doesNotContain("original"); em = new ErrorMessage(new RuntimeException("foo"), new GenericMessage<>("bar")); emString = em.toString(); assertThat(emString).contains("original"); assertThat(emString).contains(em.getOriginalMessage().toString()); } }
ErrorMessageTests
java
spring-projects__spring-boot
module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/autoconfigure/FileWatchingFailureHandler.java
{ "start": 2122, "end": 2376 }
class ____ implements FileChangeListener { private final CountDownLatch latch; Listener(CountDownLatch latch) { this.latch = latch; } @Override public void onChange(Set<ChangedFiles> changeSet) { this.latch.countDown(); } } }
Listener
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/blob/BlobServerDeleteTest.java
{ "start": 2374, "end": 16111 }
class ____ { private final Random rnd = new Random(); @TempDir private Path tempDir; @Test void testDeleteTransient1() throws IOException { testDeleteBlob(null, new JobID(), TRANSIENT_BLOB); } @Test void testDeleteTransient2() throws IOException { testDeleteBlob(new JobID(), null, TRANSIENT_BLOB); } @Test void testDeleteTransient3() throws IOException { testDeleteBlob(null, null, TRANSIENT_BLOB); } @Test void testDeleteTransient4() throws IOException { testDeleteBlob(new JobID(), new JobID(), TRANSIENT_BLOB); } @Test void testDeleteTransient5() throws IOException { JobID jobId = new JobID(); testDeleteBlob(jobId, jobId, TRANSIENT_BLOB); } @Test void testDeletePermanent() throws IOException { testDeleteBlob(new JobID(), new JobID(), PERMANENT_BLOB); } /** * Uploads a (different) byte array for each of the given jobs and verifies that deleting one of * them (via the {@link BlobServer}) does not influence the other. * * @param jobId1 first job id * @param jobId2 second job id */ private void testDeleteBlob( @Nullable JobID jobId1, @Nullable JobID jobId2, BlobKey.BlobType blobType) throws IOException { try (BlobServer server = TestingBlobUtils.createServer(tempDir)) { server.start(); byte[] data = new byte[2000000]; rnd.nextBytes(data); byte[] data2 = Arrays.copyOf(data, data.length); data2[0] ^= 1; // put first BLOB BlobKey key1 = put(server, jobId1, data, blobType); assertThat(key1).isNotNull(); // put two more BLOBs (same key, other key) for another job ID BlobKey key2a = put(server, jobId2, data, blobType); assertThat(key2a).isNotNull(); verifyKeyDifferentHashEquals(key1, key2a); BlobKey key2b = put(server, jobId2, data2, blobType); assertThat(key2b).isNotNull(); // issue a DELETE request assertThat(delete(server, jobId1, key1, blobType)).isTrue(); verifyDeleted(server, jobId1, key1); // deleting a one BLOB should not affect another BLOB with a different key // (and keys are always different now) verifyContents(server, jobId2, key2a, data); verifyContents(server, jobId2, key2b, data2); // delete first file of second job assertThat(delete(server, jobId2, key2a, blobType)).isTrue(); verifyDeleted(server, jobId2, key2a); verifyContents(server, jobId2, key2b, data2); // delete second file of second job assertThat(delete(server, jobId2, key2b, blobType)).isTrue(); verifyDeleted(server, jobId2, key2b); } } @Test void testDeleteTransientAlreadyDeletedNoJob() throws IOException { testDeleteBlobAlreadyDeleted(null, TRANSIENT_BLOB); } @Test void testDeleteTransientAlreadyDeletedForJob() throws IOException { testDeleteBlobAlreadyDeleted(new JobID(), TRANSIENT_BLOB); } @Test void testDeletePermanentAlreadyDeletedForJob() throws IOException { testDeleteBlobAlreadyDeleted(new JobID(), PERMANENT_BLOB); } /** * Uploads a byte array for the given job and verifies that deleting it (via the {@link * BlobServer}) does not fail independent of whether the file exists. * * @param jobId job id */ private void testDeleteBlobAlreadyDeleted( @Nullable final JobID jobId, BlobKey.BlobType blobType) throws IOException { try (BlobServer server = TestingBlobUtils.createServer(tempDir)) { server.start(); byte[] data = new byte[2000000]; rnd.nextBytes(data); // put BLOB BlobKey key = put(server, jobId, data, blobType); assertThat(key).isNotNull(); File blobFile = server.getStorageLocation(jobId, key); assertThat(blobFile.delete()).isTrue(); // DELETE operation should not fail if file is already deleted assertThat(delete(server, jobId, key, blobType)).isTrue(); verifyDeleted(server, jobId, key); // one more delete call that should not fail assertThat(delete(server, jobId, key, blobType)).isTrue(); verifyDeleted(server, jobId, key); } } @Tag("org.apache.flink.testutils.junit.FailsInGHAContainerWithRootUser") @Test void testDeleteTransientFailsNoJob() throws IOException { testDeleteBlobFails(null, TRANSIENT_BLOB); } @Tag("org.apache.flink.testutils.junit.FailsInGHAContainerWithRootUser") @Test void testDeleteTransientFailsForJob() throws IOException { testDeleteBlobFails(new JobID(), TRANSIENT_BLOB); } @Tag("org.apache.flink.testutils.junit.FailsInGHAContainerWithRootUser") @Test void testDeletePermanentFailsForJob() throws IOException { testDeleteBlobFails(new JobID(), PERMANENT_BLOB); } /** * Uploads a byte array for the given job and verifies that a delete operation (via the {@link * BlobServer}) does not fail even if the file is not deletable, e.g. via restricting the * permissions. * * @param jobId job id */ private void testDeleteBlobFails(@Nullable final JobID jobId, BlobKey.BlobType blobType) throws IOException { assumeThat(OperatingSystem.isWindows()).as("setWritable doesn't work on Windows").isFalse(); File blobFile = null; File directory = null; try (BlobServer server = TestingBlobUtils.createServer(tempDir)) { server.start(); try { byte[] data = new byte[2000000]; rnd.nextBytes(data); // put BLOB BlobKey key = put(server, jobId, data, blobType); assertThat(key).isNotNull(); blobFile = server.getStorageLocation(jobId, key); directory = blobFile.getParentFile(); assertThat(blobFile.setWritable(false, false)).isTrue(); assertThat(directory.setWritable(false, false)).isTrue(); // issue a DELETE request assertThat(delete(server, jobId, key, blobType)).isFalse(); // the file should still be there verifyContents(server, jobId, key, data); } finally { if (blobFile != null && directory != null) { //noinspection ResultOfMethodCallIgnored blobFile.setWritable(true, false); //noinspection ResultOfMethodCallIgnored directory.setWritable(true, false); } } } } @Test void testJobCleanup() throws IOException { testJobCleanup(TRANSIENT_BLOB); } @Test void testJobCleanupHa() throws IOException { testJobCleanup(PERMANENT_BLOB); } /** * Tests that {@link BlobServer} cleans up after calling {@link * BlobServer#globalCleanupAsync(JobID, Executor)}. * * @param blobType whether the BLOB should become permanent or transient */ private void testJobCleanup(BlobKey.BlobType blobType) throws IOException { JobID jobId1 = new JobID(); JobID jobId2 = new JobID(); final ExecutorService executorService = Executors.newSingleThreadExecutor(); try (BlobServer server = TestingBlobUtils.createServer(tempDir)) { server.start(); final byte[] data = new byte[128]; byte[] data2 = Arrays.copyOf(data, data.length); data2[0] ^= 1; BlobKey key1a = put(server, jobId1, data, blobType); BlobKey key2 = put(server, jobId2, data, blobType); assertThat(key1a.getHash()).isEqualTo(key2.getHash()); BlobKey key1b = put(server, jobId1, data2, blobType); verifyContents(server, jobId1, key1a, data); verifyContents(server, jobId1, key1b, data2); checkFileCountForJob(2, jobId1, server); verifyContents(server, jobId2, key2, data); checkFileCountForJob(1, jobId2, server); server.globalCleanupAsync(jobId1, executorService).join(); verifyDeleted(server, jobId1, key1a); verifyDeleted(server, jobId1, key1b); checkFileCountForJob(0, jobId1, server); verifyContents(server, jobId2, key2, data); checkFileCountForJob(1, jobId2, server); server.globalCleanupAsync(jobId2, executorService).join(); checkFileCountForJob(0, jobId1, server); verifyDeleted(server, jobId2, key2); checkFileCountForJob(0, jobId2, server); // calling a second time should not fail server.globalCleanupAsync(jobId2, executorService).join(); } finally { assertThat(executorService.shutdownNow()).isEmpty(); } } @Test void testConcurrentDeleteOperationsNoJobTransient() throws IOException, ExecutionException, InterruptedException { testConcurrentDeleteOperations(null); } @Test void testConcurrentDeleteOperationsForJobTransient() throws IOException, ExecutionException, InterruptedException { testConcurrentDeleteOperations(new JobID()); } /** * [FLINK-6020] Tests that concurrent delete operations don't interfere with each other. * * <p>Note: This test checks that there cannot be two threads which have checked whether a given * blob file exist and then one of them fails deleting it. Without the introduced lock, this * situation should rarely happen and make this test fail. Thus, if this test should become * "unstable", then the delete atomicity is most likely broken. * * @param jobId job ID to use (or <tt>null</tt> if job-unrelated) */ private void testConcurrentDeleteOperations(@Nullable final JobID jobId) throws IOException, InterruptedException, ExecutionException { final int concurrentDeleteOperations = 3; final ExecutorService executor = Executors.newFixedThreadPool(concurrentDeleteOperations); final List<CompletableFuture<Void>> deleteFutures = new ArrayList<>(concurrentDeleteOperations); final byte[] data = {1, 2, 3}; try (BlobServer server = TestingBlobUtils.createServer(tempDir)) { server.start(); final TransientBlobKey blobKey = (TransientBlobKey) put(server, jobId, data, TRANSIENT_BLOB); assertThat(server.getStorageLocation(jobId, blobKey)).exists(); for (int i = 0; i < concurrentDeleteOperations; i++) { CompletableFuture<Void> deleteFuture = CompletableFuture.supplyAsync( () -> { try { assertThat(delete(server, jobId, blobKey)).isTrue(); assertThat(server.getStorageLocation(jobId, blobKey)) .doesNotExist(); return null; } catch (IOException e) { throw new CompletionException( new FlinkException( "Could not delete the given blob key " + blobKey + '.')); } }, executor); deleteFutures.add(deleteFuture); } CompletableFuture<Void> waitFuture = FutureUtils.waitForAll(deleteFutures); // make sure all delete operation have completed successfully // in case of no lock, one of the delete operations should eventually fail waitFuture.get(); assertThat(server.getStorageLocation(jobId, blobKey)).doesNotExist(); } finally { executor.shutdownNow(); } } /** * Deletes a transient BLOB from the given BLOB service. * * @param service blob service * @param jobId job ID (or <tt>null</tt> if job-unrelated) * @param key blob key * @return delete success */ static boolean delete(BlobService service, @Nullable JobID jobId, TransientBlobKey key) { if (jobId == null) { return service.getTransientBlobService().deleteFromCache(key); } else { return service.getTransientBlobService().deleteFromCache(jobId, key); } } private static boolean delete( BlobServer blobServer, @Nullable JobID jobId, BlobKey key, BlobKey.BlobType blobType) { Preconditions.checkNotNull(blobServer); Preconditions.checkNotNull(key); if (blobType == PERMANENT_BLOB) { Preconditions.checkNotNull(jobId); assertThat(key).isInstanceOf(PermanentBlobKey.class); return blobServer.deletePermanent(jobId, (PermanentBlobKey) key); } else { assertThat(key).isInstanceOf(TransientBlobKey.class); return delete(blobServer, jobId, (TransientBlobKey) key); } } }
BlobServerDeleteTest
java
spring-projects__spring-boot
loader/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/MainClassFinderTests.java
{ "start": 10191, "end": 10721 }
class ____ implements Implementation { @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { return instrumentedType; } @Override public ByteCodeAppender appender(Target implementationTarget) { return new ByteCodeAppender() { @Override public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) { methodVisitor.visitInsn(Opcodes.RETURN); return Size.ZERO; } }; } } static
EmptyBodyImplementation
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocolPB/InterDatanodeProtocolTranslatorPB.java
{ "start": 2433, "end": 4944 }
class ____ implements ProtocolMetaInterface, InterDatanodeProtocol, Closeable { /** RpcController is not used and hence is set to null */ private final static RpcController NULL_CONTROLLER = null; final private InterDatanodeProtocolPB rpcProxy; public InterDatanodeProtocolTranslatorPB(InetSocketAddress addr, UserGroupInformation ugi, Configuration conf, SocketFactory factory, int socketTimeout) throws IOException { RPC.setProtocolEngine(conf, InterDatanodeProtocolPB.class, ProtobufRpcEngine2.class); rpcProxy = RPC.getProxy(InterDatanodeProtocolPB.class, RPC.getProtocolVersion(InterDatanodeProtocolPB.class), addr, ugi, conf, factory, socketTimeout); } @Override public void close() { RPC.stopProxy(rpcProxy); } @Override public ReplicaRecoveryInfo initReplicaRecovery(RecoveringBlock rBlock) throws IOException { InitReplicaRecoveryRequestProto req = InitReplicaRecoveryRequestProto .newBuilder().setBlock(PBHelper.convert(rBlock)).build(); InitReplicaRecoveryResponseProto resp; resp = ipc(() -> rpcProxy.initReplicaRecovery(NULL_CONTROLLER, req)); if (!resp.getReplicaFound()) { // No replica found on the remote node. return null; } else { if (!resp.hasBlock() || !resp.hasState()) { throw new IOException("Replica was found but missing fields. " + "Req: " + req + "\n" + "Resp: " + resp); } } BlockProto b = resp.getBlock(); return new ReplicaRecoveryInfo(b.getBlockId(), b.getNumBytes(), b.getGenStamp(), PBHelper.convert(resp.getState())); } @Override public String updateReplicaUnderRecovery(ExtendedBlock oldBlock, long recoveryId, long newBlockId, long newLength) throws IOException { UpdateReplicaUnderRecoveryRequestProto req = UpdateReplicaUnderRecoveryRequestProto.newBuilder() .setBlock(PBHelperClient.convert(oldBlock)) .setNewLength(newLength).setNewBlockId(newBlockId) .setRecoveryId(recoveryId).build(); return ipc(() -> rpcProxy.updateReplicaUnderRecovery(NULL_CONTROLLER, req) .getStorageUuid()); } @Override public boolean isMethodSupported(String methodName) throws IOException { return RpcClientUtil.isMethodSupported(rpcProxy, InterDatanodeProtocolPB.class, RPC.RpcKind.RPC_PROTOCOL_BUFFER, RPC.getProtocolVersion(InterDatanodeProtocolPB.class), methodName); } }
InterDatanodeProtocolTranslatorPB
java
mapstruct__mapstruct
processor/src/test/resources/fixtures/org/mapstruct/ap/test/collection/adder/Source2Target2MapperImpl.java
{ "start": 619, "end": 1069 }
class ____ extends Source2Target2Mapper { @Override public Target2 toTarget(Source2 source) { if ( source == null ) { return null; } Target2 target2 = new Target2(); if ( source.getAttributes() != null ) { for ( Foo attribute : source.getAttributes() ) { target2.addAttribute( attribute ); } } return target2; } }
Source2Target2MapperImpl
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/authorization/method/PostAuthorizeAuthorizationManagerTests.java
{ "start": 11033, "end": 11208 }
interface ____ { @MyPostAuthorize void inheritedAnnotations(); } @Retention(RetentionPolicy.RUNTIME) @PostAuthorize("hasRole('USER')") public @
InterfaceAnnotationsThree
java
quarkusio__quarkus
extensions/grpc/runtime/src/main/java/io/quarkus/grpc/auth/GrpcSecurityMechanism.java
{ "start": 513, "end": 1190 }
interface ____ { int DEFAULT_PRIORITY = 1000; /** * * @param metadata metadata of the gRPC call * @return true if and only if the interceptor should handle security for this metadata. An interceptor may decide * it should not be triggered for a call e.g. if some header is missing in metadata. */ boolean handles(Metadata metadata); /** * * @param metadata metadata of the gRPC call * @return authentication request based on the metadata */ AuthenticationRequest createAuthenticationRequest(Metadata metadata); default int getPriority() { return DEFAULT_PRIORITY; } }
GrpcSecurityMechanism
java
micronaut-projects__micronaut-core
http-netty/src/main/java/io/micronaut/http/netty/channel/ChannelPipelineListener.java
{ "start": 737, "end": 978 }
interface ____ allows users to configure the Netty pipeline used by Micronaut. * * @author graemerocher * @since 2.0.0 * @deprecated Use NettyClientCustomizer or NettyServerCustomizer instead. */ @Deprecated @FunctionalInterface public
that
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/lucene/read/SingletonBytesRefBuilder.java
{ "start": 708, "end": 2676 }
class ____ implements BlockLoader.SingletonBytesRefBuilder { private final int count; private final BlockFactory blockFactory; private BytesRefArray bytesRefArray; public SingletonBytesRefBuilder(int count, BlockFactory blockFactory) { this.count = count; this.blockFactory = blockFactory; } @Override public SingletonBytesRefBuilder appendBytesRefs(byte[] bytes, long[] offsets) { var values = blockFactory.bigArrays().newByteArrayWrapper(bytes); bytesRefArray = new BytesRefArray(new LongArrayWrapper(offsets), values, count, blockFactory.bigArrays()); return this; } @Override public SingletonBytesRefBuilder appendBytesRefs(byte[] bytes, long bytesRefLengths) { var values = blockFactory.bigArrays().newByteArrayWrapper(bytes); bytesRefArray = new BytesRefArray( new ConstantOffsetLongArrayWrapper(bytesRefLengths, count + 1), values, count, blockFactory.bigArrays() ); return this; } @Override public BlockLoader.Block build() { return blockFactory.newBytesRefArrayVector(bytesRefArray, count).asBlock(); } @Override public BlockLoader.Builder appendNull() { throw new UnsupportedOperationException(); } @Override public BlockLoader.Builder beginPositionEntry() { throw new UnsupportedOperationException(); } @Override public BlockLoader.Builder endPositionEntry() { throw new UnsupportedOperationException(); } @Override public void close() {} /** * An array wrapper that starts with 0 and has a constant offset between each pair of values. * For an offset of n, the values are: [0, n, 2n, 3n, ..., Xn] * This can be used to provide an "offsets" array for ByteRefs of constant length without the need to allocate an unnecessary array. */ static final
SingletonBytesRefBuilder
java
spring-projects__spring-boot
test-support/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/FileUtils.java
{ "start": 1043, "end": 1830 }
class ____ { private static final int BUFFER_SIZE = 32 * 1024; /** * Generate a SHA-1 Hash for a given file. * @param file the file to hash * @return the hash value as a String * @throws IOException if the file cannot be read */ public static String sha1Hash(File file) throws IOException { try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); try (InputStream inputStream = new FileInputStream(file)) { byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { messageDigest.update(buffer, 0, bytesRead); } return HexFormat.of().formatHex(messageDigest.digest()); } } catch (NoSuchAlgorithmException ex) { throw new IllegalStateException(ex); } } }
FileUtils
java
google__dagger
javatests/dagger/internal/codegen/DaggerSuperficialValidationTest.java
{ "start": 13312, "end": 14610 }
class ____<T>", "", " fun extendsTest(): Foo<out MissingType> = TODO()", "", " fun superTest(): Foo<in MissingType> = TODO()", "}"), (processingEnv, superficialValidation) -> { XTypeElement testClassElement = processingEnv.findTypeElement("test.TestClass"); ValidationException exception = assertThrows( ValidationException.KnownErrorType.class, () -> superficialValidation.validateElement(testClassElement)); assertThat(exception) .hasMessageThat() .contains( NEW_LINES.join( "Validation trace:", " => element (CLASS): test.TestClass", " => element (METHOD): extendsTest()", " => type (DECLARED return type): test.TestClass.Foo<? extends MissingType>", " => type (WILDCARD type argument): ? extends MissingType", " => type (ERROR extends bound type): MissingType")); }); } @Test public void missingIntersection() { runTest( CompilerTests.javaSource( "test.TestClass", "package test;", "", "
Foo
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/AgeConverter.java
{ "start": 259, "end": 541 }
class ____ implements AttributeConverter<String, Integer> { public Integer convertToDatabaseColumn(String attribute) { return Integer.valueOf( attribute.replace( ".", "" ) ); } public String convertToEntityAttribute(Integer dbData) { return dbData.toString(); } }
AgeConverter
java
google__guava
android/guava-tests/test/com/google/common/reflect/InvokableTest.java
{ "start": 29503, "end": 31226 }
class ____ { private final String prefix; private final int times; Prepender(@NotBlank @Nullable String prefix, int times) throws NullPointerException { this.prefix = prefix; this.times = times; } Prepender(String... varargs) { this(null, 0); } // just for testing private <T> Prepender() { this(null, 0); } static <T> Iterable<String> prepend(@NotBlank String first, Iterable<String> tail) { return Iterables.concat(ImmutableList.of(first), tail); } Iterable<String> prepend(Iterable<String> tail) throws IllegalArgumentException, NullPointerException { return Iterables.concat(Collections.nCopies(times, prefix), tail); } static Invokable<?, Prepender> constructor(Class<?>... parameterTypes) throws Exception { Constructor<Prepender> constructor = Prepender.class.getDeclaredConstructor(parameterTypes); return Invokable.from(constructor); } static Invokable<Prepender, Object> method(String name, Class<?>... parameterTypes) { try { Method method = Prepender.class.getDeclaredMethod(name, parameterTypes); @SuppressWarnings("unchecked") // The method is from Prepender. Invokable<Prepender, Object> invokable = (Invokable<Prepender, Object>) Invokable.from(method); return invokable; } catch (NoSuchMethodException e) { throw new IllegalArgumentException(e); } } private void privateMethod() {} private final void privateFinalMethod() {} static void staticMethod() {} static final void staticFinalMethod() {} private void privateVarArgsMethod(String... varargs) {} } private static
Prepender
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/query/KvStateRegistryTest.java
{ "start": 2047, "end": 10455 }
class ____ { @Test void testKvStateEntry() throws InterruptedException { final int threads = 10; final CountDownLatch latch1 = new CountDownLatch(threads); final CountDownLatch latch2 = new CountDownLatch(1); final List<KvStateInfo<?, ?, ?>> infos = Collections.synchronizedList(new ArrayList<>()); final JobID jobID = new JobID(); final JobVertexID jobVertexId = new JobVertexID(); final KeyGroupRange keyGroupRange = new KeyGroupRange(0, 1); final String registrationName = "foobar"; final KvStateRegistry kvStateRegistry = new KvStateRegistry(); final KvStateID stateID = kvStateRegistry.registerKvState( jobID, jobVertexId, keyGroupRange, registrationName, new DummyKvState(), getClass().getClassLoader()); final AtomicReference<Throwable> exceptionHolder = new AtomicReference<>(); for (int i = 0; i < threads; i++) { new Thread( () -> { final KvStateEntry<?, ?, ?> kvState = kvStateRegistry.getKvState(stateID); final KvStateInfo<?, ?, ?> stateInfo = kvState.getInfoForCurrentThread(); infos.add(stateInfo); latch1.countDown(); try { latch2.await(); } catch (InterruptedException e) { // compare and set, so that we do not overwrite an exception // that was (potentially) already encountered. exceptionHolder.compareAndSet(null, e); } }) .start(); } latch1.await(); final KvStateEntry<?, ?, ?> kvState = kvStateRegistry.getKvState(stateID); // verify that all the threads are done correctly. assertThat(infos).hasSize(threads); assertThat(kvState.getCacheSize()).isEqualTo(threads); latch2.countDown(); for (KvStateInfo<?, ?, ?> infoA : infos) { boolean instanceAlreadyFound = false; for (KvStateInfo<?, ?, ?> infoB : infos) { if (infoA == infoB) { if (instanceAlreadyFound) { fail("More than one thread sharing the same serializer instance."); } instanceAlreadyFound = true; } else { assertThat(infoA).isEqualTo(infoB); } } } kvStateRegistry.unregisterKvState( jobID, jobVertexId, keyGroupRange, registrationName, stateID); assertThat(kvState.getCacheSize()).isZero(); Throwable t = exceptionHolder.get(); assertThat(t).isNull(); } /** * Tests that {@link KvStateRegistryListener} only receive the notifications which are destined * for them. */ @Test void testKvStateRegistryListenerNotification() { final JobID jobId1 = new JobID(); final JobID jobId2 = new JobID(); final KvStateRegistry kvStateRegistry = new KvStateRegistry(); final ArrayDeque<JobID> registeredNotifications1 = new ArrayDeque<>(2); final ArrayDeque<JobID> deregisteredNotifications1 = new ArrayDeque<>(2); final TestingKvStateRegistryListener listener1 = new TestingKvStateRegistryListener( registeredNotifications1, deregisteredNotifications1); final ArrayDeque<JobID> registeredNotifications2 = new ArrayDeque<>(2); final ArrayDeque<JobID> deregisteredNotifications2 = new ArrayDeque<>(2); final TestingKvStateRegistryListener listener2 = new TestingKvStateRegistryListener( registeredNotifications2, deregisteredNotifications2); kvStateRegistry.registerListener(jobId1, listener1); kvStateRegistry.registerListener(jobId2, listener2); final JobVertexID jobVertexId = new JobVertexID(); final KeyGroupRange keyGroupRange = new KeyGroupRange(0, 1); final String registrationName = "foobar"; final KvStateID kvStateID = kvStateRegistry.registerKvState( jobId1, jobVertexId, keyGroupRange, registrationName, new DummyKvState(), getClass().getClassLoader()); assertThat(registeredNotifications1.poll()).isEqualTo(jobId1); assertThat(registeredNotifications2).isEmpty(); final JobVertexID jobVertexId2 = new JobVertexID(); final KeyGroupRange keyGroupRange2 = new KeyGroupRange(0, 1); final String registrationName2 = "barfoo"; final KvStateID kvStateID2 = kvStateRegistry.registerKvState( jobId2, jobVertexId2, keyGroupRange2, registrationName2, new DummyKvState(), getClass().getClassLoader()); assertThat(registeredNotifications2.poll()).isEqualTo(jobId2); assertThat(registeredNotifications1).isEmpty(); kvStateRegistry.unregisterKvState( jobId1, jobVertexId, keyGroupRange, registrationName, kvStateID); assertThat(deregisteredNotifications1.poll()).isEqualTo(jobId1); assertThat(deregisteredNotifications2).isEmpty(); kvStateRegistry.unregisterKvState( jobId2, jobVertexId2, keyGroupRange2, registrationName2, kvStateID2); assertThat(deregisteredNotifications2.poll()).isEqualTo(jobId2); assertThat(deregisteredNotifications1).isEmpty(); } /** * Tests that {@link KvStateRegistryListener} registered under {@link * HighAvailabilityServices#DEFAULT_JOB_ID} will be used for all notifications. */ @Test void testLegacyCodePathPreference() { final KvStateRegistry kvStateRegistry = new KvStateRegistry(); final ArrayDeque<JobID> stateRegistrationNotifications = new ArrayDeque<>(2); final ArrayDeque<JobID> stateDeregistrationNotifications = new ArrayDeque<>(2); final TestingKvStateRegistryListener testingListener = new TestingKvStateRegistryListener( stateRegistrationNotifications, stateDeregistrationNotifications); final ArrayDeque<JobID> anotherQueue = new ArrayDeque<>(2); final TestingKvStateRegistryListener anotherListener = new TestingKvStateRegistryListener(anotherQueue, anotherQueue); final JobID jobId = new JobID(); kvStateRegistry.registerListener(HighAvailabilityServices.DEFAULT_JOB_ID, testingListener); kvStateRegistry.registerListener(jobId, anotherListener); final JobVertexID jobVertexId = new JobVertexID(); final KeyGroupRange keyGroupRange = new KeyGroupRange(0, 1); final String registrationName = "registrationName"; final KvStateID kvStateID = kvStateRegistry.registerKvState( jobId, jobVertexId, keyGroupRange, registrationName, new DummyKvState(), getClass().getClassLoader()); assertThat(stateRegistrationNotifications.poll()).isEqualTo(jobId); // another listener should not have received any notifications assertThat(anotherQueue).isEmpty(); kvStateRegistry.unregisterKvState( jobId, jobVertexId, keyGroupRange, registrationName, kvStateID); assertThat(stateDeregistrationNotifications.poll()).isEqualTo(jobId); // another listener should not have received any notifications assertThat(anotherQueue).isEmpty(); } /** Testing implementation of {@link KvStateRegistryListener}. */ private static final
KvStateRegistryTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/EnumType.java
{ "start": 2924, "end": 5405 }
enum ____ be mapped by name. * Default is to map as ordinal. * </li> * <li> * {@value #TYPE}, a JDBC type code (legacy alternative to {@value #NAMED}). * </li> * </ul> */ @Override public void setParameterValues(Properties parameters) { // IMPL NOTE: we handle 2 distinct cases here: // 1) we are passed a ParameterType instance in the incoming Properties - generally // speaking this indicates the annotation-binding case, and the passed ParameterType // represents information about the attribute and annotation // 2) we are not passed a ParameterType - generally this indicates a hbm.xml binding case. final ParameterType reader = (ParameterType) parameters.get( PARAMETER_TYPE ); enumClass = getEnumClass( parameters, reader ); enumJavaType = (EnumJavaType<T>) typeConfiguration.getJavaTypeRegistry() .resolveDescriptor( enumClass ); if ( parameters.containsKey( TYPE ) ) { final int jdbcTypeCode = Integer.parseInt( (String) parameters.get( TYPE ) ); jdbcType = typeConfiguration.getJdbcTypeRegistry().getDescriptor( jdbcTypeCode ); isOrdinal = jdbcType.isInteger() // Both, ENUM and NAMED_ENUM are treated like ordinal with respect to the ordering || jdbcType.getDefaultSqlTypeCode() == SqlTypes.ENUM || jdbcType.getDefaultSqlTypeCode() == SqlTypes.NAMED_ENUM; } else { final LocalJdbcTypeIndicators indicators; final Long columnLength = reader == null ? null : reader.getColumnLengths()[0]; if ( parameters.containsKey (NAMED ) ) { indicators = new LocalJdbcTypeIndicators( // use ORDINAL as default for hbm.xml mappings getBoolean( NAMED, parameters ) ? STRING : ORDINAL, false, columnLength ); } else { indicators = new LocalJdbcTypeIndicators( getEnumType( reader ), isNationalized( reader ), columnLength ); } jdbcType = typeConfiguration.getJavaTypeRegistry().resolveDescriptor( enumClass ).getRecommendedJdbcType( indicators ); isOrdinal = indicators.getEnumeratedType() != STRING; } } private Class<T> getEnumClass(Properties parameters, ParameterType reader) { if ( parameters.containsKey( ENUM ) ) { final String enumClassName = (String) parameters.get( ENUM ); try { return (Class<T>) classForName( enumClassName, this.getClass() ).asSubclass( Enum.class ); } catch ( ClassNotFoundException exception ) { throw new HibernateException("Enum
should
java
spring-projects__spring-security
crypto/src/test/java/org/springframework/security/crypto/password/PasswordEncoderUtilsTests.java
{ "start": 812, "end": 2104 }
class ____ { @Test public void equalsWhenDifferentLengthThenFalse() { assertThat(PasswordEncoderUtils.equals("abc", "a")).isFalse(); assertThat(PasswordEncoderUtils.equals("a", "abc")).isFalse(); } @Test public void equalsWhenNullAndNotEmptyThenFalse() { assertThat(PasswordEncoderUtils.equals(null, "a")).isFalse(); assertThat(PasswordEncoderUtils.equals("a", null)).isFalse(); } @Test public void equalsWhenNullAndNullThenTrue() { assertThat(PasswordEncoderUtils.equals(null, null)).isTrue(); } @Test public void equalsWhenNullAndEmptyThenFalse() { assertThat(PasswordEncoderUtils.equals(null, "")).isFalse(); assertThat(PasswordEncoderUtils.equals("", null)).isFalse(); } @Test public void equalsWhenNotEmptyAndEmptyThenFalse() { assertThat(PasswordEncoderUtils.equals("abc", "")).isFalse(); assertThat(PasswordEncoderUtils.equals("", "abc")).isFalse(); } @Test public void equalsWhenEmptyAndEmptyThenTrue() { assertThat(PasswordEncoderUtils.equals("", "")).isTrue(); } @Test public void equalsWhenDifferentCaseThenFalse() { assertThat(PasswordEncoderUtils.equals("aBc", "abc")).isFalse(); } @Test public void equalsWhenSameThenTrue() { assertThat(PasswordEncoderUtils.equals("abcdef", "abcdef")).isTrue(); } }
PasswordEncoderUtilsTests
java
quarkusio__quarkus
extensions/hibernate-reactive/deployment/src/test/java/io/quarkus/hibernate/reactive/config/datasource/ConfigDefaultPUDatasourceUrlMissingStaticInjectionTest.java
{ "start": 513, "end": 1826 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot(jar -> jar.addClass(MyEntity.class)) .withConfigurationResource("application.properties") .overrideConfigKey("quarkus.datasource.reactive.url", "") // The URL won't be missing if dev services are enabled .overrideConfigKey("quarkus.devservices.enabled", "false") .assertException(e -> assertThat(e) .hasMessageContainingAll( "Unable to find datasource '<default>' for persistence unit '<default>'", "Datasource '<default>' was deactivated automatically because its URL is not set.", "To avoid this exception while keeping the bean inactive", // Message from Arc with generic hints "To activate the datasource, set configuration property 'quarkus.datasource.reactive.url'", "Refer to https://quarkus.io/guides/datasource for guidance.")); @Inject MyBean myBean; @Test public void test() { Assertions.fail("Startup should have failed"); } @ApplicationScoped public static
ConfigDefaultPUDatasourceUrlMissingStaticInjectionTest
java
alibaba__druid
core/src/main/java/com/alibaba/druid/support/ibatis/IbatisUtils.java
{ "start": 1043, "end": 5211 }
class ____ { private static Log LOG = LogFactory.getLog(IbatisUtils.class); private static boolean VERSION_2_3_4; private static Method methodGetId; private static Method methodGetResource; private static Field sessionField; static { try { Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass("com.ibatis.sqlmap.engine.mapping.result.AutoResultMap"); Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.getName().equals("setResultObjectValues")) { // ibatis 2.3.4 add method 'setResultObjectValues' VERSION_2_3_4 = true; break; } } } catch (Throwable e) { LOG.error("Error while initializing", e); } } public static boolean isVersion2_3_4() { return VERSION_2_3_4; } public static SqlMapExecutor setClientImpl(SqlMapExecutor session, SqlMapClientImplWrapper clientImplWrapper) { if (session == null || clientImplWrapper == null) { return session; } if (session.getClass() == SqlMapSessionImpl.class) { SqlMapSessionImpl sessionImpl = (SqlMapSessionImpl) session; set(sessionImpl, clientImplWrapper); } return session; } /** * 通过反射的方式得到id,能够兼容2.3.0和2.3.4 * * @param statement the statement object from which to retrieve the ID * @return the ID as a string, or null if an error occurs or if the ID is null */ protected static String getId(Object statement) { try { if (methodGetId == null) { Class<?> clazz = statement.getClass(); methodGetId = clazz.getMethod("getId"); } Object returnValue = methodGetId.invoke(statement); if (returnValue == null) { return null; } return returnValue.toString(); } catch (Exception ex) { LOG.error("createIdError", ex); return null; } } /** * 通过反射的方式得到resource,能够兼容2.3.0和2.3.4 * * @param statement the statement object from which to retrieve the resource * @return the resource as a string, or null if an error occurs */ protected static String getResource(Object statement) { try { if (methodGetResource == null) { methodGetResource = statement.getClass().getMethod("getResource"); } return (String) methodGetResource.invoke(statement); } catch (Exception ex) { return null; } } public static void set(SqlMapSessionImpl session, SqlMapClientImpl client) { if (sessionField == null) { for (Field field : SqlMapSessionImpl.class.getDeclaredFields()) { if (field.getName().equals("session") || field.getName().equals("sessionScope")) { sessionField = field; sessionField.setAccessible(true); break; } } } if (sessionField != null) { SessionScope sessionScope; try { sessionScope = (SessionScope) sessionField.get(session); if (sessionScope != null) { if (sessionScope.getSqlMapClient() != null && sessionScope.getSqlMapClient().getClass() == SqlMapClientImpl.class) { sessionScope.setSqlMapClient(client); } if (sessionScope.getSqlMapExecutor() != null && sessionScope.getSqlMapExecutor().getClass() == SqlMapClientImpl.class) { sessionScope.setSqlMapExecutor(client); } if (sessionScope.getSqlMapTxMgr() != null && sessionScope.getSqlMapTxMgr().getClass() == SqlMapClientImpl.class) { sessionScope.setSqlMapTxMgr(client); } } } catch (Exception e) { LOG.error(e.getMessage(), e); } } } }
IbatisUtils
java
spring-projects__spring-boot
module/spring-boot-flyway/src/main/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfiguration.java
{ "start": 20963, "end": 21299 }
class ____ implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.resources().registerPattern("db/migration/*"); } } /** * Adapts {@link FlywayProperties} to {@link FlywayConnectionDetails}. */ static final
FlywayAutoConfigurationRuntimeHints
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/support/ActiveProfilesUtilsTests.java
{ "start": 6986, "end": 7093 }
class ____ { } @ActiveProfiles({ "cat", "dog", " foo", "bar ", "cat" }) private static
DuplicatedProfiles
java
elastic__elasticsearch
x-pack/plugin/shutdown/src/test/java/org/elasticsearch/xpack/shutdown/TransportGetShutdownStatusActionTests.java
{ "start": 4241, "end": 4902 }
class ____ extends ESTestCase { public static final String SHUTTING_DOWN_NODE_ID = "node1"; public static final String LIVE_NODE_ID = "node2"; public static final String OTHER_LIVE_NODE_ID = "node3"; private final AtomicReference<TestDecider> canAllocate = new AtomicReference<>(); private final AtomicReference<TestDecider> canRemain = new AtomicReference<>(); private ClusterInfoService clusterInfoService; private AllocationDeciders allocationDeciders; private AllocationService allocationService; private SnapshotsInfoService snapshotsInfoService; @FunctionalInterface private
TransportGetShutdownStatusActionTests
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated-src/org/elasticsearch/xpack/esql/expression/predicate/operator/comparison/InLongEvaluator.java
{ "start": 1286, "end": 7076 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(InLongEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator lhs; private final EvalOperator.ExpressionEvaluator[] rhs; private final DriverContext driverContext; private Warnings warnings; public InLongEvaluator( Source source, EvalOperator.ExpressionEvaluator lhs, EvalOperator.ExpressionEvaluator[] rhs, DriverContext driverContext ) { this.source = source; this.lhs = lhs; this.rhs = rhs; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (LongBlock lhsBlock = (LongBlock) lhs.eval(page)) { LongBlock[] rhsBlocks = new LongBlock[rhs.length]; try (Releasable rhsRelease = Releasables.wrap(rhsBlocks)) { for (int i = 0; i < rhsBlocks.length; i++) { rhsBlocks[i] = (LongBlock) rhs[i].eval(page); } LongVector lhsVector = lhsBlock.asVector(); if (lhsVector == null) { return eval(page.getPositionCount(), lhsBlock, rhsBlocks); } LongVector[] rhsVectors = new LongVector[rhs.length]; for (int i = 0; i < rhsBlocks.length; i++) { rhsVectors[i] = rhsBlocks[i].asVector(); if (rhsVectors[i] == null) { return eval(page.getPositionCount(), lhsBlock, rhsBlocks); } } return eval(page.getPositionCount(), lhsVector, rhsVectors); } } } private BooleanBlock eval(int positionCount, LongBlock lhsBlock, LongBlock[] rhsBlocks) { try (BooleanBlock.Builder result = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) { long[] rhsValues = new long[rhs.length]; BitSet nulls = new BitSet(rhs.length); BitSet mvs = new BitSet(rhs.length); boolean foundMatch; for (int p = 0; p < positionCount; p++) { if (lhsBlock.isNull(p)) { result.appendNull(); continue; } if (lhsBlock.getValueCount(p) != 1) { if (lhsBlock.getValueCount(p) > 1) { warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); } result.appendNull(); continue; } // unpack rhsBlocks into rhsValues nulls.clear(); mvs.clear(); for (int i = 0; i < rhsBlocks.length; i++) { if (rhsBlocks[i].isNull(p)) { nulls.set(i); continue; } if (rhsBlocks[i].getValueCount(p) > 1) { mvs.set(i); warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); continue; } int o = rhsBlocks[i].getFirstValueIndex(p); rhsValues[i] = rhsBlocks[i].getLong(o); } if (nulls.cardinality() == rhsBlocks.length || mvs.cardinality() == rhsBlocks.length) { result.appendNull(); continue; } foundMatch = In.process(nulls, mvs, lhsBlock.getLong(lhsBlock.getFirstValueIndex(p)), rhsValues); if (foundMatch) { result.appendBoolean(true); } else { if (nulls.cardinality() > 0) { result.appendNull(); } else { result.appendBoolean(false); } } } return result.build(); } } private BooleanBlock eval(int positionCount, LongVector lhsVector, LongVector[] rhsVectors) { try (BooleanBlock.Builder result = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) { long[] rhsValues = new long[rhs.length]; for (int p = 0; p < positionCount; p++) { // unpack rhsVectors into rhsValues for (int i = 0; i < rhsVectors.length; i++) { rhsValues[i] = rhsVectors[i].getLong(p); } result.appendBoolean(In.process(null, null, lhsVector.getLong(p), rhsValues)); } return result.build(); } } @Override public String toString() { return "InLongEvaluator[" + "lhs=" + lhs + ", rhs=" + Arrays.toString(rhs) + "]"; } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += lhs.baseRamBytesUsed(); for (EvalOperator.ExpressionEvaluator r : rhs) { baseRamBytesUsed += r.baseRamBytesUsed(); } return baseRamBytesUsed; } @Override public void close() { Releasables.closeExpectNoException(lhs, () -> Releasables.close(rhs)); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
InLongEvaluator
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/MethodParameter.java
{ "start": 18234, "end": 22933 }
class ____ unresolvable } if (type instanceof Class<?> clazz) { return clazz; } else if (type instanceof ParameterizedType parameterizedType) { Type arg = parameterizedType.getRawType(); if (arg instanceof Class<?> clazz) { return clazz; } } return Object.class; } else { return getParameterType(); } } /** * Return the nested generic type of the method/constructor parameter. * @return the parameter type (never {@code null}) * @since 4.2 * @see #getNestingLevel() */ public Type getNestedGenericParameterType() { if (this.nestingLevel > 1) { Type type = getGenericParameterType(); for (int i = 2; i <= this.nestingLevel; i++) { if (type instanceof ParameterizedType parameterizedType) { Type[] args = parameterizedType.getActualTypeArguments(); Integer index = getTypeIndexForLevel(i); type = args[index != null ? index : args.length - 1]; } } return type; } else { return getGenericParameterType(); } } /** * Return the annotations associated with the target method/constructor itself. */ public Annotation[] getMethodAnnotations() { return adaptAnnotationArray(getAnnotatedElement().getAnnotations()); } /** * Return the method/constructor annotation of the given type, if available. * @param annotationType the annotation type to look for * @return the annotation object, or {@code null} if not found */ public <A extends Annotation> @Nullable A getMethodAnnotation(Class<A> annotationType) { A annotation = getAnnotatedElement().getAnnotation(annotationType); return (annotation != null ? adaptAnnotation(annotation) : null); } /** * Return whether the method/constructor is annotated with the given type. * @param annotationType the annotation type to look for * @since 4.3 * @see #getMethodAnnotation(Class) */ public <A extends Annotation> boolean hasMethodAnnotation(Class<A> annotationType) { return getAnnotatedElement().isAnnotationPresent(annotationType); } /** * Return the annotations associated with the specific method/constructor parameter. */ public Annotation[] getParameterAnnotations() { Annotation[] paramAnns = this.parameterAnnotations; if (paramAnns == null) { Annotation[][] annotationArray = this.executable.getParameterAnnotations(); int index = this.parameterIndex; if (this.executable instanceof Constructor && ClassUtils.isInnerClass(this.executable.getDeclaringClass()) && annotationArray.length == this.executable.getParameterCount() - 1) { // Bug in javac in JDK <9: annotation array excludes enclosing instance parameter // for inner classes, so access it with the actual parameter index lowered by 1 index = this.parameterIndex - 1; } paramAnns = (index >= 0 && index < annotationArray.length && annotationArray[index].length > 0 ? adaptAnnotationArray(annotationArray[index]) : EMPTY_ANNOTATION_ARRAY); this.parameterAnnotations = paramAnns; } return paramAnns; } /** * Return {@code true} if the parameter has at least one annotation, * {@code false} if it has none. * @see #getParameterAnnotations() */ public boolean hasParameterAnnotations() { return (getParameterAnnotations().length != 0); } /** * Return the parameter annotation of the given type, if available. * @param annotationType the annotation type to look for * @return the annotation object, or {@code null} if not found */ @SuppressWarnings("unchecked") public <A extends Annotation> @Nullable A getParameterAnnotation(Class<A> annotationType) { Annotation[] anns = getParameterAnnotations(); for (Annotation ann : anns) { if (annotationType.isInstance(ann)) { return (A) ann; } } return null; } /** * Return whether the parameter is declared with the given annotation type. * @param annotationType the annotation type to look for * @see #getParameterAnnotation(Class) */ public <A extends Annotation> boolean hasParameterAnnotation(Class<A> annotationType) { return (getParameterAnnotation(annotationType) != null); } /** * Initialize parameter name discovery for this method parameter. * <p>This method does not actually try to retrieve the parameter name at * this point; it just allows discovery to happen when the application calls * {@link #getParameterName()} (if ever). */ public void initParameterNameDiscovery(@Nullable ParameterNameDiscoverer parameterNameDiscoverer) { this.parameterNameDiscoverer = parameterNameDiscoverer; } /** * Return the name of the method/constructor parameter. * @return the parameter name (may be {@code null} if no * parameter name metadata is contained in the
if
java
alibaba__nacos
persistence/src/main/java/com/alibaba/nacos/persistence/configuration/condition/ConditionStandaloneEmbedStorage.java
{ "start": 1158, "end": 1424 }
class ____ implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return DatasourceConfiguration.isEmbeddedStorage() && EnvUtil.getStandaloneMode(); } }
ConditionStandaloneEmbedStorage
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/InvalidAliasNameException.java
{ "start": 732, "end": 1304 }
class ____ extends ElasticsearchException { public InvalidAliasNameException(Index index, String name, String desc) { super("Invalid alias name [{}], {}", name, desc); setIndex(index); } public InvalidAliasNameException(String name, String description) { super("Invalid alias name [{}]: {}", name, description); } public InvalidAliasNameException(StreamInput in) throws IOException { super(in); } @Override public RestStatus status() { return RestStatus.BAD_REQUEST; } }
InvalidAliasNameException
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/filter/AbstractFilterable.java
{ "start": 1528, "end": 6671 }
class ____<B extends Builder<B>> { @PluginElement("Filter") private Filter filter; // We are calling this attribute propertyArray because we use the more generic "properties" in several places // with different types: Array, Map and List. @PluginElement("Properties") private Property[] propertyArray; @SuppressWarnings("unchecked") public B asBuilder() { return (B) this; } public Filter getFilter() { return filter; } public Property[] getPropertyArray() { return propertyArray; } public B setFilter(final Filter filter) { this.filter = filter; return asBuilder(); } public B setPropertyArray(final Property[] properties) { this.propertyArray = properties; return asBuilder(); } /** * Sets the filter. * * @param filter The filter * @return this * @deprecated Use {@link #setFilter(Filter)}. */ @Deprecated public B withFilter(final Filter filter) { return setFilter(filter); } } /** * May be null. */ private volatile Filter filter; @PluginElement("Properties") private final Property[] propertyArray; protected AbstractFilterable() { this(null, Property.EMPTY_ARRAY); } protected AbstractFilterable(final Filter filter) { this(filter, Property.EMPTY_ARRAY); } /** * @since 2.11.2 */ protected AbstractFilterable(final Filter filter, final Property[] propertyArray) { this.filter = filter; this.propertyArray = propertyArray == null ? Property.EMPTY_ARRAY : propertyArray; } /** * Adds a filter. * @param filter The Filter to add. */ @Override public synchronized void addFilter(final Filter filter) { if (filter == null) { return; } if (this.filter == null) { this.filter = filter; } else if (this.filter instanceof CompositeFilter) { this.filter = ((CompositeFilter) this.filter).addFilter(filter); } else { final Filter[] filters = new Filter[] {this.filter, filter}; this.filter = CompositeFilter.createFilters(filters); } } /** * Returns the Filter. * @return the Filter or null. */ @Override public Filter getFilter() { return filter; } /** * Determines if a Filter is present. * @return false if no Filter is present. */ @Override public boolean hasFilter() { return filter != null; } /** * Determine if the LogEvent should be processed or ignored. * @param event The LogEvent. * @return {@code true} if the event is filtered and should be ignored; otherwise, {@code false} if * it should be processed */ @Override public boolean isFiltered(final LogEvent event) { return filter != null && filter.filter(event) == Filter.Result.DENY; } /** * Removes a Filter. * @param filter The Filter to remove. */ @Override public synchronized void removeFilter(final Filter filter) { if (this.filter == null || filter == null) { return; } if (this.filter == filter || this.filter.equals(filter)) { this.filter = null; } else if (this.filter instanceof CompositeFilter) { CompositeFilter composite = (CompositeFilter) this.filter; composite = composite.removeFilter(filter); if (composite.size() > 1) { this.filter = composite; } else if (composite.size() == 1) { final Iterator<Filter> iter = composite.iterator(); this.filter = iter.next(); } else { this.filter = null; } } } /** * Make the Filter available for use. */ @Override public void start() { this.setStarting(); if (filter != null) { filter.start(); } this.setStarted(); } /** * Cleanup the Filter. */ @Override public boolean stop(final long timeout, final TimeUnit timeUnit) { return stop(timeout, timeUnit, true); } /** * Cleanup the Filter. */ protected boolean stop(final long timeout, final TimeUnit timeUnit, final boolean changeLifeCycleState) { if (changeLifeCycleState) { this.setStopping(); } boolean stopped = true; if (filter != null) { if (filter instanceof LifeCycle2) { stopped = ((LifeCycle2) filter).stop(timeout, timeUnit); } else { filter.stop(); stopped = true; } } if (changeLifeCycleState) { this.setStopped(); } return stopped; } public Property[] getPropertyArray() { return propertyArray; } }
Builder
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/LazyLoginManualIT.java
{ "start": 996, "end": 2992 }
class ____ extends AbstractSalesforceTestBase { @Test public void lazyLoginDoesNotThrowExceptions() throws Exception { // If we got this far, then createComponent() succeeded without an exception related to lazy login // Now we just need to make sure credentials provided after startup work final SalesforceLoginConfig config = LoginConfigHelper.getLoginConfig(); component.getLoginConfig().setLoginUrl(config.getLoginUrl()); component.getLoginConfig().setClientId(config.getClientId()); component.getLoginConfig().setClientSecret(config.getClientSecret()); component.getLoginConfig().setUserName(config.getUserName()); component.getLoginConfig().setPassword(config.getPassword()); component.getLoginConfig().setKeystore(config.getKeystore()); component.getLoginConfig().setRefreshToken(config.getRefreshToken()); component.getSession().login(null); } @Override protected void createComponent() throws Exception { // create the component, but do not set any credentials or login info component = new SalesforceComponent(); component.setLazyLogin(true); final SalesforceEndpointConfig config = new SalesforceEndpointConfig(); config.setApiVersion(System.getProperty("apiVersion", SalesforceEndpointConfig.DEFAULT_VERSION)); component.setConfig(config); HashMap<String, Object> clientProperties = new HashMap<>(); clientProperties.put("timeout", "60000"); clientProperties.put("maxRetries", "3"); // 4MB for RestApiIntegrationTest.testGetBlobField() clientProperties.put("maxContentLength", String.valueOf(4 * 1024 * 1024)); component.setHttpClientProperties(clientProperties); // set DTO package component.setPackages(Merchandise__c.class.getPackage().getName()); // add it to context context().addComponent("salesforce", component); } }
LazyLoginManualIT
java
apache__camel
components/camel-fhir/camel-fhir-component/src/generated/java/org/apache/camel/component/fhir/internal/FhirApiName.java
{ "start": 256, "end": 803 }
enum ____ implements ApiName { CAPABILITIES("capabilities"), CREATE("create"), DELETE("delete"), HISTORY("history"), LOAD_PAGE("load-page"), META("meta"), OPERATION("operation"), PATCH("patch"), READ("read"), SEARCH("search"), TRANSACTION("transaction"), UPDATE("update"), VALIDATE("validate"); private final String name; private FhirApiName(String name) { this.name = name; } @Override public String getName() { return name; } }
FhirApiName
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/TestTemplateInvocationTests.java
{ "start": 24132, "end": 24472 }
class ____ { private final String constructorParameter; MyTestTemplateTestCaseWithConstructor(String constructorParameter) { this.constructorParameter = constructorParameter; } @TestTemplate void template(String parameter) { assertEquals(constructorParameter, parameter); } } static
MyTestTemplateTestCaseWithConstructor
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/MetricsSink.java
{ "start": 1323, "end": 1499 }
class ____ * implements {@link Closeable}, then the MetricsSystem will close the sink when * it is stopped. */ @InterfaceAudience.Public @InterfaceStability.Evolving public
also
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/json/MappedObjectTests.java
{ "start": 1086, "end": 2787 }
class ____ extends AbstractJsonTests { private final TestMappedObject mapped; MappedObjectTests() throws IOException { this.mapped = TestMappedObject.of(getContent("test-mapped-object.json")); } @Test void ofReadsJson() { assertThat(this.mapped.getNode()).isNotNull(); } @Test void valueAtWhenStringReturnsValue() { assertThat(this.mapped.valueAt("/string", String.class)).isEqualTo("stringvalue"); } @Test void valueAtWhenStringArrayReturnsValue() { assertThat(this.mapped.valueAt("/stringarray", String[].class)).containsExactly("a", "b"); } @Test void valueAtWhenMissingReturnsNull() { assertThat(this.mapped.valueAt("/missing", String.class)).isNull(); } @Test void valueAtWhenInterfaceReturnsProxy() { Person person = this.mapped.valueAt("/person", Person.class); assertThat(person).isNotNull(); assertThat(person.getName().getFirst()).isEqualTo("spring"); assertThat(person.getName().getLast()).isEqualTo("boot"); } @Test void valueAtWhenInterfaceAndMissingReturnsProxy() { Person person = this.mapped.valueAt("/missing", Person.class); assertThat(person).isNotNull(); assertThat(person.getName().getFirst()).isNull(); assertThat(person.getName().getLast()).isNull(); } @Test void valueAtWhenActualPropertyStartsWithUppercaseReturnsValue() { assertThat(this.mapped.valueAt("/startsWithUppercase", String.class)).isEqualTo("value"); } @Test void valueAtWhenDefaultMethodReturnsValue() { Person person = this.mapped.valueAt("/person", Person.class); assertThat(person).isNotNull(); assertThat(person.getName().getFullName()).isEqualTo("dr spring boot"); } /** * {@link MappedObject} for testing. */ static
MappedObjectTests
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/json/DelegateJsonArrayUnitTests.java
{ "start": 622, "end": 11816 }
class ____ { @Test void add() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.add(parser.createJsonValue("\"test\"")).add(parser.createJsonValue("\"test2\"")) .add(parser.createJsonValue("\"test3\"")); assertThat(underTest.size()).isEqualTo(3); assertThat(underTest.get(0).isString()).isTrue(); assertThat(underTest.get(0).asString()).isEqualTo("test"); assertThat(underTest.get(1).isString()).isTrue(); assertThat(underTest.get(1).asString()).isEqualTo("test2"); assertThat(underTest.get(2).isString()).isTrue(); assertThat(underTest.get(2).asString()).isEqualTo("test3"); } @Test void addCornerCases() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.add(null).add(parser.createJsonValue("null")).add(parser.createJsonValue("\"test3\"")); assertThatThrownBy(() -> underTest.addAll(null)).isInstanceOf(IllegalArgumentException.class); assertThat(underTest.size()).isEqualTo(3); assertThat(underTest.get(0).isNull()).isTrue(); assertThat(underTest.get(1).isNull()).isTrue(); assertThat(underTest.get(2).isString()).isTrue(); assertThat(underTest.get(2).asString()).isEqualTo("test3"); } @Test void getCornerCases() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.add(parser.createJsonValue("\"test\"")).add(parser.createJsonValue("\"test2\"")) .add(parser.createJsonValue("\"test3\"")); assertThat(underTest.get(3)).isNull(); assertThat(underTest.get(-1)).isNull(); } @Test void addAll() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray array = new DelegateJsonArray(objectMapper); array.add(parser.createJsonValue("\"test\"")).add(parser.createJsonValue("\"test2\"")) .add(parser.createJsonValue("\"test3\"")); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.addAll(array); array.remove(1); // verify source array modifications not propagated assertThat(underTest.size()).isEqualTo(3); assertThat(underTest.get(0).isString()).isTrue(); assertThat(underTest.get(0).asString()).isEqualTo("test"); assertThat(underTest.get(1).isString()).isTrue(); assertThat(underTest.get(1).asString()).isEqualTo("test2"); assertThat(underTest.get(2).isString()).isTrue(); assertThat(underTest.get(2).asString()).isEqualTo("test3"); } @Test void asList() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.add(parser.createJsonValue("1")).add(parser.createJsonValue("2")).add(parser.createJsonValue("3")); assertThat(underTest.size()).isEqualTo(3); assertThat(underTest.asList()).hasSize(3); assertThat(underTest.asList().get(0).isNumber()).isTrue(); assertThat(underTest.asList().get(0).asNumber()).isEqualTo(1); } @Test void getFirst() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.add(parser.createJsonValue("\"test\"")).add(parser.createJsonValue("\"test2\"")) .add(parser.createJsonValue("\"test3\"")); assertThat(underTest.size()).isEqualTo(3); assertThat(underTest.getFirst().isString()).isTrue(); assertThat(underTest.getFirst().asString()).isEqualTo("test"); } @Test void iterator() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.add(parser.createJsonValue("1")).add(parser.createJsonValue("2")).add(parser.createJsonValue("3")); Iterator<JsonValue> iterator = underTest.iterator(); assertThat(iterator.hasNext()).isTrue(); while (iterator.hasNext()) { assertThat(iterator.next().isNumber()).isTrue(); } } @Test void remove() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.add(parser.createJsonValue("1")).add(parser.createJsonValue("2")).add(parser.createJsonValue("3")); assertThat(underTest.remove(1).asNumber()).isEqualTo(2); assertThat(underTest.size()).isEqualTo(2); assertThat(underTest.get(0).asNumber()).isEqualTo(1); assertThat(underTest.get(1).asNumber()).isEqualTo(3); } @Test void replace() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.add(parser.createJsonValue("1")).add(parser.createJsonValue("2")).add(parser.createJsonValue("3")); JsonValue oldValue = underTest.replace(1, parser.createJsonValue("4")); assertThat(underTest.size()).isEqualTo(3); assertThat(underTest.get(0).asNumber()).isEqualTo(1); assertThat(underTest.get(1).asNumber()).isEqualTo(4); assertThat(underTest.get(2).asNumber()).isEqualTo(3); assertThat(oldValue.asNumber()).isEqualTo(2); } @Test void swap() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); JsonArray swap = underTest.add(parser.createJsonValue("1")).add(parser.createJsonValue("2")) .add(parser.createJsonValue("3")).swap(0, parser.createJsonValue("4")).swap(1, parser.createJsonValue("5")) .swap(2, parser.createJsonValue("6")); assertThat(underTest.size()).isEqualTo(3); assertThat(underTest.get(0).asNumber()).isEqualTo(4); assertThat(underTest.get(1).asNumber()).isEqualTo(5); assertThat(underTest.get(2).asNumber()).isEqualTo(6); assertThat(swap).isSameAs(underTest); } @Test void swap_throws() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); assertThrows(IndexOutOfBoundsException.class, () -> underTest.swap(3, parser.createJsonValue("4"))); } @Test void isJsonArray() { ObjectMapper objectMapper = new ObjectMapper(); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); assertThat(underTest.isJsonArray()).isTrue(); assertThat(underTest.isJsonObject()).isFalse(); assertThat(underTest.isNull()).isFalse(); assertThat(underTest.isNumber()).isFalse(); assertThat(underTest.isString()).isFalse(); } @Test void asJsonArray() { ObjectMapper objectMapper = new ObjectMapper(); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); assertThat(underTest.asJsonArray()).isSameAs(underTest); } @Test void asAnythingElse() { ObjectMapper objectMapper = new ObjectMapper(); DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); assertThat(underTest.asBoolean()).isNull(); assertThat(underTest.asJsonObject()).isNull(); assertThat(underTest.asString()).isNull(); assertThat(underTest.asNumber()).isNull(); } @Test void asListWithNestedObjects() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); // Create an array containing nested objects DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.add(parser.createJsonValue("{\"name\": \"Alice\", \"age\": 30}")); underTest.add(parser.createJsonValue("{\"name\": \"Bob\", \"age\": 25}")); // Test that asList() returns proper DelegateJsonObject instances for nested objects List<JsonValue> list = underTest.asList(); assertThat(list).hasSize(2); // Verify that elements from asList() behave consistently with get() for (int i = 0; i < list.size(); i++) { JsonValue listElement = list.get(i); JsonValue getElement = underTest.get(i); // Both should be DelegateJsonObject instances assertThat(listElement.isJsonObject()).isTrue(); assertThat(getElement.isJsonObject()).isTrue(); // Both should have the same behavior assertThat(listElement.asJsonObject()).isNotNull(); assertThat(getElement.asJsonObject()).isNotNull(); // Both should return the same string representation assertThat(listElement.toString()).isEqualTo(getElement.toString()); } } @Test void asListWithNestedArrays() { ObjectMapper objectMapper = new ObjectMapper(); DefaultJsonParser parser = new DefaultJsonParser(objectMapper); // Create an array containing nested arrays DelegateJsonArray underTest = new DelegateJsonArray(objectMapper); underTest.add(parser.createJsonValue("[1, 2, 3]")); underTest.add(parser.createJsonValue("[\"a\", \"b\", \"c\"]")); // Test that asList() returns proper DelegateJsonArray instances for nested arrays List<JsonValue> list = underTest.asList(); assertThat(list).hasSize(2); // Verify that elements from asList() behave consistently with get() for (int i = 0; i < list.size(); i++) { JsonValue listElement = list.get(i); JsonValue getElement = underTest.get(i); // Both should be DelegateJsonArray instances assertThat(listElement.isJsonArray()).isTrue(); assertThat(getElement.isJsonArray()).isTrue(); // Both should have the same behavior assertThat(listElement.asJsonArray()).isNotNull(); assertThat(getElement.asJsonArray()).isNotNull(); // Both should return the same string representation assertThat(listElement.toString()).isEqualTo(getElement.toString()); } } }
DelegateJsonArrayUnitTests
java
quarkusio__quarkus
extensions/qute/runtime/src/main/java/io/quarkus/qute/runtime/LocationLiteral.java
{ "start": 188, "end": 507 }
class ____ extends AnnotationLiteral<Location> implements Location { private static final long serialVersionUID = 1L; private final String value; public LocationLiteral(String value) { this.value = value; } @Override public String value() { return value; } }
LocationLiteral
java
apache__maven
compat/maven-model-builder/src/main/java/org/apache/maven/model/resolution/UnresolvableModelException.java
{ "start": 1043, "end": 4042 }
class ____ extends Exception { /** * The group id of the unresolvable model. */ private final String groupId; /** * The artifact id of the unresolvable model. */ private final String artifactId; /** * The version of the unresolvable model. */ private final String version; /** * Creates a new exception with specified detail message and cause. * * @param message The detail message, may be {@code null}. * @param groupId The group id of the unresolvable model, may be {@code null}. * @param artifactId The artifact id of the unresolvable model, may be {@code null}. * @param version The version of the unresolvable model, may be {@code null}. * @param cause The cause, may be {@code null}. */ public UnresolvableModelException( String message, String groupId, String artifactId, String version, Throwable cause) { super(message, cause); this.groupId = (groupId != null) ? groupId : ""; this.artifactId = (artifactId != null) ? artifactId : ""; this.version = (version != null) ? version : ""; } /** * Creates a new exception with specified detail message. * * @param message The detail message, may be {@code null}. * @param groupId The group id of the unresolvable model, may be {@code null}. * @param artifactId The artifact id of the unresolvable model, may be {@code null}. * @param version The version of the unresolvable model, may be {@code null}. */ public UnresolvableModelException(String message, String groupId, String artifactId, String version) { super(message); this.groupId = (groupId != null) ? groupId : ""; this.artifactId = (artifactId != null) ? artifactId : ""; this.version = (version != null) ? version : ""; } /** * Creates a new exception with specified cause * * @param cause * @param groupId * @param artifactId * @param version */ public UnresolvableModelException(Throwable cause, String groupId, String artifactId, String version) { super(cause); this.groupId = groupId; this.artifactId = artifactId; this.version = version; } /** * Gets the group id of the unresolvable model. * * @return The group id of the unresolvable model, can be empty but never {@code null}. */ public String getGroupId() { return groupId; } /** * Gets the artifact id of the unresolvable model. * * @return The artifact id of the unresolvable model, can be empty but never {@code null}. */ public String getArtifactId() { return artifactId; } /** * Gets the version of the unresolvable model. * * @return The version of the unresolvable model, can be empty but never {@code null}. */ public String getVersion() { return version; } }
UnresolvableModelException
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointUoWFailedTest.java
{ "start": 1438, "end": 3601 }
class ____ extends ContextTestSupport { private static String beforeThreadName; private static String afterThreadName; private final MySynchronization sync = new MySynchronization(); @Test public void testAsyncEndpoint() throws Exception { getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel"); getMockEndpoint("mock:result").expectedMessageCount(0); try { template.requestBody("direct:start", "Hello Camel", String.class); fail("Should have thrown an exception"); } catch (CamelExecutionException e) { assertIsInstanceOf(IllegalArgumentException.class, e.getCause()); assertEquals("Damn", e.getCause().getMessage()); } assertMockEndpointsSatisfied(); // wait a bit to ensure UoW has been run assertTrue(oneExchangeDone.matchesWaitTime()); assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should use different threads"); assertEquals(0, sync.isOnComplete()); assertEquals(1, sync.isOnFailure()); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.addComponent("async", new MyAsyncComponent()); from("direct:start").process(new Processor() { public void process(Exchange exchange) { beforeThreadName = Thread.currentThread().getName(); exchange.getExchangeExtension().addOnCompletion(sync); } }).to("mock:before").to("log:before").to("async:bye:camel").process(new Processor() { public void process(Exchange exchange) { afterThreadName = Thread.currentThread().getName(); } }).to("log:after").to("mock:after").throwException(new IllegalArgumentException("Damn")).to("mock:result"); } }; } private static
AsyncEndpointUoWFailedTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/FetchableAttributeSource.java
{ "start": 241, "end": 329 }
interface ____ { FetchCharacteristics getFetchCharacteristics(); }
FetchableAttributeSource
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java
{ "start": 18231, "end": 19057 }
class ____ extends FieldError implements Serializable { private @Nullable transient SpringValidatorAdapter adapter; private @Nullable transient ConstraintViolation<?> violation; public ViolationFieldError(String objectName, String field, @Nullable Object rejectedValue, String[] codes, Object[] arguments, ConstraintViolation<?> violation, SpringValidatorAdapter adapter) { super(objectName, field, rejectedValue, false, codes, arguments, violation.getMessage()); this.adapter = adapter; this.violation = violation; wrap(violation); } @Override public boolean shouldRenderDefaultMessage() { return (this.adapter != null && this.violation != null ? this.adapter.requiresMessageFormat(this.violation) : containsSpringStylePlaceholder(getDefaultMessage())); } } }
ViolationFieldError
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/bindinggraphvalidation/DuplicateBindingsValidator.java
{ "start": 15446, "end": 16008 }
class ____ { abstract Optional<DaggerAnnotation> qualifier(); abstract Equivalence.Wrapper<XType> wrappedType(); abstract Optional<MultibindingContributionIdentifier> multibindingContributionIdentifier(); private static KeyWithTypeEquivalence forKey(Key key, Equivalence<XType> typeEquivalence) { return new AutoValue_DuplicateBindingsValidator_KeyWithTypeEquivalence( key.qualifier(), typeEquivalence.wrap(key.type().xprocessing()), key.multibindingContributionIdentifier()); } } }
KeyWithTypeEquivalence
java
qos-ch__slf4j
jul-to-slf4j/src/test/java/org/slf4j/bridge/SLF4JBridgeHandlerTest.java
{ "start": 1538, "end": 8299 }
class ____ { static String LOGGER_NAME = "yay"; ListAppender listAppender = new ListAppender(); org.apache.log4j.Logger log4jRoot; java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(LOGGER_NAME); java.util.logging.Logger julRootLogger = java.util.logging.Logger.getLogger(""); @Before public void setUp() throws Exception { listAppender.extractLocationInfo = true; log4jRoot = org.apache.log4j.Logger.getRootLogger(); log4jRoot.addAppender(listAppender); log4jRoot.setLevel(org.apache.log4j.Level.TRACE); julRootLogger.setLevel(Level.FINEST); } @After public void tearDown() throws Exception { SLF4JBridgeHandler.uninstall(); log4jRoot.getLoggerRepository().resetConfiguration(); } @Test public void testSmoke() { SLF4JBridgeHandler.install(); String msg = "msg"; julLogger.info(msg); assertEquals(1, listAppender.list.size()); LoggingEvent le = (LoggingEvent) listAppender.list.get(0); assertEquals(LOGGER_NAME, le.getLoggerName()); assertEquals(msg, le.getMessage()); // get the location info in the event. // Note that this must have been computed previously // within an appender for the following assertion to // work properly LocationInfo li = le.getLocationInformation(); System.out.println(li.fullInfo); assertEquals("SLF4JBridgeHandlerTest.java", li.getFileName()); assertEquals("testSmoke", li.getMethodName()); } @Test public void LOGBACK_1612() { SLF4JBridgeHandler.install(); String msg = "LOGBACK_1612"; julLogger.finer(msg); assertEquals(1, listAppender.list.size()); LoggingEvent le = (LoggingEvent) listAppender.list.get(0); assertEquals(LOGGER_NAME, le.getLoggerName()); assertEquals(msg, le.getMessage()); } @Test public void testLevels() { SLF4JBridgeHandler.install(); String msg = "msg"; julLogger.setLevel(Level.ALL); julLogger.finest(msg); julLogger.finer(msg); julLogger.fine(msg); julLogger.info(msg); julLogger.warning(msg); julLogger.severe(msg); assertEquals(6, listAppender.list.size()); int i = 0; assertLevel(i++, org.apache.log4j.Level.TRACE); assertLevel(i++, org.apache.log4j.Level.DEBUG); assertLevel(i++, org.apache.log4j.Level.DEBUG); assertLevel(i++, org.apache.log4j.Level.INFO); assertLevel(i++, org.apache.log4j.Level.WARN); assertLevel(i++, org.apache.log4j.Level.ERROR); } @Test public void testLogWithResourceBundle() { SLF4JBridgeHandler.install(); String resourceBundleName = "org.slf4j.bridge.testLogStrings"; ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); String resourceKey = "resource_key"; String expectedMsg = bundle.getString(resourceKey); String msg = resourceKey; java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("yay", resourceBundleName); julResourceBundleLogger.info(msg); assertEquals(1, listAppender.list.size()); LoggingEvent le = listAppender.list.get(0); assertEquals(LOGGER_NAME, le.getLoggerName()); assertEquals(expectedMsg, le.getMessage()); } @Test public void testLogWithResourceBundleWithParameters() { SLF4JBridgeHandler.install(); String resourceBundleName = "org.slf4j.bridge.testLogStrings"; ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName); java.util.logging.Logger julResourceBundleLogger = java.util.logging.Logger.getLogger("foo", resourceBundleName); String resourceKey1 = "resource_key_1"; String expectedMsg1 = bundle.getString(resourceKey1); julResourceBundleLogger.info(resourceKey1); // 1st log String resourceKey2 = "resource_key_2"; Object[] params2 = new Object[] { "foo", "bar" }; String expectedMsg2 = MessageFormat.format(bundle.getString(resourceKey2), params2); julResourceBundleLogger.log(Level.INFO, resourceKey2, params2); // 2nd log String resourceKey3 = "invalidKey {0}"; Object[] params3 = new Object[] { "John" }; String expectedMsg3 = MessageFormat.format(resourceKey3, params3); julResourceBundleLogger.log(Level.INFO, resourceKey3, params3); // 3rd log julLogger.log(Level.INFO, resourceKey3, params3); // 4th log assertEquals(4, listAppender.list.size()); LoggingEvent le = null; le = listAppender.list.get(0); assertEquals("foo", le.getLoggerName()); assertEquals(expectedMsg1, le.getMessage()); le = listAppender.list.get(1); assertEquals("foo", le.getLoggerName()); assertEquals(expectedMsg2, le.getMessage()); le = listAppender.list.get(2); assertEquals("foo", le.getLoggerName()); assertEquals(expectedMsg3, le.getMessage()); le = listAppender.list.get(3); assertEquals("yay", le.getLoggerName()); assertEquals(expectedMsg3, le.getMessage()); } @Test public void testLogWithPlaceholderNoParameters() { SLF4JBridgeHandler.install(); String msg = "msg {non-number-string}"; julLogger.logp(Level.INFO, "SLF4JBridgeHandlerTest", "testLogWithPlaceholderNoParameters", msg, new Object[0]); assertEquals(1, listAppender.list.size()); LoggingEvent le = listAppender.list.get(0); assertEquals(LOGGER_NAME, le.getLoggerName()); assertEquals(msg, le.getMessage()); } // See http://jira.qos.ch/browse/SLF4J-337 @Test public void illFormattedInputShouldBeReturnedAsIs() { SLF4JBridgeHandler.install(); String msg = "foo {18=bad} {0}"; julLogger.log(Level.INFO, msg, "ignored parameter due to IllegalArgumentException"); assertEquals(1, listAppender.list.size()); LoggingEvent le = listAppender.list.get(0); assertEquals(msg, le.getMessage()); } @Test public void withNullMessage() { SLF4JBridgeHandler.install(); String msg = null; julLogger.log(Level.INFO, msg); assertEquals(1, listAppender.list.size()); LoggingEvent le = listAppender.list.get(0); assertEquals("", le.getMessage()); } void assertLevel(int index, org.apache.log4j.Level expectedLevel) { LoggingEvent le = listAppender.list.get(index); assertEquals(expectedLevel, le.getLevel()); } }
SLF4JBridgeHandlerTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/elementCollection/CollectionEmbeddableElementConversionTest.java
{ "start": 1854, "end": 2122 }
class ____ { @Id Integer productId; ProductEntity() { } ProductEntity(Integer productId) { this.productId = productId; } @ElementCollection(fetch = FetchType.EAGER) List<ProductPrice> prices = new ArrayList<>(); } @Embeddable static
ProductEntity