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
redisson__redisson
redisson/src/main/java/org/redisson/rx/RedissonReadWriteLockRx.java
{ "start": 844, "end": 1517 }
class ____ implements RReadWriteLockRx { private final RReadWriteLock instance; private final CommandRxExecutor commandExecutor; public RedissonReadWriteLockRx(CommandRxExecutor commandExecutor, String name) { this.commandExecutor = commandExecutor; this.instance = new RedissonReadWriteLock(commandExecutor, name); } @Override public RLockRx readLock() { return RxProxyBuilder.create(commandExecutor, instance.readLock(), RLockRx.class); } @Override public RLockRx writeLock() { return RxProxyBuilder.create(commandExecutor, instance.writeLock(), RLockRx.class); } }
RedissonReadWriteLockRx
java
apache__thrift
lib/java/src/main/java/org/apache/thrift/server/TThreadedSelectorServer.java
{ "start": 2568, "end": 2762 }
class ____ extends AbstractNonblockingServer { private static final Logger LOGGER = LoggerFactory.getLogger(TThreadedSelectorServer.class.getName()); public static
TThreadedSelectorServer
java
alibaba__nacos
core/src/test/java/com/alibaba/nacos/core/controller/NacosClusterControllerTest.java
{ "start": 1713, "end": 4285 }
class ____ { @InjectMocks private NacosClusterController nacosClusterController; @Mock private ServerMemberManager serverMemberManager; @BeforeEach void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); } @Test void testSelf() { Member self = new Member(); Mockito.when(serverMemberManager.getSelf()).thenReturn(self); RestResult<Member> result = nacosClusterController.self(); assertEquals(self, result.getData()); } @Test void testListNodes() { Member member1 = new Member(); member1.setIp("1.1.1.1"); List<Member> members = Arrays.asList(member1); Mockito.when(serverMemberManager.allMembers()).thenReturn(members); RestResult<Collection<Member>> result = nacosClusterController.listNodes("1.1.1.1"); assertEquals(1, result.getData().size()); } @Test void testListSimpleNodes() { Mockito.when(serverMemberManager.getMemberAddressInfos()).thenReturn(Collections.singleton("1.1.1.1")); RestResult<Collection<String>> result = nacosClusterController.listSimpleNodes(); assertEquals(1, result.getData().size()); } @Test void testGetHealth() { Member self = new Member(); self.setState(NodeState.UP); Mockito.when(serverMemberManager.getSelf()).thenReturn(self); RestResult<String> result = nacosClusterController.getHealth(); assertEquals(NodeState.UP.name(), result.getData()); } @Test void testReport() { Member self = new Member(); Mockito.when(serverMemberManager.update(Mockito.any())).thenReturn(true); Mockito.when(serverMemberManager.getSelf()).thenReturn(self); Member member = new Member(); member.setIp("1.1.1.1"); member.setPort(8848); member.setAddress("test"); RestResult<String> result = nacosClusterController.report(member); String expected = JacksonUtils.toJson(self); assertEquals(expected, result.getData()); } @Test void testSwitchLookup() { RestResult<String> result = nacosClusterController.switchLookup("test"); assertTrue(result.ok()); } @Test void testLeave() throws Exception { RestResult<String> result = nacosClusterController.leave(Collections.singletonList("1.1.1.1"), true); assertFalse(result.ok()); assertEquals(405, result.getCode()); } }
NacosClusterControllerTest
java
greenrobot__EventBus
EventBusTestJava/src/main/java/org/greenrobot/eventbus/EventBusIndexTest.java
{ "start": 962, "end": 2014 }
class ____ { private String value; /** Ensures the index is actually used and no reflection fall-back kicks in. */ @Test public void testManualIndexWithoutAnnotation() { SubscriberInfoIndex index = new SubscriberInfoIndex() { @Override public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) { Assert.assertEquals(EventBusIndexTest.class, subscriberClass); SubscriberMethodInfo[] methodInfos = { new SubscriberMethodInfo("someMethodWithoutAnnotation", String.class) }; return new SimpleSubscriberInfo(EventBusIndexTest.class, false, methodInfos); } }; EventBus eventBus = EventBus.builder().addIndex(index).build(); eventBus.register(this); eventBus.post("Yepp"); eventBus.unregister(this); Assert.assertEquals("Yepp", value); } public void someMethodWithoutAnnotation(String value) { this.value = value; } }
EventBusIndexTest
java
spring-projects__spring-boot
loader/spring-boot-jarmode-tools/src/test/java/org/springframework/boot/jarmode/tools/AbstractJarModeTests.java
{ "start": 5090, "end": 5173 }
interface ____<T extends Command> { T create(Context context); } }
CommandFactory
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/authentication/ott/OneTimeTokenAuthenticationTests.java
{ "start": 870, "end": 1648 }
class ____ { @Test void toBuilderWhenApplyThenCopies() { OneTimeTokenAuthentication factorOne = new OneTimeTokenAuthentication("alice", AuthorityUtils.createAuthorityList("FACTOR_ONE")); OneTimeTokenAuthentication factorTwo = new OneTimeTokenAuthentication("bob", AuthorityUtils.createAuthorityList("FACTOR_TWO")); OneTimeTokenAuthentication result = factorOne.toBuilder() .authorities((a) -> a.addAll(factorTwo.getAuthorities())) .principal(factorTwo.getPrincipal()) .build(); Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities()); assertThat(result.getPrincipal()).isSameAs(factorTwo.getPrincipal()); assertThat(authorities).containsExactlyInAnyOrder("FACTOR_ONE", "FACTOR_TWO"); } }
OneTimeTokenAuthenticationTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/options/OptionsTest.java
{ "start": 1485, "end": 1715 }
class ____ { @Id long id; @Column(name = "name", options = "compression pglz") String name; @ManyToOne @JoinColumn(foreignKey = @ForeignKey(name = "ToOther", options = "match full")) WithOptions other; } }
WithOptions
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/BadAnnotationImplementationTest.java
{ "start": 5191, "end": 5881 }
class ____ implements Annotation { @Override public Class<? extends Annotation> annotationType() { return TestAnnotation.class; } @Override public boolean equals(Object other) { return false; } public int hashCode(Object obj) { return 0; } } """) .doTest(); } @Test public void overridesEqualsAndHashCode() { compilationHelper .addSourceLines( "TestAnnotation.java", """ import java.lang.annotation.Annotation; public
TestAnnotation
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/context/properties/Snippet.java
{ "start": 2135, "end": 2513 }
interface ____ { /** * Accept the given prefix using the meta-data description. * @param prefix the prefix to accept */ void accept(String prefix); /** * Accept the given prefix with a defined description. * @param prefix the prefix to accept * @param description the description to use */ void accept(String prefix, String description); } }
Config
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/generic/IndexedRecord.java
{ "start": 923, "end": 1460 }
interface ____ extends GenericContainer { /** * Set the value of a field given its position in the schema. * <p> * This method is not meant to be called by user code, but only by * {@link org.apache.avro.io.DatumReader} implementations. */ void put(int i, Object v); /** * Return the value of a field given its position in the schema. * <p> * This method is not meant to be called by user code, but only by * {@link org.apache.avro.io.DatumWriter} implementations. */ Object get(int i); }
IndexedRecord
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/vectors/DenseVectorFieldMapper.java
{ "start": 65887, "end": 81042 }
enum ____ { HNSW("hnsw", false) { @Override public DenseVectorIndexOptions parseIndexOptions(String fieldName, Map<String, ?> indexOptionsMap, IndexVersion indexVersion) { Object mNode = indexOptionsMap.remove("m"); Object efConstructionNode = indexOptionsMap.remove("ef_construction"); int m = XContentMapValues.nodeIntegerValue(mNode, Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN); int efConstruction = XContentMapValues.nodeIntegerValue(efConstructionNode, Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH); MappingParser.checkNoRemainingFields(fieldName, indexOptionsMap); return new HnswIndexOptions(m, efConstruction); } @Override public boolean supportsElementType(ElementType elementType) { return true; } @Override public boolean supportsDimension(int dims) { return true; } }, INT8_HNSW("int8_hnsw", true) { @Override public DenseVectorIndexOptions parseIndexOptions(String fieldName, Map<String, ?> indexOptionsMap, IndexVersion indexVersion) { Object mNode = indexOptionsMap.remove("m"); Object efConstructionNode = indexOptionsMap.remove("ef_construction"); Object confidenceIntervalNode = indexOptionsMap.remove("confidence_interval"); Object onDiskRescoreNode = ES93GenericFlatVectorsFormat.GENERIC_VECTOR_FORMAT.isEnabled() ? indexOptionsMap.remove("on_disk_rescore") : false; int m = XContentMapValues.nodeIntegerValue(mNode, Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN); int efConstruction = XContentMapValues.nodeIntegerValue(efConstructionNode, Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH); boolean onDiskRescore = XContentMapValues.nodeBooleanValue(onDiskRescoreNode, false); Float confidenceInterval = null; if (confidenceIntervalNode != null) { confidenceInterval = (float) XContentMapValues.nodeDoubleValue(confidenceIntervalNode); } RescoreVector rescoreVector = null; if (hasRescoreIndexVersion(indexVersion)) { rescoreVector = RescoreVector.fromIndexOptions(indexOptionsMap, indexVersion); } MappingParser.checkNoRemainingFields(fieldName, indexOptionsMap); return new Int8HnswIndexOptions(m, efConstruction, confidenceInterval, onDiskRescore, rescoreVector); } @Override public boolean supportsElementType(ElementType elementType) { return elementType == ElementType.FLOAT || elementType == ElementType.BFLOAT16; } @Override public boolean supportsDimension(int dims) { return true; } }, INT4_HNSW("int4_hnsw", true) { public DenseVectorIndexOptions parseIndexOptions(String fieldName, Map<String, ?> indexOptionsMap, IndexVersion indexVersion) { Object mNode = indexOptionsMap.remove("m"); Object efConstructionNode = indexOptionsMap.remove("ef_construction"); Object confidenceIntervalNode = indexOptionsMap.remove("confidence_interval"); Object onDiskRescoreNode = ES93GenericFlatVectorsFormat.GENERIC_VECTOR_FORMAT.isEnabled() ? indexOptionsMap.remove("on_disk_rescore") : false; int m = XContentMapValues.nodeIntegerValue(mNode, Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN); int efConstruction = XContentMapValues.nodeIntegerValue(efConstructionNode, Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH); boolean onDiskRescore = XContentMapValues.nodeBooleanValue(onDiskRescoreNode, false); Float confidenceInterval = null; if (confidenceIntervalNode != null) { confidenceInterval = (float) XContentMapValues.nodeDoubleValue(confidenceIntervalNode); } RescoreVector rescoreVector = null; if (hasRescoreIndexVersion(indexVersion)) { rescoreVector = RescoreVector.fromIndexOptions(indexOptionsMap, indexVersion); } MappingParser.checkNoRemainingFields(fieldName, indexOptionsMap); return new Int4HnswIndexOptions(m, efConstruction, confidenceInterval, onDiskRescore, rescoreVector); } @Override public boolean supportsElementType(ElementType elementType) { return elementType == ElementType.FLOAT || elementType == ElementType.BFLOAT16; } @Override public boolean supportsDimension(int dims) { return dims % 2 == 0; } }, FLAT("flat", false) { @Override public DenseVectorIndexOptions parseIndexOptions(String fieldName, Map<String, ?> indexOptionsMap, IndexVersion indexVersion) { MappingParser.checkNoRemainingFields(fieldName, indexOptionsMap); return new FlatIndexOptions(); } @Override public boolean supportsElementType(ElementType elementType) { return true; } @Override public boolean supportsDimension(int dims) { return true; } }, INT8_FLAT("int8_flat", true) { @Override public DenseVectorIndexOptions parseIndexOptions(String fieldName, Map<String, ?> indexOptionsMap, IndexVersion indexVersion) { Object confidenceIntervalNode = indexOptionsMap.remove("confidence_interval"); Float confidenceInterval = null; if (confidenceIntervalNode != null) { confidenceInterval = (float) XContentMapValues.nodeDoubleValue(confidenceIntervalNode); } RescoreVector rescoreVector = null; if (hasRescoreIndexVersion(indexVersion)) { rescoreVector = RescoreVector.fromIndexOptions(indexOptionsMap, indexVersion); } MappingParser.checkNoRemainingFields(fieldName, indexOptionsMap); return new Int8FlatIndexOptions(confidenceInterval, rescoreVector); } @Override public boolean supportsElementType(ElementType elementType) { return elementType == ElementType.FLOAT || elementType == ElementType.BFLOAT16; } @Override public boolean supportsDimension(int dims) { return true; } }, INT4_FLAT("int4_flat", true) { @Override public DenseVectorIndexOptions parseIndexOptions(String fieldName, Map<String, ?> indexOptionsMap, IndexVersion indexVersion) { Object confidenceIntervalNode = indexOptionsMap.remove("confidence_interval"); Float confidenceInterval = null; if (confidenceIntervalNode != null) { confidenceInterval = (float) XContentMapValues.nodeDoubleValue(confidenceIntervalNode); } RescoreVector rescoreVector = null; if (hasRescoreIndexVersion(indexVersion)) { rescoreVector = RescoreVector.fromIndexOptions(indexOptionsMap, indexVersion); } MappingParser.checkNoRemainingFields(fieldName, indexOptionsMap); return new Int4FlatIndexOptions(confidenceInterval, rescoreVector); } @Override public boolean supportsElementType(ElementType elementType) { return elementType == ElementType.FLOAT || elementType == ElementType.BFLOAT16; } @Override public boolean supportsDimension(int dims) { return dims % 2 == 0; } }, BBQ_HNSW("bbq_hnsw", true) { @Override public DenseVectorIndexOptions parseIndexOptions(String fieldName, Map<String, ?> indexOptionsMap, IndexVersion indexVersion) { Object mNode = indexOptionsMap.remove("m"); Object efConstructionNode = indexOptionsMap.remove("ef_construction"); Object onDiskRescoreNode = ES93GenericFlatVectorsFormat.GENERIC_VECTOR_FORMAT.isEnabled() ? indexOptionsMap.remove("on_disk_rescore") : false; int m = XContentMapValues.nodeIntegerValue(mNode, Lucene99HnswVectorsFormat.DEFAULT_MAX_CONN); int efConstruction = XContentMapValues.nodeIntegerValue(efConstructionNode, Lucene99HnswVectorsFormat.DEFAULT_BEAM_WIDTH); boolean onDiskRescore = XContentMapValues.nodeBooleanValue(onDiskRescoreNode, false); RescoreVector rescoreVector = null; if (hasRescoreIndexVersion(indexVersion)) { rescoreVector = RescoreVector.fromIndexOptions(indexOptionsMap, indexVersion); if (rescoreVector == null && defaultOversampleForBBQ(indexVersion)) { rescoreVector = new RescoreVector(DEFAULT_OVERSAMPLE); } } MappingParser.checkNoRemainingFields(fieldName, indexOptionsMap); return new BBQHnswIndexOptions(m, efConstruction, onDiskRescore, rescoreVector); } @Override public boolean supportsElementType(ElementType elementType) { return elementType == ElementType.FLOAT || elementType == ElementType.BFLOAT16; } @Override public boolean supportsDimension(int dims) { return dims >= BBQ_MIN_DIMS; } }, BBQ_FLAT("bbq_flat", true) { @Override public DenseVectorIndexOptions parseIndexOptions(String fieldName, Map<String, ?> indexOptionsMap, IndexVersion indexVersion) { RescoreVector rescoreVector = null; if (hasRescoreIndexVersion(indexVersion)) { rescoreVector = RescoreVector.fromIndexOptions(indexOptionsMap, indexVersion); if (rescoreVector == null && defaultOversampleForBBQ(indexVersion)) { rescoreVector = new RescoreVector(DEFAULT_OVERSAMPLE); } } MappingParser.checkNoRemainingFields(fieldName, indexOptionsMap); return new BBQFlatIndexOptions(rescoreVector); } @Override public boolean supportsElementType(ElementType elementType) { return elementType == ElementType.FLOAT || elementType == ElementType.BFLOAT16; } @Override public boolean supportsDimension(int dims) { return dims >= BBQ_MIN_DIMS; } }, BBQ_DISK("bbq_disk", true) { @Override public DenseVectorIndexOptions parseIndexOptions(String fieldName, Map<String, ?> indexOptionsMap, IndexVersion indexVersion) { Object clusterSizeNode = indexOptionsMap.remove("cluster_size"); int clusterSize = ES920DiskBBQVectorsFormat.DEFAULT_VECTORS_PER_CLUSTER; if (clusterSizeNode != null) { clusterSize = XContentMapValues.nodeIntegerValue(clusterSizeNode); if (clusterSize < MIN_VECTORS_PER_CLUSTER || clusterSize > MAX_VECTORS_PER_CLUSTER) { throw new IllegalArgumentException( "cluster_size must be between " + MIN_VECTORS_PER_CLUSTER + " and " + MAX_VECTORS_PER_CLUSTER + ", got: " + clusterSize ); } } RescoreVector rescoreVector = RescoreVector.fromIndexOptions(indexOptionsMap, indexVersion); if (rescoreVector == null) { rescoreVector = new RescoreVector(DEFAULT_OVERSAMPLE); } Object visitPercentageNode = indexOptionsMap.remove("default_visit_percentage"); double visitPercentage = 0d; if (visitPercentageNode != null) { visitPercentage = (float) XContentMapValues.nodeDoubleValue(visitPercentageNode); if (visitPercentage < 0d || visitPercentage > 100d) { throw new IllegalArgumentException( "default_visit_percentage must be between 0.0 and 100.0, got: " + visitPercentage + " for field [" + fieldName + "]" ); } } Object onDiskRescoreNode = ES93GenericFlatVectorsFormat.GENERIC_VECTOR_FORMAT.isEnabled() ? indexOptionsMap.remove("on_disk_rescore") : false; boolean onDiskRescore = XContentMapValues.nodeBooleanValue(onDiskRescoreNode, false); MappingParser.checkNoRemainingFields(fieldName, indexOptionsMap); return new BBQIVFIndexOptions(clusterSize, visitPercentage, onDiskRescore, rescoreVector); } @Override public boolean supportsElementType(ElementType elementType) { return elementType == ElementType.FLOAT || elementType == ElementType.BFLOAT16; } @Override public boolean supportsDimension(int dims) { return true; } }; public static Optional<VectorIndexType> fromString(String type) { return Stream.of(VectorIndexType.values()).filter(vectorIndexType -> vectorIndexType.name.equals(type)).findFirst(); } private final String name; private final boolean quantized; VectorIndexType(String name, boolean quantized) { this.name = name; this.quantized = quantized; } public abstract DenseVectorIndexOptions parseIndexOptions( String fieldName, Map<String, ?> indexOptionsMap, IndexVersion indexVersion ); public abstract boolean supportsElementType(ElementType elementType); public abstract boolean supportsDimension(int dims); public boolean isQuantized() { return quantized; } public String getName() { return name; } @Override public String toString() { return name; } } static
VectorIndexType
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/replica/ReplicaSelectorTest.java
{ "start": 1350, "end": 3719 }
class ____ { @Test public void testSameRackSelector() { TopicPartition tp = new TopicPartition("test", 0); List<ReplicaView> replicaViewSet = replicaInfoSet(); ReplicaView leader = replicaViewSet.get(0); PartitionView partitionView = partitionInfo(new HashSet<>(replicaViewSet), leader); ReplicaSelector selector = new RackAwareReplicaSelector(); Optional<ReplicaView> selected = selector.select(tp, metadata("rack-b"), partitionView); assertOptional(selected, replicaInfo -> { assertEquals("rack-b", replicaInfo.endpoint().rack(), "Expect replica to be in rack-b"); assertEquals(3, replicaInfo.endpoint().id(), "Expected replica 3 since it is more caught-up"); }); selected = selector.select(tp, metadata("not-a-rack"), partitionView); assertOptional(selected, replicaInfo -> assertEquals(replicaInfo, leader, "Expect leader when we can't find any nodes in given rack") ); selected = selector.select(tp, metadata("rack-a"), partitionView); assertOptional(selected, replicaInfo -> { assertEquals("rack-a", replicaInfo.endpoint().rack(), "Expect replica to be in rack-a"); assertEquals(replicaInfo, leader, "Expect the leader since it's in rack-a"); }); } static List<ReplicaView> replicaInfoSet() { return Stream.of( replicaInfo(new Node(0, "host0", 1234, "rack-a"), 4, 0), replicaInfo(new Node(1, "host1", 1234, "rack-a"), 2, 5), replicaInfo(new Node(2, "host2", 1234, "rack-b"), 3, 3), replicaInfo(new Node(3, "host3", 1234, "rack-b"), 4, 2) ).collect(Collectors.toList()); } static ReplicaView replicaInfo(Node node, long logOffset, long timeSinceLastCaughtUpMs) { return new ReplicaView.DefaultReplicaView(node, logOffset, timeSinceLastCaughtUpMs); } static PartitionView partitionInfo(Set<ReplicaView> replicaViewSet, ReplicaView leader) { return new PartitionView.DefaultPartitionView(replicaViewSet, leader); } static ClientMetadata metadata(String rack) { return new ClientMetadata.DefaultClientMetadata(rack, "test-client", InetAddress.getLoopbackAddress(), KafkaPrincipal.ANONYMOUS, "TEST"); } }
ReplicaSelectorTest
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/schema/MyGenericService.java
{ "start": 964, "end": 1252 }
class ____ implements GenericService { public Object $invoke(String methodName, String[] parameterTypes, Object[] args) throws GenericException { if ("sayHello".equals(methodName)) { return "Welcome " + args[0]; } return null; } }
MyGenericService
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/transport/Transport.java
{ "start": 9708, "end": 11295 }
class ____ { private volatile Map<String, RequestHandlerRegistry<? extends TransportRequest>> requestHandlers = Collections.emptyMap(); synchronized <Request extends TransportRequest> void registerHandler(RequestHandlerRegistry<Request> reg) { if (requestHandlers.containsKey(reg.getAction())) { throw new IllegalArgumentException("transport handlers for action " + reg.getAction() + " is already registered"); } requestHandlers = Maps.copyMapWithAddedEntry(requestHandlers, reg.getAction(), reg); } // TODO: Only visible for testing. Perhaps move StubbableTransport from // org.elasticsearch.test.transport to org.elasticsearch.transport public synchronized <Request extends TransportRequest> void forceRegister(RequestHandlerRegistry<Request> reg) { requestHandlers = Maps.copyMapWithAddedOrReplacedEntry(requestHandlers, reg.getAction(), reg); } @SuppressWarnings("unchecked") public <T extends TransportRequest> RequestHandlerRegistry<T> getHandler(String action) { return (RequestHandlerRegistry<T>) requestHandlers.get(action); } public Map<String, TransportActionStats> getStats() { return requestHandlers.values() .stream() .filter(reg -> reg.getStats().requestCount() > 0 || reg.getStats().responseCount() > 0) .collect(Maps.toUnmodifiableSortedMap(RequestHandlerRegistry::getAction, RequestHandlerRegistry::getStats)); } } }
RequestHandlers
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/AsyncExceptionHandler.java
{ "start": 1008, "end": 1255 }
interface ____ { /** * Handles an exception thrown by another thread (e.g. a TriggerTask), other than the one * executing the main task. */ void handleAsyncException(String message, Throwable exception); }
AsyncExceptionHandler
java
quarkusio__quarkus
extensions/reactive-routes/deployment/src/test/java/io/quarkus/vertx/web/reactive/RequestContextPropagationTest.java
{ "start": 792, "end": 1295 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(MyRoutes.class, Ping.class)); @Test public void test() throws InterruptedException, ExecutionException, TimeoutException { get("/ping?val=bar").then().statusCode(200).body(is("foo_bar")); assertTrue(Ping.DESTROYED.get(2, TimeUnit.SECONDS)); } @Singleton static
RequestContextPropagationTest
java
playframework__playframework
core/play/src/main/java/play/i18n/Messages.java
{ "start": 356, "end": 452 }
interface ____ is typically backed by MessagesImpl, but does not return MessagesApi. */ public
that
java
google__guice
core/test/com/google/inject/spi/ToolStageInjectorTest.java
{ "start": 4671, "end": 5134 }
class ____ implements Provider<Object> { @Inject private static S s; @Inject private F f; private M m; @Toolable @SuppressWarnings("unused") @Inject void method(M m) { this.m = m; } private static SM sm; @Toolable @SuppressWarnings("unused") @Inject static void staticMethod(SM sm) { Tooled.sm = sm; } @Override public Object get() { return null; } } private static
Tooled
java
apache__camel
components/camel-spring-parent/camel-spring-ws/src/main/java/org/apache/camel/component/spring/ws/filter/MessageFilter.java
{ "start": 1022, "end": 1122 }
class ____ an additional configuration that can be managed in your Spring's context. */ public
provides
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/SpringApplicationAotProcessorTests.java
{ "start": 5713, "end": 5941 }
class ____ { static void main(String[] args) { invoker.invoke(args, () -> SpringApplication.run(PackagePrivateMainMethod.class, args)); } } @Configuration(proxyBeanMethods = false) public static
PackagePrivateMainMethod
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/operators/CombinerOversizedRecordsTest.java
{ "start": 9476, "end": 10012 }
class ____<T> implements MutableObjectIterator<T> { private final T value; private boolean pending = true; private SingleValueIterator(T value) { this.value = value; } @Override public T next(T reuse) { return next(); } @Override public T next() { if (pending) { pending = false; return value; } else { return null; } } } }
SingleValueIterator
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/abstract_/AbstractAssert_isNot_Test.java
{ "start": 1064, "end": 1522 }
class ____ extends AbstractAssertBaseTest { private static Condition<Object> condition; @BeforeAll static void setUpOnce() { condition = new TestCondition<>(); } @Override protected ConcreteAssert invoke_api_method() { return assertions.isNot(condition); } @Override protected void verify_internal_effects() { verify(conditions).assertIsNot(getInfo(assertions), getActual(assertions), condition); } }
AbstractAssert_isNot_Test
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/script/ScriptContext.java
{ "start": 1425, "end": 1835 }
class ____ be stateless so it is cacheable by the {@link ScriptService}. It must * have one of the following: * <ul> * <li>An abstract method named {@code newInstance} which returns an instance of <i>InstanceType</i></li> * <li>An abstract method named {@code newFactory} which returns an instance of <i>StatefulFactoryType</i></li> * </ul> * <p> * The <i>StatefulFactoryType</i> is an optional
must
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/ConnectorFeatures.java
{ "start": 11298, "end": 14455 }
class ____ implements ToXContentObject, Writeable { private final FeatureEnabled syncRulesAdvancedEnabled; private final FeatureEnabled syncRulesBasicEnabled; private SyncRulesFeatures(FeatureEnabled syncRulesAdvancedEnabled, FeatureEnabled syncRulesBasicEnabled) { this.syncRulesAdvancedEnabled = syncRulesAdvancedEnabled; this.syncRulesBasicEnabled = syncRulesBasicEnabled; } public SyncRulesFeatures(StreamInput in) throws IOException { this.syncRulesAdvancedEnabled = in.readOptionalWriteable(FeatureEnabled::new); this.syncRulesBasicEnabled = in.readOptionalWriteable(FeatureEnabled::new); } private static final ParseField SYNC_RULES_ADVANCED_ENABLED_FIELD = new ParseField("advanced"); private static final ParseField SYNC_RULES_BASIC_ENABLED_FIELD = new ParseField("basic"); private static final ConstructingObjectParser<SyncRulesFeatures, Void> PARSER = new ConstructingObjectParser<>( "sync_rules_features", true, args -> new Builder().setSyncRulesAdvancedEnabled((FeatureEnabled) args[0]) .setSyncRulesBasicEnabled((FeatureEnabled) args[1]) .build() ); static { PARSER.declareObject(optionalConstructorArg(), (p, c) -> FeatureEnabled.fromXContent(p), SYNC_RULES_ADVANCED_ENABLED_FIELD); PARSER.declareObject(optionalConstructorArg(), (p, c) -> FeatureEnabled.fromXContent(p), SYNC_RULES_BASIC_ENABLED_FIELD); } public static SyncRulesFeatures fromXContent(XContentParser p) throws IOException { return PARSER.parse(p, null); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); { if (syncRulesAdvancedEnabled != null) { builder.field(SYNC_RULES_ADVANCED_ENABLED_FIELD.getPreferredName(), syncRulesAdvancedEnabled); } if (syncRulesBasicEnabled != null) { builder.field(SYNC_RULES_BASIC_ENABLED_FIELD.getPreferredName(), syncRulesBasicEnabled); } } builder.endObject(); return builder; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalWriteable(syncRulesAdvancedEnabled); out.writeOptionalWriteable(syncRulesBasicEnabled); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SyncRulesFeatures that = (SyncRulesFeatures) o; return Objects.equals(syncRulesAdvancedEnabled, that.syncRulesAdvancedEnabled) && Objects.equals(syncRulesBasicEnabled, that.syncRulesBasicEnabled); } @Override public int hashCode() { return Objects.hash(syncRulesAdvancedEnabled, syncRulesBasicEnabled); } public static
SyncRulesFeatures
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest3.java
{ "start": 837, "end": 1182 }
class ____ extends TestCase { public void test_stuff() throws Exception { assertTrue(WallUtils.isValidateMySql(// "SELECT COUNT(p.id) FROM TB_PRO p" + " INNER JOIN TB_Db b ON b.id =p.dbid " + " WHERE p.index_status='0' AND p.sc=?")); } }
MySqlWallTest3
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/spi/CollectionTracker.java
{ "start": 319, "end": 414 }
interface ____ { void add(String name, int size); int getSize(String name); }
CollectionTracker
java
google__dagger
javatests/dagger/internal/codegen/ComponentCreatorTest.java
{ "start": 36843, "end": 38003 }
interface ____ {", " Supertype build();", " }", "}"); CompilerTests.daggerCompiler(foo, bar, supertype, component) .withProcessingOptions(compilerOptions) .compile( subject -> { subject.hasErrorCount(0); subject.hasWarningContaining( process( "test.HasSupertype.Builder.build() returns test.Supertype, but " + "test.HasSupertype declares additional component method(s): bar(). " + "In order to provide type-safe access to these methods, override " + "build() to return test.HasSupertype")) .onSource(component) .onLine(11); }); } @Test public void covariantFactoryMethodReturnType_hasNewMethod_factoryMethodInherited() { assume().that(compilerType).isEqualTo(JAVAC); Source foo = CompilerTests.javaSource( "test.Foo", "package test;", "", "import javax.inject.Inject;", "", "
Builder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/CircularElement.java
{ "start": 1038, "end": 2725 }
class ____<E> { private final int id; private final InMemorySorter<E> buffer; private final List<MemorySegment> memory; public CircularElement(int id) { this.id = id; this.buffer = null; this.memory = null; } public CircularElement(int id, InMemorySorter<E> buffer, List<MemorySegment> memory) { this.id = id; this.buffer = buffer; this.memory = memory; } public int getId() { return id; } public InMemorySorter<E> getBuffer() { return buffer; } public List<MemorySegment> getMemory() { return memory; } /** The element that is passed as marker for the end of data. */ static final CircularElement<Object> EOF_MARKER = new CircularElement<>(-1); /** The element that is passed as marker for signal beginning of spilling. */ static final CircularElement<Object> SPILLING_MARKER = new CircularElement<>(-2); /** * Gets the element that is passed as marker for the end of data. * * @return The element that is passed as marker for the end of data. */ static <T> CircularElement<T> endMarker() { @SuppressWarnings("unchecked") CircularElement<T> c = (CircularElement<T>) EOF_MARKER; return c; } /** * Gets the element that is passed as marker for signal beginning of spilling. * * @return The element that is passed as marker for signal beginning of spilling. */ static <T> CircularElement<T> spillingMarker() { @SuppressWarnings("unchecked") CircularElement<T> c = (CircularElement<T>) SPILLING_MARKER; return c; } }
CircularElement
java
apache__dubbo
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/support/MockInvoker.java
{ "start": 2079, "end": 5650 }
class ____<T> implements Invoker<T> { private final ProxyFactory proxyFactory; private static final Map<String, Invoker<?>> MOCK_MAP = new ConcurrentHashMap<>(); private static final Map<String, Throwable> THROWABLE_MAP = new ConcurrentHashMap<>(); private final URL url; private final Class<T> type; public MockInvoker(URL url, Class<T> type) { this.url = url; this.type = type; this.proxyFactory = url.getOrDefaultFrameworkModel() .getExtensionLoader(ProxyFactory.class) .getAdaptiveExtension(); } public static Object parseMockValue(String mock) throws Exception { return parseMockValue(mock, null); } public static Object parseMockValue(String mock, Type[] returnTypes) throws Exception { Object value; if ("empty".equals(mock)) { value = ReflectUtils.getEmptyObject( returnTypes != null && returnTypes.length > 0 ? (Class<?>) returnTypes[0] : null); } else if ("null".equals(mock)) { value = null; } else if ("true".equals(mock)) { value = true; } else if ("false".equals(mock)) { value = false; } else if (mock.length() >= 2 && (mock.startsWith("\"") && mock.endsWith("\"") || mock.startsWith("\'") && mock.endsWith("\'"))) { value = mock.subSequence(1, mock.length() - 1); } else if (returnTypes != null && returnTypes.length > 0 && returnTypes[0] == String.class) { value = mock; } else if (StringUtils.isNumeric(mock, false)) { value = JsonUtils.toJavaObject(mock, Object.class); } else if (mock.startsWith("{")) { value = JsonUtils.toJavaObject(mock, Map.class); } else if (mock.startsWith("[")) { value = JsonUtils.toJavaList(mock, Object.class); } else { value = mock; } if (ArrayUtils.isNotEmpty(returnTypes)) { value = PojoUtils.realize(value, (Class<?>) returnTypes[0], returnTypes.length > 1 ? returnTypes[1] : null); } return value; } @Override public Result invoke(Invocation invocation) throws RpcException { if (invocation instanceof RpcInvocation) { ((RpcInvocation) invocation).setInvoker(this); } String mock = getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY); if (StringUtils.isBlank(mock)) { throw new RpcException(new IllegalAccessException("mock can not be null. url :" + url)); } mock = normalizeMock(URL.decode(mock)); if (mock.startsWith(RETURN_PREFIX)) { mock = mock.substring(RETURN_PREFIX.length()).trim(); try { Type[] returnTypes = RpcUtils.getReturnTypes(invocation); Object value = parseMockValue(mock, returnTypes); return AsyncRpcResult.newDefaultAsyncResult(value, invocation); } catch (Exception ew) { throw new RpcException( "mock return invoke error. method :" + invocation.getMethodName() + ", mock:" + mock + ", url: " + url, ew); } } else if (mock.startsWith(THROW_PREFIX)) { mock = mock.substring(THROW_PREFIX.length()).trim(); if (StringUtils.isBlank(mock)) { throw new RpcException("mocked exception for service degradation."); } else { // user customized
MockInvoker
java
quarkusio__quarkus
independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/graal/ImageInfo.java
{ "start": 289, "end": 605 }
class ____ { public static boolean inImageRuntimeCode() { return "runtime".equals(System.getProperty("org.graalvm.nativeimage.imagecode")); } public static boolean inImageBuildtimeCode() { return "buildtime".equals(System.getProperty("org.graalvm.nativeimage.imagecode")); } }
ImageInfo
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/stream/StreamWriterTest_writeValueString1.java
{ "start": 261, "end": 803 }
class ____ extends TestCase { public void test_0() throws Exception { StringWriter out = new StringWriter(); SerializeWriter writer = new SerializeWriter(out, 10); writer.config(SerializerFeature.BrowserCompatible, true); Assert.assertEquals(10, writer.getBufferLength()); writer.writeString("abcde12345678\t"); writer.close(); String text = out.toString(); Assert.assertEquals("\"abcde12345678\\t\"", text); } }
StreamWriterTest_writeValueString1
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/AccessExecutionGraph.java
{ "start": 1737, "end": 7339 }
interface ____ extends JobStatusProvider { /** * Returns the job plan as a JobPlanInfo.Plan. * * @return job plan as a JobPlanInfo.Plan */ JobPlanInfo.Plan getPlan(); /** * Returns the stream graph as a JSON string. * * @return stream graph as a JSON string, or null if the job is submitted with a JobGraph or if * it's a streaming job. */ @Nullable String getStreamGraphJson(); /** * Returns the {@link JobID} for this execution graph. * * @return job ID for this execution graph */ JobID getJobID(); /** * Returns the job name for the execution graph. * * @return job name for this execution graph */ String getJobName(); /** * Returns the current {@link JobStatus} for this execution graph. * * @return job status for this execution graph */ JobStatus getState(); /** * Returns the {@link JobType} for this execution graph. * * @return job type for this execution graph. It may be null when an exception occurs. */ @Nullable JobType getJobType(); /** * Returns the exception that caused the job to fail. This is the first root exception that was * not recoverable and triggered job failure. * * @return failure causing exception, or null */ @Nullable ErrorInfo getFailureInfo(); /** * Returns the job vertex for the given {@link JobVertexID}. * * @param id id of job vertex to be returned * @return job vertex for the given id, or {@code null} */ @Nullable AccessExecutionJobVertex getJobVertex(JobVertexID id); /** * Returns a map containing all job vertices for this execution graph. * * @return map containing all job vertices for this execution graph */ Map<JobVertexID, ? extends AccessExecutionJobVertex> getAllVertices(); /** * Returns an iterable containing all job vertices for this execution graph in the order they * were created. * * @return iterable containing all job vertices for this execution graph in the order they were * created */ Iterable<? extends AccessExecutionJobVertex> getVerticesTopologically(); /** * Returns an iterable containing all execution vertices for this execution graph. * * @return iterable containing all execution vertices for this execution graph */ Iterable<? extends AccessExecutionVertex> getAllExecutionVertices(); /** * Returns the timestamp for the given {@link JobStatus}. * * @param status status for which the timestamp should be returned * @return timestamp for the given job status */ long getStatusTimestamp(JobStatus status); /** * Returns the {@link CheckpointCoordinatorConfiguration} or <code>null</code> if checkpointing * is disabled. * * @return JobCheckpointingConfiguration for this execution graph */ @Nullable CheckpointCoordinatorConfiguration getCheckpointCoordinatorConfiguration(); /** * Returns a snapshot of the checkpoint statistics or <code>null</code> if checkpointing is * disabled. * * @return Snapshot of the checkpoint statistics for this execution graph */ @Nullable CheckpointStatsSnapshot getCheckpointStatsSnapshot(); /** * Returns the {@link ArchivedExecutionConfig} for this execution graph. * * @return execution config summary for this execution graph, or null in case of errors */ @Nullable ArchivedExecutionConfig getArchivedExecutionConfig(); /** * Returns whether the job for this execution graph is stoppable. * * @return true, if all sources tasks are stoppable, false otherwise */ boolean isStoppable(); /** * Returns the aggregated user-defined accumulators as strings. * * @return aggregated user-defined accumulators as strings. */ StringifiedAccumulatorResult[] getAccumulatorResultsStringified(); /** * Returns a map containing the serialized values of user-defined accumulators. * * @return map containing serialized values of user-defined accumulators */ Map<String, SerializedValue<OptionalFailure<Object>>> getAccumulatorsSerialized(); /** * Returns the state backend name for this ExecutionGraph. * * @return The state backend name, or an empty Optional in the case of batch jobs */ Optional<String> getStateBackendName(); /** * Returns the checkpoint storage name for this ExecutionGraph. * * @return The checkpoint storage name, or an empty Optional in the case of batch jobs */ Optional<String> getCheckpointStorageName(); /** * Returns whether the state changelog is enabled for this ExecutionGraph. * * @return true, if state changelog enabled, false otherwise. */ TernaryBoolean isChangelogStateBackendEnabled(); /** * Returns the changelog storage name for this ExecutionGraph. * * @return The changelog storage name, or an empty Optional in the case of batch jobs */ Optional<String> getChangelogStorageName(); /** * Retrieves the count of pending operators waiting to be transferred to job vertices in the * adaptive execution of batch jobs. This value will be zero if the job is submitted with a * JobGraph or if it's a streaming job. * * @return the number of pending operators. */ int getPendingOperatorCount(); }
AccessExecutionGraph
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/sessioncontext/SessionContextListener.java
{ "start": 575, "end": 1428 }
class ____ { final CountDownLatch destroyLatch = new CountDownLatch(1); final List<ContextEvent> events = new CopyOnWriteArrayList<>(); void init(@Observes @Initialized(SessionScoped.class) Object event, EventMetadata metadata) { events.add(new ContextEvent(metadata.getQualifiers(), event.toString())); } void beforeDestroy(@Observes @BeforeDestroyed(SessionScoped.class) Object event, EventMetadata metadata) { events.add(new ContextEvent(metadata.getQualifiers(), event.toString())); } void destroy(@Observes @Destroyed(SessionScoped.class) Object event, EventMetadata metadata) { events.add(new ContextEvent(metadata.getQualifiers(), event.toString())); destroyLatch.countDown(); } record ContextEvent(Set<Annotation> qualifiers, String payload) { }; }
SessionContextListener
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/instrumentation/GraphQLOpenTelemetryTest.java
{ "start": 8950, "end": 9973 }
class ____ { @Inject CustomCDIBean cdiBean; @WithSpan @Query public String hello() { return "hello xyz"; } @WithSpan @Query public List<String> hellos() { return List.of("hello, hi, hey"); } @WithSpan @Query public String helloAfterSecond() throws InterruptedException { cdiBean.waitForSomeTime(); return "hello"; } // FIXME: error handling in spans @WithSpan @Query public String errorHello() { throw new RuntimeException("Error"); } @WithSpan @Mutation public String createHello() { return "hello created"; } // TODO: SOURCE field tests (sync) // TODO: SOURCE field tests (async) // TODO: nonblocking queries/mutations (reactive) tests // TODO: subscriptions tests (?) } @ApplicationScoped public static
HelloResource
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteEngineTests.java
{ "start": 27948, "end": 28047 }
class ____ { } @Suite @SelectClasses(SingleTestTestCase.class) private static
AbstractPrivateSuite
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/propertyeditors/CharsetEditor.java
{ "start": 1166, "end": 1550 }
class ____ extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { if (StringUtils.hasText(text)) { setValue(Charset.forName(text.trim())); } else { setValue(null); } } @Override public String getAsText() { Charset value = (Charset) getValue(); return (value != null ? value.name() : ""); } }
CharsetEditor
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/config/GatewayAutoConfigurationTests.java
{ "start": 19744, "end": 20709 }
class ____ { @Bean @Primary CustomHttpClientFactory customHttpClientFactory(HttpClientProperties properties, ServerProperties serverProperties, List<HttpClientCustomizer> customizers, HttpClientSslConfigurer sslConfigurer) { return new CustomHttpClientFactory(properties, serverProperties, sslConfigurer, customizers); } @Bean @Primary CustomSslConfigurer customSslContextFactory(ServerProperties serverProperties, HttpClientProperties httpClientProperties, SslBundles bundles) { return new CustomSslConfigurer(httpClientProperties.getSsl(), serverProperties, bundles); } @Bean @Primary SslBundles sslBundleRegistry(ObjectProvider<SslBundleRegistrar> sslBundleRegistrars) { DefaultSslBundleRegistry registry = new DefaultSslBundleRegistry(); sslBundleRegistrars.orderedStream().forEach((registrar) -> { registrar.registerBundles(registry); }); return registry; } } protected static
ServerPropertiesConfig
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/bitset/BitSetJavaTypeContributionTests.java
{ "start": 895, "end": 1535 }
class ____ { @Test public void testResolution(SessionFactoryScope scope) { final EntityPersister productType = scope.getSessionFactory() .getRuntimeMetamodels() .getMappingMetamodel() .findEntityDescriptor(Product.class); final SingularAttributeMapping bitSetAttribute = (SingularAttributeMapping) productType.findAttributeMapping("bitSet"); // make sure BitSetTypeDescriptor was selected assertThat( bitSetAttribute.getJavaType(), instanceOf( BitSetJavaType.class)); } @Table(name = "Product") //tag::basic-bitset-example-java-type-contrib[] @Entity(name = "Product") public static
BitSetJavaTypeContributionTests
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/runtime/src/main/java/io/quarkus/restclient/runtime/graal/ClientBuilderReplacement.java
{ "start": 502, "end": 804 }
class ____ { @Substitute public static ClientBuilder newBuilder() { ResteasyClientBuilder client = new ResteasyClientBuilderImpl(); client.providerFactory(new LocalResteasyProviderFactory(RestClientRecorder.providerFactory)); return client; } }
ClientBuilderReplacement
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3360/Issue3360Mapper.java
{ "start": 678, "end": 1063 }
interface ____ { Issue3360Mapper INSTANCE = Mappers.getMapper( Issue3360Mapper.class ); @SubclassMapping(target = VehicleDto.Car.class, source = Vehicle.Car.class) VehicleDto map(Vehicle vehicle); @Mapping(target = "model", source = "modelName") @BeanMapping(ignoreUnmappedSourceProperties = "computedName") VehicleDto.Car map(Vehicle.Car car); }
Issue3360Mapper
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java
{ "start": 19962, "end": 20839 }
class ____ { @Test void propertyField() { evaluate("name", "Nikola Tesla", String.class, true); // not writable because (1) name is private (2) there is no setter, only a getter evaluateAndCheckError("madeup", SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE, 0, "madeup", "org.springframework.expression.spel.testresources.Inventor"); } @Test void propertyField_SPR7100() { evaluate("_name", "Nikola Tesla", String.class); evaluate("_name_", "Nikola Tesla", String.class); } @Test void rogueTrailingDotCausesNPE_SPR6866() { assertThatExceptionOfType(SpelParseException.class) .isThrownBy(() -> new SpelExpressionParser().parseExpression("placeOfBirth.foo.")) .satisfies(ex -> { assertThat(ex.getMessageCode()).isEqualTo(SpelMessage.OOD); assertThat(ex.getPosition()).isEqualTo(16); }); } @Nested
PropertyAccessTests
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/functions/Functions.java
{ "start": 11471, "end": 11999 }
class ____<T> implements Predicate<T> { final BooleanSupplier supplier; BooleanSupplierPredicateReverse(BooleanSupplier supplier) { this.supplier = supplier; } @Override public boolean test(T t) throws Throwable { return !supplier.getAsBoolean(); } } public static <T> Predicate<T> predicateReverseFor(BooleanSupplier supplier) { return new BooleanSupplierPredicateReverse<>(supplier); } static final
BooleanSupplierPredicateReverse
java
apache__flink
flink-end-to-end-tests/flink-stream-state-ttl-test/src/main/java/org/apache/flink/streaming/tests/verify/TtlMapStateVerifier.java
{ "start": 1549, "end": 3969 }
class ____ extends AbstractTtlStateVerifier< MapStateDescriptor<String, String>, MapState<String, String>, Map<String, String>, Tuple2<String, String>, Map<String, String>> { private static final List<String> KEYS = new ArrayList<>(); static { IntStream.range(0, RANDOM.nextInt(5) + 5).forEach(i -> KEYS.add(randomString())); } TtlMapStateVerifier() { super( new MapStateDescriptor<>( TtlMapStateVerifier.class.getSimpleName(), StringSerializer.INSTANCE, StringSerializer.INSTANCE)); } @Override @Nonnull State createState(@Nonnull FunctionInitializationContext context) { return context.getKeyedStateStore().getMapState(stateDesc); } @SuppressWarnings("unchecked") @Override @Nonnull public TypeSerializer<Tuple2<String, String>> getUpdateSerializer() { return new TupleSerializer( Tuple2.class, new TypeSerializer[] {StringSerializer.INSTANCE, StringSerializer.INSTANCE}); } @Override @Nonnull public Tuple2<String, String> generateRandomUpdate() { return Tuple2.of(KEYS.get(RANDOM.nextInt(KEYS.size())), randomString()); } @Override @Nonnull Map<String, String> getInternal(@Nonnull MapState<String, String> state) throws Exception { return StreamSupport.stream(state.entries().spliterator(), false) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Override void updateInternal(@Nonnull MapState<String, String> state, Tuple2<String, String> update) throws Exception { state.put(update.f0, update.f1); } @Override @Nonnull Map<String, String> expected( @Nonnull List<ValueWithTs<Tuple2<String, String>>> updates, long currentTimestamp) { return updates.stream() .collect(Collectors.groupingBy(u -> u.getValue().f0)) .entrySet() .stream() .map(e -> e.getValue().get(e.getValue().size() - 1)) .filter(u -> !expired(u.getTimestamp(), currentTimestamp)) .map(ValueWithTs::getValue) .collect(Collectors.toMap(u -> u.f0, u -> u.f1)); } }
TtlMapStateVerifier
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/cfg/SerializationContexts.java
{ "start": 979, "end": 4969 }
class ____ implements java.io.Serializable { private static final long serialVersionUID = 3L; /* /********************************************************************** /* Configuration /********************************************************************** */ // NOTE! We do not need (or want) to serialize any of these because they // get passed via `forMapper(...)` call; all we want to serialize is identity // of this class (and possibly whatever sub-classes may want to retain). // Hence `transient` modifiers /** * Low-level {@link TokenStreamFactory} that may be used for constructing * embedded generators. */ final transient protected TokenStreamFactory _streamFactory; /** * Factory responsible for constructing standard serializers. */ final transient protected SerializerFactory _serializerFactory; /** * Cache for doing type-to-value-serializer lookups. */ final transient protected SerializerCache _cache; /* /********************************************************************** /* Life-cycle /********************************************************************** */ protected SerializationContexts() { this(null, null, null); } protected SerializationContexts(TokenStreamFactory tsf, SerializerFactory serializerFactory, SerializerCache cache) { _streamFactory = tsf; _serializerFactory = serializerFactory; _cache = cache; } /** * Mutant factory method called when instance is actually created for use by mapper * (as opposed to coming into existence during building, module registration). * Necessary usually to initialize non-configuration state, such as caching. */ public SerializationContexts forMapper(Object mapper, SerializationConfig config, TokenStreamFactory tsf, SerializerFactory serializerFactory) { return forMapper(mapper, tsf, serializerFactory, new SerializerCache(config.getCacheProvider().forSerializerCache(config))); } protected abstract SerializationContexts forMapper(Object mapper, TokenStreamFactory tsf, SerializerFactory serializerFactory, SerializerCache cache); /** * Factory method for constructing context object for individual {@code writeValue()} * calls. */ public abstract SerializationContextExt createContext(SerializationConfig config, GeneratorSettings genSettings); /* /********************************************************************** /* Access to caching details /********************************************************************** */ /** * Method that can be used to determine how many serializers this * provider is caching currently * (if it does caching: default implementation does) * Exact count depends on what kind of serializers get cached; * default implementation caches all serializers, including ones that * are eagerly constructed (for optimal access speed) *<p> * The main use case for this method is to allow conditional flushing of * serializer cache, if certain number of entries is reached. */ public int cachedSerializersCount() { return _cache.size(); } /** * Method that will drop all serializers currently cached by this provider. * This can be used to remove memory usage (in case some serializers are * only used once or so), or to force re-construction of serializers after * configuration changes for mapper than owns the provider. */ public void flushCachedSerializers() { _cache.flush(); } /* /********************************************************************** /* Vanilla implementation /********************************************************************** */ public static
SerializationContexts
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/select/SqmJpaCompoundSelection.java
{ "start": 1537, "end": 5337 }
class ____<T> extends AbstractSqmExpression<T> implements JpaCompoundSelection<T>, SqmExpressible<T> { private final List<? extends SqmSelectableNode<?>> selectableNodes; private final JavaType<T> javaType; public SqmJpaCompoundSelection( List<? extends SqmSelectableNode<?>> selectableNodes, JavaType<T> javaType, NodeBuilder criteriaBuilder) { super( null, criteriaBuilder ); this.selectableNodes = selectableNodes; this.javaType = javaType; // setExpressibleType( this ); } @Override public SqmJpaCompoundSelection<T> copy(SqmCopyContext context) { final SqmJpaCompoundSelection<T> existing = context.getCopy( this ); if ( existing != null ) { return existing; } final List<SqmSelectableNode<?>> selectableNodes = new ArrayList<>( this.selectableNodes.size() ); for ( SqmSelectableNode<?> selectableNode : this.selectableNodes ) { selectableNodes.add( selectableNode.copy( context ) ); } return context.registerCopy( this, new SqmJpaCompoundSelection<>( selectableNodes, javaType, nodeBuilder() ) ); } @Override public JavaType<T> getJavaTypeDescriptor() { return javaType; } @Override public JavaType<T> getExpressibleJavaType() { return getJavaTypeDescriptor(); } @Override public Class<T> getJavaType() { return getJavaTypeDescriptor().getJavaTypeClass(); } // @Override // public Class<T> getJavaType() { // return getJavaType(); // } @Override public List<? extends SqmSelectableNode<?>> getSelectionItems() { return selectableNodes; } @Override public JpaSelection<T> alias(String name) { return this; } @Override public @Nullable String getAlias() { return null; } @Override public boolean isCompoundSelection() { return true; } @Override public <X> X accept(SemanticQueryWalker<X> walker) { return walker.visitJpaCompoundSelection( this ); } @Override public void appendHqlString(StringBuilder hql, SqmRenderContext context) { appendSelectableNode( hql, context, selectableNodes.get( 0 ) ); for ( int i = 1; i < selectableNodes.size(); i++ ) { hql.append(", "); appendSelectableNode( hql, context, selectableNodes.get( i ) ); } } private static void appendSelectableNode(StringBuilder hql, SqmRenderContext context, SqmSelectableNode<?> sqmSelectableNode) { sqmSelectableNode.appendHqlString( hql, context ); if ( sqmSelectableNode.getAlias() != null ) { hql.append( " as " ).append( sqmSelectableNode.getAlias() ); } } @Override public boolean equals(@Nullable Object object) { if ( !(object instanceof SqmJpaCompoundSelection<?> that) || selectableNodes.size() != that.selectableNodes.size() ) { return false; } for ( SqmSelectableNode<?> selectableNode : selectableNodes ) { if ( !selectableNode.equals( that ) || !Objects.equals( selectableNode.getAlias(), that.getAlias() ) ) { return false; } } return true; } @Override public int hashCode() { return Objects.hashCode( selectableNodes ); } @Override public boolean isCompatible(Object object) { if ( !(object instanceof SqmJpaCompoundSelection<?> that) || selectableNodes.size() != that.selectableNodes.size() ) { return false; } for ( SqmSelectableNode<?> selectableNode : selectableNodes ) { if ( !selectableNode.isCompatible( that ) || !Objects.equals( selectableNode.getAlias(), that.getAlias() ) ) { return false; } } return true; } @Override public int cacheHashCode() { return SqmCacheable.cacheHashCode( selectableNodes ); } @Override public void visitSubSelectableNodes(Consumer<SqmSelectableNode<?>> jpaSelectionConsumer) { selectableNodes.forEach( jpaSelectionConsumer ); } @Override public @Nullable SqmDomainType<T> getSqmType() { return null; } }
SqmJpaCompoundSelection
java
google__error-prone
check_api/src/test/java/com/google/errorprone/util/ASTHelpersTest.java
{ "start": 43190, "end": 44054 }
class ____ { // BUG: Diagnostic contains: Cannot be overridden Test() {} // BUG: Diagnostic contains: Can be overridden void canBeOverridden() {} // BUG: Diagnostic contains: Cannot be overridden final void cannotBeOverriddenBecauseFinal() {} // BUG: Diagnostic contains: Cannot be overridden static void cannotBeOverriddenBecauseStatic() {} // BUG: Diagnostic contains: Cannot be overridden private void cannotBeOverriddenBecausePrivate() {} } """) .doTest(); } @Test public void methodCanBeOverridden_interface() { CompilationTestHelper.newInstance(MethodCanBeOverriddenChecker.class, getClass()) .addSourceLines( "Test.java", """
Test
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/logging/logback/LogbackConfigurator.java
{ "start": 1401, "end": 3506 }
class ____ { private final LoggerContext context; LogbackConfigurator(LoggerContext context) { Assert.notNull(context, "'context' must not be null"); this.context = context; } LoggerContext getContext() { return this.context; } ReentrantLock getConfigurationLock() { return this.context.getConfigurationLock(); } @SuppressWarnings("unchecked") <T extends Converter<?>> void conversionRule(String conversionWord, Class<T> converterClass, Supplier<T> converterSupplier) { Assert.hasLength(conversionWord, "'conversionWord' must not be empty"); Assert.notNull(converterSupplier, "'converterSupplier' must not be null"); Map<String, Supplier<?>> registry = (Map<String, Supplier<?>>) this.context .getObject(CoreConstants.PATTERN_RULE_REGISTRY_FOR_SUPPLIERS); if (registry == null) { registry = new HashMap<>(); this.context.putObject(CoreConstants.PATTERN_RULE_REGISTRY_FOR_SUPPLIERS, registry); } registry.put(conversionWord, converterSupplier); } void appender(String name, Appender<?> appender) { appender.setName(name); start(appender); } void logger(String name, @Nullable Level level) { logger(name, level, true); } void logger(String name, @Nullable Level level, boolean additive) { logger(name, level, additive, null); } void logger(String name, @Nullable Level level, boolean additive, @Nullable Appender<ILoggingEvent> appender) { Logger logger = this.context.getLogger(name); if (level != null) { logger.setLevel(level); } logger.setAdditive(additive); if (appender != null) { logger.addAppender(appender); } } @SafeVarargs final void root(@Nullable Level level, Appender<ILoggingEvent>... appenders) { Logger logger = this.context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); if (level != null) { logger.setLevel(level); } for (Appender<ILoggingEvent> appender : appenders) { logger.addAppender(appender); } } void start(LifeCycle lifeCycle) { if (lifeCycle instanceof ContextAware contextAware) { contextAware.setContext(this.context); } lifeCycle.start(); } }
LogbackConfigurator
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/utils/TransformationMetadata.java
{ "start": 1279, "end": 2344 }
class ____ { private final @Nullable String uid; private final String name; private final String desc; /** Used by {@link BatchExecNode}, as they don't require the uid. */ public TransformationMetadata(String name, String desc) { this(null, name, desc); } /** Used by {@link StreamExecNode}, as they require the uid. */ public TransformationMetadata(String uid, String name, String desc) { this.uid = uid; this.name = name; this.desc = desc; } public @Nullable String getUid() { return uid; } public String getName() { return name; } public String getDescription() { return desc; } /** Fill a transformation with this meta. */ public <T extends Transformation<?>> T fill(T transformation) { transformation.setName(getName()); transformation.setDescription(getDescription()); if (getUid() != null) { transformation.setUid(getUid()); } return transformation; } }
TransformationMetadata
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/vld/BasicPTVTest.java
{ "start": 2276, "end": 10372 }
class ____ @Test public void testAllowByBaseClass() throws Exception { final PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder() .allowIfBaseType(BaseValue.class) .build(); ObjectMapper mapper = jsonMapperBuilder() .activateDefaultTyping(ptv, DefaultTyping.NON_FINAL) .build(); // First, test accepted case final String json = mapper.writeValueAsString(BaseValueWrapper.withA(42)); BaseValueWrapper w = mapper.readValue(json, BaseValueWrapper.class); assertEquals(42, w.value.x); // then non-accepted final String json2 = mapper.writeValueAsString(new NumberWrapper(Byte.valueOf((byte) 4))); try { mapper.readValue(json2, NumberWrapper.class); fail("Should not pass"); } catch (InvalidTypeIdException e) { verifyException(e, "Could not resolve type id 'java.lang.Byte'"); verifyException(e, "as a subtype of"); } // and then yet again accepted one with different config ObjectMapper mapper2 = jsonMapperBuilder() .activateDefaultTyping(BasicPolymorphicTypeValidator.builder() .allowIfBaseType(Number.class) .build(), DefaultTyping.NON_FINAL) .build(); NumberWrapper nw = mapper2.readValue(json2, NumberWrapper.class); assertNotNull(nw); assertEquals(Byte.valueOf((byte) 4), nw.value); } // Then subtype-prefix @Test public void testAllowByBaseClassPrefix() throws Exception { final PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder() .allowIfBaseType("tools.jackson.") .build(); ObjectMapper mapper = jsonMapperBuilder() .activateDefaultTyping(ptv, DefaultTyping.NON_FINAL) .build(); // First, test accepted case final String json = mapper.writeValueAsString(BaseValueWrapper.withA(42)); BaseValueWrapper w = mapper.readValue(json, BaseValueWrapper.class); assertEquals(42, w.value.x); // then non-accepted final String json2 = mapper.writeValueAsString(new NumberWrapper(Byte.valueOf((byte) 4))); try { mapper.readValue(json2, NumberWrapper.class); fail("Should not pass"); } catch (InvalidTypeIdException e) { verifyException(e, "Could not resolve type id 'java.lang.Byte'"); verifyException(e, "as a subtype of"); } } // Then subtype-pattern @Test public void testAllowByBaseClassPattern() throws Exception { final PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder() .allowIfBaseType(Pattern.compile("\\w+\\.jackson\\..+")) .build(); ObjectMapper mapper = jsonMapperBuilder() .activateDefaultTyping(ptv, DefaultTyping.NON_FINAL) .build(); // First, test accepted case final String json = mapper.writeValueAsString(BaseValueWrapper.withA(42)); BaseValueWrapper w = mapper.readValue(json, BaseValueWrapper.class); assertEquals(42, w.value.x); // then non-accepted final String json2 = mapper.writeValueAsString(new NumberWrapper(Byte.valueOf((byte) 4))); try { mapper.readValue(json2, NumberWrapper.class); fail("Should not pass"); } catch (InvalidTypeIdException e) { verifyException(e, "Could not resolve type id 'java.lang.Byte'"); verifyException(e, "as a subtype of"); } } // And finally, block by specific direct-match base type @Test public void testDenyByBaseClass() throws Exception { final PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder() // indicate that all subtypes `BaseValue` would be fine .allowIfBaseType(BaseValue.class) // but that nominal base type MUST NOT be `Object.class` .denyForExactBaseType(Object.class) .build(); ObjectMapper mapper = jsonMapperBuilder() .activateDefaultTyping(ptv, DefaultTyping.NON_FINAL) .build(); final String json = mapper.writeValueAsString(new ObjectWrapper(new ValueA(15))); try { mapper.readValue(json, ObjectWrapper.class); fail("Should not pass"); // NOTE: different exception type since denial was for whole property, not just specific values } catch (InvalidDefinitionException e) { verifyException(e, "denied resolution of all subtypes of base type `java.lang.Object`"); } } /* /********************************************************************** /* Test methods: by sub type /********************************************************************** */ @Test public void testAllowBySubClass() throws Exception { final PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder() .allowIfSubType(ValueB.class) .build(); ObjectMapper mapper = jsonMapperBuilder() .activateDefaultTyping(ptv, DefaultTyping.NON_FINAL) .build(); // First, test accepted case final String json = mapper.writeValueAsString(BaseValueWrapper.withB(42)); BaseValueWrapper w = mapper.readValue(json, BaseValueWrapper.class); assertEquals(42, w.value.x); // then non-accepted try { mapper.readValue(mapper.writeValueAsString(BaseValueWrapper.withA(43)), BaseValueWrapper.class); fail("Should not pass"); } catch (InvalidTypeIdException e) { verifyException(e, "Could not resolve type id 'tools.jackson."); verifyException(e, "as a subtype of"); } } @Test public void testAllowBySubClassPrefix() throws Exception { final PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder() .allowIfSubType(ValueB.class.getName()) .build(); ObjectMapper mapper = jsonMapperBuilder() .activateDefaultTyping(ptv, DefaultTyping.NON_FINAL) .build(); // First, test accepted case final String json = mapper.writeValueAsString(BaseValueWrapper.withB(42)); BaseValueWrapper w = mapper.readValue(json, BaseValueWrapper.class); assertEquals(42, w.value.x); // then non-accepted try { mapper.readValue(mapper.writeValueAsString(BaseValueWrapper.withA(43)), BaseValueWrapper.class); fail("Should not pass"); } catch (InvalidTypeIdException e) { verifyException(e, "Could not resolve type id 'tools.jackson."); verifyException(e, "as a subtype of"); } } @Test public void testAllowBySubClassPattern() throws Exception { final PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder() .allowIfSubType(Pattern.compile(Pattern.quote(ValueB.class.getName()))) .build(); ObjectMapper mapper = jsonMapperBuilder() .activateDefaultTyping(ptv, DefaultTyping.NON_FINAL) .build(); // First, test accepted case final String json = mapper.writeValueAsString(BaseValueWrapper.withB(42)); BaseValueWrapper w = mapper.readValue(json, BaseValueWrapper.class); assertEquals(42, w.value.x); // then non-accepted try { mapper.readValue(mapper.writeValueAsString(BaseValueWrapper.withA(43)), BaseValueWrapper.class); fail("Should not pass"); } catch (InvalidTypeIdException e) { verifyException(e, "Could not resolve type id 'tools.jackson."); verifyException(e, "as a subtype of"); } } }
allowing
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnit4TestNotRunTest.java
{ "start": 22629, "end": 23140 }
class ____ { @Ignore public void testMethod() {} } """) .doTest(); } @Test public void junit4Theory_isTestAnnotation() { compilationHelper .addSourceLines( "TestTheories.java", """ import org.junit.runner.RunWith; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; @RunWith(Theories.class) public
TestStuff
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/heartbeat/NoOpHeartbeatServices.java
{ "start": 1075, "end": 1963 }
class ____ implements HeartbeatServices { private static final NoOpHeartbeatServices INSTANCE = new NoOpHeartbeatServices(); private NoOpHeartbeatServices() {} @Override public <I, O> HeartbeatManager<I, O> createHeartbeatManager( ResourceID resourceId, HeartbeatListener<I, O> heartbeatListener, ScheduledExecutor mainThreadExecutor, Logger log) { return NoOpHeartbeatManager.getInstance(); } @Override public <I, O> HeartbeatManager<I, O> createHeartbeatManagerSender( ResourceID resourceId, HeartbeatListener<I, O> heartbeatListener, ScheduledExecutor mainThreadExecutor, Logger log) { return NoOpHeartbeatManager.getInstance(); } public static NoOpHeartbeatServices getInstance() { return INSTANCE; } }
NoOpHeartbeatServices
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/bigquery/parser/BigQuerySelectParser.java
{ "start": 276, "end": 2119 }
class ____ extends SQLSelectParser { public BigQuerySelectParser(SQLExprParser exprParser, SQLSelectListCache selectListCache) { super(exprParser, selectListCache); dbType = DbType.bigquery; } protected SQLExprParser createExprParser() { return new BigQueryExprParser(lexer); } @Override protected BigQuerySelectQueryBlock createSelectQueryBlock() { return new BigQuerySelectQueryBlock(); } protected void querySelectListBefore(SQLSelectQueryBlock x) { if (lexer.nextIf(Token.DISTINCT)) { x.setDistinct(); } if (lexer.nextIf(Token.AS)) { acceptIdentifier("STRUCT"); ((BigQuerySelectQueryBlock) x).setAsStruct(true); } if (lexer.nextIf(Token.WITH)) { acceptIdentifier("DIFFERENTIAL_PRIVACY"); acceptIdentifier("OPTIONS"); BigQuerySelectQueryBlock.DifferentialPrivacy clause = new BigQuerySelectQueryBlock.DifferentialPrivacy(); exprParser.parseAssignItem(clause.getOptions(), clause); ((BigQuerySelectQueryBlock) x).setDifferentialPrivacy(clause); } } protected boolean parseSelectListFromError() { return false; } protected String tableAlias(boolean must) { Token tok = lexer.token(); if (tok == Token.TABLE || tok == Token.UPDATE) { String alias = lexer.stringVal(); lexer.nextToken(); return alias; } return super.tableAlias(must); } protected void queryBefore(SQLSelectQueryBlock x) { if (lexer.token() == Token.WITH) { BigQuerySelectQueryBlock queryBlock = (BigQuerySelectQueryBlock) x; queryBlock.setWith( this.parseWith() ); } } }
BigQuerySelectParser
java
apache__camel
components/camel-drill/src/main/java/org/apache/camel/component/drill/DrillProducer.java
{ "start": 1166, "end": 2807 }
class ____ extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(DrillProducer.class); private DrillEndpoint endpoint; private Connection connection; public DrillProducer(DrillEndpoint endpoint) { super(endpoint); this.endpoint = endpoint; } @Override protected void doStart() throws Exception { super.doStart(); createJDBCConnection(); } @Override protected void doStop() throws Exception { super.doStop(); try { connection.close(); } catch (Exception e) { } } @Override public void process(final Exchange exchange) throws Exception { final String query = exchange.getIn().getHeader(DrillConstants.DRILL_QUERY, String.class); // check query Statement st = null; ResultSet rs = null; try { st = connection.createStatement(); rs = st.executeQuery(query); exchange.getIn().setBody(endpoint.queryForList(rs)); } finally { try { rs.close(); } catch (Exception e) { } try { st.close(); } catch (Exception e) { } } } // end process private void createJDBCConnection() throws ClassNotFoundException, SQLException { Class.forName(DrillConstants.DRILL_DRIVER); if (LOG.isInfoEnabled()) { LOG.info("connection url: {}", endpoint.toJDBCUri()); } this.connection = DriverManager.getConnection(endpoint.toJDBCUri()); } }
DrillProducer
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/util/ObjectHelperTest.java
{ "start": 2726, "end": 49343 }
class ____ { @Test void testLoadResourceAsStream() throws Exception { try (InputStream res1 = org.apache.camel.util.ObjectHelper .loadResourceAsStream("org/apache/camel/util/ObjectHelperResourceTestFile.properties"); InputStream res2 = org.apache.camel.util.ObjectHelper .loadResourceAsStream("/org/apache/camel/util/ObjectHelperResourceTestFile.properties")) { assertNotNull(res1, "Cannot load resource without leading \"/\""); assertNotNull(res2, "Cannot load resource with leading \"/\""); } } @Test void testLoadResource() { URL url1 = org.apache.camel.util.ObjectHelper .loadResourceAsURL("org/apache/camel/util/ObjectHelperResourceTestFile.properties"); URL url2 = org.apache.camel.util.ObjectHelper .loadResourceAsURL("/org/apache/camel/util/ObjectHelperResourceTestFile.properties"); assertNotNull(url1, "Cannot load resource without leading \"/\""); assertNotNull(url2, "Cannot load resource with leading \"/\""); } @Test void testGetPropertyName() throws Exception { Method method = getClass().getMethod("setCheese", String.class); assertNotNull(method, "should have found a method!"); String name = org.apache.camel.util.ObjectHelper.getPropertyName(method); assertEquals("cheese", name, "Property name"); } @SuppressWarnings("Unused") public void setCheese(String cheese) { // used in the above unit test } @Test void testContains() throws Exception { try (CamelContext context = new DefaultCamelContext()) { context.start(); TypeConverter tc = context.getTypeConverter(); String[] array = { "foo", "bar" }; Collection<String> collection = Arrays.asList(array); assertTrue(ObjectHelper.typeCoerceContains(tc, array, "foo", true)); assertTrue(ObjectHelper.typeCoerceContains(tc, array, "FOO", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, array, "FOO", false)); assertTrue(ObjectHelper.typeCoerceContains(tc, collection, "foo", true)); assertTrue(ObjectHelper.typeCoerceContains(tc, collection, "FOO", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, collection, "FOO", false)); assertTrue(ObjectHelper.typeCoerceContains(tc, "foo", "foo", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, array, "xyz", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, collection, "xyz", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, "foo", "xyz", true)); } } @Test void testContainsStreamCaching() throws Exception { try (CamelContext context = new DefaultCamelContext()) { context.start(); TypeConverter tc = context.getTypeConverter(); File file = new File("src/test/resources/org/apache/camel/util/quote.txt"); FileInputStreamCache data = new FileInputStreamCache(file); assertTrue(ObjectHelper.typeCoerceContains(tc, data, "foo", true)); assertTrue(ObjectHelper.typeCoerceContains(tc, data, "FOO", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, data, "FOO", false)); assertTrue(ObjectHelper.typeCoerceContains(tc, data, "foo", true)); assertTrue(ObjectHelper.typeCoerceContains(tc, data, "FOO", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, data, "FOO", false)); assertTrue(ObjectHelper.typeCoerceContains(tc, "foo", "foo", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, data, "xyz", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, data, "xyz", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, "foo", "xyz", true)); } } @Test void testEqualsStreamCaching() throws Exception { try (CamelContext context = new DefaultCamelContext()) { context.start(); TypeConverter tc = context.getTypeConverter(); File file = new File("src/test/resources/org/apache/camel/util/foo.txt"); FileInputStreamCache data = new FileInputStreamCache(file); assertTrue(ObjectHelper.typeCoerceEquals(tc, data, "foo", true)); assertTrue(ObjectHelper.typeCoerceEquals(tc, data, "FOO", true)); assertFalse(ObjectHelper.typeCoerceEquals(tc, data, "FOO", false)); assertTrue(ObjectHelper.typeCoerceEquals(tc, data, "foo", true)); assertTrue(ObjectHelper.typeCoerceEquals(tc, data, "FOO", true)); assertFalse(ObjectHelper.typeCoerceEquals(tc, data, "FOO", false)); assertTrue(ObjectHelper.typeCoerceEquals(tc, "foo", "foo", true)); assertFalse(ObjectHelper.typeCoerceEquals(tc, data, "xyz", true)); assertFalse(ObjectHelper.typeCoerceEquals(tc, data, "xyz", true)); assertFalse(ObjectHelper.typeCoerceEquals(tc, "foo", "xyz", true)); } } @Test void testContainsStringBuilder() throws Exception { try (CamelContext context = new DefaultCamelContext()) { context.start(); TypeConverter tc = context.getTypeConverter(); StringBuilder sb = new StringBuilder(); sb.append("Hello World"); assertTrue(ObjectHelper.typeCoerceContains(tc, sb, "World", true)); assertTrue(ObjectHelper.typeCoerceContains(tc, sb, "WORLD", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, sb, "WORLD", false)); assertTrue(ObjectHelper.typeCoerceContains(tc, sb, new StringBuffer("World"), true)); assertTrue(ObjectHelper.typeCoerceContains(tc, sb, new StringBuilder("World"), true)); assertFalse(ObjectHelper.typeCoerceContains(tc, sb, "Camel", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, sb, new StringBuffer("Camel"), true)); assertFalse(ObjectHelper.typeCoerceContains(tc, sb, new StringBuilder("Camel"), true)); } } @Test void testContainsStringBuffer() throws Exception { try (CamelContext context = new DefaultCamelContext()) { context.start(); TypeConverter tc = context.getTypeConverter(); StringBuffer sb = new StringBuffer(); sb.append("Hello World"); assertTrue(ObjectHelper.typeCoerceContains(tc, sb, "World", true)); assertTrue(ObjectHelper.typeCoerceContains(tc, sb, new StringBuffer("World"), true)); assertTrue(ObjectHelper.typeCoerceContains(tc, sb, new StringBuilder("World"), true)); assertFalse(ObjectHelper.typeCoerceContains(tc, sb, "Camel", true)); assertFalse(ObjectHelper.typeCoerceContains(tc, sb, new StringBuffer("Camel"), true)); assertFalse(ObjectHelper.typeCoerceContains(tc, sb, new StringBuilder("Camel"), true)); } } @Test void testEqual() { assertTrue(org.apache.camel.util.ObjectHelper.equal(null, null)); assertTrue(org.apache.camel.util.ObjectHelper.equal("", "")); assertTrue(org.apache.camel.util.ObjectHelper.equal(" ", " ")); assertTrue(org.apache.camel.util.ObjectHelper.equal("Hello", "Hello")); assertTrue(org.apache.camel.util.ObjectHelper.equal(123, 123)); assertTrue(org.apache.camel.util.ObjectHelper.equal(true, true)); assertFalse(org.apache.camel.util.ObjectHelper.equal(null, "")); assertFalse(org.apache.camel.util.ObjectHelper.equal("", null)); assertFalse(org.apache.camel.util.ObjectHelper.equal(" ", " ")); assertFalse(org.apache.camel.util.ObjectHelper.equal("Hello", "World")); assertFalse(org.apache.camel.util.ObjectHelper.equal(true, false)); assertFalse(org.apache.camel.util.ObjectHelper.equal(new Object(), new Object())); byte[] a = new byte[] { 40, 50, 60 }; byte[] b = new byte[] { 40, 50, 60 }; assertTrue(org.apache.camel.util.ObjectHelper.equal(a, b)); a = new byte[] { 40, 50, 60 }; b = new byte[] { 40, 50, 60, 70 }; assertFalse(org.apache.camel.util.ObjectHelper.equal(a, b)); } @Test void testEqualByteArray() { assertTrue(org.apache.camel.util.ObjectHelper.equalByteArray("Hello".getBytes(), "Hello".getBytes())); assertFalse(org.apache.camel.util.ObjectHelper.equalByteArray("Hello".getBytes(), "World".getBytes())); assertTrue(org.apache.camel.util.ObjectHelper.equalByteArray("Hello Thai Elephant \u0E08".getBytes(), "Hello Thai Elephant \u0E08".getBytes())); assertTrue(org.apache.camel.util.ObjectHelper.equalByteArray(null, null)); byte[] empty = new byte[0]; assertTrue(org.apache.camel.util.ObjectHelper.equalByteArray(empty, empty)); byte[] a = new byte[] { 40, 50, 60 }; byte[] b = new byte[] { 40, 50, 60 }; assertTrue(org.apache.camel.util.ObjectHelper.equalByteArray(a, b)); a = new byte[] { 40, 50, 60 }; b = new byte[] { 40, 50, 60, 70 }; assertFalse(org.apache.camel.util.ObjectHelper.equalByteArray(a, b)); a = new byte[] { 40, 50, 60, 70 }; b = new byte[] { 40, 50, 60 }; assertFalse(org.apache.camel.util.ObjectHelper.equalByteArray(a, b)); a = new byte[] { 40, 50, 60 }; b = new byte[0]; assertFalse(org.apache.camel.util.ObjectHelper.equalByteArray(a, b)); a = new byte[0]; b = new byte[] { 40, 50, 60 }; assertFalse(org.apache.camel.util.ObjectHelper.equalByteArray(a, b)); a = new byte[] { 40, 50, 60 }; b = null; assertFalse(org.apache.camel.util.ObjectHelper.equalByteArray(a, b)); a = null; b = new byte[] { 40, 50, 60 }; assertFalse(org.apache.camel.util.ObjectHelper.equalByteArray(a, b)); a = null; b = null; assertTrue(org.apache.camel.util.ObjectHelper.equalByteArray(a, b)); } @Test void testCreateIterator() { Iterator<String> iterator = Collections.emptyIterator(); assertSame(iterator, ObjectHelper.createIterator(iterator), "Should return the same iterator"); } @Test void testCreateIteratorAllowEmpty() { String s = "a,b,,c"; Iterator<?> it = ObjectHelper.createIterator(s, ",", true); assertEquals("a", it.next()); assertEquals("b", it.next()); assertEquals("", it.next()); assertEquals("c", it.next()); } @Test void testCreateIteratorPattern() { String s = "a\nb\rc"; Iterator<?> it = ObjectHelper.createIterator(s, "\n|\r", false, true); assertEquals("a", it.next()); assertEquals("b", it.next()); assertEquals("c", it.next()); } @Test void testCreateIteratorWithStringAndCommaSeparator() { String s = "a,b,c"; Iterator<?> it = ObjectHelper.createIterator(s, ","); assertEquals("a", it.next()); assertEquals("b", it.next()); assertEquals("c", it.next()); } @Test void testCreateIteratorWithStringAndCommaSeparatorEmptyString() { String s = ""; Iterator<?> it = ObjectHelper.createIterator(s, ",", true); assertEquals("", it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertEquals("no more element available for '' at the index 1", nsee.getMessage()); } } @Test void testCreateIteratorWithStringAndSemiColonSeparator() { String s = "a;b;c"; Iterator<?> it = ObjectHelper.createIterator(s, ";"); assertEquals("a", it.next()); assertEquals("b", it.next()); assertEquals("c", it.next()); } @Test void testCreateIteratorWithStringAndCommaInParanthesesSeparator() { String s = "bean:foo?method=bar('A','B','C')"; Iterator<?> it = ObjectHelper.createIterator(s, ","); assertEquals("bean:foo?method=bar('A','B','C')", it.next()); } @Test void testCreateIteratorWithStringAndCommaInParanthesesSeparatorTwo() { String s = "bean:foo?method=bar('A','B','C'),bean:bar?method=cool('A','Hello,World')"; Iterator<?> it = ObjectHelper.createIterator(s, ","); assertEquals("bean:foo?method=bar('A','B','C')", it.next()); assertEquals("bean:bar?method=cool('A','Hello,World')", it.next()); } @Test void testCreateIteratorWithPrimitiveArrayTypes() { Iterator<?> it = ObjectHelper.createIterator(new byte[] { 13, Byte.MAX_VALUE, 7, Byte.MIN_VALUE }, null); assertTrue(it.hasNext()); assertEquals((byte) 13, it.next()); assertTrue(it.hasNext()); assertEquals(Byte.MAX_VALUE, it.next()); assertTrue(it.hasNext()); assertEquals((byte) 7, it.next()); assertTrue(it.hasNext()); assertEquals(Byte.MIN_VALUE, it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[B@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 4"), nsee.getMessage()); } it = ObjectHelper.createIterator(new byte[] {}, null); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[B@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 0"), nsee.getMessage()); } it = ObjectHelper.createIterator(new short[] { 13, Short.MAX_VALUE, 7, Short.MIN_VALUE }, null); assertTrue(it.hasNext()); assertEquals((short) 13, it.next()); assertTrue(it.hasNext()); assertEquals(Short.MAX_VALUE, it.next()); assertTrue(it.hasNext()); assertEquals((short) 7, it.next()); assertTrue(it.hasNext()); assertEquals(Short.MIN_VALUE, it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[S@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 4"), nsee.getMessage()); } it = ObjectHelper.createIterator(new short[] {}, null); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[S@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 0"), nsee.getMessage()); } it = ObjectHelper.createIterator(new int[] { 13, Integer.MAX_VALUE, 7, Integer.MIN_VALUE }, null); assertTrue(it.hasNext()); assertEquals(13, it.next()); assertTrue(it.hasNext()); assertEquals(Integer.MAX_VALUE, it.next()); assertTrue(it.hasNext()); assertEquals(7, it.next()); assertTrue(it.hasNext()); assertEquals(Integer.MIN_VALUE, it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[I@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 4"), nsee.getMessage()); } it = ObjectHelper.createIterator(new int[] {}, null); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[I@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 0"), nsee.getMessage()); } it = ObjectHelper.createIterator(new long[] { 13L, Long.MAX_VALUE, 7L, Long.MIN_VALUE }, null); assertTrue(it.hasNext()); assertEquals(13L, it.next()); assertTrue(it.hasNext()); assertEquals(Long.MAX_VALUE, it.next()); assertTrue(it.hasNext()); assertEquals(7L, it.next()); assertTrue(it.hasNext()); assertEquals(Long.MIN_VALUE, it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[J@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 4"), nsee.getMessage()); } it = ObjectHelper.createIterator(new long[] {}, null); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[J@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 0"), nsee.getMessage()); } it = ObjectHelper.createIterator(new float[] { 13.7F, Float.MAX_VALUE, 7.13F, Float.MIN_VALUE }, null); assertTrue(it.hasNext()); assertEquals(13.7F, it.next()); assertTrue(it.hasNext()); assertEquals(Float.MAX_VALUE, it.next()); assertTrue(it.hasNext()); assertEquals(7.13F, it.next()); assertTrue(it.hasNext()); assertEquals(Float.MIN_VALUE, it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[F@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 4"), nsee.getMessage()); } it = ObjectHelper.createIterator(new float[] {}, null); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[F@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 0"), nsee.getMessage()); } it = ObjectHelper.createIterator(new double[] { 13.7D, Double.MAX_VALUE, 7.13D, Double.MIN_VALUE }, null); assertTrue(it.hasNext()); assertEquals(13.7D, it.next()); assertTrue(it.hasNext()); assertEquals(Double.MAX_VALUE, it.next()); assertTrue(it.hasNext()); assertEquals(7.13D, it.next()); assertTrue(it.hasNext()); assertEquals(Double.MIN_VALUE, it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[D@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 4"), nsee.getMessage()); } it = ObjectHelper.createIterator(new double[] {}, null); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[D@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 0"), nsee.getMessage()); } it = ObjectHelper.createIterator(new char[] { 'C', 'a', 'm', 'e', 'l' }, null); assertTrue(it.hasNext()); assertEquals('C', it.next()); assertTrue(it.hasNext()); assertEquals('a', it.next()); assertTrue(it.hasNext()); assertEquals('m', it.next()); assertTrue(it.hasNext()); assertEquals('e', it.next()); assertTrue(it.hasNext()); assertEquals('l', it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[C@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 5"), nsee.getMessage()); } it = ObjectHelper.createIterator(new char[] {}, null); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[C@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 0"), nsee.getMessage()); } it = ObjectHelper.createIterator(new boolean[] { false, true, false, true, true }, null); assertTrue(it.hasNext()); assertEquals(Boolean.FALSE, it.next()); assertTrue(it.hasNext()); assertEquals(Boolean.TRUE, it.next()); assertTrue(it.hasNext()); assertEquals(Boolean.FALSE, it.next()); assertTrue(it.hasNext()); assertEquals(Boolean.TRUE, it.next()); assertTrue(it.hasNext()); assertEquals(Boolean.TRUE, it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[Z@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 5"), nsee.getMessage()); } it = ObjectHelper.createIterator(new boolean[] {}, null); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for '[Z@"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 0"), nsee.getMessage()); } } @Test void testArrayAsIterator() { String[] data = { "a", "b" }; Iterator<?> iter = ObjectHelper.createIterator(data); assertTrue(iter.hasNext(), "should have next"); Object a = iter.next(); assertEquals("a", a, "a"); assertTrue(iter.hasNext(), "should have next"); Object b = iter.next(); assertEquals("b", b, "b"); assertFalse(iter.hasNext(), "should not have a next"); } @Test void testIsEmpty() { assertTrue(org.apache.camel.util.ObjectHelper.isEmpty((Object) null)); assertTrue(org.apache.camel.util.ObjectHelper.isEmpty("")); assertTrue(org.apache.camel.util.ObjectHelper.isEmpty(" ")); assertFalse(org.apache.camel.util.ObjectHelper.isEmpty("A")); assertFalse(org.apache.camel.util.ObjectHelper.isEmpty(" A")); assertFalse(org.apache.camel.util.ObjectHelper.isEmpty(" A ")); assertFalse(org.apache.camel.util.ObjectHelper.isEmpty(new Object())); } @Test void testIsNotEmpty() { assertFalse(org.apache.camel.util.ObjectHelper.isNotEmpty((Object) null)); assertFalse(org.apache.camel.util.ObjectHelper.isNotEmpty("")); assertFalse(org.apache.camel.util.ObjectHelper.isNotEmpty(" ")); assertTrue(org.apache.camel.util.ObjectHelper.isNotEmpty("A")); assertTrue(org.apache.camel.util.ObjectHelper.isNotEmpty(" A")); assertTrue(org.apache.camel.util.ObjectHelper.isNotEmpty(" A ")); assertTrue(org.apache.camel.util.ObjectHelper.isNotEmpty(new Object())); } @Test void testIteratorWithComma() { Iterator<?> it = ObjectHelper.createIterator("Claus,Jonathan"); assertEquals("Claus", it.next()); assertEquals("Jonathan", it.next()); assertFalse(it.hasNext()); } @Test void testIteratorWithOtherDelimiter() { Iterator<?> it = ObjectHelper.createIterator("Claus#Jonathan", "#"); assertEquals("Claus", it.next()); assertEquals("Jonathan", it.next()); assertFalse(it.hasNext()); } @Test void testIteratorEmpty() { Iterator<?> it = ObjectHelper.createIterator(""); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertEquals("no more element available for '' at the index 0", nsee.getMessage()); } it = ObjectHelper.createIterator(" "); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertEquals("no more element available for ' ' at the index 0", nsee.getMessage()); } it = ObjectHelper.createIterator(null); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected } } @Test void testIteratorIdempotentNext() { Iterator<?> it = ObjectHelper.createIterator("a"); assertTrue(it.hasNext()); assertTrue(it.hasNext()); it.next(); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertEquals("no more element available for 'a' at the index 1", nsee.getMessage()); } } @Test void testIteratorIdempotentNextWithNodeList() { NodeList nodeList = new NodeList() { public Node item(int index) { return null; } public int getLength() { return 1; } }; Iterator<?> it = ObjectHelper.createIterator(nodeList); assertTrue(it.hasNext()); assertTrue(it.hasNext()); it.next(); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertTrue(nsee.getMessage().startsWith("no more element available for 'org.apache.camel.util.ObjectHelperTest$"), nsee.getMessage()); assertTrue(nsee.getMessage().endsWith("at the index 1"), nsee.getMessage()); } } @Test void testGetCamelContextPropertiesWithPrefix() { CamelContext context = new DefaultCamelContext(); Map<String, String> properties = context.getGlobalOptions(); properties.put("camel.object.helper.test1", "test1"); properties.put("camel.object.helper.test2", "test2"); properties.put("camel.object.test", "test"); Properties result = CamelContextHelper.getCamelPropertiesWithPrefix("camel.object.helper.", context); assertEquals(2, result.size(), "Get a wrong size properties"); assertEquals("test1", result.get("test1"), "It should contain the test1"); assertEquals("test2", result.get("test2"), "It should contain the test2"); } @Test void testEvaluateAsPredicate() { assertFalse(org.apache.camel.util.ObjectHelper.evaluateValuePredicate(null)); assertTrue(org.apache.camel.util.ObjectHelper.evaluateValuePredicate(123)); assertTrue(org.apache.camel.util.ObjectHelper.evaluateValuePredicate("true")); assertTrue(org.apache.camel.util.ObjectHelper.evaluateValuePredicate("TRUE")); assertFalse(org.apache.camel.util.ObjectHelper.evaluateValuePredicate("false")); assertFalse(org.apache.camel.util.ObjectHelper.evaluateValuePredicate("FALSE")); assertTrue(org.apache.camel.util.ObjectHelper.evaluateValuePredicate("foobar")); assertFalse(org.apache.camel.util.ObjectHelper.evaluateValuePredicate("")); assertFalse(org.apache.camel.util.ObjectHelper.evaluateValuePredicate(" ")); List<String> list = new ArrayList<>(); assertFalse(org.apache.camel.util.ObjectHelper.evaluateValuePredicate(list)); list.add("foo"); assertTrue(org.apache.camel.util.ObjectHelper.evaluateValuePredicate(list)); } @Test void testIsPrimitiveArrayType() { assertTrue(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(byte[].class)); assertTrue(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(short[].class)); assertTrue(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(int[].class)); assertTrue(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(long[].class)); assertTrue(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(float[].class)); assertTrue(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(double[].class)); assertTrue(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(char[].class)); assertTrue(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(boolean[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(Object[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(Byte[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(Short[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(Integer[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(Long[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(Float[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(Double[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(Character[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(Boolean[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(Void[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(CamelContext[].class)); assertFalse(org.apache.camel.util.ObjectHelper.isPrimitiveArrayType(null)); } @Test void testGetDefaultCharSet() { assertNotNull(org.apache.camel.util.ObjectHelper.getDefaultCharacterSet()); } @Test void testConvertPrimitiveTypeToWrapper() { assertEquals("java.lang.Integer", org.apache.camel.util.ObjectHelper.convertPrimitiveTypeToWrapperType(int.class).getName()); assertEquals("java.lang.Long", org.apache.camel.util.ObjectHelper.convertPrimitiveTypeToWrapperType(long.class).getName()); assertEquals("java.lang.Double", org.apache.camel.util.ObjectHelper.convertPrimitiveTypeToWrapperType(double.class).getName()); assertEquals("java.lang.Float", org.apache.camel.util.ObjectHelper.convertPrimitiveTypeToWrapperType(float.class).getName()); assertEquals("java.lang.Short", org.apache.camel.util.ObjectHelper.convertPrimitiveTypeToWrapperType(short.class).getName()); assertEquals("java.lang.Byte", org.apache.camel.util.ObjectHelper.convertPrimitiveTypeToWrapperType(byte.class).getName()); assertEquals("java.lang.Boolean", org.apache.camel.util.ObjectHelper.convertPrimitiveTypeToWrapperType(boolean.class).getName()); assertEquals("java.lang.Character", org.apache.camel.util.ObjectHelper.convertPrimitiveTypeToWrapperType(char.class).getName()); // non primitive just fall through assertEquals("java.lang.Object", org.apache.camel.util.ObjectHelper.convertPrimitiveTypeToWrapperType(Object.class).getName()); } @Test void testAsString() { String[] args = new String[] { "foo", "bar" }; String out = org.apache.camel.util.ObjectHelper.asString(args); assertNotNull(out); assertEquals("{foo, bar}", out); } @Test void testName() { assertEquals("java.lang.Integer", org.apache.camel.util.ObjectHelper.name(Integer.class)); assertNull(org.apache.camel.util.ObjectHelper.name(null)); } @Test void testClassName() { assertEquals("java.lang.Integer", org.apache.camel.util.ObjectHelper.className(Integer.valueOf("5"))); assertNull(org.apache.camel.util.ObjectHelper.className(null)); } @Test void testGetSystemPropertyDefault() { assertEquals("foo", org.apache.camel.util.ObjectHelper.getSystemProperty("CamelFooDoesNotExist", "foo")); } @Test void testGetSystemPropertyBooleanDefault() { assertTrue(org.apache.camel.util.ObjectHelper.getSystemProperty("CamelFooDoesNotExist", Boolean.TRUE)); } @Test void testMatches() { List<Object> data = new ArrayList<>(); data.add("foo"); data.add("bar"); assertTrue(org.apache.camel.util.ObjectHelper.matches(data)); data.clear(); data.add(Boolean.FALSE); data.add("bar"); assertFalse(org.apache.camel.util.ObjectHelper.matches(data)); data.clear(); assertFalse(org.apache.camel.util.ObjectHelper.matches(data)); } @Test void testToBoolean() { assertEquals(Boolean.TRUE, org.apache.camel.util.ObjectHelper.toBoolean(Boolean.TRUE)); assertEquals(Boolean.TRUE, org.apache.camel.util.ObjectHelper.toBoolean("true")); assertEquals(Boolean.TRUE, org.apache.camel.util.ObjectHelper.toBoolean(Integer.valueOf("1"))); assertEquals(Boolean.FALSE, org.apache.camel.util.ObjectHelper.toBoolean(Integer.valueOf("0"))); assertNull(org.apache.camel.util.ObjectHelper.toBoolean(new Date())); } @Test void testIteratorWithMessage() { Message msg = new DefaultMessage(new DefaultCamelContext()); msg.setBody("a,b,c"); Iterator<?> it = ObjectHelper.createIterator(msg); assertEquals("a", it.next()); assertEquals("b", it.next()); assertEquals("c", it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected } } @Test void testIteratorWithEmptyMessage() { Message msg = new DefaultMessage(new DefaultCamelContext()); msg.setBody(""); Iterator<?> it = ObjectHelper.createIterator(msg); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected assertEquals("no more element available for '' at the index 0", nsee.getMessage()); } } @Test void testIteratorWithNullMessage() { Message msg = new DefaultMessage(new DefaultCamelContext()); msg.setBody(null); Iterator<?> it = ObjectHelper.createIterator(msg); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected } } @Test void testIterable() { final List<String> data = new ArrayList<>(); data.add("A"); data.add("B"); data.add("C"); Iterable<String> itb = new Iterable<String>() { @Override public Iterator<String> iterator() { return data.iterator(); } }; Iterator<?> it = ObjectHelper.createIterator(itb); assertEquals("A", it.next()); assertEquals("B", it.next()); assertEquals("C", it.next()); assertFalse(it.hasNext()); try { it.next(); fail("Should have thrown exception"); } catch (NoSuchElementException nsee) { // expected } } @Test void testLookupConstantFieldValue() { assertEquals("CamelFileName", org.apache.camel.util.ObjectHelper.lookupConstantFieldValue(Exchange.class, "FILE_NAME")); assertNull(org.apache.camel.util.ObjectHelper.lookupConstantFieldValue(Exchange.class, "XXX")); assertNull(org.apache.camel.util.ObjectHelper.lookupConstantFieldValue(null, "FILE_NAME")); } @Test void testHasDefaultPublicNoArgConstructor() { assertTrue(org.apache.camel.util.ObjectHelper.hasDefaultPublicNoArgConstructor(ObjectHelperTest.class)); assertFalse(org.apache.camel.util.ObjectHelper.hasDefaultPublicNoArgConstructor(MyStaticClass.class)); } @Test void testIdentityHashCode() { MyDummyObject dummy = new MyDummyObject("Camel"); String code = org.apache.camel.util.ObjectHelper.getIdentityHashCode(dummy); String code2 = org.apache.camel.util.ObjectHelper.getIdentityHashCode(dummy); assertEquals(code, code2); MyDummyObject dummyB = new MyDummyObject("Camel"); String code3 = org.apache.camel.util.ObjectHelper.getIdentityHashCode(dummyB); assertNotSame(code, code3); } @Test void testIsNaN() { assertTrue(org.apache.camel.util.ObjectHelper.isNaN(Float.NaN)); assertTrue(org.apache.camel.util.ObjectHelper.isNaN(Double.NaN)); assertFalse(org.apache.camel.util.ObjectHelper.isNaN(null)); assertFalse(org.apache.camel.util.ObjectHelper.isNaN("")); assertFalse(org.apache.camel.util.ObjectHelper.isNaN("1.0")); assertFalse(org.apache.camel.util.ObjectHelper.isNaN(1)); assertFalse(org.apache.camel.util.ObjectHelper.isNaN(1.5f)); assertFalse(org.apache.camel.util.ObjectHelper.isNaN(1.5d)); assertFalse(org.apache.camel.util.ObjectHelper.isNaN(false)); assertFalse(org.apache.camel.util.ObjectHelper.isNaN(true)); } @Test void testNotNull() { Long expected = 3L; Long actual = org.apache.camel.util.ObjectHelper.notNull(expected, "expected"); assertSame(expected, actual, "Didn't get the same object back!"); Long actual2 = org.apache.camel.util.ObjectHelper.notNull(expected, "expected", "holder"); assertSame(expected, actual2, "Didn't get the same object back!"); Long expected2 = null; try { org.apache.camel.util.ObjectHelper.notNull(expected2, "expected2"); fail("Should have thrown exception"); } catch (IllegalArgumentException iae) { assertEquals("expected2 must be specified", iae.getMessage()); } try { org.apache.camel.util.ObjectHelper.notNull(expected2, "expected2", "holder"); fail("Should have thrown exception"); } catch (IllegalArgumentException iae) { assertEquals("expected2 must be specified on: holder", iae.getMessage()); } } @Test void testSameMethodIsOverride() throws Exception { Method m = MyOtherFooBean.class.getMethod("toString", Object.class); assertTrue(org.apache.camel.util.ObjectHelper.isOverridingMethod(m, m, false)); } @Test void testOverloadIsNotOverride() throws Exception { Method m1 = MyOtherFooBean.class.getMethod("toString", Object.class); Method m2 = MyOtherFooBean.class.getMethod("toString", String.class); assertFalse(org.apache.camel.util.ObjectHelper.isOverridingMethod(m2, m1, false)); } @Test void testOverrideEquivalentSignatureFromSiblingClassIsNotOverride() throws Exception { Method m1 = Double.class.getMethod("intValue"); Method m2 = Float.class.getMethod("intValue"); assertFalse(org.apache.camel.util.ObjectHelper.isOverridingMethod(m2, m1, false)); } @Test void testOverrideEquivalentSignatureFromUpperClassIsOverride() throws Exception { Method m1 = Double.class.getMethod("intValue"); Method m2 = Number.class.getMethod("intValue"); assertTrue(org.apache.camel.util.ObjectHelper.isOverridingMethod(m2, m1, false)); } @Test void testInheritedMethodCanOverrideInterfaceMethod() throws Exception { Method m1 = AbstractClassSize.class.getMethod("size"); Method m2 = InterfaceSize.class.getMethod("size"); assertTrue(org.apache.camel.util.ObjectHelper.isOverridingMethod(Clazz.class, m2, m1, false)); } @Test void testNonInheritedMethodCantOverrideInterfaceMethod() throws Exception { Method m1 = AbstractClassSize.class.getMethod("size"); Method m2 = InterfaceSize.class.getMethod("size"); assertFalse(org.apache.camel.util.ObjectHelper.isOverridingMethod(InterfaceSize.class, m2, m1, false)); } @Test void testAsList() { List<Object> out0 = org.apache.camel.util.ObjectHelper.asList(null); assertNotNull(out0); boolean b2 = out0.isEmpty(); assertTrue(b2); List<Object> out1 = org.apache.camel.util.ObjectHelper.asList(new Object[0]); assertNotNull(out1); boolean b1 = out1.isEmpty(); assertTrue(b1); String[] args = new String[] { "foo", "bar" }; List<Object> out2 = org.apache.camel.util.ObjectHelper.asList(args); assertNotNull(out2); boolean b = out2.size() == 2; assertTrue(b); assertEquals("foo", out2.get(0)); assertEquals("bar", out2.get(1)); } @Test void testIterableWithNullContent() { assertEquals("", StreamSupport.stream(ObjectHelper.createIterable(null, ";;").spliterator(), false) .collect(Collectors.joining("-"))); } @Test void testIterableWithEmptyContent() { assertEquals("", StreamSupport.stream(ObjectHelper.createIterable("", ";;").spliterator(), false) .collect(Collectors.joining("-"))); } @Test void testIterableWithOneElement() { assertEquals("foo", StreamSupport.stream(ObjectHelper.createIterable("foo", ";;").spliterator(), false) .collect(Collectors.joining("-"))); } @ParameterizedTest @ValueSource(strings = { "foo;;bar", ";;foo;;bar", "foo;;bar;;", ";;foo;;bar;;" }) void testIterableWithTwoElements(String content) { assertEquals("foo-bar", StreamSupport.stream(ObjectHelper.createIterable(content, ";;").spliterator(), false) .collect(Collectors.joining("-"))); } @Test void testIterableUsingPatternWithNullContent() { assertEquals("", StreamSupport.stream(ObjectHelper.createIterable(null, ";+", false, true).spliterator(), false) .collect(Collectors.joining("-"))); } @Test void testIterableUsingPatternWithEmptyContent() { assertEquals("", StreamSupport.stream(ObjectHelper.createIterable("", ";+", false, true).spliterator(), false) .collect(Collectors.joining("-"))); } @Test void testIterableUsingPatternWithOneElement() { assertEquals("foo", StreamSupport.stream(ObjectHelper.createIterable("foo", ";+", false, true).spliterator(), false) .collect(Collectors.joining("-"))); } @ParameterizedTest @ValueSource(strings = { "foo;;bar", ";;foo;;bar", "foo;;bar;;", ";;foo;;bar;;" }) void testIterableUsingPatternWithTwoElements(String content) { assertEquals("foo-bar", StreamSupport.stream(ObjectHelper.createIterable(content, ";+", false, true).spliterator(), false) .collect(Collectors.joining("-"))); } @Test public void testAddListByIndex() { List<Object> list = new ArrayList<>(); org.apache.camel.util.ObjectHelper.addListByIndex(list, 0, "aaa"); org.apache.camel.util.ObjectHelper.addListByIndex(list, 2, "ccc"); org.apache.camel.util.ObjectHelper.addListByIndex(list, 1, "bbb"); Assertions.assertEquals(3, list.size()); Assertions.assertEquals("aaa", list.get(0)); Assertions.assertEquals("bbb", list.get(1)); Assertions.assertEquals("ccc", list.get(2)); org.apache.camel.util.ObjectHelper.addListByIndex(list, 99, "zzz"); Assertions.assertEquals(100, list.size()); Assertions.assertNull(list.get(4)); Assertions.assertNull(list.get(50)); Assertions.assertNull(list.get(98)); Assertions.assertEquals("zzz", list.get(99)); } @Test public void testIsNumeric() { Assertions.assertTrue(org.apache.camel.util.ObjectHelper.isNumericType(int.class)); Assertions.assertTrue(org.apache.camel.util.ObjectHelper.isNumericType(Integer.class)); Assertions.assertTrue(org.apache.camel.util.ObjectHelper.isNumericType(long.class)); Assertions.assertTrue(org.apache.camel.util.ObjectHelper.isNumericType(Long.class)); Assertions.assertTrue(org.apache.camel.util.ObjectHelper.isNumericType(Double.class)); Assertions.assertTrue(org.apache.camel.util.ObjectHelper.isNumericType(float.class)); Assertions.assertTrue(org.apache.camel.util.ObjectHelper.isNumericType(byte.class)); Assertions.assertFalse(org.apache.camel.util.ObjectHelper.isNumericType(String.class)); Assertions.assertFalse(org.apache.camel.util.ObjectHelper.isNumericType(Node.class)); } }
ObjectHelperTest
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java
{ "start": 72504, "end": 72703 }
class ____ { } @ComponentScan(basePackages = "org.springframework.context.annotation.componentscan.base", excludeFilters = {}) public static
ComposedConfigurationWithAttributeOverrideForExcludeFilter
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/benchmark/deploying/DeployingDownstreamTasksInBatchJobBenchmark.java
{ "start": 1303, "end": 2318 }
class ____ extends DeployingTasksBenchmarkBase { private ExecutionVertex[] vertices; @Override public void setup(JobConfiguration jobConfiguration) throws Exception { super.setup(jobConfiguration); final JobVertex source = jobVertices.get(0); for (ExecutionVertex ev : executionGraph.getJobVertex(source.getID()).getTaskVertices()) { Execution execution = ev.getCurrentExecutionAttempt(); execution.transitionState(ExecutionState.SCHEDULED); execution.deploy(); } final JobVertex sink = jobVertices.get(1); vertices = executionGraph.getJobVertex(sink.getID()).getTaskVertices(); } public void deployDownstreamTasks() throws Exception { for (ExecutionVertex ev : vertices) { Execution execution = ev.getCurrentExecutionAttempt(); execution.transitionState(ExecutionState.SCHEDULED); execution.deploy(); } } }
DeployingDownstreamTasksInBatchJobBenchmark
java
micronaut-projects__micronaut-core
router/src/main/java/io/micronaut/web/router/DefaultFilterRoute.java
{ "start": 1463, "end": 7907 }
class ____ implements FilterRoute { private final List<String> patterns = new ArrayList<>(1); private final Supplier<GenericHttpFilter> filterSupplier; private final AnnotationMetadataResolver annotationMetadataResolver; private Set<HttpMethod> httpMethods; private FilterPatternStyle patternStyle; private volatile GenericHttpFilter filter; private AnnotationMetadata annotationMetadata; private final boolean isPreMatching; private String matchingAnnotation; DefaultFilterRoute(Supplier<GenericHttpFilter> filter, AnnotationMetadataResolver annotationMetadataResolver, boolean isPreMatching) { Objects.requireNonNull(filter, "HttpFilter argument is required"); this.filterSupplier = filter; this.annotationMetadataResolver = annotationMetadataResolver; this.isPreMatching = isPreMatching; } DefaultFilterRoute(Supplier<GenericHttpFilter> filter, AnnotationMetadata annotationMetadata, boolean isPreMatching) { Objects.requireNonNull(filter, "HttpFilter argument is required"); this.filterSupplier = filter; this.annotationMetadataResolver = AnnotationMetadataResolver.DEFAULT; this.annotationMetadata = annotationMetadata; this.isPreMatching = isPreMatching; } /** * @param pattern A pattern * @param filter A {@link Supplier} for an HTTP filter * @param annotationMetadataResolver The annotation metadata resolver */ DefaultFilterRoute(String pattern, Supplier<GenericHttpFilter> filter, AnnotationMetadataResolver annotationMetadataResolver) { this(pattern, filter, annotationMetadataResolver, false); } /** * @param pattern A pattern * @param filter A {@link Supplier} for an HTTP filter * @param annotationMetadataResolver The annotation metadata resolver * @param isPreMatching Is pre-matching filter * @since 4.6 */ DefaultFilterRoute(String pattern, Supplier<GenericHttpFilter> filter, AnnotationMetadataResolver annotationMetadataResolver, boolean isPreMatching) { this(filter, annotationMetadataResolver, isPreMatching); Objects.requireNonNull(pattern, "Pattern argument is required"); this.patterns.add(pattern); } /** * @param pattern A pattern * @param filter A {@link Supplier} for an HTTP filter * @param annotationMetadata The annotation metadata * @param isPreMatching Is pre-matching filter * @since 4.6 */ DefaultFilterRoute(String pattern, Supplier<GenericHttpFilter> filter, AnnotationMetadata annotationMetadata, boolean isPreMatching) { this(filter, AnnotationMetadataResolver.DEFAULT, isPreMatching); Objects.requireNonNull(pattern, "Pattern argument is required"); this.patterns.add(pattern); this.annotationMetadata = annotationMetadata; this.matchingAnnotation = FilterRoute.super.findMatchingAnnotation(); } /** * @param pattern A pattern * @param filter A {@link Supplier} for an HTTP filter */ DefaultFilterRoute(String pattern, Supplier<GenericHttpFilter> filter) { this(pattern, filter, AnnotationMetadataResolver.DEFAULT); } @Override public boolean isPreMatching() { return isPreMatching; } @Override public String findMatchingAnnotation() { if (matchingAnnotation == null) { matchingAnnotation = FilterRoute.super.findMatchingAnnotation(); } return matchingAnnotation; } @NonNull @Override public AnnotationMetadata getAnnotationMetadata() { AnnotationMetadata annotationMetadata = this.annotationMetadata; if (annotationMetadata == null) { synchronized (this) { // double check annotationMetadata = this.annotationMetadata; if (annotationMetadata == null) { annotationMetadata = annotationMetadataResolver.resolveMetadata(getFilter()); this.annotationMetadata = annotationMetadata; } } } return annotationMetadata; } @Override @NonNull public GenericHttpFilter getFilter() { GenericHttpFilter filter = this.filter; if (filter == null) { synchronized (this) { // double check filter = this.filter; if (filter == null) { filter = filterSupplier.get(); this.filter = filter; } } } return filter; } @NonNull @Override public Set<HttpMethod> getFilterMethods() { return httpMethods; } @NonNull @Override public String[] getPatterns() { return patterns.toArray(StringUtils.EMPTY_STRING_ARRAY); } @Override public FilterPatternStyle getPatternStyle() { return patternStyle != null ? patternStyle : FilterPatternStyle.defaultStyle(); } @Override public Optional<GenericHttpFilter> match(HttpMethod method, URI uri) { return match(method, uri.getPath()); } @Override public Optional<GenericHttpFilter> match(HttpMethod method, String path) { if (httpMethods != null && !httpMethods.contains(method)) { return Optional.empty(); } PathMatcher matcher = getPatternStyle().getPathMatcher(); for (String pattern : patterns) { if (matcher.matches(pattern, path)) { GenericHttpFilter filter = getFilter(); if (!GenericHttpFilter.isEnabled(filter)) { return Optional.empty(); } return Optional.of(filter); } } return Optional.empty(); } @Override public FilterRoute pattern(String pattern) { if (StringUtils.isNotEmpty(pattern)) { this.patterns.add(pattern); } return this; } @Override public FilterRoute methods(HttpMethod... methods) { if (ArrayUtils.isNotEmpty(methods)) { if (httpMethods == null) { httpMethods = new HashSet<>(); } httpMethods.addAll(Arrays.asList(methods)); } return this; } @Override public FilterRoute patternStyle(FilterPatternStyle patternStyle) { this.patternStyle = patternStyle; return this; } }
DefaultFilterRoute
java
elastic__elasticsearch
modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/MultiSearchTemplateResponse.java
{ "start": 1573, "end": 5489 }
class ____ implements Writeable { private final SearchTemplateResponse response; private final Exception exception; public Item(SearchTemplateResponse response, Exception exception) { this.response = response; this.exception = exception; } /** * Is it a failed search? */ public boolean isFailure() { return exception != null; } /** * The actual failure message, null if its not a failure. */ @Nullable public String getFailureMessage() { return exception == null ? null : exception.getMessage(); } /** * The actual search response, null if its a failure. */ @Nullable public SearchTemplateResponse getResponse() { return this.response; } @Override public void writeTo(StreamOutput out) throws IOException { if (response != null) { out.writeBoolean(true); response.writeTo(out); } else { out.writeBoolean(false); out.writeException(exception); } } public Exception getFailure() { return exception; } @Override public String toString() { return "Item [response=" + response + ", exception=" + exception + "]"; } } private final Item[] items; private final long tookInMillis; private final RefCounted refCounted = LeakTracker.wrap(new AbstractRefCounted() { @Override protected void closeInternal() { for (int i = 0; i < items.length; i++) { Item item = items[i]; var r = item.response; if (r != null) { r.decRef(); items[i] = null; } } } }); MultiSearchTemplateResponse(Item[] items, long tookInMillis) { this.items = items; this.tookInMillis = tookInMillis; } @Override public Iterator<Item> iterator() { return Iterators.forArray(items); } /** * The list of responses, the order is the same as the one provided in the request. */ public Item[] getResponses() { return this.items; } /** * How long the msearch_template took. */ public TimeValue getTook() { return new TimeValue(tookInMillis); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeArray(items); out.writeVLong(tookInMillis); } @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject(); builder.field("took", tookInMillis); builder.startArray(Fields.RESPONSES); for (Item item : items) { builder.startObject(); if (item.isFailure()) { ElasticsearchException.generateFailureXContent(builder, params, item.getFailure(), true); builder.field(Fields.STATUS, ExceptionsHelper.status(item.getFailure()).getStatus()); } else { item.getResponse().innerToXContent(builder, params); builder.field(Fields.STATUS, item.getResponse().status().getStatus()); } builder.endObject(); } builder.endArray(); builder.endObject(); return builder; } @Override public void incRef() { refCounted.incRef(); } @Override public boolean tryIncRef() { return refCounted.tryIncRef(); } @Override public boolean decRef() { return refCounted.decRef(); } @Override public boolean hasReferences() { return refCounted.hasReferences(); } static final
Item
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/RoundRobinVolumeChoosingPolicy.java
{ "start": 1580, "end": 5057 }
class ____<V extends FsVolumeSpi> implements VolumeChoosingPolicy<V>, Configurable { public static final Logger LOG = LoggerFactory.getLogger(RoundRobinVolumeChoosingPolicy.class); // curVolumes stores the RR counters of each storage type. // The ordinal of storage type in org.apache.hadoop.fs.StorageType // is used as the index to get data from the array. private int[] curVolumes; // syncLocks stores the locks for each storage type. private Object[] syncLocks; // The required additional available space when choosing a volume. private long additionalAvailableSpace; public RoundRobinVolumeChoosingPolicy() { int numStorageTypes = StorageType.values().length; curVolumes = new int[numStorageTypes]; syncLocks = new Object[numStorageTypes]; for (int i = 0; i < numStorageTypes; i++) { syncLocks[i] = new Object(); } } @Override public void setConf(Configuration conf) { additionalAvailableSpace = conf.getLong( DFS_DATANODE_ROUND_ROBIN_VOLUME_CHOOSING_POLICY_ADDITIONAL_AVAILABLE_SPACE_KEY, DFS_DATANODE_ROUND_ROBIN_VOLUME_CHOOSING_POLICY_ADDITIONAL_AVAILABLE_SPACE_DEFAULT); LOG.info("Round robin volume choosing policy initialized: " + DFS_DATANODE_ROUND_ROBIN_VOLUME_CHOOSING_POLICY_ADDITIONAL_AVAILABLE_SPACE_KEY + " = " + additionalAvailableSpace); } @Override public Configuration getConf() { // Nothing to do. Only added to fulfill the Configurable contract. return null; } @Override public V chooseVolume(final List<V> volumes, long blockSize, String storageId) throws IOException { if (volumes.size() < 1) { throw new DiskOutOfSpaceException("No more available volumes"); } // As all the items in volumes are with the same storage type, // so only need to get the storage type index of the first item in volumes StorageType storageType = volumes.get(0).getStorageType(); int index = storageType != null ? storageType.ordinal() : StorageType.DEFAULT.ordinal(); synchronized (syncLocks[index]) { return chooseVolume(index, volumes, blockSize); } } private V chooseVolume(final int curVolumeIndex, final List<V> volumes, long blockSize) throws IOException { // since volumes could've been removed because of the failure // make sure we are not out of bounds int curVolume = curVolumes[curVolumeIndex] < volumes.size() ? curVolumes[curVolumeIndex] : 0; int startVolume = curVolume; long maxAvailable = 0; while (true) { final V volume = volumes.get(curVolume); curVolume = (curVolume + 1) % volumes.size(); long availableVolumeSize = volume.getAvailable(); if (availableVolumeSize > blockSize + additionalAvailableSpace) { curVolumes[curVolumeIndex] = curVolume; return volume; } if (availableVolumeSize > maxAvailable) { maxAvailable = availableVolumeSize; } LOG.warn("The volume[{}] with the available space (={} B) is " + "less than the block size (={} B).", volume.getBaseURI(), availableVolumeSize, blockSize); if (curVolume == startVolume) { throw new DiskOutOfSpaceException("Out of space: " + "The volume with the most available space (=" + maxAvailable + " B) is less than the block size (=" + blockSize + " B)."); } } } }
RoundRobinVolumeChoosingPolicy
java
apache__camel
components/camel-tahu/src/generated/java/org/apache/camel/component/tahu/TahuHostComponentConfigurer.java
{ "start": 731, "end": 6306 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { private org.apache.camel.component.tahu.TahuConfiguration getOrCreateConfiguration(TahuHostComponent target) { if (target.getConfiguration() == null) { target.setConfiguration(new org.apache.camel.component.tahu.TahuConfiguration()); } return target.getConfiguration(); } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { TahuHostComponent target = (TahuHostComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "checkclientidlength": case "checkClientIdLength": getOrCreateConfiguration(target).setCheckClientIdLength(property(camelContext, boolean.class, value)); return true; case "clientid": case "clientId": getOrCreateConfiguration(target).setClientId(property(camelContext, java.lang.String.class, value)); return true; case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.tahu.TahuConfiguration.class, value)); return true; case "keepalivetimeout": case "keepAliveTimeout": getOrCreateConfiguration(target).setKeepAliveTimeout(property(camelContext, int.class, value)); return true; case "password": getOrCreateConfiguration(target).setPassword(property(camelContext, java.lang.String.class, value)); return true; case "rebirthdebouncedelay": case "rebirthDebounceDelay": getOrCreateConfiguration(target).setRebirthDebounceDelay(property(camelContext, long.class, value)); return true; case "servers": getOrCreateConfiguration(target).setServers(property(camelContext, java.lang.String.class, value)); return true; case "sslcontextparameters": case "sslContextParameters": getOrCreateConfiguration(target).setSslContextParameters(property(camelContext, org.apache.camel.support.jsse.SSLContextParameters.class, value)); return true; case "useglobalsslcontextparameters": case "useGlobalSslContextParameters": target.setUseGlobalSslContextParameters(property(camelContext, boolean.class, value)); return true; case "username": getOrCreateConfiguration(target).setUsername(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "checkclientidlength": case "checkClientIdLength": return boolean.class; case "clientid": case "clientId": return java.lang.String.class; case "configuration": return org.apache.camel.component.tahu.TahuConfiguration.class; case "keepalivetimeout": case "keepAliveTimeout": return int.class; case "password": return java.lang.String.class; case "rebirthdebouncedelay": case "rebirthDebounceDelay": return long.class; case "servers": return java.lang.String.class; case "sslcontextparameters": case "sslContextParameters": return org.apache.camel.support.jsse.SSLContextParameters.class; case "useglobalsslcontextparameters": case "useGlobalSslContextParameters": return boolean.class; case "username": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { TahuHostComponent target = (TahuHostComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "checkclientidlength": case "checkClientIdLength": return getOrCreateConfiguration(target).isCheckClientIdLength(); case "clientid": case "clientId": return getOrCreateConfiguration(target).getClientId(); case "configuration": return target.getConfiguration(); case "keepalivetimeout": case "keepAliveTimeout": return getOrCreateConfiguration(target).getKeepAliveTimeout(); case "password": return getOrCreateConfiguration(target).getPassword(); case "rebirthdebouncedelay": case "rebirthDebounceDelay": return getOrCreateConfiguration(target).getRebirthDebounceDelay(); case "servers": return getOrCreateConfiguration(target).getServers(); case "sslcontextparameters": case "sslContextParameters": return getOrCreateConfiguration(target).getSslContextParameters(); case "useglobalsslcontextparameters": case "useGlobalSslContextParameters": return target.isUseGlobalSslContextParameters(); case "username": return getOrCreateConfiguration(target).getUsername(); default: return null; } } }
TahuHostComponentConfigurer
java
bumptech__glide
library/test/src/test/java/com/bumptech/glide/request/transition/DrawableCrossFadeViewAnimationTest.java
{ "start": 2227, "end": 2535 }
class ____ { final Drawable current = new ColorDrawable(Color.GRAY); final ViewAdapter adapter = mock(ViewAdapter.class); final int duration = 200; final DrawableCrossFadeTransition animation = new DrawableCrossFadeTransition(duration, true /*isCrossFadeEnabled*/); } }
CrossFadeHarness
java
apache__camel
components/camel-cxf/camel-cxf-transport/src/main/java/org/apache/camel/component/cxf/transport/header/MessageHeaderFilter.java
{ "start": 1080, "end": 1656 }
interface ____ { /** * @return a list of binding name spaces that this relay can service */ List<String> getActivationNamespaces(); /** * This method filters (removes) headers from the given header list. <i>Out</i> direction refers to processing * headers from a Camel message to an CXF message. <i>In</i> direction is the reverse direction. * * @param direction the direction of the processing * @param headers the origin list of headers */ void filter(Direction direction, List<Header> headers); }
MessageHeaderFilter
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/plugins/convert/TypeConverters.java
{ "start": 5855, "end": 6175 }
class ____ implements TypeConverter<Charset> { @Override public Charset convert(final String s) { return Charset.forName(s); } } /** * Converts a {@link String} into a {@link Class}. */ @Plugin(name = "Class", category = CATEGORY) public static
CharsetConverter
java
processing__processing4
core/src/processing/data/LongDict.java
{ "start": 305, "end": 3764 }
class ____ { /** Number of elements in the table */ protected int count; protected String[] keys; protected long[] values; /** Internal implementation for faster lookups */ private HashMap<String, Integer> indices = new HashMap<>(); public LongDict() { count = 0; keys = new String[10]; values = new long[10]; } /** * Create a new lookup with a specific size. This is more efficient than not * specifying a size. Use it when you know the rough size of the thing you're creating. * * @nowebref */ public LongDict(int length) { count = 0; keys = new String[length]; values = new long[length]; } /** * Read a set of entries from a Reader that has each key/value pair on * a single line, separated by a tab. * * @nowebref */ public LongDict(BufferedReader reader) { String[] lines = PApplet.loadStrings(reader); keys = new String[lines.length]; values = new long[lines.length]; for (int i = 0; i < lines.length; i++) { String[] pieces = PApplet.split(lines[i], '\t'); if (pieces.length == 2) { keys[count] = pieces[0]; values[count] = PApplet.parseInt(pieces[1]); indices.put(pieces[0], count); count++; } } } /** * @nowebref */ public LongDict(String[] keys, long[] values) { if (keys.length != values.length) { throw new IllegalArgumentException("key and value arrays must be the same length"); } this.keys = keys; this.values = values; count = keys.length; for (int i = 0; i < count; i++) { indices.put(keys[i], i); } } /** * Constructor to allow (more intuitive) inline initialization, e.g.: * <pre> * new FloatDict(new Object[][] { * { "key1", 1 }, * { "key2", 2 } * }); * </pre> */ public LongDict(Object[][] pairs) { count = pairs.length; this.keys = new String[count]; this.values = new long[count]; for (int i = 0; i < count; i++) { keys[i] = (String) pairs[i][0]; values[i] = (Integer) pairs[i][1]; indices.put(keys[i], i); } } /** * Returns the number of key/value pairs * * @webref intdict:method * @webBrief Returns the number of key/value pairs */ public int size() { return count; } /** * Resize the internal data, this can only be used to shrink the list. * Helpful for situations like sorting and then grabbing the top 50 entries. */ public void resize(int length) { if (length > count) { throw new IllegalArgumentException("resize() can only be used to shrink the dictionary"); } if (length < 1) { throw new IllegalArgumentException("resize(" + length + ") is too small, use 1 or higher"); } String[] newKeys = new String[length]; long[] newValues = new long[length]; PApplet.arrayCopy(keys, newKeys, length); PApplet.arrayCopy(values, newValues, length); keys = newKeys; values = newValues; count = length; resetIndices(); } /** * Remove all entries. * * @webref intdict:method * @webBrief Remove all entries */ public void clear() { count = 0; indices = new HashMap<>(); } private void resetIndices() { indices = new HashMap<>(count); for (int i = 0; i < count; i++) { indices.put(keys[i], i); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . public
LongDict
java
apache__camel
core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultUnitOfWork.java
{ "start": 15575, "end": 16178 }
class ____ implements AsyncCallback { private final AsyncCallback delegate; private final Processor processor; private UnitOfWorkCallback(AsyncCallback delegate, Processor processor) { this.delegate = delegate; this.processor = processor; } @Override public void done(boolean doneSync) { delegate.done(doneSync); afterProcess(processor, exchange, delegate, doneSync); } @Override public String toString() { return delegate.toString(); } } }
UnitOfWorkCallback
java
spring-projects__spring-boot
loader/spring-boot-loader/src/test/java/org/springframework/boot/loader/zip/ZipEndOfCentralDirectoryRecordTests.java
{ "start": 924, "end": 3801 }
class ____ { @Test void loadLocatesAndLoadsData() throws Exception { DataBlock dataBlock = new ByteArrayDataBlock(new byte[] { // 0x50, 0x4b, 0x05, 0x06, // 0x01, 0x00, // 0x02, 0x00, // 0x03, 0x00, // 0x04, 0x00, // 0x05, 0x00, 0x00, 0x00, // 0x06, 0x00, 0x00, 0x00, // 0x07, 0x00 }); // ZipEndOfCentralDirectoryRecord.Located located = ZipEndOfCentralDirectoryRecord.load(dataBlock); assertThat(located.pos()).isEqualTo(0L); ZipEndOfCentralDirectoryRecord record = located.endOfCentralDirectoryRecord(); assertThat(record.numberOfThisDisk()).isEqualTo((short) 1); assertThat(record.diskWhereCentralDirectoryStarts()).isEqualTo((short) 2); assertThat(record.numberOfCentralDirectoryEntriesOnThisDisk()).isEqualTo((short) 3); assertThat(record.totalNumberOfCentralDirectoryEntries()).isEqualTo((short) 4); assertThat(record.sizeOfCentralDirectory()).isEqualTo(5); assertThat(record.offsetToStartOfCentralDirectory()).isEqualTo(6); assertThat(record.commentLength()).isEqualTo((short) 7); } @Test void loadWhenMultipleBuffersBackLoadsData() throws Exception { byte[] bytes = new byte[ZipEndOfCentralDirectoryRecord.BUFFER_SIZE * 4]; byte[] data = new byte[] { // 0x50, 0x4b, 0x05, 0x06, // 0x01, 0x00, // 0x02, 0x00, // 0x03, 0x00, // 0x04, 0x00, // 0x05, 0x00, 0x00, 0x00, // 0x06, 0x00, 0x00, 0x00, // 0x07, 0x00 }; // System.arraycopy(data, 0, bytes, 4, data.length); ZipEndOfCentralDirectoryRecord.Located located = ZipEndOfCentralDirectoryRecord .load(new ByteArrayDataBlock(bytes)); assertThat(located.pos()).isEqualTo(4L); } @Test void loadWhenSignatureDoesNotMatchThrowsException() { DataBlock dataBlock = new ByteArrayDataBlock(new byte[] { // 0x51, 0x4b, 0x05, 0x06, // 0x01, 0x00, // 0x02, 0x00, // 0x03, 0x00, // 0x04, 0x00, // 0x05, 0x00, 0x00, 0x00, // 0x06, 0x00, 0x00, 0x00, // 0x07, 0x00 }); // assertThatIOException().isThrownBy(() -> ZipEndOfCentralDirectoryRecord.load(dataBlock)) .withMessageContaining("'End Of Central Directory Record' not found"); } @Test void asByteArrayReturnsByteArray() throws Exception { byte[] bytes = new byte[] { // 0x50, 0x4b, 0x05, 0x06, // 0x01, 0x00, // 0x02, 0x00, // 0x03, 0x00, // 0x04, 0x00, // 0x05, 0x00, 0x00, 0x00, // 0x06, 0x00, 0x00, 0x00, // 0x07, 0x00 }; // ZipEndOfCentralDirectoryRecord.Located located = ZipEndOfCentralDirectoryRecord .load(new ByteArrayDataBlock(bytes)); assertThat(located.endOfCentralDirectoryRecord().asByteArray()).isEqualTo(bytes); } @Test void sizeReturnsSize() { ZipEndOfCentralDirectoryRecord record = new ZipEndOfCentralDirectoryRecord((short) 1, (short) 2, (short) 3, (short) 4, 5, 6, (short) 7); assertThat(record.size()).isEqualTo(29L); } }
ZipEndOfCentralDirectoryRecordTests
java
spring-projects__spring-boot
module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/autoconfigure/metrics/DataSourcePoolMetricsAutoConfiguration.java
{ "start": 5272, "end": 6465 }
class ____ implements MeterBinder { private static final Log logger = LogFactory.getLog(HikariDataSourceMeterBinder.class); private final ObjectProvider<DataSource> dataSources; HikariDataSourceMeterBinder(ObjectProvider<DataSource> dataSources) { this.dataSources = dataSources; } @Override public void bindTo(MeterRegistry registry) { this.dataSources.stream(ObjectProvider.UNFILTERED, false).forEach((dataSource) -> { HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(dataSource, HikariConfigMXBean.class, HikariDataSource.class); if (hikariDataSource != null) { bindMetricsRegistryToHikariDataSource(hikariDataSource, registry); } }); } private void bindMetricsRegistryToHikariDataSource(HikariDataSource hikari, MeterRegistry registry) { if (hikari.getMetricRegistry() == null && hikari.getMetricsTrackerFactory() == null) { try { hikari.setMetricsTrackerFactory(new MicrometerMetricsTrackerFactory(registry)); } catch (Exception ex) { logger.warn(LogMessage.format("Failed to bind Hikari metrics: %s", ex.getMessage())); } } } } } }
HikariDataSourceMeterBinder
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/action/user/GetUsersResponseTests.java
{ "start": 1197, "end": 5693 }
class ____ extends ESTestCase { public void testToXContent() throws IOException { final Settings settings = Settings.builder() .put(AnonymousUser.USERNAME_SETTING.getKey(), "_" + randomAlphaOfLengthBetween(5, 18)) .put(AnonymousUser.ROLES_SETTING.getKey(), "superuser") .build(); final User reservedUser = randomFrom(new ElasticUser(true), new KibanaSystemUser(true)); final User anonymousUser = new AnonymousUser(settings); final User nativeUser = AuthenticationTestHelper.randomUser(); final Map<String, String> profileUidLookup; if (randomBoolean()) { profileUidLookup = new HashMap<>(); if (randomBoolean()) { profileUidLookup.put(reservedUser.principal(), "u_profile_" + reservedUser.principal()); } if (randomBoolean()) { profileUidLookup.put(anonymousUser.principal(), "u_profile_" + anonymousUser.principal()); } if (randomBoolean()) { profileUidLookup.put(nativeUser.principal(), "u_profile_" + nativeUser.principal()); } } else { profileUidLookup = null; } final var response = new GetUsersResponse(List.of(reservedUser, anonymousUser, nativeUser), profileUidLookup); final XContentBuilder builder = XContentFactory.jsonBuilder(); response.toXContent(builder, ToXContent.EMPTY_PARAMS); assertThat( Strings.toString(builder), equalTo( XContentHelper.stripWhitespace( Strings.format( """ { "%s": { "username": "%s", "roles": [ %s ], "full_name": null, "email": null, "metadata": { "_reserved": true }, "enabled": true%s }, "%s": { "username": "%s", "roles": [ "superuser" ], "full_name": null, "email": null, "metadata": { "_reserved": true }, "enabled": true%s }, "%s": { "username": "%s", "roles": [ %s ], "full_name": null, "email": null, "metadata": {}, "enabled": true%s } }""", reservedUser.principal(), reservedUser.principal(), getRolesOutput(reservedUser), getProfileUidOutput(reservedUser, profileUidLookup), anonymousUser.principal(), anonymousUser.principal(), getProfileUidOutput(anonymousUser, profileUidLookup), nativeUser.principal(), nativeUser.principal(), getRolesOutput(nativeUser), getProfileUidOutput(nativeUser, profileUidLookup) ) ) ) ); } private String getRolesOutput(User user) { return Arrays.stream(user.roles()).map(r -> "\"" + r + "\"").collect(Collectors.joining(",")); } private String getProfileUidOutput(User user, Map<String, String> profileUidLookup) { if (profileUidLookup == null) { return ""; } else { final String uid = profileUidLookup.get(user.principal()); if (uid == null) { return ""; } else { return ", \"profile_uid\": \"" + uid + "\""; } } } }
GetUsersResponseTests
java
apache__logging-log4j2
log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/resolver/TimestampResolver.java
{ "start": 7098, "end": 10836 }
class ____ implements EventResolver { private final InstantFormatter formatter; private PatternResolver(final InstantFormatter formatter) { this.formatter = formatter; } @Override public void resolve(final LogEvent logEvent, final JsonWriter jsonWriter) { jsonWriter.writeString(formatter::formatTo, logEvent.getInstant()); } } private static EventResolver createEpochResolver(final TemplateResolverConfig config) { final String unit = config.getString(new String[] {"epoch", "unit"}); final Boolean rounded = config.getBoolean(new String[] {"epoch", "rounded"}); if ("nanos".equals(unit) && !Boolean.FALSE.equals(rounded)) { return EPOCH_NANOS_RESOLVER; } else if ("millis".equals(unit)) { return !Boolean.TRUE.equals(rounded) ? EPOCH_MILLIS_RESOLVER : EPOCH_MILLIS_ROUNDED_RESOLVER; } else if ("millis.nanos".equals(unit) && rounded == null) { return EPOCH_MILLIS_NANOS_RESOLVER; } else if ("secs".equals(unit)) { return !Boolean.TRUE.equals(rounded) ? EPOCH_SECS_RESOLVER : EPOCH_SECS_ROUNDED_RESOLVER; } else if ("secs.nanos".equals(unit) && rounded == null) { return EPOCH_SECS_NANOS_RESOLVER; } throw new IllegalArgumentException("invalid epoch configuration: " + config); } private static final EventResolver EPOCH_NANOS_RESOLVER = (logEvent, jsonWriter) -> { final StringBuilder buffer = jsonWriter.getStringBuilder(); final Instant instant = logEvent.getInstant(); InstantNumberFormatter.EPOCH_NANOS.formatTo(buffer, instant); }; private static final EventResolver EPOCH_MILLIS_RESOLVER = (logEvent, jsonWriter) -> { final StringBuilder buffer = jsonWriter.getStringBuilder(); final Instant instant = logEvent.getInstant(); InstantNumberFormatter.EPOCH_MILLIS.formatTo(buffer, instant); }; private static final EventResolver EPOCH_MILLIS_ROUNDED_RESOLVER = (logEvent, jsonWriter) -> { final StringBuilder buffer = jsonWriter.getStringBuilder(); final Instant instant = logEvent.getInstant(); InstantNumberFormatter.EPOCH_MILLIS_ROUNDED.formatTo(buffer, instant); }; private static final EventResolver EPOCH_MILLIS_NANOS_RESOLVER = (logEvent, jsonWriter) -> { final StringBuilder buffer = jsonWriter.getStringBuilder(); final Instant instant = logEvent.getInstant(); InstantNumberFormatter.EPOCH_MILLIS_NANOS.formatTo(buffer, instant); }; private static final EventResolver EPOCH_SECS_RESOLVER = (logEvent, jsonWriter) -> { final StringBuilder buffer = jsonWriter.getStringBuilder(); final Instant instant = logEvent.getInstant(); InstantNumberFormatter.EPOCH_SECONDS.formatTo(buffer, instant); }; private static final EventResolver EPOCH_SECS_ROUNDED_RESOLVER = (logEvent, jsonWriter) -> { final StringBuilder buffer = jsonWriter.getStringBuilder(); final Instant instant = logEvent.getInstant(); InstantNumberFormatter.EPOCH_SECONDS_ROUNDED.formatTo(buffer, instant); }; private static final EventResolver EPOCH_SECS_NANOS_RESOLVER = (logEvent, jsonWriter) -> { final StringBuilder buffer = jsonWriter.getStringBuilder(); final Instant instant = logEvent.getInstant(); InstantNumberFormatter.EPOCH_SECONDS_NANOS.formatTo(buffer, instant); }; static String getName() { return "timestamp"; } @Override public void resolve(final LogEvent logEvent, final JsonWriter jsonWriter) { internalResolver.resolve(logEvent, jsonWriter); } }
PatternResolver
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/interfaces/hbm/allAudited/joined/JoinedAllAuditedTest.java
{ "start": 507, "end": 569 }
class ____ extends AbstractAllAuditedTest { }
JoinedAllAuditedTest
java
spring-projects__spring-boot
module/spring-boot-tomcat/src/test/java/org/springframework/boot/tomcat/SslConnectorCustomizerTests.java
{ "start": 2037, "end": 6514 }
class ____ { private final Log logger = LogFactory.getLog(SslConnectorCustomizerTests.class); private Tomcat tomcat; @BeforeEach void setup() { this.tomcat = new Tomcat(); Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setPort(0); this.tomcat.setConnector(connector); } @AfterEach void stop() throws Exception { System.clearProperty("javax.net.ssl.trustStorePassword"); this.tomcat.stop(); } @Test @WithPackageResources("test.jks") void sslCiphersConfiguration() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyStore("classpath:test.jks"); ssl.setKeyStorePassword("secret"); ssl.setCiphers(new String[] { "ALPHA", "BRAVO", "CHARLIE" }); Connector connector = this.tomcat.getConnector(); SslConnectorCustomizer customizer = new SslConnectorCustomizer(this.logger, connector, ssl.getClientAuth()); customizer.customize(WebServerSslBundle.get(ssl), Collections.emptyMap()); this.tomcat.start(); SSLHostConfig[] sslHostConfigs = connector.getProtocolHandler().findSslHostConfigs(); assertThat(sslHostConfigs[0].getCiphers()).isEqualTo("ALPHA:BRAVO:CHARLIE"); } @Test @WithPackageResources("test.jks") void sslEnabledMultipleProtocolsConfiguration() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setKeyStore("classpath:test.jks"); ssl.setEnabledProtocols(new String[] { "TLSv1.1", "TLSv1.2" }); ssl.setCiphers(new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "BRAVO" }); Connector connector = this.tomcat.getConnector(); SslConnectorCustomizer customizer = new SslConnectorCustomizer(this.logger, connector, ssl.getClientAuth()); customizer.customize(WebServerSslBundle.get(ssl), Collections.emptyMap()); this.tomcat.start(); SSLHostConfig sslHostConfig = connector.getProtocolHandler().findSslHostConfigs()[0]; assertThat(sslHostConfig.getSslProtocol()).isEqualTo("TLS"); assertThat(sslHostConfig.getEnabledProtocols()).containsExactlyInAnyOrder("TLSv1.1", "TLSv1.2"); } @Test @WithPackageResources("test.jks") void sslEnabledProtocolsConfiguration() throws Exception { Ssl ssl = new Ssl(); ssl.setKeyPassword("password"); ssl.setKeyStore("classpath:test.jks"); ssl.setEnabledProtocols(new String[] { "TLSv1.2" }); ssl.setCiphers(new String[] { "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "BRAVO" }); Connector connector = this.tomcat.getConnector(); SslConnectorCustomizer customizer = new SslConnectorCustomizer(this.logger, connector, ssl.getClientAuth()); customizer.customize(WebServerSslBundle.get(ssl), Collections.emptyMap()); this.tomcat.start(); SSLHostConfig sslHostConfig = connector.getProtocolHandler().findSslHostConfigs()[0]; assertThat(sslHostConfig.getSslProtocol()).isEqualTo("TLS"); assertThat(sslHostConfig.getEnabledProtocols()).containsExactly("TLSv1.2"); } @Test void customizeWhenSslIsEnabledWithNoKeyStoreAndNotPkcs11ThrowsException() { assertThatIllegalStateException().isThrownBy(() -> { SslConnectorCustomizer customizer = new SslConnectorCustomizer(this.logger, this.tomcat.getConnector(), Ssl.ClientAuth.NONE); customizer.customize(WebServerSslBundle.get(new Ssl()), Collections.emptyMap()); }).withMessageContaining("SSL is enabled but no trust material is configured"); } @Test @WithPackageResources("test.jks") void customizeWhenSslIsEnabledWithPkcs11AndKeyStoreThrowsException() { Ssl ssl = new Ssl(); ssl.setKeyStoreType("PKCS11"); ssl.setKeyStoreProvider(MockPkcs11SecurityProvider.NAME); ssl.setKeyStore("classpath:test.jks"); ssl.setKeyPassword("password"); assertThatIllegalStateException().isThrownBy(() -> { SslConnectorCustomizer customizer = new SslConnectorCustomizer(this.logger, this.tomcat.getConnector(), ssl.getClientAuth()); customizer.customize(WebServerSslBundle.get(ssl), Collections.emptyMap()); }).withMessageContaining("must be empty or null for PKCS11 hardware key stores"); } @Test void customizeWhenSslIsEnabledWithPkcs11AndKeyStoreProvider() { Ssl ssl = new Ssl(); ssl.setKeyStoreType("PKCS11"); ssl.setKeyStoreProvider(MockPkcs11SecurityProvider.NAME); ssl.setKeyStorePassword("1234"); SslConnectorCustomizer customizer = new SslConnectorCustomizer(this.logger, this.tomcat.getConnector(), ssl.getClientAuth()); assertThatNoException() .isThrownBy(() -> customizer.customize(WebServerSslBundle.get(ssl), Collections.emptyMap())); } }
SslConnectorCustomizerTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/sql/PersonSummaryDTO.java
{ "start": 212, "end": 572 }
class ____ { private Number id; private String name; //Getters and setters are omitted for brevity public Number getId() { return id; } public void setId(Number id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } //end::sql-hibernate-dto-query-example[]
PersonSummaryDTO
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/dispatcher/JobMasterTester.java
{ "start": 3428, "end": 4277 }
class ____ implements Closeable { private static final Duration TIMEOUT = Duration.ofMinutes(1); private static TaskStateSnapshot createNonEmptyStateSnapshot(TaskInformation taskInformation) { final TaskStateSnapshot checkpointStateHandles = new TaskStateSnapshot(); checkpointStateHandles.putSubtaskStateByOperatorID( OperatorID.fromJobVertexID(taskInformation.getJobVertexId()), OperatorSubtaskState.builder() .setManagedOperatorState( new OperatorStreamStateHandle( Collections.emptyMap(), new ByteStreamStateHandle("foobar", new byte[0]))) .build()); return checkpointStateHandles; } private static
JobMasterTester
java
google__guava
guava/src/com/google/common/collect/Iterables.java
{ "start": 3662, "end": 44602 }
class ____<T extends @Nullable Object> extends FluentIterable<T> { private final Iterable<? extends T> iterable; private UnmodifiableIterable(Iterable<? extends T> iterable) { this.iterable = iterable; } @Override public Iterator<T> iterator() { return Iterators.unmodifiableIterator(iterable.iterator()); } @Override public void forEach(Consumer<? super T> action) { iterable.forEach(action); } @SuppressWarnings("unchecked") // safe upcast, assuming no one has a crazy Spliterator subclass @Override public Spliterator<T> spliterator() { return (Spliterator<T>) iterable.spliterator(); } @Override public String toString() { return iterable.toString(); } // no equals and hashCode; it would break the contract! } /** Returns the number of elements in {@code iterable}. */ public static int size(Iterable<?> iterable) { return (iterable instanceof Collection) ? ((Collection<?>) iterable).size() : Iterators.size(iterable.iterator()); } /** * Returns {@code true} if {@code iterable} contains any element {@code o} for which {@code * Objects.equals(o, element)} would return {@code true}. Otherwise returns {@code false}, even in * cases where {@link Collection#contains} might throw {@link NullPointerException} or {@link * ClassCastException}. */ public static boolean contains(Iterable<?> iterable, @Nullable Object element) { if (iterable instanceof Collection) { Collection<?> collection = (Collection<?>) iterable; return Collections2.safeContains(collection, element); } return Iterators.contains(iterable.iterator(), element); } /** * Removes, from an iterable, every element that belongs to the provided collection. * * <p>This method calls {@link Collection#removeAll} if {@code iterable} is a collection, and * {@link Iterators#removeAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRemove the elements to remove * @return {@code true} if any element was removed from {@code iterable} */ @CanIgnoreReturnValue public static boolean removeAll(Iterable<?> removeFrom, Collection<?> elementsToRemove) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove)) : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); } /** * Removes, from an iterable, every element that does not belong to the provided collection. * * <p>This method calls {@link Collection#retainAll} if {@code iterable} is a collection, and * {@link Iterators#retainAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRetain the elements to retain * @return {@code true} if any element was removed from {@code iterable} */ @CanIgnoreReturnValue public static boolean retainAll(Iterable<?> removeFrom, Collection<?> elementsToRetain) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain)) : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); } /** * Removes, from an iterable, every element that satisfies the provided predicate. * * <p>Removals may or may not happen immediately as each element is tested against the predicate. * The behavior of this method is not specified if {@code predicate} is dependent on {@code * removeFrom}. * * <p><b>Java 8+ users:</b> if {@code removeFrom} is a {@link Collection}, use {@code * removeFrom.removeIf(predicate)} instead. * * @param removeFrom the iterable to (potentially) remove elements from * @param predicate a predicate that determines whether an element should be removed * @return {@code true} if any elements were removed from the iterable * @throws UnsupportedOperationException if the iterable does not support {@code remove()}. * @since 2.0 */ @CanIgnoreReturnValue public static <T extends @Nullable Object> boolean removeIf( Iterable<T> removeFrom, Predicate<? super T> predicate) { if (removeFrom instanceof Collection) { return ((Collection<T>) removeFrom).removeIf(predicate); } return Iterators.removeIf(removeFrom.iterator(), predicate); } /** Removes and returns the first matching element, or returns {@code null} if there is none. */ static <T extends @Nullable Object> @Nullable T removeFirstMatching( Iterable<T> removeFrom, Predicate<? super T> predicate) { checkNotNull(predicate); Iterator<T> iterator = removeFrom.iterator(); while (iterator.hasNext()) { T next = iterator.next(); if (predicate.apply(next)) { iterator.remove(); return next; } } return null; } /** * Determines whether two iterables contain equal elements in the same order. More specifically, * this method returns {@code true} if {@code iterable1} and {@code iterable2} contain the same * number of elements and every element of {@code iterable1} is equal to the corresponding element * of {@code iterable2}. */ public static boolean elementsEqual(Iterable<?> iterable1, Iterable<?> iterable2) { if (iterable1 instanceof Collection && iterable2 instanceof Collection) { Collection<?> collection1 = (Collection<?>) iterable1; Collection<?> collection2 = (Collection<?>) iterable2; if (collection1.size() != collection2.size()) { return false; } } return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator()); } /** * Returns a string representation of {@code iterable}, with the format {@code [e1, e2, ..., en]} * (that is, identical to {@link java.util.Arrays Arrays}{@code * .toString(Iterables.toArray(iterable))}). Note that for <i>most</i> implementations of {@link * Collection}, {@code collection.toString()} also gives the same result, but that behavior is not * generally guaranteed. */ public static String toString(Iterable<?> iterable) { return Iterators.toString(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}. * * <p><b>Java 8+ users:</b> the {@code Stream} equivalent to this method is {@code * stream.collect(MoreCollectors.onlyElement())}. * * @throws NoSuchElementException if the iterable is empty * @throws IllegalArgumentException if the iterable contains multiple elements */ @ParametricNullness public static <T extends @Nullable Object> T getOnlyElement(Iterable<T> iterable) { return Iterators.getOnlyElement(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}, or {@code defaultValue} if the * iterable is empty. * * <p><b>Java 8+ users:</b> the {@code Stream} equivalent to this method is {@code * stream.collect(MoreCollectors.toOptional()).orElse(defaultValue)}. * * @throws IllegalArgumentException if the iterator contains multiple elements */ @ParametricNullness public static <T extends @Nullable Object> T getOnlyElement( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { return Iterators.getOnlyElement(iterable.iterator(), defaultValue); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @param type the type of the elements * @return a newly-allocated array into which all the elements of the iterable have been copied */ @GwtIncompatible // Array.newInstance(Class, int) public static <T extends @Nullable Object> T[] toArray( Iterable<? extends T> iterable, Class<@NonNull T> type) { return toArray(iterable, ObjectArrays.newArray(type, 0)); } static <T extends @Nullable Object> T[] toArray(Iterable<? extends T> iterable, T[] array) { Collection<? extends T> collection = castOrCopyToCollection(iterable); return collection.toArray(array); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @return a newly-allocated array into which all the elements of the iterable have been copied */ static @Nullable Object[] toArray(Iterable<?> iterable) { return castOrCopyToCollection(iterable).toArray(); } /** * Converts an iterable into a collection. If the iterable is already a collection, it is * returned. Otherwise, an {@link java.util.ArrayList} is created with the contents of the * iterable in the same iteration order. */ private static <E extends @Nullable Object> Collection<E> castOrCopyToCollection( Iterable<E> iterable) { return (iterable instanceof Collection) ? (Collection<E>) iterable : Lists.newArrayList(iterable.iterator()); } /** * Adds all elements in {@code iterable} to {@code collection}. * * @return {@code true} if {@code collection} was modified as a result of this operation. */ @CanIgnoreReturnValue public static <T extends @Nullable Object> boolean addAll( Collection<T> addTo, Iterable<? extends T> elementsToAdd) { if (elementsToAdd instanceof Collection) { Collection<? extends T> c = (Collection<? extends T>) elementsToAdd; return addTo.addAll(c); } return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator()); } /** * Returns the number of elements in the specified iterable that equal the specified object. This * implementation avoids a full iteration when the iterable is a {@link Multiset} or {@link Set}. * * <p><b>Java 8+ users:</b> In most cases, the {@code Stream} equivalent of this method is {@code * stream.filter(element::equals).count()}. If {@code element} might be null, use {@code * stream.filter(Predicate.isEqual(element)).count()} instead. * * @see java.util.Collections#frequency(Collection, Object) Collections.frequency(Collection, * Object) */ public static int frequency(Iterable<?> iterable, @Nullable Object element) { if ((iterable instanceof Multiset)) { return ((Multiset<?>) iterable).count(element); } else if ((iterable instanceof Set)) { return ((Set<?>) iterable).contains(element) ? 1 : 0; } return Iterators.frequency(iterable.iterator(), element); } /** * Returns an iterable whose iterators cycle indefinitely over the elements of {@code iterable}. * * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After {@code * remove()} is called, subsequent cycles omit the removed element, which is no longer in {@code * iterable}. The iterator's {@code hasNext()} method returns {@code true} until {@code iterable} * is empty. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You * should use an explicit {@code break} or be certain that you will eventually remove all the * elements. * * <p>To cycle over the iterable {@code n} times, use the following: {@code * Iterables.concat(Collections.nCopies(n, iterable))} * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * Stream.generate(() -> iterable).flatMap(Streams::stream)}. */ public static <T extends @Nullable Object> Iterable<T> cycle(Iterable<T> iterable) { checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.cycle(iterable); } @Override public Spliterator<T> spliterator() { return Stream.generate(() -> iterable).<T>flatMap(Streams::stream).spliterator(); } @Override public String toString() { return iterable.toString() + " (cycled)"; } }; } /** * Returns an iterable whose iterators cycle indefinitely over the provided elements. * * <p>After {@code remove} is invoked on a generated iterator, the removed element will no longer * appear in either that iterator or any other iterator created from the same source iterable. * That is, this method behaves exactly as {@code Iterables.cycle(Lists.newArrayList(elements))}. * The iterator's {@code hasNext} method returns {@code true} until all of the original elements * have been removed. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You * should use an explicit {@code break} or be certain that you will eventually remove all the * elements. * * <p>To cycle over the elements {@code n} times, use the following: {@code * Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))} * * <p><b>Java 8+ users:</b> If passing a single element {@code e}, the {@code Stream} equivalent * of this method is {@code Stream.generate(() -> e)}. Otherwise, put the elements in a collection * and use {@code Stream.generate(() -> collection).flatMap(Collection::stream)}. */ @SafeVarargs public static <T extends @Nullable Object> Iterable<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); } /** * Combines two iterables into a single iterable. The returned iterable has an iterator that * traverses the elements in {@code a}, followed by the elements in {@code b}. The source * iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * Stream.concat(a, b)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b) { return FluentIterable.concat(a, b); } /** * Combines three iterables into a single iterable. The returned iterable has an iterator that * traverses the elements in {@code a}, followed by the elements in {@code b}, followed by the * elements in {@code c}. The source iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * Streams.concat(a, b, c)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) { return FluentIterable.concat(a, b, c); } /** * Combines four iterables into a single iterable. The returned iterable has an iterator that * traverses the elements in {@code a}, followed by the elements in {@code b}, followed by the * elements in {@code c}, followed by the elements in {@code d}. The source iterators are not * polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * Streams.concat(a, b, c, d)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c, Iterable<? extends T> d) { return FluentIterable.concat(a, b, c, d); } /** * Combines multiple iterables into a single iterable. The returned iterable has an iterator that * traverses the elements of each iterable in {@code inputs}. The input iterators are not polled * until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * Streams.concat(...)}. * * @throws NullPointerException if any of the provided iterables is null */ @SafeVarargs public static <T extends @Nullable Object> Iterable<T> concat(Iterable<? extends T>... inputs) { return FluentIterable.concat(inputs); } /** * Combines multiple iterables into a single iterable. The returned iterable has an iterator that * traverses the elements of each iterable in {@code inputs}. The input iterators are not polled * until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. The methods of the returned iterable may throw {@code * NullPointerException} if any of the input iterators is null. * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * streamOfStreams.flatMap(s -> s)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends Iterable<? extends T>> inputs) { return FluentIterable.concat(inputs); } /** * Divides an iterable into unmodifiable sublists of the given size (the final iterable may be * smaller). For example, partitioning an iterable containing {@code [a, b, c, d, e]} with a * partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer iterable containing two * inner lists of three and two elements, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()} * method. The returned lists implement {@link RandomAccess}, whether or not the input list does. * * <p><b>Note:</b> The current implementation eagerly allocates storage for {@code size} elements. * As a consequence, passing values like {@code Integer.MAX_VALUE} can lead to {@link * OutOfMemoryError}. * * <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link Lists#partition(List, int)} * instead. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition (the last may be smaller) * @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided * into partitions * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T extends @Nullable Object> Iterable<List<T>> partition( Iterable<T> iterable, int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.partition(iterable.iterator(), size); } }; } /** * Divides an iterable into unmodifiable sublists of the given size, padding the final iterable * with null values if necessary. For example, partitioning an iterable containing {@code [a, b, * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer * iterable containing two inner lists of three elements each, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()} * method. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition * @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided * into partitions (the final iterable may have trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T extends @Nullable Object> Iterable<List<@Nullable T>> paddedPartition( Iterable<T> iterable, int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<@Nullable T>>() { @Override public Iterator<List<@Nullable T>> iterator() { return Iterators.paddedPartition(iterable.iterator(), size); } }; } /** * Returns a view of {@code unfiltered} containing all elements that satisfy the input predicate * {@code retainIfTrue}. The returned iterable's iterator does not support {@code remove()}. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#filter}. */ public static <T extends @Nullable Object> Iterable<T> filter( Iterable<T> unfiltered, Predicate<? super T> retainIfTrue) { checkNotNull(unfiltered); checkNotNull(retainIfTrue); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), retainIfTrue); } @Override public void forEach(Consumer<? super T> action) { checkNotNull(action); unfiltered.forEach( (@ParametricNullness T a) -> { if (retainIfTrue.test(a)) { action.accept(a); } }); } @Override @GwtIncompatible("Spliterator") public Spliterator<T> spliterator() { return CollectSpliterators.filter(unfiltered.spliterator(), retainIfTrue); } }; } /** * Returns a view of {@code unfiltered} containing all elements that are of the type {@code * desiredType}. The returned iterable's iterator does not support {@code remove()}. * * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(type::isInstance).map(type::cast)}. * This does perform a little more work than necessary, so another option is to insert an * unchecked cast at some later point: * * {@snippet : * @SuppressWarnings("unchecked") // safe because of ::isInstance check * ImmutableList<NewType> result = * (ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList()); * } */ @SuppressWarnings("unchecked") @GwtIncompatible // Class.isInstance public static <T> Iterable<T> filter(Iterable<?> unfiltered, Class<T> desiredType) { checkNotNull(unfiltered); checkNotNull(desiredType); return (Iterable<T>) filter(unfiltered, Predicates.instanceOf(desiredType)); } /** * Returns {@code true} if any element in {@code iterable} satisfies the predicate. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#anyMatch}. */ public static <T extends @Nullable Object> boolean any( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.any(iterable.iterator(), predicate); } /** * Returns {@code true} if every element in {@code iterable} satisfies the predicate. If {@code * iterable} is empty, {@code true} is returned. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#allMatch}. */ public static <T extends @Nullable Object> boolean all( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.all(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given predicate; use this * method only when such an element is known to exist. If it is possible that <i>no</i> element * will match, use {@link #tryFind} or {@link #find(Iterable, Predicate, Object)} instead. * * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst().get()} * * @throws NoSuchElementException if no element in {@code iterable} matches the given predicate */ @ParametricNullness public static <T extends @Nullable Object> T find( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.find(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given predicate, or {@code * defaultValue} if none found. Note that this can usually be handled more naturally using {@code * tryFind(iterable, predicate).or(defaultValue)}. * * <p><b>{@code Stream} equivalent:</b> {@code * stream.filter(predicate).findFirst().orElse(defaultValue)} * * @since 7.0 */ // The signature we really want here is... // // <T extends @Nullable Object> @JointlyNullable T find( // Iterable<? extends T> iterable, // Predicate<? super T> predicate, // @JointlyNullable T defaultValue); // // ...where "@JointlyNullable" is similar to @PolyNull but slightly different: // // - @PolyNull means "@Nullable or @Nonnull" // (That would be unsound for an input Iterable<@Nullable Foo>. So, if we wanted to use // @PolyNull, we would have to restrict this method to non-null <T>. But it has users who pass // iterables with null elements.) // // - @JointlyNullable means "@Nullable or no annotation" public static <T extends @Nullable Object> @Nullable T find( Iterable<? extends T> iterable, Predicate<? super T> predicate, @Nullable T defaultValue) { return Iterators.<T>find(iterable.iterator(), predicate, defaultValue); } /** * Returns an {@link Optional} containing the first element in {@code iterable} that satisfies the * given predicate, if such an element exists. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null} * is matched in {@code iterable}, a NullPointerException will be thrown. * * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()} * * @since 11.0 */ public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.tryFind(iterable.iterator(), predicate); } /** * Returns the index in {@code iterable} of the first element that satisfies the provided {@code * predicate}, or {@code -1} if the Iterable has no such elements. * * <p>More formally, returns the lowest index {@code i} such that {@code * predicate.apply(Iterables.get(iterable, i))} returns {@code true}, or {@code -1} if there is no * such index. * * @since 2.0 */ public static <T extends @Nullable Object> int indexOf( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.indexOf(iterable.iterator(), predicate); } /** * Returns a view containing the result of applying {@code function} to each element of {@code * fromIterable}. * * <p>The returned iterable's iterator supports {@code remove()} if {@code fromIterable}'s * iterator does. After a successful {@code remove()} call, {@code fromIterable} no longer * contains the corresponding element. * * <p>If the input {@code Iterable} is known to be a {@code List} or other {@code Collection}, * consider {@link Lists#transform} and {@link Collections2#transform}. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#map} */ public static <F extends @Nullable Object, T extends @Nullable Object> Iterable<T> transform( Iterable<F> fromIterable, Function<? super F, ? extends T> function) { checkNotNull(fromIterable); checkNotNull(function); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.transform(fromIterable.iterator(), function); } @Override public void forEach(Consumer<? super T> action) { checkNotNull(action); fromIterable.forEach((F f) -> action.accept(function.apply(f))); } @Override @GwtIncompatible("Spliterator") public Spliterator<T> spliterator() { return CollectSpliterators.map(fromIterable.spliterator(), 0, function); } }; } /** * Returns the element at the specified position in an iterable. * * <p><b>{@code Stream} equivalent:</b> {@code stream.skip(position).findFirst().get()} (throws * {@code NoSuchElementException} if out of bounds) * * @param position position of the element to return * @return the element at the specified position in {@code iterable} * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to * the size of {@code iterable} */ @ParametricNullness public static <T extends @Nullable Object> T get(Iterable<T> iterable, int position) { checkNotNull(iterable); return (iterable instanceof List) ? ((List<T>) iterable).get(position) : Iterators.get(iterable.iterator(), position); } /** * Returns the element at the specified position in an iterable or a default value otherwise. * * <p><b>{@code Stream} equivalent:</b> {@code * stream.skip(position).findFirst().orElse(defaultValue)} (returns the default value if the index * is out of bounds) * * @param position position of the element to return * @param defaultValue the default value to return if {@code position} is greater than or equal to * the size of the iterable * @return the element at the specified position in {@code iterable} or {@code defaultValue} if * {@code iterable} contains fewer than {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ @ParametricNullness public static <T extends @Nullable Object> T get( Iterable<? extends T> iterable, int position, @ParametricNullness T defaultValue) { checkNotNull(iterable); Iterators.checkNonnegative(position); if (iterable instanceof List) { List<? extends T> list = (List<? extends T>) iterable; return (position < list.size()) ? list.get(position) : defaultValue; } else { Iterator<? extends T> iterator = iterable.iterator(); Iterators.advance(iterator, position); return Iterators.getNext(iterator, defaultValue); } } /** * Returns the first element in {@code iterable} or {@code defaultValue} if the iterable is empty. * The {@link Iterators} analog to this method is {@link Iterators#getNext}. * * <p>If no default value is desired (and the caller instead wants a {@link * NoSuchElementException} to be thrown), it is recommended that {@code * iterable.iterator().next()} is used instead. * * <p>To get the only element in a single-element {@code Iterable}, consider using {@link * #getOnlyElement(Iterable)} or {@link #getOnlyElement(Iterable, Object)} instead. * * <p><b>{@code Stream} equivalent:</b> {@code stream.findFirst().orElse(defaultValue)} * * <p><b>Java 21+ users:</b> if {code iterable} is a {@code SequencedCollection} (e.g., any list), * consider using {@code collection.getFirst()} instead. Note that if the collection is empty, * {@code getFirst()} throws a {@code NoSuchElementException}, while this method returns the * default value. * * @param defaultValue the default value to return if the iterable is empty * @return the first element of {@code iterable} or the default value * @since 7.0 */ @ParametricNullness public static <T extends @Nullable Object> T getFirst( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { return Iterators.getNext(iterable.iterator(), defaultValue); } /** * Returns the last element of {@code iterable}. If {@code iterable} is a {@link List} with {@link * RandomAccess} support, then this operation is guaranteed to be {@code O(1)}. * * <p><b>{@code Stream} equivalent:</b> {@link Streams#findLast Streams.findLast(stream).get()} * * <p><b>Java 21+ users:</b> if {code iterable} is a {@code SequencedCollection} (e.g., any list), * consider using {@code collection.getLast()} instead. * * @return the last element of {@code iterable} * @throws NoSuchElementException if the iterable is empty */ @ParametricNullness public static <T extends @Nullable Object> T getLast(Iterable<T> iterable) { // TODO(kevinb): Support a concurrently modified collection? if (iterable instanceof List) { List<T> list = (List<T>) iterable; if (list.isEmpty()) { throw new NoSuchElementException(); } return getLastInNonemptyList(list); } else if (iterable instanceof SortedSet) { return ((SortedSet<T>) iterable).last(); } return Iterators.getLast(iterable.iterator()); } /** * Returns the last element of {@code iterable} or {@code defaultValue} if the iterable is empty. * If {@code iterable} is a {@link List} with {@link RandomAccess} support, then this operation is * guaranteed to be {@code O(1)}. * * <p><b>{@code Stream} equivalent:</b> {@code Streams.findLast(stream).orElse(defaultValue)} * * <p><b>Java 21+ users:</b> if {code iterable} is a {@code SequencedCollection} (e.g., any list), * consider using {@code collection.getLast()} instead. Note that if the collection is empty, * {@code getLast()} throws a {@code NoSuchElementException}, while this method returns the * default value. * * @param defaultValue the value to return if {@code iterable} is empty * @return the last element of {@code iterable} or the default value * @since 3.0 */ @ParametricNullness public static <T extends @Nullable Object> T getLast( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { if (iterable instanceof Collection) { Collection<? extends T> c = (Collection<? extends T>) iterable; if (c.isEmpty()) { return defaultValue; } else if (iterable instanceof List) { return getLastInNonemptyList((List<? extends T>) iterable); } else if (iterable instanceof SortedSet) { return ((SortedSet<? extends T>) iterable).last(); } } return Iterators.getLast(iterable.iterator(), defaultValue); } @ParametricNullness private static <T extends @Nullable Object> T getLastInNonemptyList(List<T> list) { return list.get(list.size() - 1); } /** * Returns a view of {@code iterable} that skips its first {@code numberToSkip} elements. If * {@code iterable} contains fewer than {@code numberToSkip} elements, the returned iterable skips * all of its elements. * * <p>Modifications to the underlying {@link Iterable} before a call to {@code iterator()} are * reflected in the returned iterator. That is, the iterator skips the first {@code numberToSkip} * elements that exist when the {@code Iterator} is created, not when {@code skip()} is called. * * <p>The returned iterable's iterator supports {@code remove()} if the iterator of the underlying * iterable supports it. Note that it is <i>not</i> possible to delete the last skipped element by * immediately calling {@code remove()} on that iterator, as the {@code Iterator} contract states * that a call to {@code remove()} before a call to {@code next()} will throw an {@link * IllegalStateException}. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#skip} * * @since 3.0 */ public static <T extends @Nullable Object> Iterable<T> skip( Iterable<T> iterable, int numberToSkip) { checkNotNull(iterable); checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { if (iterable instanceof List) { List<T> list = (List<T>) iterable; int toSkip = Math.min(list.size(), numberToSkip); return list.subList(toSkip, list.size()).iterator(); } Iterator<T> iterator = iterable.iterator(); Iterators.advance(iterator, numberToSkip); /* * We can't just return the iterator because an immediate call to its * remove() method would remove one of the skipped elements instead of * throwing an IllegalStateException. */ return new Iterator<T>() { boolean atStart = true; @Override public boolean hasNext() { return iterator.hasNext(); } @Override @ParametricNullness public T next() { T result = iterator.next(); atStart = false; // not called if next() fails return result; } @Override public void remove() { checkRemove(!atStart); iterator.remove(); } }; } @Override public Spliterator<T> spliterator() { if (iterable instanceof List) { List<T> list = (List<T>) iterable; int toSkip = Math.min(list.size(), numberToSkip); return list.subList(toSkip, list.size()).spliterator(); } else { return Streams.stream(iterable).skip(numberToSkip).spliterator(); } } }; } /** * Returns a view of {@code iterable} containing its first {@code limitSize} elements. If {@code * iterable} contains fewer than {@code limitSize} elements, the returned view contains all of its * elements. The returned iterable's iterator supports {@code remove()} if {@code iterable}'s * iterator does. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#limit} * * @param iterable the iterable to limit * @param limitSize the maximum number of elements in the returned iterable * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T extends @Nullable Object> Iterable<T> limit( Iterable<T> iterable, int limitSize) { checkNotNull(iterable); checkArgument(limitSize >= 0, "limit is negative"); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.limit(iterable.iterator(), limitSize); } @Override public Spliterator<T> spliterator() { return Streams.stream(iterable).limit(limitSize).spliterator(); } }; } /** * Returns a view of the supplied iterable that wraps each generated {@link Iterator} through * {@link Iterators#consumingIterator(Iterator)}. * * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will instead use {@link * Queue#isEmpty} and {@link Queue#remove()}, since {@link Queue}'s iteration order is undefined. * Calling {@link Iterator#hasNext()} on a generated iterator from the returned iterable may cause * an item to be immediately dequeued for return on a subsequent call to {@link Iterator#next()}. * * <p>Whether the input {@code iterable} is a {@link Queue} or not, the returned {@code Iterable} * is not thread-safe. * * @param iterable the iterable to wrap * @return a view of the supplied iterable that wraps each generated iterator through {@link * Iterators#consumingIterator(Iterator)}; for queues, an iterable that generates iterators * that return and consume the queue's elements in queue order * @see Iterators#consumingIterator(Iterator) * @since 2.0 */ public static <T extends @Nullable Object> Iterable<T> consumingIterable(Iterable<T> iterable) { checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return (iterable instanceof Queue) ? new ConsumingQueueIterator<>((Queue<T>) iterable) : Iterators.consumingIterator(iterable.iterator()); } @Override public String toString() { return "Iterables.consumingIterable(...)"; } }; } // Methods only in Iterables, not in Iterators /** * Determines if the given iterable contains no elements. * * <p>There is no precise {@link Iterator} equivalent to this method, since one can only ask an * iterator whether it has any elements <i>remaining</i> (which one does using {@link * Iterator#hasNext}). * * <p><b>{@code Stream} equivalent:</b> {@code !stream.findAny().isPresent()} * * @return {@code true} if the iterable contains no elements */ public static boolean isEmpty(Iterable<?> iterable) { if (iterable instanceof Collection) { return ((Collection<?>) iterable).isEmpty(); } return !iterable.iterator().hasNext(); } /** * Returns an iterable over the merged contents of all given {@code iterables}. Equivalent entries * will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterables} are in non-descending order as this * method does not sort its input. * * <p>For any equivalent elements across all {@code iterables}, elements are returned in the order * of their source iterables. That is, if element A from iterable 1 and element B from iterable 2 * compare as equal, A will be returned before B if iterable 1 was passed before iterable 2. * * @since 11.0 */ public static <T extends @Nullable Object> Iterable<T> mergeSorted( Iterable<? extends Iterable<? extends T>> iterables, Comparator<? super T> comparator) { checkNotNull(iterables, "iterables"); checkNotNull(comparator, "comparator"); Iterable<T> iterable = new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.mergeSorted( Iterables.transform(iterables, Iterable::iterator), comparator); } }; return new UnmodifiableIterable<>(iterable); } }
UnmodifiableIterable
java
spring-projects__spring-framework
spring-jms/src/main/java/org/springframework/jms/support/converter/JacksonJsonMessageConverter.java
{ "start": 18044, "end": 18112 }
class ____: " + conversionHint); } return classes[0]; } }
argument
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 94275, "end": 94810 }
class ____ { void test(Function<Integer, Integer> f) { List<Integer> xs = new ArrayList<>(); test(x -> xs.get(x)); } } """) .doTest(); } @Test public void lambda_canHaveMutableVariablesWithin() { compilationHelper .addSourceLines( "Test.java", """ import com.google.errorprone.annotations.Immutable; import java.util.ArrayList; import java.util.List;
Test
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/util/subpackage/Person.java
{ "start": 797, "end": 924 }
interface ____ necessary in order to test support for * JDK dynamic proxies. * * @author Sam Brannen * @since 4.3 */ public
is
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvtVO/PushMsg.java
{ "start": 165, "end": 3689 }
class ____ implements Serializable { public static final String DIR_PUSH = "push"; /** * */ private static final long serialVersionUID = 8145512296629061628L; public static final String TAG = PushMsg.class.getSimpleName(); public static final String TYPE_SYS = "sys"; public static final String TYPE_WL = "wl"; public static final long STATUS_TRANK_NO_NEW = 128; /** * id of PushMsg */ private String id; /** * type */ private String tp; /** * start time with unit second(s) */ private long st; /** * end time with unit second(s) */ private long et; /** * delay range 以10秒为单位,客户端会在[0 ~ dr*10seconds]的范围内,进行随机延时请求msg,防止服务器过载。 */ private long dr; private Msg msg; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTp() { return tp; } public void setTp(String tp) { this.tp = tp; } public long getSt() { return st; } public void setSt(long st) { this.st = st; } public long getEt() { return et; } public void setEt(long et) { this.et = et; } public Msg getMsg() { return msg; } public void setMsg(Msg msg) { this.msg = msg; } /** * 条件: <br/> * 1、没过期(et>=当前时间,st可以大于也可以小于当前时间)<br/> * 2、消息体有效<br/> * * @return true if valid. */ public boolean isValid() { long now = new Date().getTime() / 1000; if (now > et) { return false; }// end if if (msg == null) { return false; }// end if if (!msg.isValid()) { return false; }// end if return true; } /** * 条件 1. isValid 2. st <= now <= et * */ public boolean isActiveNow() { if (!isValid()) { return false; } long now = new Date().getTime() / 1000; if (now < st) { return false; }// end if if (now > et) { return false; }// end if if (!isImagesReady()) { return false; }// end if return true; } /** * 消息的URL是否存在 * * @return true if exist. */ public boolean hasUrl() { boolean result = true; if (null != msg) { } else { result = false; } return result; } public boolean hasText() { boolean result = true; if (null != msg) { } else { result = false; } return result; } /** * 通知所需的图片资源是否就绪 * * @return true if ready, otherwise return false. */ private boolean isImagesReady() { List<String> list = getNewImageUrlList(); boolean ret = null == list || 0 == list.size(); if (!ret) { preparedImages(list); } return ret; } /** * 主动下载未缓存到客户端的资源图片 */ public void preparedImages() { List<String> list = getNewImageUrlList(); preparedImages(list); } public void preparedImages(List<String> list) { } /** * 获取需要下载图片的URL列表 * * @return list of image URL which image's URL is not cached, otherwise * return null. */ private List<String> getNewImageUrlList() { return null; } public static
PushMsg
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/conf/Configuration.java
{ "start": 9874, "end": 13259 }
class ____ { private final Object resource; private final String name; private final boolean restrictParser; public Resource(Object resource) { this(resource, resource.toString()); } public Resource(Object resource, boolean useRestrictedParser) { this(resource, resource.toString(), useRestrictedParser); } public Resource(Object resource, String name) { this(resource, name, getRestrictParserDefault(resource)); } public Resource(Object resource, String name, boolean restrictParser) { this.resource = resource; this.name = name; this.restrictParser = restrictParser; } public String getName(){ return name; } public Object getResource() { return resource; } public boolean isParserRestricted() { return restrictParser; } @Override public String toString() { return name; } private static boolean getRestrictParserDefault(Object resource) { if (resource instanceof String || !UserGroupInformation.isInitialized()) { return false; } UserGroupInformation user; try { user = UserGroupInformation.getCurrentUser(); } catch (IOException e) { throw new RuntimeException("Unable to determine current user", e); } return user.getRealUser() != null; } } /** * List of configuration resources. */ private ArrayList<Resource> resources = new ArrayList<Resource>(); /** * The value reported as the setting resource when a key is set * by code rather than a file resource by dumpConfiguration. */ static final String UNKNOWN_RESOURCE = "Unknown"; /** * List of configuration parameters marked <b>final</b>. */ private Set<String> finalParameters = Collections.newSetFromMap( new ConcurrentHashMap<String, Boolean>()); private boolean loadDefaults = true; /** * Configuration objects. */ private static final WeakHashMap<Configuration,Object> REGISTRY = new WeakHashMap<Configuration,Object>(); /** * Map to hold properties by there tag groupings. */ private final Map<String, Properties> propertyTagsMap = new ConcurrentHashMap<>(); /** * List of default Resources. Resources are loaded in the order of the list * entries */ private static final CopyOnWriteArrayList<String> defaultResources = new CopyOnWriteArrayList<String>(); private static final Map<ClassLoader, Map<String, WeakReference<Class<?>>>> CACHE_CLASSES = new WeakHashMap<ClassLoader, Map<String, WeakReference<Class<?>>>>(); /** * Sentinel value to store negative cache results in {@link #CACHE_CLASSES}. */ private static final Class<?> NEGATIVE_CACHE_SENTINEL = NegativeCacheSentinel.class; /** * Stores the mapping of key to the resource which modifies or loads * the key most recently. Created lazily to avoid wasting memory. */ private volatile Map<String, String[]> updatingResource; /** * Specify exact input factory to avoid time finding correct one. * Factory is reusable across un-synchronized threads once initialized */ private static final WstxInputFactory XML_INPUT_FACTORY = new WstxInputFactory(); /** * Class to keep the information about the keys which replace the deprecated * ones. * * This
Resource
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/MetadataLoadBalancerProvider.java
{ "start": 1325, "end": 2704 }
class ____ extends LoadBalancerProvider { @Override public NameResolver.ConfigOrError parseLoadBalancingPolicyConfig( Map<String, ?> rawLoadBalancingPolicyConfig) { String metadataKey = JsonUtil.getString(rawLoadBalancingPolicyConfig, "metadataKey"); if (metadataKey == null) { return NameResolver.ConfigOrError.fromError( Status.UNAVAILABLE.withDescription("no 'metadataKey' defined")); } String metadataValue = JsonUtil.getString(rawLoadBalancingPolicyConfig, "metadataValue"); if (metadataValue == null) { return NameResolver.ConfigOrError.fromError( Status.UNAVAILABLE.withDescription("no 'metadataValue' defined")); } return NameResolver.ConfigOrError.fromConfig( new MetadataLoadBalancerConfig(metadataKey, metadataValue)); } @Override public LoadBalancer newLoadBalancer(Helper helper) { MetadataHelper metadataHelper = new MetadataHelper(helper); return new MetadataLoadBalancer(metadataHelper, LoadBalancerRegistry.getDefaultRegistry().getProvider("round_robin") .newLoadBalancer(metadataHelper)); } @Override public boolean isAvailable() { return true; } @Override public int getPriority() { return 5; } @Override public String getPolicyName() { return "test.MetadataLoadBalancer"; } static
MetadataLoadBalancerProvider
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/urls/Urls_assertHasNoParameter_Test.java
{ "start": 1225, "end": 6736 }
class ____ extends UrlsBaseTest { @Test void should_pass_if_parameter_is_missing() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news"); String name = "article"; // WHEN/THEN urls.assertHasNoParameter(info, url, name); } @Test void should_fail_if_parameter_is_present_without_value() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news?article"); String name = "article"; List<String> actualValues = newArrayList((String) null); // WHEN var assertionError = expectAssertionError(() -> urls.assertHasNoParameter(info, url, name)); // THEN then(assertionError).hasMessage(shouldHaveNoParameter(url, name, actualValues).create()); } @Test void should_fail_if_parameter_is_present_with_value() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news?article=10"); String name = "article"; List<String> actualValues = newArrayList("10"); // WHEN var assertionError = expectAssertionError(() -> urls.assertHasNoParameter(info, url, name)); // THEN then(assertionError).hasMessage(shouldHaveNoParameter(url, name, actualValues).create()); } @Test void should_fail_if_parameter_is_present_multiple_times() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news?article&article=10"); String name = "article"; List<String> actualValues = newArrayList(null, "10"); // WHEN var assertionError = expectAssertionError(() -> urls.assertHasNoParameter(info, url, name)); // THEN then(assertionError).hasMessage(shouldHaveNoParameter(url, name, actualValues).create()); } @Test void should_pass_if_parameter_without_value_is_missing() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news"); String name = "article"; String unwantedValue = null; // WHEN/THEN urls.assertHasNoParameter(info, url, name, unwantedValue); } @Test void should_fail_if_parameter_without_value_is_present() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news?article"); String name = "article"; String expectedValue = null; List<String> actualValues = newArrayList((String) null); // WHEN var assertionError = expectAssertionError(() -> urls.assertHasNoParameter(info, url, name, expectedValue)); // THEN then(assertionError).hasMessage(shouldHaveNoParameter(url, name, expectedValue, actualValues).create()); } @Test void should_pass_if_parameter_without_value_is_present_with_value() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news=10"); String name = "article"; String unwantedValue = null; // WHEN/THEN urls.assertHasNoParameter(info, url, name, unwantedValue); } @Test void should_pass_if_parameter_with_value_is_missing() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news"); String name = "article"; String unwantedValue = "10"; // WHEN/THEN urls.assertHasNoParameter(info, url, name, unwantedValue); } @Test void should_pass_if_parameter_with_value_is_present_without_value() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news?article"); String name = "article"; String unwantedValue = "10"; // WHEN/THEN urls.assertHasNoParameter(info, url, name, unwantedValue); } @Test void should_pass_if_parameter_with_value_is_present_with_wrong_value() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news?article=11"); String name = "article"; String unwantedValue = "10"; // WHEN/THEN urls.assertHasNoParameter(info, url, name, unwantedValue); } @Test void should_fail_if_parameter_with_value_is_present() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news?article=10"); String name = "article"; String expectedValue = "10"; List<String> actualValues = newArrayList("10"); // WHEN var assertionError = expectAssertionError(() -> urls.assertHasNoParameter(info, url, name, expectedValue)); // THEN then(assertionError).hasMessage(shouldHaveNoParameter(url, name, expectedValue, actualValues).create()); } @Test void should_pass_if_url_has_no_parameters() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news"); // WHEN/THEN urls.assertHasNoParameters(info, url); } @Test void should_fail_if_url_has_some_parameters() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news?article=10&locked=false"); Set<String> actualValues = newLinkedHashSet("article", "locked"); // WHEN var assertionError = expectAssertionError(() -> urls.assertHasNoParameters(info, url)); // THEN then(assertionError).hasMessage(shouldHaveNoParameters(url, actualValues).create()); } @Test void should_fail_if_url_has_one_parameter() throws MalformedURLException { // GIVEN URL url = new URL("http://assertj.org/news?article=10"); Set<String> actualValues = newLinkedHashSet("article"); // WHEN var assertionError = expectAssertionError(() -> urls.assertHasNoParameters(info, url)); // THEN then(assertionError).hasMessage(shouldHaveNoParameters(url, actualValues).create()); } }
Urls_assertHasNoParameter_Test
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/introspect/TestNamingStrategyStd.java
{ "start": 912, "end": 1363 }
class ____ { public String WWW; public String someURL; public String someURIs; public Acronyms() {this(null, null, null);} public Acronyms(String WWW, String someURL, String someURIs) { this.WWW = WWW; this.someURL = someURL; this.someURIs = someURIs; } } @JsonPropertyOrder({"from_user", "user", "from$user", "from7user", "_x"}) static
Acronyms
java
quarkusio__quarkus
extensions/security/runtime/src/main/java/io/quarkus/security/runtime/QuarkusIdentityProviderManagerImpl.java
{ "start": 1093, "end": 8189 }
class ____ implements IdentityProviderManager { private static final Logger log = Logger.getLogger(QuarkusIdentityProviderManagerImpl.class); private final Map<Class<? extends AuthenticationRequest>, List<IdentityProvider<? extends AuthenticationRequest>>> providers; private final SecurityIdentityAugmentor[] augmenters; private final AuthenticationRequestContext blockingRequestContext; QuarkusIdentityProviderManagerImpl(Builder builder) { this.providers = builder.providers; this.augmenters = builder.augmentors.toArray(SecurityIdentityAugmentor[]::new); this.blockingRequestContext = new AuthenticationRequestContext() { @Override public Uni<SecurityIdentity> runBlocking(Supplier<SecurityIdentity> function) { return builder.blockingExecutor.executeBlocking(function); } }; } /** * Attempts to create an authenticated identity for the provided {@link AuthenticationRequest}. * <p> * If authentication succeeds the resulting identity will be augmented with any configured {@link SecurityIdentityAugmentor} * instances that have been registered. * * @param request The authentication request * @return The first identity provider that was registered with this type */ public Uni<SecurityIdentity> authenticate(AuthenticationRequest request) { try { var providers = this.providers.get(request.getClass()); if (providers == null) { return Uni.createFrom().failure(new IllegalArgumentException( "No IdentityProviders were registered to handle AuthenticationRequest " + request)); } if (providers.size() == 1) { return handleSingleProvider(getProvider(0, request, providers), request); } return handleProviders(providers, request); } catch (Throwable t) { return Uni.createFrom().failure(t); } } private <T extends AuthenticationRequest> Uni<SecurityIdentity> handleSingleProvider(IdentityProvider<T> identityProvider, T request) { Uni<SecurityIdentity> authenticated = identityProvider.authenticate(request, blockingRequestContext) .onItem().ifNull().failWith(new Supplier<Throwable>() { @Override public Throwable get() { // reject request with the invalid credential return new AuthenticationFailedException(); } }); if (augmenters.length > 0) { authenticated = authenticated .flatMap(new Function<SecurityIdentity, Uni<? extends SecurityIdentity>>() { @Override public Uni<? extends SecurityIdentity> apply(SecurityIdentity securityIdentity) { return handleIdentityFromProvider(0, securityIdentity, request.getAttributes()); } }); } return authenticated; } /** * Attempts to create an authenticated identity for the provided {@link AuthenticationRequest} in a blocking manner * <p> * If authentication succeeds the resulting identity will be augmented with any configured {@link SecurityIdentityAugmentor} * instances that have been registered. * * @param request The authentication request * @return The first identity provider that was registered with this type */ public SecurityIdentity authenticateBlocking(AuthenticationRequest request) { var providers = this.providers.get(request.getClass()); if (providers == null) { throw new IllegalArgumentException( "No IdentityProviders were registered to handle AuthenticationRequest " + request); } return handleProviders(providers, request).await().indefinitely(); } private Uni<SecurityIdentity> handleProviders( List<IdentityProvider<? extends AuthenticationRequest>> providers, AuthenticationRequest request) { return handleProvider(0, providers, request) .onItem() .transformToUni(new Function<SecurityIdentity, Uni<? extends SecurityIdentity>>() { @Override public Uni<? extends SecurityIdentity> apply(SecurityIdentity securityIdentity) { return handleIdentityFromProvider(0, securityIdentity, request.getAttributes()); } }); } private Uni<SecurityIdentity> handleProvider(int pos, List<IdentityProvider<? extends AuthenticationRequest>> providers, AuthenticationRequest request) { if (pos == providers.size()) { //we failed to authentication log.debug("Authentication failed as providers would authenticate the request"); return Uni.createFrom().failure(new AuthenticationFailedException()); } return getProvider(pos, request, providers) .authenticate(request, blockingRequestContext) .onItem().transformToUni(new Function<SecurityIdentity, Uni<? extends SecurityIdentity>>() { @Override public Uni<SecurityIdentity> apply(SecurityIdentity securityIdentity) { if (securityIdentity != null) { return Uni.createFrom().item(securityIdentity); } return handleProvider(pos + 1, providers, request); } }); } private Uni<SecurityIdentity> handleIdentityFromProvider(int pos, SecurityIdentity identity, Map<String, Object> attributes) { if (pos == augmenters.length) { return Uni.createFrom().item(identity); } SecurityIdentityAugmentor a = augmenters[pos]; return a.augment(identity, blockingRequestContext, attributes) .flatMap(new Function<SecurityIdentity, Uni<? extends SecurityIdentity>>() { @Override public Uni<SecurityIdentity> apply(SecurityIdentity securityIdentity) { return handleIdentityFromProvider(pos + 1, securityIdentity, attributes); } }); } @SuppressWarnings("unchecked") private static <T extends AuthenticationRequest> IdentityProvider<T> getProvider(int pos, T ignored, List<IdentityProvider<? extends AuthenticationRequest>> providers) { return (IdentityProvider<T>) providers.get(pos); } /** * Creates a builder for constructing instances of {@link QuarkusIdentityProviderManagerImpl} * * @return A builder */ public static Builder builder() { return new Builder(); } /** * A builder for constructing instances of {@link QuarkusIdentityProviderManagerImpl} */ public static
QuarkusIdentityProviderManagerImpl
java
elastic__elasticsearch
qa/smoke-test-http/src/internalClusterTest/java/org/elasticsearch/http/snapshots/RestGetSnapshotsIT.java
{ "start": 2494, "end": 27349 }
class ____ extends AbstractSnapshotRestTestCase { /** * Large snapshot pool settings to set up nodes for tests involving multiple repositories that need to have enough * threads so that blocking some threads on one repository doesn't block other repositories from doing work */ private static final Settings LARGE_SNAPSHOT_POOL_SETTINGS = Settings.builder() .put("thread_pool.snapshot.core", 3) .put("thread_pool.snapshot.max", 3) .build(); @Override protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) { return Settings.builder() .put(super.nodeSettings(nodeOrdinal, otherSettings)) .put(LARGE_SNAPSHOT_POOL_SETTINGS) .put(ThreadPool.ESTIMATED_TIME_INTERVAL_SETTING.getKey(), 0) // We have tests that check by-timestamp order .build(); } public void testSortOrder() throws Exception { final String repoName = "test-repo"; AbstractSnapshotIntegTestCase.createRepository(logger, repoName, "fs"); final List<String> snapshotNamesWithoutIndex = AbstractSnapshotIntegTestCase.createNSnapshots( logger, repoName, randomIntBetween(3, 20) ); createIndexWithContent("test-index"); final List<String> snapshotNamesWithIndex = AbstractSnapshotIntegTestCase.createNSnapshots( logger, repoName, randomIntBetween(3, 20) ); final Collection<String> allSnapshotNames = new HashSet<>(snapshotNamesWithIndex); allSnapshotNames.addAll(snapshotNamesWithoutIndex); doTestSortOrder(repoName, allSnapshotNames, SortOrder.ASC); doTestSortOrder(repoName, allSnapshotNames, SortOrder.DESC); } private void doTestSortOrder(String repoName, Collection<String> allSnapshotNames, SortOrder order) throws IOException { final boolean includeIndexNames = randomBoolean(); final List<SnapshotInfo> defaultSorting = clusterAdmin().prepareGetSnapshots(TEST_REQUEST_TIMEOUT, repoName) .setOrder(order) .setIncludeIndexNames(includeIndexNames) .get() .getSnapshots(); assertSnapshotListSorted(defaultSorting, null, order); assertSnapshotListSorted( allSnapshotsSorted(allSnapshotNames, repoName, SnapshotSortKey.NAME, order, includeIndexNames), SnapshotSortKey.NAME, order ); assertSnapshotListSorted( allSnapshotsSorted(allSnapshotNames, repoName, SnapshotSortKey.DURATION, order, includeIndexNames), SnapshotSortKey.DURATION, order ); assertSnapshotListSorted( allSnapshotsSorted(allSnapshotNames, repoName, SnapshotSortKey.INDICES, order, includeIndexNames), SnapshotSortKey.INDICES, order ); assertSnapshotListSorted( allSnapshotsSorted(allSnapshotNames, repoName, SnapshotSortKey.START_TIME, order, includeIndexNames), SnapshotSortKey.START_TIME, order ); assertSnapshotListSorted( allSnapshotsSorted(allSnapshotNames, repoName, SnapshotSortKey.SHARDS, order, includeIndexNames), SnapshotSortKey.SHARDS, order ); assertSnapshotListSorted( allSnapshotsSorted(allSnapshotNames, repoName, SnapshotSortKey.FAILED_SHARDS, order, includeIndexNames), SnapshotSortKey.FAILED_SHARDS, order ); assertSnapshotListSorted( allSnapshotsSorted(allSnapshotNames, repoName, SnapshotSortKey.REPOSITORY, order, includeIndexNames), SnapshotSortKey.REPOSITORY, order ); } public void testResponseSizeLimit() throws Exception { final String repoName = "test-repo"; AbstractSnapshotIntegTestCase.createRepository(logger, repoName, "fs"); final List<String> names = AbstractSnapshotIntegTestCase.createNSnapshots(logger, repoName, randomIntBetween(6, 20)); for (SnapshotSortKey sort : SnapshotSortKey.values()) { for (SortOrder order : SortOrder.values()) { logger.info("--> testing pagination for [{}] [{}]", sort, order); doTestPagination(repoName, names, sort, order); } } } private void doTestPagination(String repoName, List<String> names, SnapshotSortKey sort, SortOrder order) throws IOException { final boolean includeIndexNames = randomBoolean(); final List<SnapshotInfo> allSnapshotsSorted = allSnapshotsSorted(names, repoName, sort, order, includeIndexNames); final GetSnapshotsResponse batch1 = sortedWithLimit(repoName, sort, null, 2, order, includeIndexNames); assertEquals(allSnapshotsSorted.subList(0, 2), batch1.getSnapshots()); final GetSnapshotsResponse batch2 = sortedWithLimit(repoName, sort, batch1.next(), 2, order, includeIndexNames); assertEquals(allSnapshotsSorted.subList(2, 4), batch2.getSnapshots()); final int lastBatch = names.size() - batch1.getSnapshots().size() - batch2.getSnapshots().size(); final GetSnapshotsResponse batch3 = sortedWithLimit(repoName, sort, batch2.next(), lastBatch, order, includeIndexNames); assertEquals( batch3.getSnapshots(), allSnapshotsSorted.subList(batch1.getSnapshots().size() + batch2.getSnapshots().size(), names.size()) ); final GetSnapshotsResponse batch3NoLimit = sortedWithLimit( repoName, sort, batch2.next(), GetSnapshotsRequest.NO_LIMIT, order, includeIndexNames ); assertNull(batch3NoLimit.next()); assertEquals(batch3.getSnapshots(), batch3NoLimit.getSnapshots()); final GetSnapshotsResponse batch3LargeLimit = sortedWithLimit( repoName, sort, batch2.next(), lastBatch + randomIntBetween(1, 100), order, includeIndexNames ); assertEquals(batch3.getSnapshots(), batch3LargeLimit.getSnapshots()); assertNull(batch3LargeLimit.next()); } public void testSortAndPaginateWithInProgress() throws Exception { final String repoName = "test-repo"; AbstractSnapshotIntegTestCase.createRepository(logger, repoName, "mock"); final Collection<String> allSnapshotNames = new HashSet<>( AbstractSnapshotIntegTestCase.createNSnapshots(logger, repoName, randomIntBetween(3, 20)) ); createIndexWithContent("test-index-1"); allSnapshotNames.addAll(AbstractSnapshotIntegTestCase.createNSnapshots(logger, repoName, randomIntBetween(3, 20))); createIndexWithContent("test-index-2"); final int inProgressCount = randomIntBetween(6, 20); final List<ActionFuture<CreateSnapshotResponse>> inProgressSnapshots = new ArrayList<>(inProgressCount); AbstractSnapshotIntegTestCase.blockAllDataNodes(repoName); for (int i = 0; i < inProgressCount; i++) { final String snapshotName = "snap-" + i; allSnapshotNames.add(snapshotName); inProgressSnapshots.add(AbstractSnapshotIntegTestCase.startFullSnapshot(logger, repoName, snapshotName, false)); } AbstractSnapshotIntegTestCase.awaitNumberOfSnapshotsInProgress(logger, inProgressCount); AbstractSnapshotIntegTestCase.awaitClusterState(state -> { final var snapshotsInProgress = SnapshotsInProgress.get(state); boolean firstIndexSuccessfullySnapshot = snapshotsInProgress.asStream() .flatMap(s -> s.shards().entrySet().stream()) .allMatch( e -> e.getKey().getIndexName().equals("test-index-1") == false || e.getValue().state() == SnapshotsInProgress.ShardState.SUCCESS ); boolean secondIndexIsBlocked = snapshotsInProgress.asStream() .flatMap(s -> s.shards().entrySet().stream()) .filter(e -> e.getKey().getIndexName().equals("test-index-2")) .map(e -> e.getValue().state()) .collect(Collectors.groupingBy(e -> e, Collectors.counting())) .equals(Map.of(SnapshotsInProgress.ShardState.INIT, 1L, SnapshotsInProgress.ShardState.QUEUED, (long) inProgressCount - 1)); return firstIndexSuccessfullySnapshot && secondIndexIsBlocked; }); assertStablePagination(repoName, allSnapshotNames, SnapshotSortKey.START_TIME); assertStablePagination(repoName, allSnapshotNames, SnapshotSortKey.NAME); assertStablePagination(repoName, allSnapshotNames, SnapshotSortKey.INDICES); AbstractSnapshotIntegTestCase.unblockAllDataNodes(repoName); for (ActionFuture<CreateSnapshotResponse> inProgressSnapshot : inProgressSnapshots) { AbstractSnapshotIntegTestCase.assertSuccessful(logger, inProgressSnapshot); } assertStablePagination(repoName, allSnapshotNames, SnapshotSortKey.START_TIME); assertStablePagination(repoName, allSnapshotNames, SnapshotSortKey.NAME); assertStablePagination(repoName, allSnapshotNames, SnapshotSortKey.INDICES); } public void testFilterBySLMPolicy() throws Exception { final String repoName = "test-repo"; AbstractSnapshotIntegTestCase.createRepository(logger, repoName, "fs"); AbstractSnapshotIntegTestCase.createNSnapshots(logger, repoName, randomIntBetween(1, 5)); final List<SnapshotInfo> snapshotsWithoutPolicy = clusterAdmin().prepareGetSnapshots(TEST_REQUEST_TIMEOUT, "*") .setSnapshots("*") .setSort(SnapshotSortKey.NAME) .get() .getSnapshots(); final String snapshotWithPolicy = "snapshot-with-policy"; final String policyName = "some-policy"; final SnapshotInfo withPolicy = AbstractSnapshotIntegTestCase.assertSuccessful( logger, clusterAdmin().prepareCreateSnapshot(TEST_REQUEST_TIMEOUT, repoName, snapshotWithPolicy) .setUserMetadata(Map.of(SnapshotsService.POLICY_ID_METADATA_FIELD, policyName)) .setWaitForCompletion(true) .execute() ); assertThat(getAllSnapshotsForPolicies(policyName), is(List.of(withPolicy))); assertThat(getAllSnapshotsForPolicies("some-*"), is(List.of(withPolicy))); assertThat(getAllSnapshotsForPolicies("*", "-" + policyName), empty()); assertThat(getAllSnapshotsForPolicies(GetSnapshotsRequest.NO_POLICY_PATTERN), is(snapshotsWithoutPolicy)); assertThat(getAllSnapshotsForPolicies(GetSnapshotsRequest.NO_POLICY_PATTERN, "-" + policyName), is(snapshotsWithoutPolicy)); assertThat(getAllSnapshotsForPolicies(GetSnapshotsRequest.NO_POLICY_PATTERN), is(snapshotsWithoutPolicy)); assertThat(getAllSnapshotsForPolicies(GetSnapshotsRequest.NO_POLICY_PATTERN, "-*"), is(snapshotsWithoutPolicy)); assertThat(getAllSnapshotsForPolicies("no-such-policy"), empty()); assertThat(getAllSnapshotsForPolicies("no-such-policy*"), empty()); final String snapshotWithOtherPolicy = "snapshot-with-other-policy"; final String otherPolicyName = "other-policy"; final SnapshotInfo withOtherPolicy = AbstractSnapshotIntegTestCase.assertSuccessful( logger, clusterAdmin().prepareCreateSnapshot(TEST_REQUEST_TIMEOUT, repoName, snapshotWithOtherPolicy) .setUserMetadata(Map.of(SnapshotsService.POLICY_ID_METADATA_FIELD, otherPolicyName)) .setWaitForCompletion(true) .execute() ); assertThat(getAllSnapshotsForPolicies("*"), is(List.of(withOtherPolicy, withPolicy))); assertThat(getAllSnapshotsForPolicies(policyName, otherPolicyName), is(List.of(withOtherPolicy, withPolicy))); assertThat(getAllSnapshotsForPolicies(policyName, otherPolicyName, "no-such-policy*"), is(List.of(withOtherPolicy, withPolicy))); final List<SnapshotInfo> allSnapshots = clusterAdmin().prepareGetSnapshots(TEST_REQUEST_TIMEOUT, "*") .setSnapshots("*") .setSort(SnapshotSortKey.NAME) .get() .getSnapshots(); assertThat(getAllSnapshotsForPolicies(GetSnapshotsRequest.NO_POLICY_PATTERN, policyName, otherPolicyName), is(allSnapshots)); assertThat(getAllSnapshotsForPolicies(GetSnapshotsRequest.NO_POLICY_PATTERN, "*"), is(allSnapshots)); } public void testSortAfterStartTime() throws Exception { final String repoName = "test-repo"; AbstractSnapshotIntegTestCase.createRepository(logger, repoName, "fs"); final HashSet<Long> startTimes = new HashSet<>(); final SnapshotInfo snapshot1 = createFullSnapshotWithUniqueStartTime(repoName, "snapshot-1", startTimes); final SnapshotInfo snapshot2 = createFullSnapshotWithUniqueStartTime(repoName, "snapshot-2", startTimes); final SnapshotInfo snapshot3 = createFullSnapshotWithUniqueStartTime(repoName, "snapshot-3", startTimes); final List<SnapshotInfo> allSnapshotInfo = clusterAdmin().prepareGetSnapshots(TEST_REQUEST_TIMEOUT, matchAllPattern()) .setSnapshots(matchAllPattern()) .setSort(SnapshotSortKey.START_TIME) .get() .getSnapshots(); assertThat(allSnapshotInfo, is(List.of(snapshot1, snapshot2, snapshot3))); final long startTime1 = snapshot1.startTime(); final long startTime2 = snapshot2.startTime(); final long startTime3 = snapshot3.startTime(); assertThat(allAfterStartTimeAscending(startTime1 - 1), is(allSnapshotInfo)); assertThat(allAfterStartTimeAscending(startTime1), is(allSnapshotInfo)); assertThat(allAfterStartTimeAscending(startTime2), is(List.of(snapshot2, snapshot3))); assertThat(allAfterStartTimeAscending(startTime3), is(List.of(snapshot3))); assertThat(allAfterStartTimeAscending(startTime3 + 1), empty()); final List<SnapshotInfo> allSnapshotInfoDesc = clusterAdmin().prepareGetSnapshots(TEST_REQUEST_TIMEOUT, matchAllPattern()) .setSnapshots(matchAllPattern()) .setSort(SnapshotSortKey.START_TIME) .setOrder(SortOrder.DESC) .get() .getSnapshots(); assertThat(allSnapshotInfoDesc, is(List.of(snapshot3, snapshot2, snapshot1))); assertThat(allBeforeStartTimeDescending(startTime3 + 1), is(allSnapshotInfoDesc)); assertThat(allBeforeStartTimeDescending(startTime3), is(allSnapshotInfoDesc)); assertThat(allBeforeStartTimeDescending(startTime2), is(List.of(snapshot2, snapshot1))); assertThat(allBeforeStartTimeDescending(startTime1), is(List.of(snapshot1))); assertThat(allBeforeStartTimeDescending(startTime1 - 1), empty()); } // create a snapshot that is guaranteed to have a unique start time private SnapshotInfo createFullSnapshotWithUniqueStartTime(String repoName, String snapshotName, Set<Long> forbiddenStartTimes) { while (true) { final SnapshotInfo snapshotInfo = AbstractSnapshotIntegTestCase.createFullSnapshot(logger, repoName, snapshotName); if (forbiddenStartTimes.contains(snapshotInfo.startTime())) { logger.info("--> snapshot start time collided"); assertAcked(clusterAdmin().prepareDeleteSnapshot(TEST_REQUEST_TIMEOUT, repoName, snapshotName).get()); } else { assertTrue(forbiddenStartTimes.add(snapshotInfo.startTime())); return snapshotInfo; } } } private List<SnapshotInfo> allAfterStartTimeAscending(long timestamp) throws IOException { final Request request = baseGetSnapshotsRequest("*"); request.addParameter("sort", SnapshotSortKey.START_TIME.toString()); request.addParameter("from_sort_value", String.valueOf(timestamp)); final Response response = getRestClient().performRequest(request); return readSnapshotInfos(response).getSnapshots(); } private List<SnapshotInfo> allBeforeStartTimeDescending(long timestamp) throws IOException { final Request request = baseGetSnapshotsRequest("*"); request.addParameter("sort", SnapshotSortKey.START_TIME.toString()); request.addParameter("from_sort_value", String.valueOf(timestamp)); request.addParameter("order", SortOrder.DESC.toString()); final Response response = getRestClient().performRequest(request); return readSnapshotInfos(response).getSnapshots(); } private static List<SnapshotInfo> getAllSnapshotsForPolicies(String... policies) throws IOException { final Request requestWithPolicy = new Request(HttpGet.METHOD_NAME, "/_snapshot/*/*"); requestWithPolicy.addParameter("slm_policy_filter", Strings.arrayToCommaDelimitedString(policies)); requestWithPolicy.addParameter("sort", SnapshotSortKey.NAME.toString()); return readSnapshotInfos(getRestClient().performRequest(requestWithPolicy)).getSnapshots(); } private void createIndexWithContent(String indexName) { logger.info("--> creating index [{}]", indexName); createIndex(indexName, 1, 0); ensureGreen(indexName); indexDoc(indexName, "some_id", "foo", "bar"); } private static void assertStablePagination(String repoName, Collection<String> allSnapshotNames, SnapshotSortKey sort) throws IOException { final SortOrder order = randomFrom(SortOrder.values()); final boolean includeIndexNames = sort == SnapshotSortKey.INDICES || randomBoolean(); final List<SnapshotInfo> allSorted = allSnapshotsSorted(allSnapshotNames, repoName, sort, order, includeIndexNames); for (int i = 1; i <= allSnapshotNames.size(); i++) { final List<SnapshotInfo> subsetSorted = sortedWithLimit(repoName, sort, null, i, order, includeIndexNames).getSnapshots(); assertEquals(subsetSorted, allSorted.subList(0, i)); } for (int j = 0; j < allSnapshotNames.size(); j++) { final SnapshotInfo after = allSorted.get(j); for (int i = 1; i < allSnapshotNames.size() - j; i++) { final GetSnapshotsResponse getSnapshotsResponse = sortedWithLimit( repoName, sort, sort.encodeAfterQueryParam(after), i, order, includeIndexNames ); final GetSnapshotsResponse getSnapshotsResponseNumeric = sortedWithLimit( repoName, sort, j + 1, i, order, includeIndexNames ); final List<SnapshotInfo> subsetSorted = getSnapshotsResponse.getSnapshots(); assertEquals(subsetSorted, getSnapshotsResponseNumeric.getSnapshots()); assertEquals(subsetSorted, allSorted.subList(j + 1, j + i + 1)); assertEquals(allSnapshotNames.size(), getSnapshotsResponse.totalCount()); assertEquals(allSnapshotNames.size() - (j + i + 1), getSnapshotsResponse.remaining()); assertEquals(getSnapshotsResponseNumeric.totalCount(), getSnapshotsResponse.totalCount()); assertEquals(getSnapshotsResponseNumeric.remaining(), getSnapshotsResponse.remaining()); } } } private static List<SnapshotInfo> allSnapshotsSorted( Collection<String> allSnapshotNames, String repoName, SnapshotSortKey sortBy, SortOrder order, boolean includeIndices ) throws IOException { final Request request = baseGetSnapshotsRequest(repoName); request.addParameter("sort", sortBy.toString()); if (order == SortOrder.DESC || randomBoolean()) { request.addParameter("order", order.toString()); } addIndexNamesParameter(includeIndices, request); final GetSnapshotsResponse getSnapshotsResponse = readSnapshotInfos(getRestClient().performRequest(request)); final List<SnapshotInfo> snapshotInfos = getSnapshotsResponse.getSnapshots(); if (includeIndices == false) { for (SnapshotInfo snapshotInfo : snapshotInfos) { assertThat(snapshotInfo.indices(), empty()); } } assertEquals(snapshotInfos.size(), allSnapshotNames.size()); assertEquals(getSnapshotsResponse.totalCount(), allSnapshotNames.size()); assertEquals(0, getSnapshotsResponse.remaining()); for (SnapshotInfo snapshotInfo : snapshotInfos) { assertThat(snapshotInfo.snapshotId().getName(), is(in(allSnapshotNames))); } return snapshotInfos; } private static Request baseGetSnapshotsRequest(String repoName) { return new Request(HttpGet.METHOD_NAME, "/_snapshot/" + repoName + "/*"); } private static GetSnapshotsResponse readSnapshotInfos(Response response) throws IOException { try ( InputStream input = response.getEntity().getContent(); XContentParser parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY, input) ) { return GET_SNAPSHOT_PARSER.parse(parser, null); } } private static GetSnapshotsResponse sortedWithLimit( String repoName, SnapshotSortKey sortBy, String after, int size, SortOrder order, boolean includeIndices ) throws IOException { final Request request = baseGetSnapshotsRequest(repoName); request.addParameter("sort", sortBy.toString()); if (size != GetSnapshotsRequest.NO_LIMIT || randomBoolean()) { request.addParameter("size", String.valueOf(size)); } if (after != null) { request.addParameter("after", after); } if (order == SortOrder.DESC || randomBoolean()) { request.addParameter("order", order.toString()); } addIndexNamesParameter(includeIndices, request); final Response response = getRestClient().performRequest(request); return readSnapshotInfos(response); } private static void addIndexNamesParameter(boolean includeIndices, Request request) { if (includeIndices == false) { request.addParameter(SnapshotInfo.INDEX_NAMES_XCONTENT_PARAM, "false"); } else if (randomBoolean()) { request.addParameter(SnapshotInfo.INDEX_NAMES_XCONTENT_PARAM, "true"); } } private static GetSnapshotsResponse sortedWithLimit( String repoName, SnapshotSortKey sortBy, int offset, int size, SortOrder order, boolean includeIndices ) throws IOException { final Request request = baseGetSnapshotsRequest(repoName); request.addParameter("sort", sortBy.toString()); if (size != GetSnapshotsRequest.NO_LIMIT || randomBoolean()) { request.addParameter("size", String.valueOf(size)); } request.addParameter("offset", String.valueOf(offset)); if (order == SortOrder.DESC || randomBoolean()) { request.addParameter("order", order.toString()); } addIndexNamesParameter(includeIndices, request); final Response response = getRestClient().performRequest(request); return readSnapshotInfos(response); } private static final int UNKNOWN_COUNT = -1; @SuppressWarnings("unchecked") private static final ConstructingObjectParser<GetSnapshotsResponse, Void> GET_SNAPSHOT_PARSER = new ConstructingObjectParser<>( GetSnapshotsResponse.class.getName(), true, (args) -> new GetSnapshotsResponse( (List<SnapshotInfo>) args[0], (String) args[1], args[2] == null ? UNKNOWN_COUNT : (int) args[2], args[3] == null ? UNKNOWN_COUNT : (int) args[3] ) ); static { GET_SNAPSHOT_PARSER.declareObjectArray( ConstructingObjectParser.constructorArg(), (p, c) -> SnapshotInfoUtils.snapshotInfoFromXContent(p), new ParseField("snapshots") ); GET_SNAPSHOT_PARSER.declareStringOrNull(ConstructingObjectParser.optionalConstructorArg(), new ParseField("next")); GET_SNAPSHOT_PARSER.declareIntOrNull(ConstructingObjectParser.optionalConstructorArg(), UNKNOWN_COUNT, new ParseField("total")); GET_SNAPSHOT_PARSER.declareIntOrNull(ConstructingObjectParser.optionalConstructorArg(), UNKNOWN_COUNT, new ParseField("remaining")); } }
RestGetSnapshotsIT
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/WritableFactory.java
{ "start": 979, "end": 1088 }
class ____ Writable. * @see WritableFactories */ @InterfaceAudience.Public @InterfaceStability.Stable public
of
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/SelectWithWrongResultTypeTest.java
{ "start": 3982, "end": 4211 }
class ____ { @Id @GeneratedValue Integer id; @ManyToOne Node node; public Element(Node node) { this.node = node; } public Element() { } } @Entity(name = "Node") @Table(name = "Node") public static
Element
java
mapstruct__mapstruct
core/src/main/java/org/mapstruct/ValueMapping.java
{ "start": 3274, "end": 3469 }
enum ____: C2C * </pre> * * @author Sjaak Derksen */ @Repeatable(ValueMappings.class) @Retention(RetentionPolicy.CLASS) @Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @
constant
java
elastic__elasticsearch
modules/transport-netty4/src/main/java/org/elasticsearch/http/netty4/MissingReadDetector.java
{ "start": 1228, "end": 3193 }
class ____ extends ChannelDuplexHandler { private static final Logger logger = LogManager.getLogger(MissingReadDetector.class); private final long interval; private final TimeProvider timer; private boolean pendingRead; private long lastRead; private ScheduledFuture<?> checker; MissingReadDetector(TimeProvider timer, long missingReadIntervalMillis) { this.interval = missingReadIntervalMillis; this.timer = timer; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { checker = ctx.channel().eventLoop().scheduleAtFixedRate(() -> { if (pendingRead == false) { long now = timer.absoluteTimeInMillis(); if (now >= lastRead + interval) { // if you encounter this warning during test make sure you consume content of RestRequest if it's a stream // or use AggregatingDispatcher that will consume stream fully and produce RestRequest with full content. logger.warn("chan-id={} haven't read from channel for [{}ms]", ctx.channel().id(), (now - lastRead)); } } }, interval, interval, TimeUnit.MILLISECONDS); super.handlerAdded(ctx); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { if (checker != null) { FutureUtils.cancel(checker); } super.handlerRemoved(ctx); } @Override public void read(ChannelHandlerContext ctx) throws Exception { pendingRead = true; ctx.read(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { assert ctx.channel().config().isAutoRead() == false : "auto-read must be always disabled"; pendingRead = false; lastRead = timer.absoluteTimeInMillis(); ctx.fireChannelRead(msg); } }
MissingReadDetector
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/core/userdetails/User.java
{ "start": 11074, "end": 11831 }
class ____ implements Comparator<GrantedAuthority>, Serializable { private static final long serialVersionUID = 620L; @Override public int compare(GrantedAuthority g1, GrantedAuthority g2) { // Neither should ever be null as each entry is checked before adding it to // the set. If the authority is null, it is a custom authority and should // precede others. if (g2.getAuthority() == null) { return -1; } if (g1.getAuthority() == null) { return 1; } return g1.getAuthority().compareTo(g2.getAuthority()); } } /** * Builds the user to be added. At minimum the username, password, and authorities * should provided. The remaining attributes have reasonable defaults. */ public static final
AuthorityComparator
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest26.java
{ "start": 1067, "end": 3456 }
class ____ extends OracleTest { public void test_types() throws Exception { String sql = // "CREATE TABLE dept_20 " + " (employee_id NUMBER(4), "// + " last_name VARCHAR2(10), "// + " job_id VARCHAR2(9), "// + " manager_id NUMBER(4), "// + " hire_date DATE, "// + " salary NUMBER(7,2), "// + " commission_pct NUMBER(7,2), "// + " department_id CONSTRAINT fk_deptno "// + " REFERENCES departments(department_id) ); "; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); assertEquals("CREATE TABLE dept_20 (" + "\n\temployee_id NUMBER(4),"// + "\n\tlast_name VARCHAR2(10),"// + "\n\tjob_id VARCHAR2(9),"// + "\n\tmanager_id NUMBER(4),"// + "\n\thire_date DATE,"// + "\n\tsalary NUMBER(7, 2),"// + "\n\tcommission_pct NUMBER(7, 2),"// + "\n\tdepartment_id"// + "\n\t\tCONSTRAINT fk_deptno REFERENCES departments (department_id)"// + "\n);", SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE)); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(8, visitor.getColumns().size()); assertTrue(visitor.getColumns().contains(new TableStat.Column("dept_20", "employee_id"))); } }
OracleCreateTableTest26
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/DefaultStateTransitionManagerTest.java
{ "start": 14444, "end": 16698 }
class ____ extends Phase { private TestPhase() { super(Instant::now, null); } } private static void assertPhaseWithoutStateTransition( TestingStateTransitionManagerContext ctx, DefaultStateTransitionManager testInstance, Class<? extends Phase> expectedPhase) { assertThat(ctx.stateTransitionWasTriggered()).isFalse(); assertThat(testInstance.getPhase()).isInstanceOf(expectedPhase); } private static void assertFinalStateTransitionHappened( TestingStateTransitionManagerContext ctx, DefaultStateTransitionManager testInstance) { assertThat(ctx.stateTransitionWasTriggered()).isTrue(); assertThat(testInstance.getPhase()).isInstanceOf(Transitioning.class); } private static void changeWithoutPhaseMove( TestingStateTransitionManagerContext ctx, DefaultStateTransitionManager testInstance, Class<? extends Phase> expectedPhase) { assertPhaseWithoutStateTransition(ctx, testInstance, expectedPhase); testInstance.onChange(); assertPhaseWithoutStateTransition(ctx, testInstance, expectedPhase); } private static void triggerWithoutPhaseMove( TestingStateTransitionManagerContext ctx, DefaultStateTransitionManager testInstance, Class<? extends Phase> expectedPhase) { assertPhaseWithoutStateTransition(ctx, testInstance, expectedPhase); testInstance.onTrigger(); assertPhaseWithoutStateTransition(ctx, testInstance, expectedPhase); } private static void withSufficientChange( TestingStateTransitionManagerContext ctx, DefaultStateTransitionManager testInstance) { ctx.withSufficientResources(); testInstance.onChange(); } private static void withDesiredChange( TestingStateTransitionManagerContext ctx, DefaultStateTransitionManager testInstance) { ctx.withDesiredResources(); testInstance.onChange(); } /** * {@code TestingStateTransitionManagerContext} provides methods for adjusting the elapsed time * and for adjusting the available resources for rescaling. */ private static
TestPhase
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableMergeMaxConcurrentTest.java
{ "start": 1222, "end": 3609 }
class ____ extends RxJavaTest { Observer<String> stringObserver; @Before public void before() { stringObserver = TestHelper.mockObserver(); } @Test public void whenMaxConcurrentIsOne() { for (int i = 0; i < 100; i++) { List<Observable<String>> os = new ArrayList<>(); os.add(Observable.just("one", "two", "three", "four", "five").subscribeOn(Schedulers.newThread())); os.add(Observable.just("one", "two", "three", "four", "five").subscribeOn(Schedulers.newThread())); os.add(Observable.just("one", "two", "three", "four", "five").subscribeOn(Schedulers.newThread())); List<String> expected = Arrays.asList("one", "two", "three", "four", "five", "one", "two", "three", "four", "five", "one", "two", "three", "four", "five"); Iterator<String> iter = Observable.merge(os, 1).blockingIterable().iterator(); List<String> actual = new ArrayList<>(); while (iter.hasNext()) { actual.add(iter.next()); } assertEquals(expected, actual); } } @Test public void maxConcurrent() { for (int times = 0; times < 100; times++) { int observableCount = 100; // Test maxConcurrent from 2 to 12 int maxConcurrent = 2 + (times % 10); AtomicInteger subscriptionCount = new AtomicInteger(0); List<Observable<String>> os = new ArrayList<>(); List<SubscriptionCheckObservable> scos = new ArrayList<>(); for (int i = 0; i < observableCount; i++) { SubscriptionCheckObservable sco = new SubscriptionCheckObservable(subscriptionCount, maxConcurrent); scos.add(sco); os.add(Observable.unsafeCreate(sco)); } Iterator<String> iter = Observable.merge(os, maxConcurrent).blockingIterable().iterator(); List<String> actual = new ArrayList<>(); while (iter.hasNext()) { actual.add(iter.next()); } // System.out.println("actual: " + actual); assertEquals(5 * observableCount, actual.size()); for (SubscriptionCheckObservable sco : scos) { assertFalse(sco.failed); } } } private static
ObservableMergeMaxConcurrentTest
java
quarkusio__quarkus
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/RuntimeSettings.java
{ "start": 129, "end": 941 }
class ____ { private final Map<String, Object> settings; private RuntimeSettings(Map<String, Object> settings) { this.settings = Collections.unmodifiableMap(new HashMap<>(settings)); } public Map<String, Object> getSettings() { return settings; } public Object get(String key) { return settings.get(key); } public boolean getBoolean(String key) { Object propertyValue = settings.get(key); return propertyValue != null && Boolean.parseBoolean(propertyValue.toString()); } public boolean isConfigured(String key) { return settings.containsKey(key); } @Override public String toString() { return this.getClass().getSimpleName() + " {" + settings.toString() + "}"; } public static
RuntimeSettings
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/NoneAudited.java
{ "start": 820, "end": 1159 }
class ____ { @Test public void testRevisionInfoTableNotCreated(DomainModelScope scope) { @SuppressWarnings("unchecked") List<PersistentClass> pcs = collectionToList( scope.getDomainModel().getEntityBindings() ); assertEquals( 1, pcs.size() ); assertTrue( pcs.get( 0 ).getClassName().contains( "BasicTestEntity3" ) ); } }
NoneAudited
java
micronaut-projects__micronaut-core
http-client-tck/src/main/java/io/micronaut/http/client/tck/tests/ContinueTest.java
{ "start": 4810, "end": 5250 }
class ____ { @Post("/plain") @ExecuteOn(TaskExecutors.BLOCKING) public String plain(@Body Publisher<String> data) { return String.join("", Flux.from(data).collectList().block()); } @Post("/part") @Consumes({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_FORM_URLENCODED}) public String part(@Part String foo) { return foo; } } }
SimpleController
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/sql/internal/AbstractSqlAstQueryNodeProcessingStateImpl.java
{ "start": 721, "end": 2383 }
class ____ extends SqlAstProcessingStateImpl implements SqlAstQueryNodeProcessingState { private final Map<SqmFrom<?, ?>, Boolean> sqmFromRegistrations = new HashMap<>(); public AbstractSqlAstQueryNodeProcessingStateImpl( SqlAstProcessingState parent, SqlAstCreationState creationState, Supplier<Clause> currentClauseAccess) { super( parent, creationState, currentClauseAccess ); } public AbstractSqlAstQueryNodeProcessingStateImpl( SqlAstProcessingState parent, SqlAstCreationState creationState, Function<SqlExpressionResolver, SqlExpressionResolver> expressionResolverDecorator, Supplier<Clause> currentClauseAccess) { super( parent, creationState, expressionResolverDecorator, currentClauseAccess ); } @Override public void registerTreatedFrom(SqmFrom<?, ?> sqmFrom) { sqmFromRegistrations.put( sqmFrom, null ); } @Override public void registerFromUsage(SqmFrom<?, ?> sqmFrom, boolean downgradeTreatUses) { if ( !( sqmFrom instanceof SqmTreatedPath<?, ?> ) ) { if ( !sqmFromRegistrations.containsKey( sqmFrom ) ) { if ( getParentState() instanceof SqlAstQueryPartProcessingState parentState ) { parentState.registerFromUsage( sqmFrom, downgradeTreatUses ); } } else { // If downgrading was once forcibly disabled, don't overwrite that anymore final Boolean currentValue = sqmFromRegistrations.get( sqmFrom ); if ( currentValue != Boolean.FALSE ) { sqmFromRegistrations.put( sqmFrom, downgradeTreatUses ); } } } } @Override public Map<SqmFrom<?, ?>, Boolean> getFromRegistrations() { return sqmFromRegistrations; } }
AbstractSqlAstQueryNodeProcessingStateImpl
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/rules/logical/OptimizerRules.java
{ "start": 975, "end": 1677 }
class ____<SubPlan extends LogicalPlan> extends Rule<SubPlan, LogicalPlan> { private final TransformDirection direction; public OptimizerRule() { this(TransformDirection.DOWN); } protected OptimizerRule(TransformDirection direction) { this.direction = direction; } @Override public final LogicalPlan apply(LogicalPlan plan) { return direction == TransformDirection.DOWN ? plan.transformDown(typeToken(), this::rule) : plan.transformUp(typeToken(), this::rule); } protected abstract LogicalPlan rule(SubPlan plan); } public abstract static
OptimizerRule
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FutureTransformAsyncTest.java
{ "start": 14835, "end": 15375 }
class ____ { private Executor executor; ListenableFuture<Void> test() { ListenableFuture<Void> future = Futures.transformAsync( Futures.immediateFuture("x"), value -> Futures.<Void>immediateFuture(null), executor); return future; } } """) .addOutputLines( "out/Test.java", """ import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import java.util.concurrent.Executor;
Test
java
netty__netty
microbench/src/main/java/io/netty/handler/codec/DateFormatter2Benchmark.java
{ "start": 1045, "end": 3506 }
class ____ extends AbstractMicrobenchmark { @Param({"Sun, 27 Jan 2016 19:18:46 GMT", "Sun, 27 Dec 2016 19:18:46 GMT"}) String DATE_STRING; @Benchmark public Date parseHttpHeaderDateFormatterNew() { return DateFormatter.parseHttpDate(DATE_STRING); } /* @Benchmark public Date parseHttpHeaderDateFormatter() { return DateFormatterOld.parseHttpDate(DATE_STRING); } */ /* * Benchmark (DATE_STRING) Mode Cnt Score Error Units * parseHttpHeaderDateFormatter Sun, 27 Jan 2016 19:18:46 GMT thrpt 6 4142781.221 ± 82155.002 ops/s * parseHttpHeaderDateFormatter Sun, 27 Dec 2016 19:18:46 GMT thrpt 6 3781810.558 ± 38679.061 ops/s * parseHttpHeaderDateFormatterNew Sun, 27 Jan 2016 19:18:46 GMT thrpt 6 4372569.705 ± 30257.537 ops/s * parseHttpHeaderDateFormatterNew Sun, 27 Dec 2016 19:18:46 GMT thrpt 6 4339785.100 ± 57542.660 ops/s */ /*Old DateFormatter.tryParseMonth method: private boolean tryParseMonth(CharSequence txt, int tokenStart, int tokenEnd) { int len = tokenEnd - tokenStart; if (len != 3) { return false; } if (matchMonth("Jan", txt, tokenStart)) { month = Calendar.JANUARY; } else if (matchMonth("Feb", txt, tokenStart)) { month = Calendar.FEBRUARY; } else if (matchMonth("Mar", txt, tokenStart)) { month = Calendar.MARCH; } else if (matchMonth("Apr", txt, tokenStart)) { month = Calendar.APRIL; } else if (matchMonth("May", txt, tokenStart)) { month = Calendar.MAY; } else if (matchMonth("Jun", txt, tokenStart)) { month = Calendar.JUNE; } else if (matchMonth("Jul", txt, tokenStart)) { month = Calendar.JULY; } else if (matchMonth("Aug", txt, tokenStart)) { month = Calendar.AUGUST; } else if (matchMonth("Sep", txt, tokenStart)) { month = Calendar.SEPTEMBER; } else if (matchMonth("Oct", txt, tokenStart)) { month = Calendar.OCTOBER; } else if (matchMonth("Nov", txt, tokenStart)) { month = Calendar.NOVEMBER; } else if (matchMonth("Dec", txt, tokenStart)) { month = Calendar.DECEMBER; } else { return false; } return true; } */ }
DateFormatter2Benchmark
java
reactor__reactor-core
reactor-core/src/jcstress/java/reactor/core/publisher/FluxReplayStressTest.java
{ "start": 11660, "end": 12516 }
class ____ extends RefCntConcurrentSubscriptionBaseStressTest<Integer> { public RefCntConcurrentSubscriptionRangeNoneFusionStressTest() { super(Flux.range(0, 10).hide()); } @Actor public void subscribe1() { sharedSource.subscribe(subscriber1); } @Actor public void subscribe2() { sharedSource.subscribe(subscriber2); } @Arbiter public void arbiter(IIIIII_Result r) { r.r1 = subscriber1.onNextCalls.get(); r.r2 = subscriber2.onNextCalls.get(); r.r3 = subscriber1.onCompleteCalls.get(); r.r4 = subscriber2.onCompleteCalls.get(); r.r5 = subscriber1.onErrorCalls.get(); r.r6 = subscriber2.onErrorCalls.get(); } } @JCStressTest @Outcome(id = {"0, 0, 1, 1, 0, 0"}, expect = ACCEPTABLE, desc = "concurrent subscription succeeded") @State public static
RefCntConcurrentSubscriptionRangeNoneFusionStressTest