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
|
quarkusio__quarkus
|
extensions/grpc/deployment/src/test/java/io/quarkus/grpc/client/HelloWorldTlsEndpointTest.java
|
{
"start": 665,
"end": 1306
}
|
class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addPackage(HelloWorldTlsEndpoint.class.getPackage())
.addPackage(io.grpc.examples.helloworld.GreeterGrpc.class.getPackage()))
.withConfigurationResource("grpc-client-tls-configuration.properties");
@Test
void shouldExposeAndConsumeTLSWithKeysFromFiles() {
String response = get("/hello/blocking/neo").asString();
assertThat(response).isEqualTo("Hello neo");
}
}
|
HelloWorldTlsEndpointTest
|
java
|
spring-projects__spring-framework
|
spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java
|
{
"start": 21051,
"end": 21265
}
|
class ____ {
public final String name;
public final boolean isTopic;
public DestinationNameHolder(String name, boolean isTopic) {
this.name = name;
this.isTopic = isTopic;
}
}
}
|
DestinationNameHolder
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/index/IndexSettings.java
|
{
"start": 3284,
"end": 3731
}
|
class ____ all index level settings and handles settings updates.
* It's created per index and available to all index level classes and allows them to retrieve
* the latest updated settings instance. Classes that need to listen to settings updates can register
* a settings consumer at index creation via {@link IndexModule#addSettingsUpdateConsumer(Setting, Consumer)} that will
* be called for each settings update.
*/
public final
|
encapsulates
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeStaticTest.java
|
{
"start": 6192,
"end": 6760
}
|
class ____ {
private static final String staticFinalInitializer;
static {
staticFinalInitializer = "string";
}
private static final String staticFinal = "string";
private int nonFinal = 3;
private static int staticNonFinal = 4;
private final Object finalMutable = new Object();
private final int nonLiteral = new java.util.Random().nextInt();
private final Person pojo = new Person("Bob", 42);
private static
|
Test
|
java
|
elastic__elasticsearch
|
modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/PortugueseAnalyzerProvider.java
|
{
"start": 886,
"end": 1477
}
|
class ____ extends AbstractIndexAnalyzerProvider<PortugueseAnalyzer> {
private final PortugueseAnalyzer analyzer;
PortugueseAnalyzerProvider(IndexSettings indexSettings, Environment env, String name, Settings settings) {
super(name);
analyzer = new PortugueseAnalyzer(
Analysis.parseStopWords(env, settings, PortugueseAnalyzer.getDefaultStopSet()),
Analysis.parseStemExclusion(settings, CharArraySet.EMPTY_SET)
);
}
@Override
public PortugueseAnalyzer get() {
return this.analyzer;
}
}
|
PortugueseAnalyzerProvider
|
java
|
quarkusio__quarkus
|
extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/EnvVarValidator.java
|
{
"start": 6423,
"end": 7378
}
|
class ____ {
private final KubernetesEnvBuildItem.EnvType type;
private final String name;
ItemKey(KubernetesEnvBuildItem.EnvType type, String name) {
this.type = type;
this.name = name;
}
public static ItemKey keyFor(KubernetesEnvBuildItem item) {
return new ItemKey(item.getType(), item.getName());
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ItemKey itemKey = (ItemKey) o;
if (type != itemKey.type)
return false;
return name.equals(itemKey.name);
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + name.hashCode();
return result;
}
}
}
|
ItemKey
|
java
|
apache__flink
|
flink-table/flink-sql-gateway/src/test/java/org/apache/flink/table/gateway/service/utils/IgnoreExceptionHandler.java
|
{
"start": 987,
"end": 1442
}
|
class ____ implements Thread.UncaughtExceptionHandler {
public static final IgnoreExceptionHandler INSTANCE = new IgnoreExceptionHandler();
private static final Logger LOG = LoggerFactory.getLogger(IgnoreExceptionHandler.class);
@Override
public void uncaughtException(Thread t, Throwable e) {
// ignore error
LOG.error("Thread '{}' produced an uncaught exception. Ignore...", t.getName(), e);
}
}
|
IgnoreExceptionHandler
|
java
|
hibernate__hibernate-orm
|
hibernate-vector/src/main/java/org/hibernate/vector/internal/OracleSparseByteVectorJdbcType.java
|
{
"start": 747,
"end": 3610
}
|
class ____ extends AbstractOracleSparseVectorJdbcType {
public OracleSparseByteVectorJdbcType(JdbcType elementJdbcType, boolean isVectorSupported) {
super( elementJdbcType, isVectorSupported );
}
@Override
public String getVectorParameters() {
return "*,int8,sparse";
}
@Override
public String getFriendlyName() {
return "SPARSE_VECTOR_INT8";
}
@Override
public int getDefaultSqlTypeCode() {
return SqlTypes.SPARSE_VECTOR_INT8;
}
@Override
protected <X> Object getBindValue(JavaType<X> javaType, X value, WrapperOptions options) {
if ( isVectorSupported ) {
final SparseByteVector sparseVector = javaType.unwrap( value, SparseByteVector.class, options );
return VECTOR.SparseByteArray.of( sparseVector.size(), sparseVector.indices(), sparseVector.bytes() );
}
else {
return getStringVector( value, javaType, options );
}
}
@Override
public <X> ValueExtractor<X> getExtractor(final JavaType<X> javaTypeDescriptor) {
return new BasicExtractor<>( javaTypeDescriptor, this ) {
@Override
protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException {
if ( isVectorSupported ) {
return getJavaType().wrap( wrapNativeValue( rs.getObject( paramIndex, VECTOR.SparseByteArray.class ) ), options );
}
else {
return getJavaType().wrap( wrapStringValue( rs.getString( paramIndex ) ), options );
}
}
@Override
protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException {
if ( isVectorSupported ) {
return getJavaType().wrap( wrapNativeValue( statement.getObject( index, VECTOR.SparseByteArray.class ) ), options );
}
else {
return getJavaType().wrap( wrapStringValue( statement.getString( index ) ), options );
}
}
@Override
protected X doExtract(CallableStatement statement, String name, WrapperOptions options)
throws SQLException {
if ( isVectorSupported ) {
return getJavaType().wrap( wrapNativeValue( statement.getObject( name, VECTOR.SparseByteArray.class ) ), options );
}
else {
return getJavaType().wrap( wrapStringValue( statement.getString( name ) ), options );
}
}
private Object wrapNativeValue(VECTOR.SparseByteArray nativeValue) {
return nativeValue == null
? null
: new SparseByteVector( nativeValue.length(), nativeValue.indices(), nativeValue.values() );
}
private Object wrapStringValue(String value) {
return ((AbstractOracleVectorJdbcType) getJdbcType() ).getVectorArray( value );
}
};
}
@Override
protected SparseByteVector getVectorArray(String string) {
if ( string == null ) {
return null;
}
return new SparseByteVector( string );
}
@Override
protected Class<?> getNativeJavaType() {
return VECTOR.SparseByteArray.class;
}
}
|
OracleSparseByteVectorJdbcType
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
|
{
"start": 54308,
"end": 55817
}
|
interface ____ {",
" @Provides",
" @IntoSet",
" static Integer provideInt() {",
" return 9;",
" }",
"}");
CompilerTests.daggerCompiler(
parent, child1, child2, repeatedSub, child1Module, child2Module, repeatedSubModule)
.withProcessingOptions(compilerMode.processorOptions())
.compile(
subject -> {
subject.hasErrorCount(1);
subject.hasErrorContaining(
String.join(
"\n",
"Object cannot be provided without an @Inject constructor or an "
+ "@Provides-annotated method.",
"",
" Object is requested at",
" [RepeatedSub] RepeatedSub.getObject() "
+ "[Parent → Child1 → RepeatedSub]",
"",
"Note: Object is provided in the following other components:",
" [Child2] Child2Module.provideObject(…)",
"",
"======================"));
});
}
@Test
public void differentComponentPkgSameSimpleNameMissingBinding() {
Source parent =
CompilerTests.javaSource(
"test.Parent",
"package test;",
"",
"import dagger.Component;",
"",
"@Component",
"
|
RepeatedSubModule
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-jackson/runtime/src/main/java/io/quarkus/resteasy/reactive/jackson/runtime/serialisers/AbstractServerJacksonMessageBodyReader.java
|
{
"start": 721,
"end": 2113
}
|
class ____ extends AbstractJsonMessageBodyReader {
protected final LazyValue<ObjectReader> defaultReader;
// used by Arc
protected AbstractServerJacksonMessageBodyReader() {
defaultReader = null;
}
public AbstractServerJacksonMessageBodyReader(Instance<ObjectMapper> mapper) {
this.defaultReader = new LazyValue<>(new Supplier<>() {
@Override
public ObjectReader get() {
return mapper.get().reader();
}
});
}
@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException,
WebApplicationException {
return doReadFrom(type, genericType, entityStream);
}
protected ObjectReader getEffectiveReader() {
return defaultReader.get();
}
private Object doReadFrom(Class<Object> type, Type genericType, InputStream entityStream) throws IOException {
if (entityStream instanceof EmptyInputStream) {
return null;
}
ObjectReader reader = getEffectiveReader();
return reader.forType(reader.getTypeFactory().constructType(genericType != null ? genericType : type))
.readValue(entityStream);
}
}
|
AbstractServerJacksonMessageBodyReader
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ha/ActiveStandbyElector.java
|
{
"start": 4125,
"end": 6771
}
|
interface ____ {
/**
* This method is called when the app becomes the active leader.
* If the service fails to become active, it should throw
* ServiceFailedException. This will cause the elector to
* sleep for a short period, then re-join the election.
*
* Callback implementations are expected to manage their own
* timeouts (e.g. when making an RPC to a remote node).
*
* @throws ServiceFailedException Service Failed Exception.
*/
void becomeActive() throws ServiceFailedException;
/**
* This method is called when the app becomes a standby
*/
void becomeStandby();
/**
* If the elector gets disconnected from Zookeeper and does not know about
* the lock state, then it will notify the service via the enterNeutralMode
* interface. The service may choose to ignore this or stop doing state
* changing operations. Upon reconnection, the elector verifies the leader
* status and calls back on the becomeActive and becomeStandby app
* interfaces. <br>
* Zookeeper disconnects can happen due to network issues or loss of
* Zookeeper quorum. Thus enterNeutralMode can be used to guard against
* split-brain issues. In such situations it might be prudent to call
* becomeStandby too. However, such state change operations might be
* expensive and enterNeutralMode can help guard against doing that for
* transient issues.
*/
void enterNeutralMode();
/**
* If there is any fatal error (e.g. wrong ACL's, unexpected Zookeeper
* errors or Zookeeper persistent unavailability) then notifyFatalError is
* called to notify the app about it.
*
* @param errorMessage error message.
*/
void notifyFatalError(String errorMessage);
/**
* If an old active has failed, rather than exited gracefully, then
* the new active may need to take some fencing actions against it
* before proceeding with failover.
*
* @param oldActiveData the application data provided by the prior active
*/
void fenceOldActive(byte[] oldActiveData);
}
/**
* Name of the lock znode used by the library. Protected for access in test
* classes
*/
@VisibleForTesting
protected static final String LOCK_FILENAME = "ActiveStandbyElectorLock";
@VisibleForTesting
protected static final String BREADCRUMB_FILENAME = "ActiveBreadCrumb";
public static final Logger LOG =
LoggerFactory.getLogger(ActiveStandbyElector.class);
private static final int SLEEP_AFTER_FAILURE_TO_BECOME_ACTIVE = 1000;
private
|
ActiveStandbyElectorCallback
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/clients/consumer/KafkaConsumerTest.java
|
{
"start": 189966,
"end": 193541
}
|
class ____ implements ConsumerInterceptor<byte[], byte[]> {
@Override
public ConsumerRecords<byte[], byte[]> onConsume(ConsumerRecords<byte[], byte[]> records) {
return records;
}
@Override
public void onCommit(Map<TopicPartition, OffsetAndMetadata> offsets) {
}
@Override
public void close() {
}
@Override
public void configure(Map<String, ?> configs) {
CLIENT_IDS.add(configs.get(ConsumerConfig.CLIENT_ID_CONFIG).toString());
}
}
@ParameterizedTest
@EnumSource(value = GroupProtocol.class)
void testMonitorablePlugins(GroupProtocol groupProtocol) {
try {
String clientId = "testMonitorablePlugins";
Map<String, Object> configs = new HashMap<>();
configs.put(ConsumerConfig.CLIENT_ID_CONFIG, clientId);
configs.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9999");
configs.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, MonitorableDeserializer.class.getName());
configs.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, MonitorableDeserializer.class.getName());
configs.put(ConsumerConfig.GROUP_PROTOCOL_CONFIG, groupProtocol.name);
configs.put(ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG, MonitorableInterceptor.class.getName());
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(configs);
Map<MetricName, ? extends Metric> metrics = consumer.metrics();
MetricName expectedKeyDeserializerMetric = expectedMetricName(
clientId,
ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
MonitorableDeserializer.class);
assertTrue(metrics.containsKey(expectedKeyDeserializerMetric));
assertEquals(VALUE, metrics.get(expectedKeyDeserializerMetric).metricValue());
MetricName expectedValueDeserializerMetric = expectedMetricName(
clientId,
ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
MonitorableDeserializer.class);
assertTrue(metrics.containsKey(expectedValueDeserializerMetric));
assertEquals(VALUE, metrics.get(expectedValueDeserializerMetric).metricValue());
MetricName expectedInterceptorMetric = expectedMetricName(
clientId,
ConsumerConfig.INTERCEPTOR_CLASSES_CONFIG,
MonitorableInterceptor.class);
assertTrue(metrics.containsKey(expectedInterceptorMetric));
assertEquals(VALUE, metrics.get(expectedInterceptorMetric).metricValue());
consumer.close(CloseOptions.timeout(Duration.ZERO));
metrics = consumer.metrics();
assertFalse(metrics.containsKey(expectedKeyDeserializerMetric));
assertFalse(metrics.containsKey(expectedValueDeserializerMetric));
assertFalse(metrics.containsKey(expectedInterceptorMetric));
} finally {
MockConsumerInterceptor.resetCounters();
}
}
/**
* This test ensures that both {@link Consumer} implementations fail on creation when the underlying
* {@link NetworkClient} fails creation.
*
* The logic to check for this case is admittedly a bit awkward because the constructor can fail for all
* manner of reasons. So a failure case is created by specifying an invalid
* {@link javax.security.auth.spi.LoginModule}
|
ConsumerInterceptorForClientId
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/ser/jdk/IterableSerializationTest.java
|
{
"start": 1167,
"end": 1414
}
|
class ____ {
private final ArrayList<String> values = new ArrayList<String>();
{
values.add("itValue");
}
public Iterator<String> getValues() { return values.iterator(); }
}
static
|
BeanWithIterator
|
java
|
spring-projects__spring-framework
|
spring-messaging/src/main/java/org/springframework/messaging/converter/AbstractMessageConverter.java
|
{
"start": 1405,
"end": 1787
}
|
class ____ {@link SmartMessageConverter} implementations including
* support for common properties and a partial implementation of the conversion methods,
* mainly to check if the converter supports the conversion based on the payload class
* and MIME type.
*
* @author Rossen Stoyanchev
* @author Sebastien Deleuze
* @author Juergen Hoeller
* @since 4.0
*/
public abstract
|
for
|
java
|
google__guava
|
guava/src/com/google/common/collect/RegularImmutableBiMap.java
|
{
"start": 7565,
"end": 8666
}
|
class ____ extends ImmutableBiMap<V, K> {
@Override
public int size() {
return inverse().size();
}
@Override
public ImmutableBiMap<K, V> inverse() {
return RegularImmutableBiMap.this;
}
@Override
public void forEach(BiConsumer<? super V, ? super K> action) {
checkNotNull(action);
RegularImmutableBiMap.this.forEach((k, v) -> action.accept(v, k));
}
@Override
public @Nullable K get(@Nullable Object value) {
if (value == null || valueTable == null) {
return null;
}
int bucket = Hashing.smear(value.hashCode()) & mask;
for (ImmutableMapEntry<K, V> entry = valueTable[bucket];
entry != null;
entry = entry.getNextInValueBucket()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
@Override
ImmutableSet<V> createKeySet() {
return new ImmutableMapKeySet<>(this);
}
@Override
ImmutableSet<Entry<V, K>> createEntrySet() {
return new InverseEntrySet();
}
final
|
Inverse
|
java
|
spring-projects__spring-boot
|
module/spring-boot-webflux/src/test/java/org/springframework/boot/webflux/error/DefaultErrorAttributesTests.java
|
{
"start": 19628,
"end": 19851
}
|
class ____ extends RuntimeException {
CustomException() {
}
CustomException(String message) {
super(message);
}
}
@ResponseStatus(value = HttpStatus.EXPECTATION_FAILED, reason = "Nope!")
static
|
CustomException
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jersey/src/test/java/org/springframework/boot/jersey/autoconfigure/actuate/endpoint/web/JerseyEndpointIntegrationTests.java
|
{
"start": 7433,
"end": 8262
}
|
class ____ extends StdScalarSerializer<Object> {
ReverseStringSerializer() {
super(String.class, false);
}
@Override
public boolean isEmpty(SerializerProvider provider, Object value) {
return ((String) value).isEmpty();
}
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
serialize(value, gen);
}
@Override
public final void serializeWithType(Object value, JsonGenerator gen, SerializerProvider provider,
TypeSerializer typeSer) throws IOException {
serialize(value, gen);
}
private void serialize(Object value, JsonGenerator gen) throws IOException {
StringBuilder builder = new StringBuilder((String) value);
gen.writeString(builder.reverse().toString());
}
}
}
}
|
ReverseStringSerializer
|
java
|
netty__netty
|
transport/src/main/java/io/netty/channel/ChannelHandlerContext.java
|
{
"start": 3567,
"end": 5929
}
|
interface ____ extends AttributeMap, ChannelInboundInvoker, ChannelOutboundInvoker {
/**
* Return the {@link Channel} which is bound to the {@link ChannelHandlerContext}.
*/
Channel channel();
/**
* Returns the {@link EventExecutor} which is used to execute an arbitrary task.
*/
EventExecutor executor();
/**
* The unique name of the {@link ChannelHandlerContext}.The name was used when then {@link ChannelHandler}
* was added to the {@link ChannelPipeline}. This name can also be used to access the registered
* {@link ChannelHandler} from the {@link ChannelPipeline}.
*/
String name();
/**
* The {@link ChannelHandler} that is bound this {@link ChannelHandlerContext}.
*/
ChannelHandler handler();
/**
* Return {@code true} if the {@link ChannelHandler} which belongs to this context was removed
* from the {@link ChannelPipeline}. Note that this method is only meant to be called from with in the
* {@link EventLoop}.
*/
boolean isRemoved();
@Override
ChannelHandlerContext fireChannelRegistered();
@Override
ChannelHandlerContext fireChannelUnregistered();
@Override
ChannelHandlerContext fireChannelActive();
@Override
ChannelHandlerContext fireChannelInactive();
@Override
ChannelHandlerContext fireExceptionCaught(Throwable cause);
@Override
ChannelHandlerContext fireUserEventTriggered(Object evt);
@Override
ChannelHandlerContext fireChannelRead(Object msg);
@Override
ChannelHandlerContext fireChannelReadComplete();
@Override
ChannelHandlerContext fireChannelWritabilityChanged();
@Override
ChannelHandlerContext read();
@Override
ChannelHandlerContext flush();
/**
* Return the assigned {@link ChannelPipeline}
*/
ChannelPipeline pipeline();
/**
* Return the assigned {@link ByteBufAllocator} which will be used to allocate {@link ByteBuf}s.
*/
ByteBufAllocator alloc();
/**
* @deprecated Use {@link Channel#attr(AttributeKey)}
*/
@Deprecated
@Override
<T> Attribute<T> attr(AttributeKey<T> key);
/**
* @deprecated Use {@link Channel#hasAttr(AttributeKey)}
*/
@Deprecated
@Override
<T> boolean hasAttr(AttributeKey<T> key);
}
|
ChannelHandlerContext
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/query/OrderByThreeEntityTest.java
|
{
"start": 3188,
"end": 7680
}
|
class ____ {
@Id
private Integer id;
@Column(name = "val")
private String value;
public Item() {
}
public Item(Integer id, String value) {
this.id = id;
this.value = value;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Item item = (Item) o;
return Objects.equals( id, item.id ) &&
Objects.equals( value, item.value );
}
@Override
public int hashCode() {
return Objects.hash( id, value );
}
@Override
public String toString() {
return "Item{" +
"id=" + id +
", value='" + value + '\'' +
'}';
}
}
private Integer containerId;
@BeforeClassTemplate
public void initData(EntityManagerFactoryScope scope) {
// Rev 1
this.containerId = scope.fromTransaction( entityManager -> {
final Container container = new Container();
final Key key1 = new Key( 1, "A" );
final Key key2 = new Key( 2, "B" );
final Item item1 = new Item( 1, "I1" );
final Item item2 = new Item( 2, "I2" );
entityManager.persist( item1 );
entityManager.persist( item2 );
entityManager.persist( key1 );
entityManager.persist( key2 );
container.getData().put( key1, item2 );
container.getData().put( key2, item1 );
entityManager.persist( container );
return container.getId();
} );
// Rev 2
scope.inTransaction( entityManager -> {
final Container container = entityManager.find( Container.class, containerId );
final Key key = new Key( 3, "C" );
final Item item = new Item( 3, "I3" );
entityManager.persist( key );
entityManager.persist( item );
container.getData().put( key, item );
entityManager.merge( container );
} );
// Rev 3
scope.inTransaction( entityManager -> {
final Container container = entityManager.find( Container.class, containerId );
container.getData().keySet().forEach(
key -> {
if ( "B".equals( key.getValue() ) ) {
final Item item = container.getData().get( key );
container.getData().remove( key );
entityManager.remove( key );
entityManager.remove( item );
}
}
);
entityManager.merge( container );
} );
// Rev 4
scope.inTransaction( entityManager -> {
final Container container = entityManager.find( Container.class, containerId );
container.getData().entrySet().forEach(
entry -> {
entityManager.remove( entry.getKey() );
entityManager.remove( entry.getValue() );
}
);
container.getData().clear();
entityManager.merge( container );
} );
}
@Test
public void testRevisionCounts(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
assertEquals( Arrays.asList( 1, 2, 3, 4 ),
AuditReaderFactory.get( em ).getRevisions( Container.class, this.containerId ) );
assertEquals( Arrays.asList( 1, 4 ), AuditReaderFactory.get( em ).getRevisions( Key.class, 1 ) );
assertEquals( Arrays.asList( 1, 3 ), AuditReaderFactory.get( em ).getRevisions( Key.class, 2 ) );
assertEquals( Arrays.asList( 2, 4 ), AuditReaderFactory.get( em ).getRevisions( Key.class, 3 ) );
assertEquals( Arrays.asList( 1, 3 ), AuditReaderFactory.get( em ).getRevisions( Item.class, 1 ) );
assertEquals( Arrays.asList( 1, 4 ), AuditReaderFactory.get( em ).getRevisions( Item.class, 2 ) );
assertEquals( Arrays.asList( 2, 4 ), AuditReaderFactory.get( em ).getRevisions( Item.class, 3 ) );
} );
}
@Test
public void testRevision1History(EntityManagerFactoryScope scope) {
scope.inEntityManager( em -> {
final Container container = AuditReaderFactory.get( em ).find( Container.class, this.containerId, 1 );
assertNotNull( container );
assertFalse( container.getData().isEmpty() );
assertEquals( 2, container.getData().size() );
final Iterator<Map.Entry<Key, Item>> iterator = container.getData().entrySet().iterator();
final Map.Entry<Key, Item> first = iterator.next();
assertEquals( new Key( 1, "A" ), first.getKey() );
assertEquals( new Item( 2, "I2" ), first.getValue() );
final Map.Entry<Key, Item> second = iterator.next();
assertEquals( new Key( 2, "B" ), second.getKey() );
assertEquals( new Item( 1, "I1" ), second.getValue() );
} );
}
}
|
Item
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/WildcardImportTest.java
|
{
"start": 12281,
"end": 12509
}
|
class ____ {}
}
""")
.expectUnchanged()
.addInputLines(
"in/test/Test.java",
"""
package test;
import static a.One.*;
public
|
Inner
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/RestClientTestUtil.java
|
{
"start": 55,
"end": 666
}
|
class ____ {
public static String setUrlForClass(Class<?> clazz) {
return urlPropNameFor(clazz) + "=${test.url}\n";
}
public static String urlPropNameFor(Class<?> clazz) {
return propNameFor("url", clazz);
}
public static String propNameFor(String property, Class<?> clazz) {
return clazz.getName() + "/mp-rest/" + property;
}
public static String quarkusPropNameFor(String property, Class<?> clazz) {
return String.format("quarkus.rest-client.\"%s\".%s", clazz.getName(), property);
}
private RestClientTestUtil() {
}
}
|
RestClientTestUtil
|
java
|
apache__dubbo
|
dubbo-metrics/dubbo-metrics-api/src/main/java/org/apache/dubbo/metrics/model/container/LongContainer.java
|
{
"start": 1294,
"end": 3744
}
|
class ____<N extends Number> extends ConcurrentHashMap<Metric, N> {
/**
* Provide the metric type name
*/
private final transient MetricsKeyWrapper metricsKeyWrapper;
/**
* The initial value corresponding to the key is generally 0 of different data types
*/
private final transient Function<Metric, N> initFunc;
/**
* Statistical data calculation function, which can be self-increment, self-decrement, or more complex avg function
*/
private final transient BiConsumer<Long, N> consumerFunc;
/**
* Data output function required by {@link GaugeMetricSample GaugeMetricSample}
*/
private transient Function<Metric, Long> valueSupplier;
public LongContainer(MetricsKeyWrapper metricsKeyWrapper, Supplier<N> initFunc, BiConsumer<Long, N> consumerFunc) {
super(128, 0.5f);
this.metricsKeyWrapper = metricsKeyWrapper;
this.initFunc = s -> initFunc.get();
this.consumerFunc = consumerFunc;
this.valueSupplier = k -> this.get(k).longValue();
}
public boolean specifyType(String type) {
return type.equals(getMetricsKeyWrapper().getType());
}
public MetricsKeyWrapper getMetricsKeyWrapper() {
return metricsKeyWrapper;
}
public boolean isKeyWrapper(MetricsKey metricsKey, String registryOpType) {
return metricsKeyWrapper.isKey(metricsKey, registryOpType);
}
public Function<Metric, N> getInitFunc() {
return initFunc;
}
public BiConsumer<Long, N> getConsumerFunc() {
return consumerFunc;
}
public Function<Metric, Long> getValueSupplier() {
return valueSupplier;
}
public void setValueSupplier(Function<Metric, Long> valueSupplier) {
this.valueSupplier = valueSupplier;
}
@Override
public String toString() {
return "LongContainer{" + "metricsKeyWrapper=" + metricsKeyWrapper + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
LongContainer<?> that = (LongContainer<?>) o;
return metricsKeyWrapper.equals(that.metricsKeyWrapper);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + metricsKeyWrapper.hashCode();
return result;
}
}
|
LongContainer
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/test/PackagePrivateBeanBindingTests.java
|
{
"start": 1370,
"end": 2063
}
|
class ____ {
private final List<ConfigurationPropertySource> sources = new ArrayList<>();
private Binder binder;
private ConfigurationPropertyName name;
@BeforeEach
void setup() {
this.binder = new Binder(this.sources);
this.name = ConfigurationPropertyName.of("foo");
}
@Test
void bindToPackagePrivateClassShouldBindToInstance() {
MockConfigurationPropertySource source = new MockConfigurationPropertySource();
source.put("foo.bar", "999");
this.sources.add(source);
ExamplePackagePrivateBean bean = this.binder.bind(this.name, Bindable.of(ExamplePackagePrivateBean.class))
.get();
assertThat(bean.getBar()).isEqualTo(999);
}
static
|
PackagePrivateBeanBindingTests
|
java
|
apache__flink
|
flink-filesystems/flink-s3-fs-hadoop/src/test/java/org/apache/flink/fs/s3hadoop/HadoopS3RecoverableWriterExceptionITCase.java
|
{
"start": 1653,
"end": 3027
}
|
class ____
extends AbstractHadoopRecoverableWriterExceptionITCase {
// ----------------------- S3 general configuration -----------------------
private static final long PART_UPLOAD_MIN_SIZE_VALUE = 7L << 20;
private static final int MAX_CONCURRENT_UPLOADS_VALUE = 2;
@BeforeAll
static void checkCredentialsAndSetup() throws IOException {
// check whether credentials exist
S3TestCredentials.assumeCredentialsAvailable();
basePath = new Path(S3TestCredentials.getTestBucketUri() + "tests-" + UUID.randomUUID());
// initialize configuration with valid credentials
final Configuration conf = new Configuration();
conf.setString("s3.access.key", S3TestCredentials.getS3AccessKey());
conf.setString("s3.secret.key", S3TestCredentials.getS3SecretKey());
conf.set(PART_UPLOAD_MIN_SIZE, PART_UPLOAD_MIN_SIZE_VALUE);
conf.set(MAX_CONCURRENT_UPLOADS, MAX_CONCURRENT_UPLOADS_VALUE);
final String defaultTmpDir = tempFolder.getAbsolutePath() + "s3_tmp_dir";
conf.set(CoreOptions.TMP_DIRS, defaultTmpDir);
FileSystem.initialize(conf);
skipped = false;
}
@Override
protected String getLocalTmpDir() throws Exception {
return ((FlinkS3FileSystem) getFileSystem()).getLocalTmpDir();
}
}
|
HadoopS3RecoverableWriterExceptionITCase
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/collection/xml/ContactType.java
|
{
"start": 269,
"end": 1469
}
|
class ____ implements Serializable {
private Long id;
private int version;
private String type;
public Long getId() {
return this.id;
}
public void setId(final Long id) {
this.id = id;
}
public int getVersion() {
return this.version;
}
public void setVersion(final int version) {
this.version = version;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( !( obj instanceof ContactType ) ) {
return false;
}
ContactType other = (ContactType) obj;
if ( id != null ) {
if ( !id.equals( other.id ) ) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ( ( id == null ) ? 0 : id.hashCode() );
return result;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
String result = getClass().getSimpleName() + " ";
if ( id != null ) {
result += "id: " + id;
}
result += ", version: " + version;
if ( type != null && !type.trim().isEmpty() ) {
result += ", type: " + type;
}
return result;
}
}
|
ContactType
|
java
|
netty__netty
|
codec-classes-quic/src/main/java/io/netty/handler/codec/quic/BoringSSLCertificateCallback.java
|
{
"start": 1337,
"end": 2180
}
|
class ____ {
private static final byte[] BEGIN_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n".getBytes(CharsetUtil.US_ASCII);
private static final byte[] END_PRIVATE_KEY = "\n-----END PRIVATE KEY-----\n".getBytes(CharsetUtil.US_ASCII);
/**
* The types contained in the {@code keyTypeBytes} array.
*/
// Extracted from https://github.com/openssl/openssl/blob/master/include/openssl/tls1.h
private static final byte TLS_CT_RSA_SIGN = 1;
private static final byte TLS_CT_DSS_SIGN = 2;
private static final byte TLS_CT_RSA_FIXED_DH = 3;
private static final byte TLS_CT_DSS_FIXED_DH = 4;
private static final byte TLS_CT_ECDSA_SIGN = 64;
private static final byte TLS_CT_RSA_FIXED_ECDH = 65;
private static final byte TLS_CT_ECDSA_FIXED_ECDH = 66;
// Code in this
|
BoringSSLCertificateCallback
|
java
|
spring-projects__spring-boot
|
module/spring-boot-http-converter/src/main/java/org/springframework/boot/http/converter/autoconfigure/JacksonHttpMessageConvertersConfiguration.java
|
{
"start": 1510,
"end": 1836
}
|
class ____ {
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JsonMapper.class)
@ConditionalOnBean(JsonMapper.class)
@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY,
havingValue = "jackson", matchIfMissing = true)
static
|
JacksonHttpMessageConvertersConfiguration
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/parser/ReadOnlyMapTest_final_field.java
|
{
"start": 594,
"end": 707
}
|
class ____ {
public final Map<String, A> values = new HashMap<String, A>();
}
public static
|
Entity
|
java
|
elastic__elasticsearch
|
modules/lang-painless/src/main/java/org/elasticsearch/painless/action/PainlessContextAction.java
|
{
"start": 2410,
"end": 2706
}
|
class ____ {
public static final ActionType<Response> INSTANCE = new ActionType<>("cluster:admin/scripts/painless/context");
private static final String SCRIPT_CONTEXT_NAME_PARAM = "context";
private PainlessContextAction() {/* no instances */}
public static
|
PainlessContextAction
|
java
|
alibaba__nacos
|
api/src/test/java/com/alibaba/nacos/api/naming/pojo/maintainer/SubscriberInfoTest.java
|
{
"start": 1072,
"end": 3345
}
|
class ____ {
private ObjectMapper mapper;
private SubscriberInfo subscriberInfo;
@BeforeEach
void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
subscriberInfo = new SubscriberInfo();
subscriberInfo.setNamespaceId("namespaceId");
subscriberInfo.setGroupName("groupName");
subscriberInfo.setServiceName("serviceName");
subscriberInfo.setIp("1.1.1.1");
subscriberInfo.setPort(8080);
subscriberInfo.setAgent("agent");
subscriberInfo.setAppName("appName");
}
@Test
void testSerialize() throws JsonProcessingException {
String json = mapper.writeValueAsString(subscriberInfo);
assertTrue(json.contains("\"namespaceId\":\"namespaceId\""));
assertTrue(json.contains("\"groupName\":\"groupName\""));
assertTrue(json.contains("\"serviceName\":\"serviceName\""));
assertTrue(json.contains("\"ip\":\"1.1.1.1\""));
assertTrue(json.contains("\"port\":8080"));
assertTrue(json.contains("\"agent\":\"agent\""));
assertTrue(json.contains("\"appName\":\"appName\""));
}
@Test
void testDeserialize() throws IOException {
String jsonString = "{\"namespaceId\":\"namespaceId\",\"groupName\":\"groupName\",\"serviceName\":\"serviceName\","
+ "\"ip\":\"1.1.1.1\",\"port\":8080,\"agent\":\"agent\",\"appName\":\"appName\"}";
SubscriberInfo subscriberInfo1 = mapper.readValue(jsonString, SubscriberInfo.class);
assertEquals(subscriberInfo.getNamespaceId(), subscriberInfo1.getNamespaceId());
assertEquals(subscriberInfo.getGroupName(), subscriberInfo1.getGroupName());
assertEquals(subscriberInfo.getServiceName(), subscriberInfo1.getServiceName());
assertEquals(subscriberInfo.getIp(), subscriberInfo1.getIp());
assertEquals(subscriberInfo.getPort(), subscriberInfo1.getPort());
assertEquals(subscriberInfo.getAgent(), subscriberInfo1.getAgent());
assertEquals(subscriberInfo.getAppName(), subscriberInfo1.getAppName());
assertEquals(subscriberInfo.getAddress(), subscriberInfo1.getAddress());
}
}
|
SubscriberInfoTest
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/test/vans/VansData.java
|
{
"start": 172,
"end": 467
}
|
class ____ implements Serializable{
public int[] textures;
public ArrayList<String> images;
public VansObject object;
public VansMetaData metadata;
public ArrayList<VansGeometry> geometries;
public ArrayList<VansAnimation> animations;
public Object materials;
}
|
VansData
|
java
|
redisson__redisson
|
redisson/src/test/java/org/redisson/misc/LogHelperTest.java
|
{
"start": 241,
"end": 9623
}
|
class ____ {
@Test
public void toStringWithNull() {
assertThat(LogHelper.toString(null)).isEqualTo("null");
}
@Test
public void toStringWithNestedPrimitives() {
Object[] input = new Object[] { "0", 1, 2L, 3.1D, 4.2F, (byte) 5, '6' };
assertThat(LogHelper.toString(input)).isEqualTo("[0, 1, 2, 3.1, 4.2, 5, 6]");
}
@Test
public void toStringWithPrimitive() {
assertThat(LogHelper.toString("0")).isEqualTo("0");
assertThat(LogHelper.toString(1)).isEqualTo("1");
assertThat(LogHelper.toString(2L)).isEqualTo("2");
assertThat(LogHelper.toString(3.1D)).isEqualTo("3.1");
assertThat(LogHelper.toString(4.2F)).isEqualTo("4.2");
assertThat(LogHelper.toString((byte) 5)).isEqualTo("5");
assertThat(LogHelper.toString('6')).isEqualTo("6");
}
@Test
public void toStringWithNestedSmallArrays() {
String[] strings = new String[] { "0" };
int[] ints = new int[] { 1 };
long[] longs = new long[] { 2L };
double[] doubles = new double[] { 3.1D };
float[] floats = new float[] { 4.2F };
byte[] bytes = new byte[] { (byte) 5 };
char[] chars = new char[] { '6' };
Object[] input = new Object[] { strings, ints, longs, doubles, floats, bytes, chars };
assertThat(LogHelper.toString(input)).isEqualTo("[[0], [1], [2], [3.1], [4.2], [5], [6]]");
}
@Test
public void toStringWithNestedSmallCollections() {
List<String> strings = Arrays.asList("0" );
List<Integer> ints = Arrays.asList( 1 );
List<Long> longs = Arrays.asList( 2L );
List<Double> doubles = Arrays.asList( 3.1D );
List<Float> floats = Arrays.asList( 4.2F );
List<Byte> bytes = Arrays.asList( (byte) 5 );
List<Character> chars = Arrays.asList( '6' );
Object[] input = new Object[] { strings, ints, longs, doubles, floats, bytes, chars };
assertThat(LogHelper.toString(input)).isEqualTo("[[0], [1], [2], [3.1], [4.2], [5], [6]]");
}
@Test
public void toStringWithSmallArrays() {
String[] strings = new String[] { "0" };
int[] ints = new int[] { 1 };
long[] longs = new long[] { 2L };
double[] doubles = new double[] { 3.1D };
float[] floats = new float[] { 4.2F };
byte[] bytes = new byte[] { (byte) 5 };
char[] chars = new char[] { '6' };
assertThat(LogHelper.toString(strings)).isEqualTo("[0]");
assertThat(LogHelper.toString(ints)).isEqualTo("[1]");
assertThat(LogHelper.toString(longs)).isEqualTo("[2]");
assertThat(LogHelper.toString(doubles)).isEqualTo("[3.1]");
assertThat(LogHelper.toString(floats)).isEqualTo("[4.2]");
assertThat(LogHelper.toString(bytes)).isEqualTo("[5]");
assertThat(LogHelper.toString(chars)).isEqualTo("[6]");
}
@Test
public void toStringWithSmallCollections() {
List<String> strings = Collections.nCopies(1, "0");
List<Integer> ints = Collections.nCopies(1, 1);
List<Long> longs = Collections.nCopies(1, 2L);
List<Double> doubles = Collections.nCopies(1, 3.1D);
List<Float> floats = Collections.nCopies(1, 4.2F);
List<Byte> bytes = Collections.nCopies(1, (byte)5);
List<Character> chars = Collections.nCopies(1, '6');
assertThat(LogHelper.toString(strings)).isEqualTo("[0]");
assertThat(LogHelper.toString(ints)).isEqualTo("[1]");
assertThat(LogHelper.toString(longs)).isEqualTo("[2]");
assertThat(LogHelper.toString(doubles)).isEqualTo("[3.1]");
assertThat(LogHelper.toString(floats)).isEqualTo("[4.2]");
assertThat(LogHelper.toString(bytes)).isEqualTo("[5]");
assertThat(LogHelper.toString(chars)).isEqualTo("[6]");
}
@Test
public void toStringWithNestedBigArrays() {
String[] strings = new String[15];
Arrays.fill(strings, "0");
int[] ints = new int[15];
Arrays.fill(ints, 1);
long[] longs = new long[15];
Arrays.fill(longs, 2L);
double[] doubles = new double[15];
Arrays.fill(doubles, 3.1D);
float[] floats = new float[15];
Arrays.fill(floats, 4.2F);
byte[] bytes = new byte[15];
Arrays.fill(bytes, (byte) 5);
char[] chars = new char[15];
Arrays.fill(chars, '6');
Object[] input = new Object[] { strings, ints, longs, doubles, floats, bytes, chars };
StringBuilder sb = new StringBuilder();
sb.append("[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...], ");
sb.append("[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...], ");
sb.append("[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, ...], ");
sb.append("[3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, ...], ");
sb.append("[4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, ...], ");
sb.append("[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, ...], ");
sb.append("[6, 6, 6, 6, 6, 6, 6, 6, 6, 6, ...]]");
assertThat(LogHelper.toString(input)).isEqualTo(sb.toString());
}
@Test
public void toStringWithNestedBigCollections() {
List<String> strings = Collections.nCopies(15, "0");
List<Integer> ints = Collections.nCopies(15, 1);
List<Long> longs = Collections.nCopies(15, 2L);
List<Double> doubles = Collections.nCopies(15, 3.1D);
List<Float> floats = Collections.nCopies(15, 4.2F);
List<Byte> bytes = Collections.nCopies(15, (byte)5);
List<Character> chars = Collections.nCopies(15, '6');
Object[] input = new Object[] { strings, ints, longs, doubles, floats, bytes, chars };
StringBuilder sb = new StringBuilder();
sb.append("[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...], ");
sb.append("[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...], ");
sb.append("[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, ...], ");
sb.append("[3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, ...], ");
sb.append("[4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, ...], ");
sb.append("[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, ...], ");
sb.append("[6, 6, 6, 6, 6, 6, 6, 6, 6, 6, ...]]");
assertThat(LogHelper.toString(input)).isEqualTo(sb.toString());
}
@Test
public void toStringWithBigArrays() {
String[] strings = new String[15];
Arrays.fill(strings, "0");
int[] ints = new int[15];
Arrays.fill(ints, 1);
long[] longs = new long[15];
Arrays.fill(longs, 2L);
double[] doubles = new double[15];
Arrays.fill(doubles, 3.1D);
float[] floats = new float[15];
Arrays.fill(floats, 4.2F);
byte[] bytes = new byte[15];
Arrays.fill(bytes, (byte) 5);
char[] chars = new char[15];
Arrays.fill(chars, '6');
assertThat(LogHelper.toString(strings)).isEqualTo("[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...]");
assertThat(LogHelper.toString(ints)).isEqualTo("[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...]");
assertThat(LogHelper.toString(longs)).isEqualTo("[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, ...]");
assertThat(LogHelper.toString(doubles)).isEqualTo("[3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, ...]");
assertThat(LogHelper.toString(floats)).isEqualTo("[4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, ...]");
assertThat(LogHelper.toString(bytes)).isEqualTo("[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, ...]");
assertThat(LogHelper.toString(chars)).isEqualTo("[6, 6, 6, 6, 6, 6, 6, 6, 6, 6, ...]");
}
@Test
public void toStringWithBigCollections() {
List<String> strings = Collections.nCopies(15, "0");
List<Integer> ints = Collections.nCopies(15, 1);
List<Long> longs = Collections.nCopies(15, 2L);
List<Double> doubles = Collections.nCopies(15, 3.1D);
List<Float> floats = Collections.nCopies(15, 4.2F);
List<Byte> bytes = Collections.nCopies(15, (byte)5);
List<Character> chars = Collections.nCopies(15, '6');
assertThat(LogHelper.toString(strings)).isEqualTo("[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ...]");
assertThat(LogHelper.toString(ints)).isEqualTo("[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...]");
assertThat(LogHelper.toString(longs)).isEqualTo("[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, ...]");
assertThat(LogHelper.toString(doubles)).isEqualTo("[3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, 3.1, ...]");
assertThat(LogHelper.toString(floats)).isEqualTo("[4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, ...]");
assertThat(LogHelper.toString(bytes)).isEqualTo("[5, 5, 5, 5, 5, 5, 5, 5, 5, 5, ...]");
assertThat(LogHelper.toString(chars)).isEqualTo("[6, 6, 6, 6, 6, 6, 6, 6, 6, 6, ...]");
}
@Test
public void toStringWithSmallString() {
char[] charsForStr = new char[100];
Arrays.fill(charsForStr, '7');
String string = new String(charsForStr);
assertThat(LogHelper.toString(string)).isEqualTo(string);
}
@Test
public void toStringWithBigString() {
char[] charsForStr = new char[1500];
Arrays.fill(charsForStr, '7');
String string = new String(charsForStr);
assertThat(LogHelper.toString(string)).isEqualTo(string.substring(0, 1000) + "...");
}
}
|
LogHelperTest
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/CrcUtil.java
|
{
"start": 1208,
"end": 9099
}
|
class ____ {
public static final int MULTIPLICATIVE_IDENTITY = 0x80000000;
public static final int GZIP_POLYNOMIAL = 0xEDB88320;
public static final int CASTAGNOLI_POLYNOMIAL = 0x82F63B78;
private static final long UNIT = 0x8000_0000_0000_0000L;
/**
* @return a * b (mod p),
* where mod p is computed by the given mod function.
*/
static int multiplyMod(int a, int b, ToIntFunction<Long> mod) {
final long left = ((long)a) << 32;
final long right = ((long)b) << 32;
final long product
= ((((((left & (UNIT /* */)) == 0L? 0L : right)
^ ((left & (UNIT >>> 1)) == 0L? 0L : right >>> 1))
^ (((left & (UNIT >>> 2)) == 0L? 0L : right >>> 2)
^ ((left & (UNIT >>> 3)) == 0L? 0L : right >>> 3)))
^ ((((left & (UNIT >>> 4)) == 0L? 0L : right >>> 4)
^ ((left & (UNIT >>> 5)) == 0L? 0L : right >>> 5))
^ (((left & (UNIT >>> 6)) == 0L? 0L : right >>> 6)
^ ((left & (UNIT >>> 7)) == 0L? 0L : right >>> 7))))
^ (((((left & (UNIT >>> 8)) == 0L? 0L : right >>> 8)
^ ((left & (UNIT >>> 9)) == 0L? 0L : right >>> 9))
^ (((left & (UNIT >>> 10)) == 0L? 0L : right >>> 10)
^ ((left & (UNIT >>> 11)) == 0L? 0L : right >>> 11)))
^ ((((left & (UNIT >>> 12)) == 0L? 0L : right >>> 12)
^ ((left & (UNIT >>> 13)) == 0L? 0L : right >>> 13))
^ (((left & (UNIT >>> 14)) == 0L? 0L : right >>> 14)
^ ((left & (UNIT >>> 15)) == 0L? 0L : right >>> 15)))))
^ ((((((left & (UNIT >>> 16)) == 0L? 0L : right >>> 16)
^ ((left & (UNIT >>> 17)) == 0L? 0L : right >>> 17))
^ (((left & (UNIT >>> 18)) == 0L? 0L : right >>> 18)
^ ((left & (UNIT >>> 19)) == 0L? 0L : right >>> 19)))
^ ((((left & (UNIT >>> 20)) == 0L? 0L : right >>> 20)
^ ((left & (UNIT >>> 21)) == 0L? 0L : right >>> 21))
^ (((left & (UNIT >>> 22)) == 0L? 0L : right >>> 22)
^ ((left & (UNIT >>> 23)) == 0L? 0L : right >>> 23))))
^ (((((left & (UNIT >>> 24)) == 0L? 0L : right >>> 24)
^ ((left & (UNIT >>> 25)) == 0L? 0L : right >>> 25))
^ (((left & (UNIT >>> 26)) == 0L? 0L : right >>> 26)
^ ((left & (UNIT >>> 27)) == 0L? 0L : right >>> 27)))
^ ((((left & (UNIT >>> 28)) == 0L? 0L : right >>> 28)
^ ((left & (UNIT >>> 29)) == 0L? 0L : right >>> 29))
^ (((left & (UNIT >>> 30)) == 0L? 0L : right >>> 30)
^ ((left & (UNIT >>> 31)) == 0L? 0L : right >>> 31)))));
return mod.applyAsInt(product);
}
/**
* Hide default constructor for a static utils class.
*/
private CrcUtil() {
}
/**
* Compute x^({@code lengthBytes} * 8) mod {@code mod}, where {@code mod} is
* in "reversed" (little-endian) format such that {@code mod & 1} represents
* x^31 and has an implicit term x^32.
*
* @param lengthBytes lengthBytes.
* @param mod mod.
* @return monomial.
*/
public static int getMonomial(long lengthBytes, ToIntFunction<Long> mod) {
if (lengthBytes == 0) {
return MULTIPLICATIVE_IDENTITY;
} else if (lengthBytes < 0) {
throw new IllegalArgumentException(
"lengthBytes must be positive, got " + lengthBytes);
}
// Decompose into
// x^degree == x ^ SUM(bit[i] * 2^i) == PRODUCT(x ^ (bit[i] * 2^i))
// Generate each x^(2^i) by squaring.
// Since 'degree' is in 'bits', but we only need to support byte
// granularity we can begin with x^8.
int multiplier = MULTIPLICATIVE_IDENTITY >>> 8;
int product = MULTIPLICATIVE_IDENTITY;
long degree = lengthBytes;
while (degree > 0) {
if ((degree & 1) != 0) {
product = (product == MULTIPLICATIVE_IDENTITY) ? multiplier :
multiplyMod(product, multiplier, mod);
}
multiplier = multiplyMod(multiplier, multiplier, mod);
degree >>= 1;
}
return product;
}
/**
* composeWithMonomial.
*
* @param crcA crcA.
* @param crcB crcB.
* @param monomial Precomputed x^(lengthBInBytes * 8) mod {@code mod}
* @param mod mod.
* @return compose with monomial.
*/
public static int composeWithMonomial(
int crcA, int crcB, int monomial, ToIntFunction<Long> mod) {
return multiplyMod(crcA, monomial, mod) ^ crcB;
}
/**
* compose.
*
* @param crcA crcA.
* @param crcB crcB.
* @param lengthB length of content corresponding to {@code crcB}, in bytes.
* @param mod mod.
* @return compose result.
*/
public static int compose(int crcA, int crcB, long lengthB, ToIntFunction<Long> mod) {
int monomial = getMonomial(lengthB, mod);
return composeWithMonomial(crcA, crcB, monomial, mod);
}
/**
* @return 4-byte array holding the big-endian representation of
* {@code value}.
*
* @param value value.
*/
public static byte[] intToBytes(int value) {
byte[] buf = new byte[4];
writeInt(buf, 0, value);
return buf;
}
/**
* Writes big-endian representation of {@code value} into {@code buf}
* starting at {@code offset}. buf.length must be greater than or
* equal to offset + 4.
*
* @param buf buf size.
* @param offset offset.
* @param value value.
*/
public static void writeInt(byte[] buf, int offset, int value) {
if (offset + 4 > buf.length) {
throw new ArrayIndexOutOfBoundsException(String.format(
"writeInt out of bounds: buf.length=%d, offset=%d",
buf.length, offset));
}
buf[offset ] = (byte)((value >>> 24) & 0xff);
buf[offset + 1] = (byte)((value >>> 16) & 0xff);
buf[offset + 2] = (byte)((value >>> 8) & 0xff);
buf[offset + 3] = (byte)(value & 0xff);
}
/**
* Reads 4-byte big-endian int value from {@code buf} starting at
* {@code offset}. buf.length must be greater than or equal to offset + 4.
*
* @param offset offset.
* @param buf buf.
* @return int.
*/
public static int readInt(byte[] buf, int offset) {
if (offset + 4 > buf.length) {
throw new ArrayIndexOutOfBoundsException(String.format(
"readInt out of bounds: buf.length=%d, offset=%d",
buf.length, offset));
}
return ((buf[offset ] & 0xff) << 24) |
((buf[offset + 1] & 0xff) << 16) |
((buf[offset + 2] & 0xff) << 8) |
((buf[offset + 3] & 0xff));
}
/**
* For use with debug statements; verifies bytes.length on creation,
* expecting it to represent exactly one CRC, and returns a hex
* formatted value.
*
* @param bytes bytes.
* @return a list of hex formatted values.
*/
public static String toSingleCrcString(final byte[] bytes) {
if (bytes.length != 4) {
throw new IllegalArgumentException((String.format(
"Unexpected byte[] length '%d' for single CRC. Contents: %s",
bytes.length, Arrays.toString(bytes))));
}
return String.format("0x%08x", readInt(bytes, 0));
}
/**
* For use with debug statements; verifies bytes.length on creation,
* expecting it to be divisible by CRC byte size, and returns a list of
* hex formatted values.
*
* @param bytes bytes.
* @return a list of hex formatted values.
*/
public static String toMultiCrcString(final byte[] bytes) {
if (bytes.length % 4 != 0) {
throw new IllegalArgumentException((String.format(
"Unexpected byte[] length '%d' not divisible by 4. Contents: %s",
bytes.length, Arrays.toString(bytes))));
}
StringBuilder sb = new StringBuilder();
sb.append('[');
for (int i = 0; i < bytes.length; i += 4) {
sb.append(String.format("0x%08x", readInt(bytes, i)));
if (i != bytes.length - 4) {
sb.append(", ");
}
}
sb.append(']');
return sb.toString();
}
}
|
CrcUtil
|
java
|
netty__netty
|
codec-socks/src/main/java/io/netty/handler/codec/socks/SocksRequestType.java
|
{
"start": 716,
"end": 783
}
|
enum ____ {
INIT,
AUTH,
CMD,
UNKNOWN
}
|
SocksRequestType
|
java
|
google__error-prone
|
core/src/main/java/com/google/errorprone/bugpatterns/InsecureCipherMode.java
|
{
"start": 1547,
"end": 6568
}
|
class ____ extends BugChecker implements MethodInvocationTreeMatcher {
private static final String MESSAGE_BASE = "Insecure usage of a crypto API: ";
private static final Matcher<ExpressionTree> CIPHER_GETINSTANCE_MATCHER =
staticMethod().onClass("javax.crypto.Cipher").named("getInstance");
private static final Matcher<ExpressionTree> KEY_STRUCTURE_GETINSTANCE_MATCHER =
anyOf(
staticMethod().onClass("java.security.KeyPairGenerator").named("getInstance"),
staticMethod().onClass("java.security.KeyFactory").named("getInstance"),
staticMethod().onClass("javax.crypto.KeyAgreement").named("getInstance"));
private Description buildErrorMessage(MethodInvocationTree tree, String explanation) {
Description.Builder description = buildDescription(tree);
String message = MESSAGE_BASE + explanation + ".";
description.setMessage(message);
return description.build();
}
private Description identifyEcbVulnerability(MethodInvocationTree tree) {
// We analyze the first argument of all the overloads of Cipher.getInstance().
Object argument = ASTHelpers.constValue(tree.getArguments().getFirst());
if (argument == null) {
// We flag call sites where the transformation string is dynamically computed.
return buildErrorMessage(
tree, "the transformation is not a compile-time constant expression");
}
// Otherwise, we know that the transformation is specified by a string literal.
String transformation = (String) argument;
// We exclude stream ciphers (this check only makes sense for block ciphers), i.e., the RC4
// cipher. The name of this algorithm is "ARCFOUR" in the SunJce and "ARC4" in Conscrypt.
// Some other providers like JCraft also seem to use the name "RC4".
if (transformation.matches("ARCFOUR.*")
|| transformation.matches("ARC4.*")
|| transformation.matches("RC4.*")) {
return Description.NO_MATCH;
}
if (!transformation.matches(".*/.*/.*")) {
// The mode and padding shall be explicitly specified. We don't allow default settings to be
// used, regardless of the algorithm and provider.
return buildErrorMessage(tree, "the mode and padding must be explicitly specified");
}
if (transformation.matches(".*/ECB/.*")
&& !transformation.matches("RSA/.*")
&& !transformation.matches("AESWrap/.*")) {
// Otherwise, ECB mode should be explicitly specified in order to trigger the check. RSA
// is an exception, as this transformation doesn't actually implement a block cipher
// encryption mode (the input is limited by the size of the key). AESWrap is another
// exception, because this algorithm is only used to encrypt encryption keys.
return buildErrorMessage(tree, "ECB mode must not be used");
}
if (transformation.matches("ECIES.*") || transformation.matches("DHIES.*")) {
// Existing implementations of IES-based algorithms use ECB under the hood and must also be
// flagged as vulnerable. See b/30424901 for a more detailed rationale.
return buildErrorMessage(tree, "IES-based algorithms use ECB mode and are insecure");
}
return Description.NO_MATCH;
}
private Description identifyDiffieHellmanAndDsaVulnerabilities(MethodInvocationTree tree) {
// The first argument holds a string specifying the algorithm used for the operation
// considered.
Object argument = ASTHelpers.constValue(tree.getArguments().getFirst());
if (argument == null) {
// We flag call sites where the algorithm specification string is dynamically computed.
return buildErrorMessage(
tree, "the algorithm specification is not a compile-time constant expression");
}
// Otherwise, we know that the algorithm is specified by a string literal.
String algorithm = (String) argument;
if (algorithm.matches("DH")) {
// Most implementations of Diffie-Hellman on prime fields have vulnerabilities. See b/31574444
// for a more detailed rationale.
return buildErrorMessage(tree, "using Diffie-Hellman on prime fields is insecure");
}
if (algorithm.matches("DSA")) {
// Some crypto libraries may accept invalid DSA signatures in specific configurations (see
// b/30262692 for details).
return buildErrorMessage(tree, "using DSA is insecure");
}
return Description.NO_MATCH;
}
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
Description description = checkInvocation(tree, state);
return description;
}
Description checkInvocation(MethodInvocationTree tree, VisitorState state) {
if (CIPHER_GETINSTANCE_MATCHER.matches(tree, state)) {
return identifyEcbVulnerability(tree);
}
if (KEY_STRUCTURE_GETINSTANCE_MATCHER.matches(tree, state)) {
return identifyDiffieHellmanAndDsaVulnerabilities(tree);
}
return Description.NO_MATCH;
}
}
|
InsecureCipherMode
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/search/runtime/LongScriptFieldTermsQuery.java
|
{
"start": 752,
"end": 1995
}
|
class ____ extends AbstractLongScriptFieldQuery {
private final Set<Long> terms;
public LongScriptFieldTermsQuery(
Script script,
Function<LeafReaderContext, AbstractLongFieldScript> leafFactory,
String fieldName,
Set<Long> terms
) {
super(script, leafFactory, fieldName);
this.terms = terms;
}
@Override
protected boolean matches(long[] values, int count) {
for (int i = 0; i < count; i++) {
if (terms.contains(values[i])) {
return true;
}
}
return false;
}
@Override
public final String toString(String field) {
if (fieldName().contentEquals(field)) {
return terms.toString();
}
return fieldName() + ":" + terms;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), terms);
}
@Override
public boolean equals(Object obj) {
if (false == super.equals(obj)) {
return false;
}
LongScriptFieldTermsQuery other = (LongScriptFieldTermsQuery) obj;
return terms.equals(other.terms);
}
Set<Long> terms() {
return terms;
}
}
|
LongScriptFieldTermsQuery
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddb/Ddb2Component.java
|
{
"start": 1118,
"end": 2947
}
|
class ____ extends HealthCheckComponent {
@Metadata
private Ddb2Configuration configuration = new Ddb2Configuration();
public Ddb2Component() {
this(null);
}
public Ddb2Component(CamelContext context) {
super(context);
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
if (remaining == null || remaining.isBlank()) {
throw new IllegalArgumentException("Table name must be specified.");
}
Ddb2Configuration configuration = this.configuration != null ? this.configuration.copy() : new Ddb2Configuration();
configuration.setTableName(remaining);
Ddb2Endpoint endpoint = new Ddb2Endpoint(uri, this, configuration);
setProperties(endpoint, parameters);
if (Boolean.FALSE.equals(configuration.isUseDefaultCredentialsProvider())
&& Boolean.FALSE.equals(configuration.isUseProfileCredentialsProvider())
&& Boolean.FALSE.equals(configuration.isUseSessionCredentials())
&& configuration.getAmazonDDBClient() == null
&& (configuration.getAccessKey() == null || configuration.getSecretKey() == null)) {
throw new IllegalArgumentException(
"useDefaultCredentialsProvider is set to false, useProfileCredentialsProvider is set to false, useSessionCredentials is set to false, amazonDDBClient or accessKey and secretKey must be specified");
}
return endpoint;
}
public Ddb2Configuration getConfiguration() {
return configuration;
}
/**
* The component configuration
*/
public void setConfiguration(Ddb2Configuration configuration) {
this.configuration = configuration;
}
}
|
Ddb2Component
|
java
|
processing__processing4
|
core/src/processing/core/PApplet.java
|
{
"start": 332115,
"end": 332187
}
|
class ____ the command line.
* <p>
* Usage: PApplet [options] <
|
from
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/dialect/phoenix/ast/PhoenixObject.java
|
{
"start": 834,
"end": 925
}
|
interface ____ extends SQLObject {
void accept0(PhoenixASTVisitor visitor);
}
|
PhoenixObject
|
java
|
elastic__elasticsearch
|
plugins/analysis-icu/src/main/java/org/elasticsearch/plugin/analysis/icu/IcuFoldingTokenFilterFactory.java
|
{
"start": 1433,
"end": 2210
}
|
class ____ extends AbstractTokenFilterFactory implements NormalizingTokenFilterFactory {
/** Store here the same Normalizer used by the lucene ICUFoldingFilter */
private static final Normalizer2 ICU_FOLDING_NORMALIZER = ICUFoldingFilter.NORMALIZER;
private final Normalizer2 normalizer;
public IcuFoldingTokenFilterFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings) {
super(name);
this.normalizer = IcuNormalizerTokenFilterFactory.wrapWithUnicodeSetFilter(ICU_FOLDING_NORMALIZER, settings);
}
@Override
public TokenStream create(TokenStream tokenStream) {
return new org.apache.lucene.analysis.icu.ICUNormalizer2Filter(tokenStream, normalizer);
}
}
|
IcuFoldingTokenFilterFactory
|
java
|
mybatis__mybatis-3
|
src/main/java/org/apache/ibatis/annotations/Case.java
|
{
"start": 1136,
"end": 1710
}
|
interface ____ {
/**
* Return the condition value to apply this mapping.
*
* @return the condition value
*/
String value();
/**
* Return the object type that create a object using this mapping.
*
* @return the object type
*/
Class<?> type();
/**
* Return mapping definitions for property.
*
* @return mapping definitions for property
*/
Result[] results() default {};
/**
* Return mapping definitions for constructor.
*
* @return mapping definitions for constructor
*/
Arg[] constructArgs() default {};
}
|
Case
|
java
|
alibaba__nacos
|
config/src/test/java/com/alibaba/nacos/config/server/service/ConfigFuzzyWatchContextServiceTest.java
|
{
"start": 1811,
"end": 11846
}
|
class ____ {
MockedStatic<EnvUtil> envUtilMockedStatic;
MockedStatic<ConfigCommonConfig> configCommonConfigMockedStatic;
private static int mocMaxPattern = 5;
private static int mocMaxPatternConfigCount = 10;
/**
* before.
*/
@BeforeEach
public void before() {
envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class);
envUtilMockedStatic.when(() -> EnvUtil.getProperty(eq("nacos.config.cache.type"), anyString()))
.thenReturn("nacos");
configCommonConfigMockedStatic = Mockito.mockStatic(ConfigCommonConfig.class);
ConfigCommonConfig configCommonConfig = Mockito.mock(ConfigCommonConfig.class);
when(configCommonConfig.getMaxPatternCount()).thenReturn(mocMaxPattern);
when(configCommonConfig.getMaxMatchedConfigCount()).thenReturn(mocMaxPatternConfigCount);
configCommonConfigMockedStatic.when(() -> ConfigCommonConfig.getInstance()).thenReturn(configCommonConfig);
}
@AfterEach
public void after() {
envUtilMockedStatic.close();
configCommonConfigMockedStatic.close();
}
@Test
public void testTrimFuzzyWatchContext() throws NacosException {
ConfigFuzzyWatchContextService configFuzzyWatchContextService = new ConfigFuzzyWatchContextService();
String groupKey = GroupKey.getKeyTenant("data124", "group", "12345");
//init
String collectionId = "id";
String groupKeyPattern = FuzzyGroupKeyPattern.generatePattern("data*", "group", "12345");
configFuzzyWatchContextService.addFuzzyWatch(groupKeyPattern, collectionId);
configFuzzyWatchContextService.syncGroupKeyContext(groupKey, ADD_CONFIG);
//test
Set<String> matchedClients = configFuzzyWatchContextService.getMatchedClients(groupKey);
Assertions.assertTrue(matchedClients.size() == 1);
Set<String> notMatchedClients = configFuzzyWatchContextService.getMatchedClients(
GroupKey.getKeyTenant("da124", "group", "12345"));
Assertions.assertTrue(notMatchedClients.size() == 0);
Set<String> matchedGroupKeys = configFuzzyWatchContextService.matchGroupKeys(groupKeyPattern);
Assertions.assertTrue(matchedGroupKeys.size() > 0);
Assertions.assertTrue(matchedGroupKeys.contains(groupKey));
// remove connection is watch
configFuzzyWatchContextService.clearFuzzyWatchContext(collectionId);
//trim once, matchedClients2 is empty,matchedGroupKeys2 is not empty
configFuzzyWatchContextService.trimFuzzyWatchContext();
Set<String> matchedClients2 = configFuzzyWatchContextService.getMatchedClients(groupKey);
Assertions.assertTrue(matchedClients2 != null && matchedClients2.isEmpty());
Set<String> matchedGroupKeys2 = configFuzzyWatchContextService.matchGroupKeys(groupKeyPattern);
Assertions.assertTrue(matchedGroupKeys2 != null && matchedGroupKeys2.contains(groupKey));
//trim twice, matchedGroupKeys2 is empty
configFuzzyWatchContextService.trimFuzzyWatchContext();
Set<String> matchedGroupKeys3 = configFuzzyWatchContextService.matchGroupKeys(groupKeyPattern);
Assertions.assertTrue(matchedGroupKeys3.isEmpty());
}
@Test
public void testSyncGroupKeyContext() throws NacosException {
ConfigFuzzyWatchContextService configFuzzyWatchContextService = new ConfigFuzzyWatchContextService();
//init
String collectionId = "id";
String groupKeyPattern = FuzzyGroupKeyPattern.generatePattern("data*", "group", "12345");
configFuzzyWatchContextService.addFuzzyWatch(groupKeyPattern, collectionId);
String keyTenant = GroupKey.getKeyTenant("data1245", "group", "12345");
boolean needNotify1 = configFuzzyWatchContextService.syncGroupKeyContext(keyTenant, ADD_CONFIG);
Assertions.assertTrue(needNotify1);
boolean needNotify2 = configFuzzyWatchContextService.syncGroupKeyContext(keyTenant, ADD_CONFIG);
Assertions.assertFalse(needNotify2);
boolean needNotify3 = configFuzzyWatchContextService.syncGroupKeyContext(keyTenant, DELETE_CONFIG);
Assertions.assertTrue(needNotify3);
boolean needNotify4 = configFuzzyWatchContextService.syncGroupKeyContext(keyTenant, DELETE_CONFIG);
Assertions.assertFalse(needNotify4);
}
@Test
public void testMakeupGroupKeyContext() throws NacosException {
ConfigFuzzyWatchContextService configFuzzyWatchContextService = new ConfigFuzzyWatchContextService();
//init
String collectionId = "id";
String groupKeyPattern = FuzzyGroupKeyPattern.generatePattern("data*", "group", "12345");
configFuzzyWatchContextService.addFuzzyWatch(groupKeyPattern, collectionId);
for (int i = 0; i <= mocMaxPatternConfigCount; i++) {
String keyTenant = GroupKey.getKeyTenant("data1" + i, "group", "12345");
boolean needNotify1 = configFuzzyWatchContextService.syncGroupKeyContext(keyTenant, ADD_CONFIG);
Assertions.assertEquals(i < mocMaxPatternConfigCount ? true : false, needNotify1);
}
String overLimitKey = GroupKey.getKeyTenant("data1" + mocMaxPatternConfigCount, "group", "12345");
Assertions.assertFalse(configFuzzyWatchContextService.matchGroupKeys(groupKeyPattern).contains(overLimitKey));
//sync init cache service
ConfigCacheService.dump("data1" + mocMaxPatternConfigCount, "group", "12345", "content",
System.currentTimeMillis(), null, null);
String deletedKey = GroupKey.getKeyTenant("data1" + 0, "group", "12345");
configFuzzyWatchContextService.syncGroupKeyContext(deletedKey, DELETE_CONFIG);
Assertions.assertTrue(configFuzzyWatchContextService.matchGroupKeys(groupKeyPattern).contains(overLimitKey));
}
@Test
public void testInitGroupKeyContext() throws NacosException {
ConfigFuzzyWatchContextService configFuzzyWatchContextService = new ConfigFuzzyWatchContextService();
String dataIdPrefix = "testinitD";
// init config
for (int i = 0; i <= mocMaxPatternConfigCount; i++) {
ConfigCacheService.dump(dataIdPrefix + i, "group", "12345", "content", System.currentTimeMillis(), null,
null);
}
String collectionId = "id";
String groupKeyPattern = FuzzyGroupKeyPattern.generatePattern(dataIdPrefix + "*", "group", "12345");
// test init config
configFuzzyWatchContextService.addFuzzyWatch(groupKeyPattern, collectionId);
Assertions.assertEquals(mocMaxPatternConfigCount,
configFuzzyWatchContextService.matchGroupKeys(groupKeyPattern).size());
for (int i = 1; i < mocMaxPattern; i++) {
String groupKeyPattern0 = FuzzyGroupKeyPattern.generatePattern(dataIdPrefix + "*" + i, "group", "12345");
configFuzzyWatchContextService.addFuzzyWatch(groupKeyPattern0, collectionId);
}
try {
String groupKeyPatternOver = FuzzyGroupKeyPattern.generatePattern(dataIdPrefix + "*" + mocMaxPattern,
"group", "12345");
configFuzzyWatchContextService.addFuzzyWatch(groupKeyPatternOver, collectionId);
Assertions.assertTrue(false);
} catch (NacosException nacosException) {
Assertions.assertEquals(FUZZY_WATCH_PATTERN_OVER_LIMIT.getCode(), nacosException.getErrCode());
Assertions.assertEquals(FUZZY_WATCH_PATTERN_OVER_LIMIT.getMsg(), nacosException.getErrMsg());
}
}
@Test
public void testFuzzyWatch() throws NacosException {
ConfigFuzzyWatchContextService configFuzzyWatchContextService = new ConfigFuzzyWatchContextService();
//init
String collectionId = "id";
String groupKeyPattern = FuzzyGroupKeyPattern.generatePattern("data*", "group", "12345");
configFuzzyWatchContextService.addFuzzyWatch(groupKeyPattern, collectionId);
String groupKey = GroupKey.getKeyTenant("data1245", "group", "12345");
boolean needNotify = configFuzzyWatchContextService.syncGroupKeyContext(groupKey, ADD_CONFIG);
Assertions.assertTrue(needNotify);
Set<String> matchedClients1 = configFuzzyWatchContextService.getMatchedClients(groupKey);
Assertions.assertTrue(matchedClients1.contains(collectionId));
configFuzzyWatchContextService.removeFuzzyListen(groupKeyPattern, collectionId);
Set<String> matchedClients = configFuzzyWatchContextService.getMatchedClients(groupKey);
Assertions.assertTrue(CollectionUtils.isEmpty(matchedClients));
}
@Test
public void testFuzzyWatchOverLimit() throws NacosException {
ConfigFuzzyWatchContextService configFuzzyWatchContextService = new ConfigFuzzyWatchContextService();
//init
String collectionId = "id";
String groupKeyPattern = FuzzyGroupKeyPattern.generatePattern("data*", "group", "12345");
configFuzzyWatchContextService.addFuzzyWatch(groupKeyPattern, collectionId);
String groupKey = GroupKey.getKeyTenant("data1245", "group", "12345");
boolean needNotify = configFuzzyWatchContextService.syncGroupKeyContext(groupKey, ADD_CONFIG);
Assertions.assertTrue(needNotify);
configFuzzyWatchContextService.removeFuzzyListen(groupKeyPattern, collectionId);
Set<String> matchedClients = configFuzzyWatchContextService.getMatchedClients(groupKey);
Assertions.assertTrue(CollectionUtils.isEmpty(matchedClients));
}
}
|
ConfigFuzzyWatchContextServiceTest
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
|
{
"start": 70426,
"end": 70668
}
|
interface ____ {}
""")
.addSourceLines(
"MutableImpl.java",
"""
import com.google.errorprone.annotations.Immutable;
@SuppressWarnings("Immutable")
|
ImmutableInterface
|
java
|
spring-projects__spring-data-jpa
|
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/procedures/PostgresStoredProcedureNullHandlingIntegrationTests.java
|
{
"start": 3734,
"end": 4173
}
|
interface ____ extends JpaRepository<TestModel, Long> {
@Procedure("countByUuid")
void countUuid(UUID this_uuid);
@Procedure("countByLocalDate")
void countLocalDate(@Temporal Date this_local_date);
}
@EnableJpaRepositories(considerNestedRepositories = true,
includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = TestModelRepository.class))
@EnableTransactionManagement
static
|
TestModelRepository
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/tofix/BuilderCreatorSubtype4742Test.java
|
{
"start": 784,
"end": 948
}
|
class ____ {
@JsonProperty("animals")
public List<Animal> animals;
}
@JsonDeserialize(builder = Animal.Builder.class)
public static
|
Animals
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/demo/hibernate/data/Payment.java
|
{
"start": 705,
"end": 2498
}
|
class ____ implements java.io.Serializable
{
private PaymentId id;
private Customer customer;
private Date paymentDate;
private double amount;
public Payment() { }
public Payment(PaymentId id, Customer customer, Date paymentDate,
double amount) {
this.id = id;
this.customer = customer;
this.paymentDate = paymentDate;
this.amount = amount;
}
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "customerNumber", column = @Column(name = "customerNumber", nullable = false)),
@AttributeOverride(name = "checkNumber", column = @Column(name = "checkNumber", nullable = false, length = 50)) })
public PaymentId getId() {
return this.id;
}
public void setId(PaymentId id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "customerNumber", nullable = false, insertable = false, updatable = false)
@JsonIgnore
public Customer getCustomer() {
return this.customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
@Column(name = "paymentDate", nullable = false, length = 19)
public Date getPaymentDate() {
return this.paymentDate;
}
public void setPaymentDate(Date paymentDate) {
this.paymentDate = paymentDate;
}
@Column(name = "amount", nullable = false, precision = 22, scale = 0)
public double getAmount() {
return this.amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
}
|
Payment
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/core/NestedExceptionUtils.java
|
{
"start": 853,
"end": 1064
}
|
class ____ different exception types.
*
* <p>Mainly for use within the framework.
*
* @author Juergen Hoeller
* @since 2.0
* @see NestedRuntimeException
* @see NestedCheckedException
*/
public abstract
|
among
|
java
|
google__gson
|
gson/src/main/java/com/google/gson/FieldAttributes.java
|
{
"start": 1031,
"end": 1390
}
|
class ____ {
private final Field field;
/**
* Constructs a Field Attributes object from the {@code f}.
*
* @param f the field to pull attributes from
*/
public FieldAttributes(Field f) {
this.field = Objects.requireNonNull(f);
}
/**
* Gets the declaring Class that contains this field
*
* @return the declaring
|
FieldAttributes
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/bug/Bug_for_long_whitespace.java
|
{
"start": 410,
"end": 755
}
|
class ____ {
private long f1;
private int f2;
public long getF1() {
return f1;
}
public void setF1(long f1) {
this.f1 = f1;
}
public int getF2() {
return f2;
}
public void setF2(int f2) {
this.f2 = f2;
}
}
}
|
VO
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/usertype/CompositeUserType.java
|
{
"start": 5447,
"end": 5548
}
|
class ____ represents the embeddable mapping of the type.
*/
Class<?> embeddable();
/**
* The
|
that
|
java
|
spring-cloud__spring-cloud-gateway
|
spring-cloud-gateway-integration-tests/grpc/src/test/java/org/springframework/cloud/gateway/tests/grpc/JsonToGrpcApplicationTests.java
|
{
"start": 2368,
"end": 4609
}
|
class ____ {
@LocalServerPort
private int gatewayPort;
private RestTemplate restTemplate;
@BeforeEach
void setUp() {
restTemplate = createUnsecureClient();
}
@Test
public void shouldConvertFromJSONToGRPC() {
// Since GRPC server and GW run in same instance and don't know server port until
// test starts,
// we need to configure route dynamically using the actuator endpoint.
final RouteConfigurer configurer = new RouteConfigurer(gatewayPort);
int grpcServerPort = gatewayPort + 1;
configurer.addRoute(grpcServerPort, "/json/hello",
"JsonToGrpc=HelloService,hello,file:src/main/proto/hello.pb");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>("{\"firstName\":\"Duff\", \"lastName\":\"McKagan\"}", headers);
String response = restTemplate
.postForEntity("https://localhost:" + this.gatewayPort + "/json/hello", request, String.class)
.getBody();
Assertions.assertThat(response).isNotNull();
Assertions.assertThat(response).contains("{\"greeting\":\"Hello, Duff McKagan\"}");
}
private RestTemplate createUnsecureClient() {
TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
SSLContext sslContext;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
}
catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new RuntimeException(e);
}
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslSocketFactory)
.register("http", new PlainConnectionSocketFactory())
.build();
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(requestFactory);
}
}
|
JsonToGrpcApplicationTests
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ClassInitializationDeadlockTest.java
|
{
"start": 4214,
"end": 4443
}
|
class ____ implements A {}
}
""")
.doTest();
}
@Test
public void negativePrivateConstructor() {
testHelper
.addSourceLines(
"A.java",
"""
public
|
B
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/db/OracleDataDrivenDBRecordReader.java
|
{
"start": 1233,
"end": 1799
}
|
class ____<T extends DBWritable>
extends DataDrivenDBRecordReader<T> {
public OracleDataDrivenDBRecordReader(DBInputFormat.DBInputSplit split,
Class<T> inputClass, Configuration conf, Connection conn,
DBConfiguration dbConfig, String cond, String [] fields,
String table) throws SQLException {
super(split, inputClass, conf, conn, dbConfig, cond, fields, table,
"ORACLE");
// Must initialize the tz used by the connection for Oracle.
OracleDBRecordReader.setSessionTimeZone(conf, conn);
}
}
|
OracleDataDrivenDBRecordReader
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/script/StatsSummary.java
|
{
"start": 851,
"end": 3198
}
|
class ____ implements DoubleConsumer {
private long count = 0;
private double sum = 0d;
private Double min;
private Double max;
public StatsSummary() {}
StatsSummary(long count, double sum, double min, double max) {
this.count = count;
this.sum = sum;
this.min = min;
this.max = max;
}
@Override
public void accept(double value) {
count++;
sum += value;
min = min == null ? value : (value < min ? value : min);
max = max == null ? value : (value > max ? value : max);
}
/**
* Returns the min for recorded value.
*/
public double getMin() {
return min == null ? 0.0 : min;
}
/**
* Returns the max for recorded values.
*/
public double getMax() {
return max == null ? 0.0 : max;
}
/**
* Returns the arithmetic mean for recorded values.
*/
public double getAverage() {
return count == 0.0 ? 0.0 : sum / count;
}
/**
* Returns the sum of all recorded values.
*/
public double getSum() {
return sum;
}
/**
* Returns the number of recorded values.
*/
public long getCount() {
return count;
}
/**
* Resets the accumulator, clearing all accumulated statistics.
* After calling this method, the accumulator will be in its initial state.
*/
public void reset() {
count = 0;
sum = 0d;
min = null;
max = null;
}
@Override
public int hashCode() {
return Objects.hash(count, sum, min, max);
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
StatsSummary other = (StatsSummary) obj;
return Objects.equals(count, other.count)
&& Objects.equals(sum, other.sum)
&& Objects.equals(min, other.min)
&& Objects.equals(max, other.max);
}
@Override
public String toString() {
return Strings.format(
"%s{count=%d, sum=%f, min=%f, average=%f, max=%f}",
this.getClass().getSimpleName(),
getCount(),
getSum(),
getMin(),
getAverage(),
getMax()
);
}
}
|
StatsSummary
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/leaderelection/LeaderElectionTest.java
|
{
"start": 2452,
"end": 4978
}
|
class ____ {
@RegisterExtension
private static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE =
TestingUtils.defaultExecutorExtension();
@RegisterExtension
private final TestingFatalErrorHandlerExtension testingFatalErrorHandlerResource =
new TestingFatalErrorHandlerExtension();
@Parameters(name = "Leader election: {0}")
public static Collection<ServiceClass> parameters() {
return Arrays.asList(
new ZooKeeperServiceClass(),
new EmbeddedServiceClass(),
new StandaloneServiceClass());
}
@Parameter public ServiceClass serviceClass;
@BeforeEach
void setup() throws Exception {
serviceClass.setup(testingFatalErrorHandlerResource.getTestingFatalErrorHandler());
}
@AfterEach
void teardown() throws Exception {
serviceClass.teardown();
}
@TestTemplate
void testHasLeadershipAsync() throws Exception {
final ManualLeaderContender manualLeaderContender = new ManualLeaderContender();
try {
final LeaderElection leaderElection = serviceClass.createLeaderElection();
leaderElection.startLeaderElection(manualLeaderContender);
final UUID leaderSessionId = manualLeaderContender.waitForLeaderSessionId();
assertThatFuture(leaderElection.hasLeadershipAsync(leaderSessionId))
.eventuallySucceeds()
.isEqualTo(true);
assertThatFuture(leaderElection.hasLeadershipAsync(UUID.randomUUID()))
.eventuallySucceeds()
.isEqualTo(false);
assertThatFuture(leaderElection.confirmLeadershipAsync(leaderSessionId, "foobar"))
.eventuallySucceeds();
assertThatFuture(leaderElection.hasLeadershipAsync(leaderSessionId))
.eventuallySucceeds()
.isEqualTo(true);
leaderElection.close();
assertThatFuture(leaderElection.hasLeadershipAsync(leaderSessionId))
.eventuallySucceeds()
.isEqualTo(false);
assertThat(manualLeaderContender.waitForLeaderSessionId())
.as("The leadership has been revoked from the contender.")
.isEqualTo(ManualLeaderContender.NULL_LEADER_SESSION_ID);
} finally {
manualLeaderContender.rethrowError();
}
}
private static final
|
LeaderElectionTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/analytics/action/PutAnalyticsCollectionAction.java
|
{
"start": 1466,
"end": 3250
}
|
class ____ extends MasterNodeRequest<Request> implements ToXContentObject {
private final String name;
public static final ParseField NAME_FIELD = new ParseField("name");
public Request(StreamInput in) throws IOException {
super(in);
this.name = in.readString();
}
public Request(TimeValue masterNodeTimeout, String name) {
super(masterNodeTimeout);
this.name = name;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (name == null || name.isEmpty()) {
validationException = addValidationError("Analytics collection name is missing", validationException);
}
return validationException;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(name);
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Request that = (Request) o;
return Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(NAME_FIELD.getPreferredName(), name);
builder.endObject();
return builder;
}
}
public static
|
Request
|
java
|
elastic__elasticsearch
|
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/input/http/HttpInput.java
|
{
"start": 9192,
"end": 9478
}
|
interface ____ {
ParseField REQUEST = new ParseField("request");
ParseField EXTRACT = new ParseField("extract");
ParseField STATUS_CODE = new ParseField("status_code");
ParseField RESPONSE_CONTENT_TYPE = new ParseField("response_content_type");
}
}
|
Field
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/model/internal/ToOneBinder.java
|
{
"start": 2739,
"end": 2837
}
|
class ____ stateless, unlike most of the other "binders".
*
* @author Emmanuel Bernard
*/
public
|
is
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/metrics/FederationStateStoreClientMetrics.java
|
{
"start": 2056,
"end": 7440
}
|
class ____ implements MetricsSource {
public static final Logger LOG =
LoggerFactory.getLogger(FederationStateStoreClientMetrics.class);
private static final MetricsRegistry REGISTRY =
new MetricsRegistry("FederationStateStoreClientMetrics");
private final static Method[] STATESTORE_API_METHODS =
FederationStateStore.class.getMethods();
// Map method names to counter objects
private static final Map<String, MutableCounterLong> API_TO_FAILED_CALLS =
new HashMap<String, MutableCounterLong>();
private static final Map<String, MutableRate> API_TO_SUCCESSFUL_CALLS =
new HashMap<String, MutableRate>();
// Provide quantile latency for each api call.
private static final Map<String, MutableQuantiles> API_TO_QUANTILE_METRICS =
new HashMap<String, MutableQuantiles>();
// Error string templates for logging calls from methods not in
// FederationStateStore API
private static final String UNKOWN_FAIL_ERROR_MSG =
"Not recording failed call for unknown FederationStateStore method {}";
private static final String UNKNOWN_SUCCESS_ERROR_MSG =
"Not recording successful call for unknown "
+ "FederationStateStore method {}";
// Aggregate metrics are shared, and don't have to be looked up per call
@Metric("Total number of successful calls and latency(ms)")
private static MutableRate totalSucceededCalls;
@Metric("Total number of failed StateStore calls")
private static MutableCounterLong totalFailedCalls;
@Metric("Total number of Connections")
private static MutableGaugeInt totalConnections;
// This after the static members are initialized, or the constructor will
// throw a NullPointerException
private static final FederationStateStoreClientMetrics S_INSTANCE =
DefaultMetricsSystem.instance()
.register(new FederationStateStoreClientMetrics());
synchronized public static FederationStateStoreClientMetrics getInstance() {
return S_INSTANCE;
}
private FederationStateStoreClientMetrics() {
// Create the metrics for each method and put them into the map
for (Method m : STATESTORE_API_METHODS) {
String methodName = m.getName();
LOG.debug("Registering Federation StateStore Client metrics for {}",
methodName);
// This metric only records the number of failed calls; it does not
// capture latency information
API_TO_FAILED_CALLS.put(methodName,
REGISTRY.newCounter(methodName + "_numFailedCalls",
"# failed calls to " + methodName, 0L));
// This metric records both the number and average latency of successful
// calls.
API_TO_SUCCESSFUL_CALLS.put(methodName,
REGISTRY.newRate(methodName + "_successfulCalls",
"# successful calls and latency(ms) for" + methodName));
// This metric records the quantile-based latency of each successful call,
// re-sampled every 10 seconds.
API_TO_QUANTILE_METRICS.put(methodName,
REGISTRY.newQuantiles(methodName + "Latency",
"Quantile latency (ms) for " + methodName, "ops", "latency", 10));
}
}
public static void failedStateStoreCall() {
String methodName =
Thread.currentThread().getStackTrace()[2].getMethodName();
MutableCounterLong methodMetric = API_TO_FAILED_CALLS.get(methodName);
if (methodMetric == null) {
LOG.error(UNKOWN_FAIL_ERROR_MSG, methodName);
return;
}
totalFailedCalls.incr();
methodMetric.incr();
}
public static void succeededStateStoreCall(long duration) {
String methodName =
Thread.currentThread().getStackTrace()[2].getMethodName();
MutableRate methodMetric = API_TO_SUCCESSFUL_CALLS.get(methodName);
MutableQuantiles methodQuantileMetric =
API_TO_QUANTILE_METRICS.get(methodName);
if (methodMetric == null || methodQuantileMetric == null) {
LOG.error(UNKNOWN_SUCCESS_ERROR_MSG, methodName);
return;
}
totalSucceededCalls.add(duration);
methodMetric.add(duration);
methodQuantileMetric.add(duration);
}
public static void incrConnections() {
totalConnections.incr();
}
public static void decrConnections() {
totalConnections.decr();
}
@Override
public void getMetrics(MetricsCollector collector, boolean all) {
REGISTRY.snapshot(collector.addRecord(REGISTRY.info()), all);
}
// Getters for unit testing
@VisibleForTesting
static long getNumFailedCallsForMethod(String methodName) {
return API_TO_FAILED_CALLS.get(methodName).value();
}
@VisibleForTesting
static long getNumSucceessfulCallsForMethod(String methodName) {
return API_TO_SUCCESSFUL_CALLS.get(methodName).lastStat().numSamples();
}
@VisibleForTesting
static double getLatencySucceessfulCallsForMethod(String methodName) {
return API_TO_SUCCESSFUL_CALLS.get(methodName).lastStat().mean();
}
@VisibleForTesting
static long getNumFailedCalls() {
return totalFailedCalls.value();
}
@VisibleForTesting
static long getNumSucceededCalls() {
return totalSucceededCalls.lastStat().numSamples();
}
@VisibleForTesting
static double getLatencySucceededCalls() {
return totalSucceededCalls.lastStat().mean();
}
@VisibleForTesting
public static int getNumConnections() {
return totalConnections.value();
}
}
|
FederationStateStoreClientMetrics
|
java
|
apache__maven
|
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/ReactorContext.java
|
{
"start": 1108,
"end": 1912
}
|
class ____ {
private final MavenExecutionResult result;
private final ClassLoader originalContextClassLoader;
private final ReactorBuildStatus reactorBuildStatus;
public ReactorContext(
MavenExecutionResult result,
ClassLoader originalContextClassLoader,
ReactorBuildStatus reactorBuildStatus) {
this.result = result;
this.originalContextClassLoader = originalContextClassLoader;
this.reactorBuildStatus = reactorBuildStatus;
}
public ReactorBuildStatus getReactorBuildStatus() {
return reactorBuildStatus;
}
public MavenExecutionResult getResult() {
return result;
}
public ClassLoader getOriginalContextClassLoader() {
return originalContextClassLoader;
}
}
|
ReactorContext
|
java
|
quarkusio__quarkus
|
integration-tests/maven/src/test/resources-filtered/projects/test-source-sets/src/main/java/org/acme/GreetingResource.java
|
{
"start": 164,
"end": 335
}
|
class ____ {
static final String HELLO = "Hello";
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return HELLO;
}
}
|
GreetingResource
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/fetchscroll/Order.java
|
{
"start": 249,
"end": 1226
}
|
class ____ {
private OrderId id;
private PurchaseOrg purchaseOrg;
private Set<OrderLine> lines;
public Order() {
}
public Order(PurchaseOrg purchaseOrg, String number) {
this.id = new OrderId();
this.id.setPurchaseOrgId(purchaseOrg.getId());
this.id.setNumber(number);
this.purchaseOrg = purchaseOrg;
}
@EmbeddedId
public OrderId getId() {
return id;
}
public void setId(OrderId id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PURCHASE_ORG_ID", referencedColumnName = "PURCHASE_ORG_ID", nullable = false, insertable = false, updatable = false)
public PurchaseOrg getPurchaseOrg() {
return purchaseOrg;
}
public void setPurchaseOrg(PurchaseOrg purchaseOrg) {
this.purchaseOrg = purchaseOrg;
}
@OneToMany(mappedBy = "header", orphanRemoval = true, cascade = CascadeType.ALL)
public Set<OrderLine> getLines() {
return lines;
}
public void setLines(Set<OrderLine> lines) {
this.lines = lines;
}
}
|
Order
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/reflect/TypeTokenResolutionTest.java
|
{
"start": 9687,
"end": 10341
}
|
class ____<T> {
final Type t = new TypeToken<T>(getClass()) {}.getType();
final Type array = new TypeToken<T[]>(getClass()) {}.getType();
}
public void testGenericArrayType() {
GenericArray<?> genericArray = new GenericArray<>();
assertEquals(GenericArray.class.getTypeParameters()[0], genericArray.t);
assertEquals(Types.newArrayType(genericArray.t), genericArray.array);
}
public void testClassWrapper() {
TypeToken<String> typeExpression = TypeToken.of(String.class);
assertEquals(String.class, typeExpression.getType());
assertEquals(String.class, typeExpression.getRawType());
}
private static
|
GenericArray
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/GetConf.java
|
{
"start": 5327,
"end": 6386
}
|
class ____ {
String key; // Configuration key to lookup
CommandHandler() {
this(null);
}
CommandHandler(String key) {
this.key = key;
}
final int doWork(GetConf tool, String[] args) {
try {
checkArgs(args);
return doWorkInternal(tool, args);
} catch (Exception e) {
tool.printError(e.getMessage());
}
return -1;
}
protected void checkArgs(String args[]) {
if (args.length > 0) {
throw new HadoopIllegalArgumentException(
"Did not expect argument: " + args[0]);
}
}
/** Method to be overridden by sub classes for specific behavior */
int doWorkInternal(GetConf tool, String[] args) throws Exception {
String value = tool.getConf().getTrimmed(key);
if (value != null) {
tool.printOut(value);
return 0;
}
tool.printError("Configuration " + key + " is missing.");
return -1;
}
}
/**
* Handler for {@link Command#NAMENODE}
*/
static
|
CommandHandler
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/api/protocolrecords/impl/pb/GetCountersRequestPBImpl.java
|
{
"start": 1403,
"end": 3220
}
|
class ____ extends ProtoBase<GetCountersRequestProto> implements GetCountersRequest {
GetCountersRequestProto proto = GetCountersRequestProto.getDefaultInstance();
GetCountersRequestProto.Builder builder = null;
boolean viaProto = false;
private JobId jobId = null;
public GetCountersRequestPBImpl() {
builder = GetCountersRequestProto.newBuilder();
}
public GetCountersRequestPBImpl(GetCountersRequestProto proto) {
this.proto = proto;
viaProto = true;
}
public GetCountersRequestProto getProto() {
mergeLocalToProto();
proto = viaProto ? proto : builder.build();
viaProto = true;
return proto;
}
private void mergeLocalToBuilder() {
if (this.jobId != null) {
builder.setJobId(convertToProtoFormat(this.jobId));
}
}
private void mergeLocalToProto() {
if (viaProto)
maybeInitBuilder();
mergeLocalToBuilder();
proto = builder.build();
viaProto = true;
}
private void maybeInitBuilder() {
if (viaProto || builder == null) {
builder = GetCountersRequestProto.newBuilder(proto);
}
viaProto = false;
}
@Override
public JobId getJobId() {
GetCountersRequestProtoOrBuilder p = viaProto ? proto : builder;
if (this.jobId != null) {
return this.jobId;
}
if (!p.hasJobId()) {
return null;
}
this.jobId = convertFromProtoFormat(p.getJobId());
return this.jobId;
}
@Override
public void setJobId(JobId jobId) {
maybeInitBuilder();
if (jobId == null)
builder.clearJobId();
this.jobId = jobId;
}
private JobIdPBImpl convertFromProtoFormat(JobIdProto p) {
return new JobIdPBImpl(p);
}
private JobIdProto convertToProtoFormat(JobId t) {
return ((JobIdPBImpl)t).getProto();
}
}
|
GetCountersRequestPBImpl
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/jmx/JmxException.java
|
{
"start": 909,
"end": 1316
}
|
class ____ extends NestedRuntimeException {
/**
* Constructor for JmxException.
* @param msg the detail message
*/
public JmxException(String msg) {
super(msg);
}
/**
* Constructor for JmxException.
* @param msg the detail message
* @param cause the root cause (usually a raw JMX API exception)
*/
public JmxException(String msg, Throwable cause) {
super(msg, cause);
}
}
|
JmxException
|
java
|
apache__camel
|
components/camel-hazelcast/src/main/java/org/apache/camel/component/hazelcast/set/HazelcastSetProducer.java
|
{
"start": 1442,
"end": 3805
}
|
class ____ extends HazelcastDefaultProducer {
private final ISet<Object> set;
public HazelcastSetProducer(HazelcastInstance hazelcastInstance, HazelcastDefaultEndpoint endpoint, String setName) {
super(endpoint);
this.set = hazelcastInstance.getSet(setName);
}
@Override
public void process(Exchange exchange) throws Exception {
final HazelcastOperation operation = lookupOperation(exchange);
switch (operation) {
case ADD:
this.add(exchange);
break;
case REMOVE_VALUE:
this.remove(exchange);
break;
case CLEAR:
this.clear();
break;
case ADD_ALL:
this.addAll(exchange);
break;
case REMOVE_ALL:
this.removeAll(exchange);
break;
case RETAIN_ALL:
this.retainAll(exchange);
break;
case GET_ALL:
this.getAll(exchange);
break;
default:
throw new IllegalArgumentException(
String.format("The value '%s' is not allowed for parameter '%s' on the SET cache.", operation,
HazelcastConstants.OPERATION));
}
// finally copy headers
HazelcastComponentHelper.copyHeaders(exchange);
}
private void add(Exchange exchange) {
final Object body = exchange.getIn().getBody();
set.add(body);
}
private void remove(Exchange exchange) {
final Object body = exchange.getIn().getBody();
set.remove(body);
}
private void clear() {
set.clear();
}
private void addAll(Exchange exchange) {
final Object body = exchange.getIn().getBody();
set.addAll((Collection<? extends Object>) body);
}
private void removeAll(Exchange exchange) {
final Object body = exchange.getIn().getBody();
set.removeAll((Collection<?>) body);
}
private void retainAll(Exchange exchange) {
final Object body = exchange.getIn().getBody();
set.retainAll((Collection<?>) body);
}
private void getAll(Exchange exchange) {
exchange.getMessage().setBody(set);
}
}
|
HazelcastSetProducer
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/common/ClusterTest.java
|
{
"start": 1286,
"end": 9392
}
|
class ____ {
private static final Node[] NODES = new Node[] {
new Node(0, "localhost", 99),
new Node(1, "localhost", 100),
new Node(2, "localhost", 101),
new Node(11, "localhost", 102)
};
private static final String TOPIC_A = "topicA";
private static final String TOPIC_B = "topicB";
private static final String TOPIC_C = "topicC";
private static final String TOPIC_D = "topicD";
private static final String TOPIC_E = "topicE";
@Test
public void testBootstrap() {
String ipAddress = "140.211.11.105";
String hostName = "www.example.com";
Cluster cluster = Cluster.bootstrap(Arrays.asList(
new InetSocketAddress(ipAddress, 9002),
new InetSocketAddress(hostName, 9002)
));
Set<String> expectedHosts = Set.of(ipAddress, hostName);
Set<String> actualHosts = new HashSet<>();
for (Node node : cluster.nodes())
actualHosts.add(node.host());
assertEquals(expectedHosts, actualHosts);
}
@Test
public void testReturnUnmodifiableCollections() {
List<PartitionInfo> allPartitions = asList(new PartitionInfo(TOPIC_A, 0, NODES[0], NODES, NODES),
new PartitionInfo(TOPIC_A, 1, null, NODES, NODES),
new PartitionInfo(TOPIC_A, 2, NODES[2], NODES, NODES),
new PartitionInfo(TOPIC_B, 0, null, NODES, NODES),
new PartitionInfo(TOPIC_B, 1, NODES[0], NODES, NODES),
new PartitionInfo(TOPIC_C, 0, null, NODES, NODES),
new PartitionInfo(TOPIC_D, 0, NODES[1], NODES, NODES),
new PartitionInfo(TOPIC_E, 0, NODES[0], NODES, NODES)
);
Set<String> unauthorizedTopics = Set.of(TOPIC_C);
Set<String> invalidTopics = Set.of(TOPIC_D);
Set<String> internalTopics = Set.of(TOPIC_E);
Cluster cluster = new Cluster("clusterId", asList(NODES), allPartitions, unauthorizedTopics,
invalidTopics, internalTopics, NODES[1]);
assertThrows(UnsupportedOperationException.class, () -> cluster.invalidTopics().add("foo"));
assertThrows(UnsupportedOperationException.class, () -> cluster.internalTopics().add("foo"));
assertThrows(UnsupportedOperationException.class, () -> cluster.unauthorizedTopics().add("foo"));
assertThrows(UnsupportedOperationException.class, () -> cluster.topics().add("foo"));
assertThrows(UnsupportedOperationException.class, () -> cluster.nodes().add(NODES[3]));
assertThrows(UnsupportedOperationException.class, () -> cluster.partitionsForTopic(TOPIC_A).add(
new PartitionInfo(TOPIC_A, 3, NODES[0], NODES, NODES)));
assertThrows(UnsupportedOperationException.class, () -> cluster.availablePartitionsForTopic(TOPIC_B).add(
new PartitionInfo(TOPIC_B, 2, NODES[0], NODES, NODES)));
assertThrows(UnsupportedOperationException.class, () -> cluster.partitionsForNode(NODES[1].id()).add(
new PartitionInfo(TOPIC_B, 2, NODES[1], NODES, NODES)));
}
@Test
public void testNotEquals() {
String clusterId1 = "clusterId1";
String clusterId2 = "clusterId2";
Node node0 = new Node(0, "host0", 100);
Node node1 = new Node(1, "host1", 100);
Set<PartitionInfo> partitions1 = Collections.singleton(new PartitionInfo("topic1", 0, node0, new Node[]{node0, node1}, new Node[]{node0}));
Set<PartitionInfo> partitions2 = Collections.singleton(new PartitionInfo("topic2", 0, node0, new Node[]{node1, node0}, new Node[]{node1}));
Set<String> unauthorizedTopics1 = Collections.singleton("topic1");
Set<String> unauthorizedTopics2 = Collections.singleton("topic2");
Set<String> invalidTopics1 = Collections.singleton("topic1");
Set<String> invalidTopics2 = Collections.singleton("topic2");
Set<String> internalTopics1 = Collections.singleton("topic3");
Set<String> internalTopics2 = Collections.singleton("topic4");
Node controller1 = new Node(2, "host2", 100);
Node controller2 = new Node(3, "host3", 100);
Map<String, Uuid> topicIds1 = Collections.singletonMap("topic1", Uuid.randomUuid());
Map<String, Uuid> topicIds2 = Collections.singletonMap("topic2", Uuid.randomUuid());
Cluster cluster1 = new Cluster(clusterId1, Collections.singletonList(node0), partitions1,
unauthorizedTopics1, invalidTopics1, internalTopics1, controller1, topicIds1);
Cluster differentTopicIds = new Cluster(clusterId1, Collections.singletonList(node0), partitions1,
unauthorizedTopics1, invalidTopics1, internalTopics1, controller1, topicIds2);
Cluster differentController = new Cluster(clusterId1, Collections.singletonList(node0), partitions1,
unauthorizedTopics1, invalidTopics1, internalTopics1, controller2, topicIds1);
Cluster differentInternalTopics = new Cluster(clusterId1, Collections.singletonList(node0), partitions1,
unauthorizedTopics1, invalidTopics1, internalTopics2, controller1, topicIds1);
Cluster differentInvalidTopics = new Cluster(clusterId1, Collections.singletonList(node0), partitions1,
unauthorizedTopics1, invalidTopics2, internalTopics1, controller1, topicIds1);
Cluster differentUnauthorizedTopics = new Cluster(clusterId1, Collections.singletonList(node0), partitions1,
unauthorizedTopics2, invalidTopics1, internalTopics1, controller1, topicIds1);
Cluster differentPartitions = new Cluster(clusterId1, Collections.singletonList(node0), partitions2,
unauthorizedTopics1, invalidTopics1, internalTopics1, controller1, topicIds1);
Cluster differentNodes = new Cluster(clusterId1, Arrays.asList(node0, node1), partitions1,
unauthorizedTopics1, invalidTopics1, internalTopics1, controller1, topicIds1);
Cluster differentClusterId = new Cluster(clusterId2, Collections.singletonList(node0), partitions1,
unauthorizedTopics1, invalidTopics1, internalTopics1, controller1, topicIds1);
assertNotEquals(cluster1, differentTopicIds);
assertNotEquals(cluster1, differentController);
assertNotEquals(cluster1, differentInternalTopics);
assertNotEquals(cluster1, differentInvalidTopics);
assertNotEquals(cluster1, differentUnauthorizedTopics);
assertNotEquals(cluster1, differentPartitions);
assertNotEquals(cluster1, differentNodes);
assertNotEquals(cluster1, differentClusterId);
}
@Test
public void testEquals() {
String clusterId1 = "clusterId1";
Node node1 = new Node(1, "host0", 100);
Node node1duplicate = new Node(1, "host0", 100);
Set<PartitionInfo> partitions1 = Collections.singleton(new PartitionInfo("topic1", 0, node1, new Node[]{node1}, new Node[]{node1}));
Set<PartitionInfo> partitions1duplicate = Collections.singleton(new PartitionInfo("topic1", 0, node1duplicate, new Node[]{node1duplicate}, new Node[]{node1duplicate}));
Set<String> unauthorizedTopics1 = Collections.singleton("topic1");
Set<String> invalidTopics1 = Collections.singleton("topic1");
Set<String> internalTopics1 = Collections.singleton("topic3");
Node controller1 = new Node(2, "host0", 100);
Node controller1duplicate = new Node(2, "host0", 100);
Uuid topicId1 = Uuid.randomUuid();
Map<String, Uuid> topicIds1 = Collections.singletonMap("topic1", topicId1);
Map<String, Uuid> topicIds1duplicate = Collections.singletonMap("topic1", topicId1);
Cluster cluster1 = new Cluster(clusterId1, Collections.singletonList(node1), partitions1, unauthorizedTopics1,
invalidTopics1, internalTopics1, controller1, topicIds1);
Cluster cluster1duplicate = new Cluster(clusterId1, Collections.singletonList(node1duplicate), partitions1duplicate,
unauthorizedTopics1, invalidTopics1, internalTopics1, controller1duplicate, topicIds1duplicate);
assertEquals(cluster1, cluster1duplicate);
}
}
|
ClusterTest
|
java
|
spring-projects__spring-boot
|
buildSrc/src/main/java/org/springframework/boot/build/antora/GenerateAntoraPlaybook.java
|
{
"start": 1940,
"end": 7655
}
|
class ____ extends DefaultTask {
private static final String GENERATED_DOCS = "build/generated/docs/";
private final Path root;
private final Provider<String> playbookOutputDir;
private final String version;
private final AntoraExtensions antoraExtensions;
private final AsciidocExtensions asciidocExtensions;
private final ContentSource contentSource;
@OutputFile
public abstract RegularFileProperty getOutputFile();
public GenerateAntoraPlaybook() {
this.root = toRealPath(getProject().getRootDir().toPath());
this.antoraExtensions = getProject().getObjects().newInstance(AntoraExtensions.class, this.root);
this.asciidocExtensions = getProject().getObjects().newInstance(AsciidocExtensions.class);
this.version = getProject().getVersion().toString();
this.playbookOutputDir = configurePlaybookOutputDir(getProject());
this.contentSource = getProject().getObjects().newInstance(ContentSource.class, this.root);
setGroup("Documentation");
setDescription("Generates an Antora playbook.yml file for local use");
getOutputFile().convention(getProject().getLayout()
.getBuildDirectory()
.file("generated/docs/antora-playbook/antora-playbook.yml"));
this.contentSource.addStartPath(getProject()
.provider(() -> getProject().getLayout().getProjectDirectory().dir(AntoraConventions.ANTORA_SOURCE_DIR)));
}
@Nested
public AntoraExtensions getAntoraExtensions() {
return this.antoraExtensions;
}
@Nested
public AsciidocExtensions getAsciidocExtensions() {
return this.asciidocExtensions;
}
@Nested
public ContentSource getContentSource() {
return this.contentSource;
}
private Provider<String> configurePlaybookOutputDir(Project project) {
Path siteDirectory = getProject().getLayout().getBuildDirectory().dir("site").get().getAsFile().toPath();
return project.provider(() -> {
Path playbookDir = toRealPath(getOutputFile().get().getAsFile().toPath()).getParent();
Path outputDir = toRealPath(siteDirectory);
return "." + File.separator + playbookDir.relativize(outputDir);
});
}
@TaskAction
public void writePlaybookYml() throws IOException {
File file = getOutputFile().get().getAsFile();
file.getParentFile().mkdirs();
try (FileWriter out = new FileWriter(file)) {
createYaml().dump(getData(), out);
}
}
private Map<String, Object> getData() throws IOException {
Map<String, Object> data = loadPlaybookTemplate();
addExtensions(data);
addSources(data);
addDir(data);
return data;
}
@SuppressWarnings("unchecked")
private Map<String, Object> loadPlaybookTemplate() throws IOException {
try (InputStream resource = getClass().getResourceAsStream("antora-playbook-template.yml")) {
return createYaml().loadAs(resource, LinkedHashMap.class);
}
}
@SuppressWarnings("unchecked")
private void addExtensions(Map<String, Object> data) {
Map<String, Object> antora = (Map<String, Object>) data.get("antora");
antora.put("extensions", Extensions.antora((extensions) -> {
extensions.xref(
(xref) -> xref.stub(this.antoraExtensions.getXref().getStubs().getOrElse(Collections.emptyList())));
extensions.zipContentsCollector((zipContentsCollector) -> {
zipContentsCollector.versionFile("gradle.properties");
zipContentsCollector.locations(this.antoraExtensions.getZipContentsCollector()
.getLocations()
.getOrElse(Collections.emptyList()));
zipContentsCollector
.alwaysInclude(this.antoraExtensions.getZipContentsCollector().getAlwaysInclude().getOrNull());
});
extensions.rootComponent((rootComponent) -> rootComponent.name("boot"));
}));
Map<String, Object> asciidoc = (Map<String, Object>) data.get("asciidoc");
List<String> asciidocExtensions = Extensions.asciidoc();
if (this.asciidocExtensions.getExcludeJavadocExtension().getOrElse(Boolean.FALSE)) {
asciidocExtensions = new ArrayList<>(asciidocExtensions);
asciidocExtensions.remove("@springio/asciidoctor-extensions/javadoc-extension");
}
asciidoc.put("extensions", asciidocExtensions);
}
private void addSources(Map<String, Object> data) {
List<Map<String, Object>> contentSources = getList(data, "content.sources");
contentSources.add(createContentSource());
}
private Map<String, Object> createContentSource() {
Map<String, Object> source = new LinkedHashMap<>();
Path playbookPath = getOutputFile().get().getAsFile().toPath().getParent();
StringBuilder url = new StringBuilder(".");
this.root.relativize(playbookPath).normalize().forEach((path) -> url.append(File.separator).append(".."));
source.put("url", url.toString());
source.put("branches", "HEAD");
source.put("version", this.version);
source.put("start_paths", this.contentSource.getStartPaths().get());
return source;
}
private void addDir(Map<String, Object> data) {
data.put("output", Map.of("dir", this.playbookOutputDir.get()));
}
@SuppressWarnings("unchecked")
private <T> List<T> getList(Map<String, Object> data, String location) {
return (List<T>) get(data, location);
}
@SuppressWarnings("unchecked")
private Object get(Map<String, Object> data, String location) {
Object result = data;
String[] keys = location.split("\\.");
for (String key : keys) {
result = ((Map<String, Object>) result).get(key);
}
return result;
}
private Yaml createYaml() {
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);
return new Yaml(options);
}
private static Path toRealPath(Path path) {
try {
return Files.exists(path) ? path.toRealPath() : path;
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public abstract static
|
GenerateAntoraPlaybook
|
java
|
alibaba__nacos
|
naming/src/test/java/com/alibaba/nacos/naming/core/v2/index/ClientServiceIndexesManagerTest.java
|
{
"start": 1579,
"end": 8807
}
|
class ____ {
private static final String NACOS = "nacos";
@Mock
private Service service;
@Mock
private ClientOperationEvent.ClientReleaseEvent clientReleaseEvent;
@Mock
private ClientOperationEvent clientOperationEvent;
@Mock
private Client client;
private ClientServiceIndexesManager clientServiceIndexesManager;
@BeforeEach
void setUp() throws NoSuchFieldException, IllegalAccessException {
clientServiceIndexesManager = new ClientServiceIndexesManager();
Class<ClientServiceIndexesManager> clientServiceIndexesManagerClass = ClientServiceIndexesManager.class;
Field publisherIndexesField = clientServiceIndexesManagerClass.getDeclaredField("publisherIndexes");
publisherIndexesField.setAccessible(true);
ConcurrentMap<Service, Set<String>> publisherIndexes = (ConcurrentMap<Service, Set<String>>) publisherIndexesField.get(
clientServiceIndexesManager);
publisherIndexes.put(service, new HashSet<>(Collections.singletonList(NACOS)));
Field subscriberIndexesField = clientServiceIndexesManagerClass.getDeclaredField("subscriberIndexes");
subscriberIndexesField.setAccessible(true);
ConcurrentMap<Service, Set<String>> subscriberIndexes = (ConcurrentMap<Service, Set<String>>) subscriberIndexesField.get(
clientServiceIndexesManager);
subscriberIndexes.put(service, new HashSet<>(Collections.singletonList(NACOS)));
}
@Test
void testGetAllClientsRegisteredService() {
Collection<String> allClientsRegisteredService = clientServiceIndexesManager.getAllClientsRegisteredService(service);
assertNotNull(allClientsRegisteredService);
assertEquals(1, allClientsRegisteredService.size());
}
@Test
void testGetAllClientsSubscribeService() {
Collection<String> allClientsSubscribeService = clientServiceIndexesManager.getAllClientsSubscribeService(service);
assertNotNull(allClientsSubscribeService);
assertEquals(1, allClientsSubscribeService.size());
}
@Test
void testGetSubscribedService() {
Collection<Service> subscribedService = clientServiceIndexesManager.getSubscribedService();
assertNotNull(subscribedService);
assertEquals(1, subscribedService.size());
}
@Test
void testRemovePublisherIndexesByEmptyService() throws NoSuchFieldException, IllegalAccessException {
clientServiceIndexesManager.removePublisherIndexesByEmptyService(service);
Class<ClientServiceIndexesManager> clientServiceIndexesManagerClass = ClientServiceIndexesManager.class;
Field publisherIndexesField = clientServiceIndexesManagerClass.getDeclaredField("publisherIndexes");
publisherIndexesField.setAccessible(true);
ConcurrentMap<Service, Set<String>> publisherIndexes = (ConcurrentMap<Service, Set<String>>) publisherIndexesField.get(
clientServiceIndexesManager);
assertEquals(1, publisherIndexes.size());
}
@Test
void testSubscribeTypes() {
List<Class<? extends Event>> classes = clientServiceIndexesManager.subscribeTypes();
assertNotNull(classes);
assertEquals(5, classes.size());
}
@Test
void testOnEvent() {
Mockito.when(clientReleaseEvent.getClient()).thenReturn(client);
clientServiceIndexesManager.onEvent(clientReleaseEvent);
Mockito.verify(clientReleaseEvent).getClient();
clientServiceIndexesManager.onEvent(clientOperationEvent);
Mockito.verify(clientOperationEvent).getService();
Mockito.verify(clientOperationEvent).getClientId();
}
@Test
void testAddPublisherIndexes() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String clientId = "clientId";
Class<ClientServiceIndexesManager> clientServiceIndexesManagerClass = ClientServiceIndexesManager.class;
Method addPublisherIndexes = clientServiceIndexesManagerClass.getDeclaredMethod("addPublisherIndexes", Service.class, String.class);
addPublisherIndexes.setAccessible(true);
addPublisherIndexes.invoke(clientServiceIndexesManager, service, clientId);
Collection<String> allClientsSubscribeService = clientServiceIndexesManager.getAllClientsRegisteredService(service);
assertNotNull(allClientsSubscribeService);
assertEquals(2, allClientsSubscribeService.size());
}
@Test
void testRemovePublisherIndexes() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String clientId = "clientId";
Class<ClientServiceIndexesManager> clientServiceIndexesManagerClass = ClientServiceIndexesManager.class;
Method removePublisherIndexes = clientServiceIndexesManagerClass.getDeclaredMethod("removePublisherIndexes", Service.class,
String.class);
removePublisherIndexes.setAccessible(true);
removePublisherIndexes.invoke(clientServiceIndexesManager, service, clientId);
Collection<String> allClientsSubscribeService = clientServiceIndexesManager.getAllClientsRegisteredService(service);
assertNotNull(allClientsSubscribeService);
assertEquals(1, allClientsSubscribeService.size());
}
@Test
void testAddSubscriberIndexes() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String clientId = "clientId";
Class<ClientServiceIndexesManager> clientServiceIndexesManagerClass = ClientServiceIndexesManager.class;
Method addSubscriberIndexes = clientServiceIndexesManagerClass.getDeclaredMethod("addSubscriberIndexes", Service.class,
String.class);
addSubscriberIndexes.setAccessible(true);
addSubscriberIndexes.invoke(clientServiceIndexesManager, service, clientId);
Collection<String> allClientsSubscribeService = clientServiceIndexesManager.getAllClientsSubscribeService(service);
assertNotNull(allClientsSubscribeService);
assertEquals(2, allClientsSubscribeService.size());
}
@Test
void testRemoveSubscriberIndexes() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
String clientId = "clientId";
Class<ClientServiceIndexesManager> clientServiceIndexesManagerClass = ClientServiceIndexesManager.class;
Method removeSubscriberIndexes = clientServiceIndexesManagerClass.getDeclaredMethod("removeSubscriberIndexes", Service.class,
String.class);
removeSubscriberIndexes.setAccessible(true);
removeSubscriberIndexes.invoke(clientServiceIndexesManager, service, clientId);
Collection<String> allClientsSubscribeService = clientServiceIndexesManager.getAllClientsSubscribeService(service);
assertNotNull(allClientsSubscribeService);
assertEquals(1, allClientsSubscribeService.size());
}
}
|
ClientServiceIndexesManagerTest
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/search/slice/TermsSliceQuery.java
|
{
"start": 1838,
"end": 3845
}
|
class ____ extends SliceQuery {
// Fixed seed for computing term hashCode
public static final int SEED = 7919;
public TermsSliceQuery(String field, int id, int max) {
super(field, id, max);
}
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
return new ConstantScoreWeight(this, boost) {
@Override
public ScorerSupplier scorerSupplier(LeafReaderContext context) throws IOException {
final DocIdSet disi = build(context.reader());
final DocIdSetIterator leafIt = disi.iterator();
Scorer scorer = new ConstantScoreScorer(score(), scoreMode, leafIt);
return new DefaultScorerSupplier(scorer);
}
@Override
public boolean isCacheable(LeafReaderContext ctx) {
return true;
}
};
}
/**
* Returns a DocIdSet per segments containing the matching docs for the specified slice.
*/
private DocIdSet build(LeafReader reader) throws IOException {
final DocIdSetBuilder builder = new DocIdSetBuilder(reader.maxDoc());
final Terms terms = reader.terms(getField());
if (terms == null) {
return DocIdSet.EMPTY;
}
final TermsEnum te = terms.iterator();
PostingsEnum docsEnum = null;
for (BytesRef term = te.next(); term != null; term = te.next()) {
// use a fixed seed instead of term.hashCode() otherwise this query may return inconsistent results when
// running on another replica (StringHelper sets its default seed at startup with current time)
int hashCode = StringHelper.murmurhash3_x86_32(term, SEED);
if (contains(hashCode)) {
docsEnum = te.postings(docsEnum, PostingsEnum.NONE);
builder.add(docsEnum);
}
}
return builder.build();
}
}
|
TermsSliceQuery
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/cluster/coordination/JoinReasonService.java
|
{
"start": 1493,
"end": 5959
}
|
class ____ {
private final LongSupplier relativeTimeInMillisSupplier;
// only used on cluster applier thread to detect changes, no need for synchronization, and deliberately an Object to remove temptation
// to use this field for other reasons
private Object discoveryNodes;
// keyed by persistent node ID to track nodes across restarts
private final Map<String, TrackedNode> trackedNodes = ConcurrentCollections.newConcurrentMap();
public JoinReasonService(LongSupplier relativeTimeInMillisSupplier) {
this.relativeTimeInMillisSupplier = relativeTimeInMillisSupplier;
}
/**
* Called when a new cluster state was applied by a master-eligible node, possibly adding or removing some nodes.
*/
public void onClusterStateApplied(DiscoveryNodes discoveryNodes) {
assert ThreadPool.assertCurrentThreadPool(ClusterApplierService.CLUSTER_UPDATE_THREAD_NAME);
assert discoveryNodes.getLocalNode().isMasterNode();
if (this.discoveryNodes != discoveryNodes) {
this.discoveryNodes = discoveryNodes;
final Set<String> absentNodeIds = new HashSet<>(trackedNodes.keySet());
for (final DiscoveryNode discoveryNode : discoveryNodes) {
trackedNodes.compute(
discoveryNode.getId(),
(ignored, trackedNode) -> (trackedNode == null ? UNKNOWN_NODE : trackedNode).present(discoveryNode.getEphemeralId())
);
absentNodeIds.remove(discoveryNode.getId());
}
final long currentTimeMillis = relativeTimeInMillisSupplier.getAsLong();
for (final String absentNodeId : absentNodeIds) {
trackedNodes.computeIfPresent(
absentNodeId,
(ignored, trackedNode) -> trackedNode.absent(currentTimeMillis, discoveryNodes.getMasterNode())
);
}
if (absentNodeIds.size() > 2 * discoveryNodes.getSize()) {
final List<Tuple<Long, String>> absentNodes = new ArrayList<>(absentNodeIds.size());
for (Map.Entry<String, TrackedNode> trackedNodesEntry : trackedNodes.entrySet()) {
final long removalAgeMillis = trackedNodesEntry.getValue().getRemovalAgeMillis(currentTimeMillis);
if (removalAgeMillis != NOT_REMOVED) {
absentNodes.add(Tuple.tuple(removalAgeMillis, trackedNodesEntry.getKey()));
}
}
absentNodes.sort(Comparator.comparing(Tuple::v1));
for (int i = discoveryNodes.getSize(); i < absentNodes.size(); i++) {
trackedNodes.remove(absentNodes.get(i).v2());
}
}
assert trackedNodes.size() <= discoveryNodes.getSize() * 3;
}
}
/**
* Called on the master when a {@code node-left} task completes successfully and after the resulting cluster state is applied. If the
* absent node is still tracked then this adds the removal reason ({@code disconnected}, {@code lagging}, etc.) to the tracker.
*/
public void onNodeRemoved(DiscoveryNode discoveryNode, String reason) {
assert MasterService.assertMasterUpdateOrTestThread();
trackedNodes.computeIfPresent(discoveryNode.getId(), (ignored, trackedNode) -> trackedNode.withRemovalReason(reason));
}
/**
* @param discoveryNode The joining node.
* @param currentMode The current mode of the master that the node is joining.
* @return A description of the reason for the join, possibly including some details of its earlier removal.
*/
public JoinReason getJoinReason(DiscoveryNode discoveryNode, Coordinator.Mode currentMode) {
return trackedNodes.getOrDefault(discoveryNode.getId(), UNKNOWN_NODE)
.getJoinReason(relativeTimeInMillisSupplier.getAsLong(), discoveryNode.getEphemeralId(), currentMode);
}
/**
* Get the name of the node and do something reasonable if the node is missing or has no name.
*/
private static String getNodeNameSafe(@Nullable DiscoveryNode discoveryNode) {
if (discoveryNode == null) {
return "_unknown_";
}
final String name = discoveryNode.getName();
if (Strings.hasText(name)) {
return name;
}
return discoveryNode.getId();
}
private
|
JoinReasonService
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ValidatorEndpointBuilderFactory.java
|
{
"start": 1450,
"end": 1579
}
|
interface ____ {
/**
* Builder for endpoint for the Validator component.
*/
public
|
ValidatorEndpointBuilderFactory
|
java
|
apache__flink
|
flink-table/flink-table-api-java/src/test/java/org/apache/flink/table/test/program/TableApiTestStep.java
|
{
"start": 3925,
"end": 4032
}
|
interface ____ starting a {@link Table}. It abstracts away the {@link TableEnvironment}.
*/
public
|
for
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3ABlockOutputStream.java
|
{
"start": 45379,
"end": 47424
}
|
class ____ {
private final S3ADataBlocks.DataBlock block;
private final ProgressListener nextListener;
private final Instant transferQueueTime;
private Instant transferStartTime;
private long size;
/**
* Track the progress of a single block upload.
* @param block block to monitor
* @param transferQueueTime time the block was transferred
* into the queue
*/
private BlockUploadProgress(S3ADataBlocks.DataBlock block,
ProgressListener nextListener,
Instant transferQueueTime) {
this.block = block;
this.transferQueueTime = transferQueueTime;
this.size = block.dataSize();
this.nextListener = nextListener;
this.transferStartTime = now(); // will be updated when progress is made
}
public void progressChanged(ProgressListenerEvent eventType) {
switch (eventType) {
case PUT_STARTED_EVENT:
case TRANSFER_PART_STARTED_EVENT:
transferStartTime = now();
statistics.blockUploadStarted(
Duration.between(transferQueueTime, transferStartTime),
size);
incrementWriteOperations();
break;
case TRANSFER_PART_COMPLETED_EVENT:
case PUT_COMPLETED_EVENT:
statistics.blockUploadCompleted(
Duration.between(transferStartTime, now()),
size);
statistics.bytesTransferred(size);
break;
case TRANSFER_PART_FAILED_EVENT:
case PUT_FAILED_EVENT:
case PUT_INTERRUPTED_EVENT:
statistics.blockUploadFailed(
Duration.between(transferStartTime, now()),
size);
LOG.warn("Transfer failure of block {}", block);
break;
default:
// nothing
}
if (nextListener != null) {
nextListener.progressChanged(eventType, size);
}
}
}
/**
* Bridge from {@link ProgressListener} to Hadoop {@link Progressable}.
* All progress events invoke {@link Progressable#progress()}.
*/
private static final
|
BlockUploadProgress
|
java
|
mybatis__mybatis-3
|
src/main/java/org/apache/ibatis/reflection/wrapper/DefaultObjectWrapperFactory.java
|
{
"start": 843,
"end": 1222
}
|
class ____ implements ObjectWrapperFactory {
@Override
public boolean hasWrapperFor(Object object) {
return false;
}
@Override
public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
throw new ReflectionException(
"The DefaultObjectWrapperFactory should never be called to provide an ObjectWrapper.");
}
}
|
DefaultObjectWrapperFactory
|
java
|
apache__flink
|
flink-table/flink-sql-parser/src/main/java/org/apache/flink/sql/parser/ddl/SqlCreateTable.java
|
{
"start": 2001,
"end": 7865
}
|
class ____ extends SqlCreateObject implements ExtendedSqlNode {
private static final SqlSpecialOperator OPERATOR =
new SqlSpecialOperator("CREATE TABLE", SqlKind.CREATE_TABLE);
private final SqlNodeList columnList;
private final List<SqlTableConstraint> tableConstraints;
private final SqlDistribution distribution;
protected final SqlNodeList partitionKeyList;
private final SqlWatermark watermark;
public SqlCreateTable(
SqlParserPos pos,
SqlIdentifier tableName,
SqlNodeList columnList,
List<SqlTableConstraint> tableConstraints,
SqlNodeList propertyList,
SqlDistribution distribution,
SqlNodeList partitionKeyList,
@Nullable SqlWatermark watermark,
@Nullable SqlCharStringLiteral comment,
boolean isTemporary,
boolean ifNotExists) {
this(
OPERATOR,
pos,
tableName,
columnList,
tableConstraints,
propertyList,
distribution,
partitionKeyList,
watermark,
comment,
isTemporary,
ifNotExists,
false);
}
protected SqlCreateTable(
SqlSpecialOperator operator,
SqlParserPos pos,
SqlIdentifier tableName,
SqlNodeList columnList,
List<SqlTableConstraint> tableConstraints,
SqlNodeList propertyList,
@Nullable SqlDistribution distribution,
SqlNodeList partitionKeyList,
@Nullable SqlWatermark watermark,
@Nullable SqlCharStringLiteral comment,
boolean isTemporary,
boolean ifNotExists,
boolean replace) {
super(operator, pos, tableName, isTemporary, replace, ifNotExists, propertyList, comment);
this.columnList = requireNonNull(columnList, "columnList should not be null");
this.tableConstraints =
requireNonNull(tableConstraints, "table constraints should not be null");
requireNonNull(propertyList, "propertyList should not be null");
this.distribution = distribution;
this.partitionKeyList =
requireNonNull(partitionKeyList, "partitionKeyList should not be null");
this.watermark = watermark;
}
@Override
public @Nonnull List<SqlNode> getOperandList() {
return ImmutableNullableList.of(
name,
columnList,
new SqlNodeList(tableConstraints, SqlParserPos.ZERO),
properties,
partitionKeyList,
watermark,
comment);
}
public SqlNodeList getColumnList() {
return columnList;
}
public final SqlDistribution getDistribution() {
return distribution;
}
public List<String> getPartitionKeyList() {
return SqlParseUtils.extractList(partitionKeyList);
}
public List<SqlTableConstraint> getTableConstraints() {
return tableConstraints;
}
public Optional<SqlWatermark> getWatermark() {
return Optional.ofNullable(watermark);
}
@Override
protected String getScope() {
return "TABLE";
}
@Override
public void validate() throws SqlValidateException {
SqlConstraintValidator.validateAndChangeColumnNullability(tableConstraints, columnList);
}
/** Returns the column constraints plus the table constraints. */
public List<SqlTableConstraint> getFullConstraints() {
return SqlConstraintValidator.getFullConstraints(tableConstraints, columnList);
}
/**
* Returns the projection format of the DDL columns(including computed columns). i.e. the
* following DDL:
*
* <pre>
* create table tbl1(
* col1 int,
* col2 varchar,
* col3 as to_timestamp(col2)
* ) with (
* 'connector' = 'csv'
* )
* </pre>
*
* <p>is equivalent with query "col1, col2, to_timestamp(col2) as col3", caution that the
* "computed column" operands have been reversed.
*/
public String getColumnSqlString() {
SqlPrettyWriter writer =
new SqlPrettyWriter(
SqlPrettyWriter.config()
.withDialect(AnsiSqlDialect.DEFAULT)
.withAlwaysUseParentheses(true)
.withSelectListItemsOnSeparateLines(false)
.withIndentation(0));
writer.startList("", "");
for (SqlNode column : columnList) {
writer.sep(",");
SqlTableColumn tableColumn = (SqlTableColumn) column;
if (tableColumn instanceof SqlComputedColumn) {
SqlComputedColumn computedColumn = (SqlComputedColumn) tableColumn;
computedColumn.getExpr().unparse(writer, 0, 0);
writer.keyword("AS");
}
tableColumn.getName().unparse(writer, 0, 0);
}
return writer.toString();
}
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
unparseCreateIfNotExists(writer, leftPrec, rightPrec);
SqlUnparseUtils.unparseTableSchema(
columnList, tableConstraints, watermark, writer, leftPrec, rightPrec);
SqlUnparseUtils.unparseComment(comment, true, writer, leftPrec, rightPrec);
SqlUnparseUtils.unparseDistribution(distribution, writer, leftPrec, rightPrec);
SqlUnparseUtils.unparsePartitionKeyList(partitionKeyList, writer, leftPrec, rightPrec);
SqlUnparseUtils.unparseProperties(properties, writer, leftPrec, rightPrec);
}
}
|
SqlCreateTable
|
java
|
apache__flink
|
flink-walkthroughs/flink-walkthrough-common/src/main/java/org/apache/flink/walkthrough/common/sink/LoggerOutputFormat.java
|
{
"start": 1152,
"end": 1631
}
|
class ____ implements OutputFormat<String> {
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(LoggerOutputFormat.class);
@Override
public void configure(Configuration parameters) {}
@Override
public void open(InitializationContext context) {}
@Override
public void writeRecord(String record) {
LOG.info(record);
}
@Override
public void close() {}
}
|
LoggerOutputFormat
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/internal/Float2DArrays.java
|
{
"start": 830,
"end": 6127
}
|
class ____ {
private static final Float2DArrays INSTANCE = new Float2DArrays();
/**
* Returns the singleton instance of this class.
* @return the singleton instance of this class.
*/
public static Float2DArrays instance() {
return INSTANCE;
}
private Arrays2D arrays = Arrays2D.instance();
// TODO reduce the visibility of the fields annotated with @VisibleForTesting
Failures failures = Failures.instance();
// TODO reduce the visibility of the fields annotated with @VisibleForTesting
public void setArrays(Arrays2D arrays) {
this.arrays = arrays;
}
/**
* Asserts that the given array is {@code null} or empty.
* @param info contains information about the assertion.
* @param actual the given array.
* @throws AssertionError if the given array is not {@code null} *and* contains one or more elements.
*/
public void assertNullOrEmpty(AssertionInfo info, float[][] actual) {
arrays.assertNullOrEmpty(info, failures, actual);
}
/**
* Asserts that the given array is empty.
* @param info contains information about the assertion.
* @param actual the given array.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array is not empty.
*/
public void assertEmpty(AssertionInfo info, float[][] actual) {
arrays.assertEmpty(info, failures, actual);
}
/**
* Asserts that the given array is not empty.
* @param info contains information about the assertion.
* @param actual the given array.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the given array is empty.
*/
public void assertNotEmpty(AssertionInfo info, float[][] actual) {
arrays.assertNotEmpty(info, failures, actual);
}
/**
* Asserts that the number of elements in the given array is equal to the expected one.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param expectedFirstDimension the expected first dimension size of {@code actual}.
* @param expectedSecondDimension the expected second dimension size of {@code actual}.
* @throws AssertionError if the given array is {@code null}.
* @throws AssertionError if the actual array's dimensions are not equal to the given ones.
*/
public void assertHasDimensions(AssertionInfo info, float[][] actual, int expectedFirstDimension,
int expectedSecondDimension) {
arrays.assertHasDimensions(info, failures, actual, expectedFirstDimension, expectedSecondDimension);
}
/**
* Assert that the actual array has the same dimensions as the other array.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param other the group to compare
* @throws AssertionError if the actual group is {@code null}.
* @throws AssertionError if the other group is {@code null}.
* @throws AssertionError if the actual group does not have the same dimension.
*/
public void assertHasSameDimensionsAs(AssertionInfo info, float[][] actual, Object other) {
arrays.assertHasSameDimensionsAs(info, actual, other);
}
/**
* Asserts that the number of rows in the given array is equal to the expected one.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param expectedNumberOfRows the expected first dimension size of {@code actual}.
*/
public void assertNumberOfRows(AssertionInfo info, float[][] actual, int expectedNumberOfRows) {
arrays.assertNumberOfRows(info, failures, actual, expectedNumberOfRows);
}
/**
* Verifies that the given array contains the given value at the given index.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param value the value to look for.
* @param index the index where the value should be stored in the given array.
* @throws AssertionError if the given array is {@code null} or empty.
* @throws NullPointerException if the given {@code Index} is {@code null}.
* @throws IndexOutOfBoundsException if the value of the given {@code Index} is equal to or greater than the size of the given
* array.
* @throws AssertionError if the given array does not contain the given value at the given index.
*/
public void assertContains(AssertionInfo info, float[][] actual, float[] value, Index index) {
arrays.assertContains(info, failures, actual, value, index);
}
/**
* Verifies that the given array does not contain the given value at the given index.
*
* @param info contains information about the assertion.
* @param actual the given array.
* @param value the value to look for.
* @param index the index where the value should be stored in the given array.
* @throws AssertionError if the given array is {@code null}.
* @throws NullPointerException if the given {@code Index} is {@code null}.
* @throws AssertionError if the given array contains the given value at the given index.
*/
public void assertDoesNotContain(AssertionInfo info, float[][] actual, float[] value, Index index) {
arrays.assertDoesNotContain(info, failures, actual, value, index);
}
}
|
Float2DArrays
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsRepeatableAnnotationTests.java
|
{
"start": 16992,
"end": 17220
}
|
interface ____ {
RepeatableWithContainerWithMultipleAttributes[] value();
String name() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(ContainerWithMultipleAttributes.class)
@
|
ContainerWithMultipleAttributes
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/cluster/node/DiscoveryNodeFilters.java
|
{
"start": 919,
"end": 1174
}
|
class ____ {
public static final Set<String> SINGLE_NODE_NAMES = Set.of("_id", "_name", "name");
static final Set<String> NON_ATTRIBUTE_NAMES = Set.of("_ip", "_host_ip", "_publish_ip", "host", "_id", "_name", "name");
public
|
DiscoveryNodeFilters
|
java
|
spring-projects__spring-boot
|
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/env/EnvironmentEndpointTests.java
|
{
"start": 18987,
"end": 19190
}
|
class ____ {
@Bean
EnvironmentEndpoint environmentEndpoint(Environment environment) {
return new EnvironmentEndpoint(environment, Collections.emptyList(), Show.ALWAYS);
}
}
public static
|
Config
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/collection/StringSetEntity.java
|
{
"start": 467,
"end": 1351
}
|
class ____ {
@Id
@GeneratedValue
private Integer id;
@Audited
@ElementCollection
private Set<String> strings;
public StringSetEntity() {
strings = new HashSet<String>();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Set<String> getStrings() {
return strings;
}
public void setStrings(Set<String> strings) {
this.strings = strings;
}
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof StringSetEntity) ) {
return false;
}
StringSetEntity that = (StringSetEntity) o;
if ( id != null ? !id.equals( that.id ) : that.id != null ) {
return false;
}
return true;
}
public int hashCode() {
return (id != null ? id.hashCode() : 0);
}
public String toString() {
return "SSE(id = " + id + ", strings = " + strings + ")";
}
}
|
StringSetEntity
|
java
|
spring-cloud__spring-cloud-gateway
|
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/support/ServerWebExchangeUtilsTests.java
|
{
"start": 2097,
"end": 5759
}
|
class ____ {
@Test
public void expandWorks() {
HashMap<String, String> vars = new HashMap<>();
vars.put("foo", "bar");
vars.put("baz", "bam");
MockServerWebExchange exchange = mockExchange(vars);
String expanded = expand(exchange, "my-{foo}-{baz}");
assertThat(expanded).isEqualTo("my-bar-bam");
expanded = expand(exchange, "my-noop");
assertThat(expanded).isEqualTo("my-noop");
}
@Test
public void missingVarThrowsException() {
MockServerWebExchange exchange = mockExchange(Collections.emptyMap());
Assertions.assertThatThrownBy(() -> expand(exchange, "my-{foo}-{baz}"))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void defaultDataBufferHandling() {
MockServerWebExchange exchange = mockExchange(Collections.emptyMap());
exchange.getAttributes().put(CACHED_REQUEST_BODY_ATTR, "foo");
ServerWebExchangeUtils
.cacheRequestBodyAndRequest(exchange,
(serverHttpRequest) -> ServerRequest.create(exchange.mutate().request(serverHttpRequest).build(),
HandlerStrategies.withDefaults().messageReaders())
.bodyToMono(DefaultDataBuffer.class))
.block();
}
@Test
public void duplicatedCachingDataBufferHandling() {
MockServerWebExchange exchange = mockExchange(HttpMethod.POST, Collections.emptyMap());
DataBuffer dataBufferBeforeCaching = exchange.getResponse()
.bufferFactory()
.wrap("Cached buffer".getBytes(StandardCharsets.UTF_8));
exchange.getAttributes().put(CACHED_REQUEST_BODY_ATTR, dataBufferBeforeCaching);
ServerWebExchangeUtils
.cacheRequestBodyAndRequest(exchange,
(serverHttpRequest) -> ServerRequest.create(exchange.mutate().request(serverHttpRequest).build(),
HandlerStrategies.withDefaults().messageReaders())
.bodyToMono(DefaultDataBuffer.class))
.block();
DataBuffer dataBufferAfterCached = exchange.getAttribute(CACHED_REQUEST_BODY_ATTR);
Assertions.assertThat(dataBufferBeforeCaching).isEqualTo(dataBufferAfterCached);
}
@Test
public void forwardedRequestsHaveDisruptiveAttributesAndHeadersRemoved() {
DispatcherHandler handler = Mockito.mock(DispatcherHandler.class);
Mockito.when(handler.handle(any(ServerWebExchange.class))).thenReturn(Mono.empty());
ServerWebExchange originalExchange = mockExchange(Map.of()).mutate()
.request(request -> request.headers(headers -> headers.setOrigin("https://example.com")))
.build();
originalExchange.getAttributes().put(GATEWAY_PREDICATE_PATH_CONTAINER_ATTR, parsePath("/example/path"));
ServerWebExchangeUtils.handle(handler, originalExchange).block();
Mockito.verify(handler).handle(assertArg(exchange -> {
Assertions.assertThat(exchange.getAttributes())
.as("exchange attributes")
.doesNotContainKey(GATEWAY_PREDICATE_PATH_CONTAINER_ATTR);
Assertions.assertThat(exchange.getRequest().getHeaders().headerNames())
.as("request headers")
.doesNotContain(HttpHeaders.ORIGIN);
}));
}
private MockServerWebExchange mockExchange(Map<String, String> vars) {
return mockExchange(HttpMethod.GET, vars);
}
private MockServerWebExchange mockExchange(HttpMethod method, Map<String, String> vars) {
MockServerHttpRequest request = null;
if (HttpMethod.GET.equals(method)) {
request = MockServerHttpRequest.get("/get").build();
}
else if (HttpMethod.POST.equals(method)) {
request = MockServerHttpRequest.post("/post").body("post body");
}
Assertions.assertThat(request).as("Method was not one of GET or POST").isNotNull();
MockServerWebExchange exchange = MockServerWebExchange.from(request);
ServerWebExchangeUtils.putUriTemplateVariables(exchange, vars);
return exchange;
}
}
|
ServerWebExchangeUtilsTests
|
java
|
elastic__elasticsearch
|
x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/integration/DataStreamLifecycleServiceRuntimeSecurityIT.java
|
{
"start": 3732,
"end": 17164
}
|
class ____ extends SecurityIntegTestCase {
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return List.of(
LocalStateSecurity.class,
DataStreamsPlugin.class,
SystemDataStreamTestPlugin.class,
MapperExtrasPlugin.class,
Wildcard.class
);
}
@Override
protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) {
Settings.Builder settings = Settings.builder().put(super.nodeSettings(nodeOrdinal, otherSettings));
settings.put(DataStreamLifecycleService.DATA_STREAM_LIFECYCLE_POLL_INTERVAL, "1s");
settings.put(DataStreamLifecycle.CLUSTER_LIFECYCLE_DEFAULT_ROLLOVER_SETTING.getKey(), "min_docs=1,max_docs=1");
return settings.build();
}
public void testRolloverLifecycleAndForceMergeAuthorized() throws Exception {
String dataStreamName = randomDataStreamName();
// with failure store and empty lifecycle contains the default rollover
prepareDataStreamAndIndex(dataStreamName, null);
List<String> backingIndices = waitForDataStreamBackingIndices(dataStreamName, 2);
String backingIndex = backingIndices.get(0);
assertThat(backingIndex, backingIndexEqualTo(dataStreamName, 1));
String writeIndex = backingIndices.get(1);
assertThat(writeIndex, backingIndexEqualTo(dataStreamName, 2));
// initialise the failure store
indexFailedDoc(dataStreamName);
List<String> failureIndices = waitForDataStreamIndices(dataStreamName, 2, true);
String firstFailureIndex = failureIndices.get(0);
assertThat(firstFailureIndex, dataStreamIndexEqualTo(dataStreamName, 3, true));
String secondFailureIndexGen = failureIndices.get(1);
assertThat(secondFailureIndexGen, dataStreamIndexEqualTo(dataStreamName, 4, true));
assertNoAuthzErrors();
// Index another doc to force another rollover and trigger an attempted force-merge. The force-merge may be a noop under
// the hood but for authz purposes this doesn't matter, it only matters that the force-merge API was called
indexDoc(dataStreamName);
waitForDataStreamBackingIndices(dataStreamName, 3);
assertNoAuthzErrors();
}
public void testRolloverAndRetentionAuthorized() throws Exception {
String dataStreamName = randomDataStreamName();
prepareDataStreamAndIndex(dataStreamName, TimeValue.ZERO);
assertBusy(() -> {
assertNoAuthzErrors();
List<Index> backingIndices = getDataStreamBackingIndices(dataStreamName);
assertThat(backingIndices.size(), equalTo(1));
// we expect the data stream to have only one backing index, the write one, with generation 2
// as generation 1 would've been deleted by the data stream lifecycle given the lifecycle configuration
String writeIndex = backingIndices.get(0).getName();
assertThat(writeIndex, backingIndexEqualTo(dataStreamName, 2));
});
// test failure store too, we index the failure later to have predictable generation suffixes
indexFailedDoc(dataStreamName);
assertBusy(() -> {
assertNoAuthzErrors();
List<String> failureIndices = getDataStreamBackingIndexNames(dataStreamName, true);
assertThat(failureIndices.size(), equalTo(1));
// we expect the data stream to have only one failure index, with generation 4
// as generation 3 would've been deleted by the data stream lifecycle given the lifecycle configuration
String writeIndex = failureIndices.get(0);
assertThat(writeIndex, dataStreamIndexEqualTo(dataStreamName, 4, true));
});
}
public void testUnauthorized() throws Exception {
// this is an example index pattern for a system index that the data stream lifecycle does not have access for. Data stream
// lifecycle will therefore fail at runtime with an authz exception
prepareDataStreamAndIndex(SECURITY_MAIN_ALIAS, null);
indexFailedDoc(SECURITY_MAIN_ALIAS);
assertBusy(() -> {
Map<String, String> indicesAndErrors = collectErrorsFromStoreAsMap();
// Both the backing and failures indices should have errors
assertThat(indicesAndErrors.size(), is(2));
for (String index : indicesAndErrors.keySet()) {
assertThat(index, anyOf(containsString(DataStream.BACKING_INDEX_PREFIX), containsString(DataStream.FAILURE_STORE_PREFIX)));
}
assertThat(
indicesAndErrors.values(),
hasItem(allOf(containsString("security_exception"), containsString("unauthorized for user [_data_stream_lifecycle]")))
);
});
}
public void testRolloverAndRetentionWithSystemDataStreamAuthorized() throws Exception {
String dataStreamName = SystemDataStreamTestPlugin.SYSTEM_DATA_STREAM_NAME;
indexDoc(dataStreamName);
assertBusy(() -> {
assertNoAuthzErrors();
List<Index> backingIndices = getDataStreamBackingIndices(dataStreamName);
assertThat(backingIndices.size(), equalTo(1));
// we expect the data stream to have only one backing index, the write one, with generation 2
// as generation 1 would've been deleted by the data stream lifecycle given the lifecycle configuration
String writeIndex = backingIndices.get(0).getName();
assertThat(writeIndex, backingIndexEqualTo(dataStreamName, 2));
});
// test failure store too, we index the failure later to have predictable generation suffixes
indexFailedDoc(dataStreamName);
assertBusy(() -> {
assertNoAuthzErrors();
List<String> failureIndices = getDataStreamBackingIndexNames(dataStreamName, true);
assertThat(failureIndices.size(), equalTo(1));
// we expect the data stream to have only one backing index, the write one, with generation 2
// as generation 1 would've been deleted by the data stream lifecycle given the lifecycle configuration
String writeIndex = failureIndices.get(0);
assertThat(writeIndex, dataStreamIndexEqualTo(dataStreamName, 4, true));
});
}
private static String randomDataStreamName() {
// lower-case since this is required for a valid data stream name
return randomAlphaOfLengthBetween(5, 10).toLowerCase(Locale.ROOT);
}
private Map<String, String> collectErrorsFromStoreAsMap() {
Iterable<DataStreamLifecycleService> lifecycleServices = internalCluster().getInstances(DataStreamLifecycleService.class);
Map<String, String> indicesAndErrors = new HashMap<>();
for (DataStreamLifecycleService lifecycleService : lifecycleServices) {
DataStreamLifecycleErrorStore errorStore = lifecycleService.getErrorStore();
Set<String> allIndices = errorStore.getAllIndices(Metadata.DEFAULT_PROJECT_ID);
for (var index : allIndices) {
ErrorEntry error = errorStore.getError(Metadata.DEFAULT_PROJECT_ID, index);
if (error != null) {
indicesAndErrors.put(index, error.error());
}
}
}
return indicesAndErrors;
}
private void prepareDataStreamAndIndex(String dataStreamName, TimeValue retention) throws IOException, InterruptedException,
ExecutionException {
var dataLifecycle = retention == null
? DataStreamLifecycle.Template.DATA_DEFAULT
: DataStreamLifecycle.dataLifecycleBuilder().enabled(true).dataRetention(retention).buildTemplate();
var failuresLifecycle = retention == null ? null : DataStreamLifecycle.createFailuresLifecycleTemplate(true, retention);
putComposableIndexTemplate("id1", """
{
"properties": {
"@timestamp" : {
"type": "date"
},
"count": {
"type": "long"
}
}
}""", List.of(dataStreamName + "*"), null, null, dataLifecycle, failuresLifecycle);
CreateDataStreamAction.Request createDataStreamRequest = new CreateDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
TEST_REQUEST_TIMEOUT,
dataStreamName
);
client().execute(CreateDataStreamAction.INSTANCE, createDataStreamRequest).get();
indexDoc(dataStreamName);
}
private List<Index> getDataStreamBackingIndices(String dataStreamName) {
GetDataStreamAction.Request getDataStreamRequest = new GetDataStreamAction.Request(
TEST_REQUEST_TIMEOUT,
new String[] { dataStreamName }
);
GetDataStreamAction.Response getDataStreamResponse = client().execute(GetDataStreamAction.INSTANCE, getDataStreamRequest)
.actionGet();
assertThat(getDataStreamResponse.getDataStreams().size(), equalTo(1));
assertThat(getDataStreamResponse.getDataStreams().get(0).getDataStream().getName(), equalTo(dataStreamName));
return getDataStreamResponse.getDataStreams().get(0).getDataStream().getIndices();
}
private void assertNoAuthzErrors() {
var indicesAndErrors = collectErrorsFromStoreAsMap();
for (var entry : indicesAndErrors.entrySet()) {
assertThat(
"unexpected authz error for index [" + entry.getKey() + "] with error message [" + entry.getValue() + "]",
entry.getValue(),
not(anyOf(containsString("security_exception"), containsString("unauthorized for user [_data_stream_lifecycle]")))
);
}
}
private static void putComposableIndexTemplate(
String id,
@Nullable String mappings,
List<String> patterns,
@Nullable Settings settings,
@Nullable Map<String, Object> metadata,
@Nullable DataStreamLifecycle.Template dataLifecycle,
@Nullable DataStreamLifecycle.Template failuresLifecycle
) throws IOException {
TransportPutComposableIndexTemplateAction.Request request = new TransportPutComposableIndexTemplateAction.Request(id);
request.indexTemplate(
ComposableIndexTemplate.builder()
.indexPatterns(patterns)
.template(
Template.builder()
.settings(settings)
.mappings(mappings == null ? null : CompressedXContent.fromJSON(mappings))
.lifecycle(dataLifecycle)
.dataStreamOptions(new DataStreamOptions.Template(new DataStreamFailureStore.Template(true, failuresLifecycle)))
)
.metadata(metadata)
.dataStreamTemplate(new ComposableIndexTemplate.DataStreamTemplate())
.build()
);
client().execute(TransportPutComposableIndexTemplateAction.TYPE, request).actionGet();
}
private static void indexDoc(String dataStream) {
BulkRequest bulkRequest = new BulkRequest();
String value = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.formatMillis(System.currentTimeMillis());
bulkRequest.add(
new IndexRequest(dataStream).opType(DocWriteRequest.OpType.CREATE)
.source(String.format(Locale.ROOT, "{\"%s\":\"%s\"}", DEFAULT_TIMESTAMP_FIELD, value), XContentType.JSON)
);
BulkResponse bulkResponse = client().bulk(bulkRequest).actionGet();
assertThat(bulkResponse.getItems().length, equalTo(1));
String backingIndexPrefix = DataStream.BACKING_INDEX_PREFIX + dataStream;
for (BulkItemResponse itemResponse : bulkResponse) {
assertThat(itemResponse.getFailureMessage(), nullValue());
assertThat(itemResponse.status(), equalTo(RestStatus.CREATED));
assertThat(itemResponse.getIndex(), startsWith(backingIndexPrefix));
}
indicesAdmin().refresh(new RefreshRequest(dataStream)).actionGet();
}
private static void indexFailedDoc(String dataStream) {
BulkRequest bulkRequest = new BulkRequest();
String value = DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.formatMillis(System.currentTimeMillis());
bulkRequest.add(
new IndexRequest(dataStream).opType(DocWriteRequest.OpType.CREATE)
.source(
String.format(Locale.ROOT, "{\"%s\":\"%s\",\"count\":\"not-a-number\"}", DEFAULT_TIMESTAMP_FIELD, value),
XContentType.JSON
)
);
BulkResponse bulkResponse = client().bulk(bulkRequest).actionGet();
assertThat(bulkResponse.getItems().length, equalTo(1));
String backingIndexPrefix = DataStream.FAILURE_STORE_PREFIX + dataStream;
for (BulkItemResponse itemResponse : bulkResponse) {
assertThat(itemResponse.getFailureMessage(), nullValue());
assertThat(itemResponse.status(), equalTo(RestStatus.CREATED));
assertThat(itemResponse.getIndex(), startsWith(backingIndexPrefix));
}
indicesAdmin().refresh(new RefreshRequest(dataStream)).actionGet();
}
public static
|
DataStreamLifecycleServiceRuntimeSecurityIT
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerRedundantIsEnabledTest.java
|
{
"start": 1569,
"end": 5445
}
|
class ____ {
public void basicCase(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atInfo().isEnabled()) {
logger.atInfo().log("test");
}
}
public void nestedIf(FluentLogger logger) {
if (7 == 7) {
// BUG: Diagnostic contains: redundant
if (logger.atInfo().isEnabled()) {
logger.atInfo().log("test");
}
}
}
public void checkBinaryInIf(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (7 == 7 && logger.atInfo().isEnabled()) {
logger.atInfo().log("test");
}
}
public void checkBinaryOtherWay(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atInfo().isEnabled() && 7 == 7) {
logger.atInfo().log("test");
}
}
public void complexBinary(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (7 == 7 && (logger != null && logger.atInfo().isEnabled())) {
logger.atInfo().log("test");
}
}
public void negated(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (!logger.atInfo().isEnabled()) {
logger.atInfo().log("test");
}
}
public void binaryNegated(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (!logger.atInfo().isEnabled() && 7 == 7) {
logger.atInfo().log("test");
}
}
public void checkConfig(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atConfig().isEnabled()) {
logger.atConfig().log("test");
}
}
public void checkFine(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atFine().isEnabled()) {
logger.atFine().log("test");
}
}
public void checkFiner(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atFiner().isEnabled()) {
logger.atFiner().log("test");
}
}
public void checkFinest(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atFinest().isEnabled()) {
logger.atFinest().log("test");
}
}
public void checkWarning(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atWarning().isEnabled()) {
logger.atWarning().log("test");
}
}
public void checkSevere(FluentLogger logger) {
// BUG: Diagnostic contains: redundant
if (logger.atSevere().isEnabled()) {
logger.atSevere().log("test");
}
}
}\
""")
.doTest();
}
@Test
public void doNegativeCases() {
compilationTestHelper
.addSourceLines(
"FloggerRedundantIsEnabledNegativeCases.java",
"""
package com.google.errorprone.bugpatterns.flogger.testdata;
import com.google.common.flogger.FluentLogger;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @author mariasam@google.com (Maria Sam)
*/
public
|
FloggerRedundantIsEnabledPositiveCases
|
java
|
spring-projects__spring-security
|
kerberos/kerberos-core/src/test/java/org/springframework/security/kerberos/authentication/KerberosAuthenticationProviderTests.java
|
{
"start": 1457,
"end": 1558
}
|
class ____ {@link KerberosAuthenticationProvider}
*
* @author Mike Wiesner
* @since 1.0
*/
public
|
for
|
java
|
apache__flink
|
flink-python/src/main/java/org/apache/flink/streaming/runtime/translators/python/PythonKeyedBroadcastStateTransformationTranslator.java
|
{
"start": 2561,
"end": 6854
}
|
class ____<OUT>
extends AbstractTwoInputTransformationTranslator<
Row, Row, OUT, PythonKeyedBroadcastStateTransformation<OUT>> {
@Override
protected Collection<Integer> translateForBatchInternal(
PythonKeyedBroadcastStateTransformation<OUT> transformation, Context context) {
Preconditions.checkNotNull(transformation);
Preconditions.checkNotNull(context);
Configuration config = transformation.getConfiguration();
AbstractPythonFunctionOperator<OUT> operator;
if (config.get(PythonOptions.PYTHON_EXECUTION_MODE).equals("thread")) {
operator =
new EmbeddedPythonBatchKeyedCoBroadcastProcessOperator<>(
transformation.getConfiguration(),
transformation.getDataStreamPythonFunctionInfo(),
transformation.getRegularInput().getOutputType(),
transformation.getBroadcastInput().getOutputType(),
transformation.getOutputType());
} else {
operator =
new ExternalPythonBatchKeyedCoBroadcastProcessOperator<>(
transformation.getConfiguration(),
transformation.getDataStreamPythonFunctionInfo(),
transformation.getRegularInput().getOutputType(),
transformation.getBroadcastInput().getOutputType(),
transformation.getOutputType());
}
DelegateOperatorTransformation.configureOperator(transformation, operator);
Collection<Integer> result =
translateInternal(
transformation,
transformation.getRegularInput(),
transformation.getBroadcastInput(),
SimpleOperatorFactory.of(operator),
transformation.getStateKeyType(),
transformation.getKeySelector(),
null,
context);
BatchExecutionUtils.applyBatchExecutionSettings(
transformation.getId(),
context,
StreamConfig.InputRequirement.SORTED,
StreamConfig.InputRequirement.PASS_THROUGH);
return result;
}
@Override
protected Collection<Integer> translateForStreamingInternal(
PythonKeyedBroadcastStateTransformation<OUT> transformation, Context context) {
Preconditions.checkNotNull(transformation);
Preconditions.checkNotNull(context);
Configuration config = transformation.getConfiguration();
AbstractPythonFunctionOperator<OUT> operator;
if (config.get(PythonOptions.PYTHON_EXECUTION_MODE).equals("thread")) {
operator =
new EmbeddedPythonKeyedCoProcessOperator<>(
transformation.getConfiguration(),
transformation.getDataStreamPythonFunctionInfo(),
transformation.getRegularInput().getOutputType(),
transformation.getBroadcastInput().getOutputType(),
transformation.getOutputType());
} else {
operator =
new ExternalPythonKeyedCoProcessOperator<>(
transformation.getConfiguration(),
transformation.getDataStreamPythonFunctionInfo(),
transformation.getRegularInput().getOutputType(),
transformation.getBroadcastInput().getOutputType(),
transformation.getOutputType());
}
DelegateOperatorTransformation.configureOperator(transformation, operator);
return translateInternal(
transformation,
transformation.getRegularInput(),
transformation.getBroadcastInput(),
SimpleOperatorFactory.of(operator),
transformation.getStateKeyType(),
transformation.getKeySelector(),
null,
context);
}
}
|
PythonKeyedBroadcastStateTransformationTranslator
|
java
|
spring-projects__spring-framework
|
spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/MessageMapping.java
|
{
"start": 5551,
"end": 6225
}
|
interface ____ {
/**
* Destination-based mapping expressed by this annotation.
* <p>For STOMP over WebSocket messages this is
* {@link org.springframework.util.AntPathMatcher AntPathMatcher}-style
* patterns matched against the STOMP destination of the message.
* <p>for RSocket this is either
* {@link org.springframework.util.AntPathMatcher AntPathMatcher} or
* {@link org.springframework.web.util.pattern.PathPattern PathPattern}
* based pattern, depending on which is configured, matched to the route of
* the stream request.
* <p>If no patterns are configured, the mapping matches all destinations.
*/
String[] value() default {};
}
|
MessageMapping
|
java
|
greenrobot__EventBus
|
EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java
|
{
"start": 3170,
"end": 7302
}
|
class ____ (subscribers to super classes will be notified).
* Switching this feature off will improve posting of events. For simple event classes extending Object directly,
* we measured a speed up of 20% for event posting. For more complex event hierarchies, the speed up should be
* greater than 20%.
* <p/>
* However, keep in mind that event posting usually consumes just a small proportion of CPU time inside an app,
* unless it is posting at high rates, e.g. hundreds/thousands of events per second.
*/
public EventBusBuilder eventInheritance(boolean eventInheritance) {
this.eventInheritance = eventInheritance;
return this;
}
/**
* Provide a custom thread pool to EventBus used for async and background event delivery. This is an advanced
* setting to that can break things: ensure the given ExecutorService won't get stuck to avoid undefined behavior.
*/
public EventBusBuilder executorService(ExecutorService executorService) {
this.executorService = executorService;
return this;
}
/**
* Method name verification is done for methods starting with onEvent to avoid typos; using this method you can
* exclude subscriber classes from this check. Also disables checks for method modifiers (public, not static nor
* abstract).
*/
public EventBusBuilder skipMethodVerificationFor(Class<?> clazz) {
if (skipMethodVerificationForClasses == null) {
skipMethodVerificationForClasses = new ArrayList<>();
}
skipMethodVerificationForClasses.add(clazz);
return this;
}
/** Forces the use of reflection even if there's a generated index (default: false). */
public EventBusBuilder ignoreGeneratedIndex(boolean ignoreGeneratedIndex) {
this.ignoreGeneratedIndex = ignoreGeneratedIndex;
return this;
}
/** Enables strict method verification (default: false). */
public EventBusBuilder strictMethodVerification(boolean strictMethodVerification) {
this.strictMethodVerification = strictMethodVerification;
return this;
}
/** Adds an index generated by EventBus' annotation preprocessor. */
public EventBusBuilder addIndex(SubscriberInfoIndex index) {
if (subscriberInfoIndexes == null) {
subscriberInfoIndexes = new ArrayList<>();
}
subscriberInfoIndexes.add(index);
return this;
}
/**
* Set a specific log handler for all EventBus logging.
* <p/>
* By default, all logging is via {@code android.util.Log} on Android or System.out on JVM.
*/
public EventBusBuilder logger(Logger logger) {
this.logger = logger;
return this;
}
Logger getLogger() {
if (logger != null) {
return logger;
} else {
return Logger.Default.get();
}
}
MainThreadSupport getMainThreadSupport() {
if (mainThreadSupport != null) {
return mainThreadSupport;
} else if (AndroidComponents.areAvailable()) {
return AndroidComponents.get().defaultMainThreadSupport;
} else {
return null;
}
}
/**
* Installs the default EventBus returned by {@link EventBus#getDefault()} using this builders' values. Must be
* done only once before the first usage of the default EventBus.
*
* @throws EventBusException if there's already a default EventBus instance in place
*/
public EventBus installDefaultEventBus() {
synchronized (EventBus.class) {
if (EventBus.defaultInstance != null) {
throw new EventBusException("Default instance already exists." +
" It may be only set once before it's used the first time to ensure consistent behavior.");
}
EventBus.defaultInstance = build();
return EventBus.defaultInstance;
}
}
/** Builds an EventBus based on the current configuration. */
public EventBus build() {
return new EventBus(this);
}
}
|
hierarchy
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/router/security/token/TestSQLDelegationTokenSecretManagerImpl.java
|
{
"start": 23854,
"end": 25651
}
|
class ____ extends SQLDelegationTokenSecretManagerImpl {
private ReentrantLock keyRollLock;
private synchronized ReentrantLock getKeyRollLock() {
if (keyRollLock == null) {
keyRollLock = new ReentrantLock();
}
return keyRollLock;
}
TestDelegationTokenSecretManager(Configuration conf) {
super(conf, new TestConnectionFactory(conf),
SQLSecretManagerRetriableHandlerImpl.getInstance(conf, new TestRetryHandler()));
}
// Tests can call this method to prevent delegation keys from
// being rolled in the middle of a test to prevent race conditions
public void lockKeyRoll() {
getKeyRollLock().lock();
}
public void unlockKeyRoll() {
if (getKeyRollLock().isHeldByCurrentThread()) {
getKeyRollLock().unlock();
}
}
@Override
protected void rollMasterKey() throws IOException {
try {
lockKeyRoll();
super.rollMasterKey();
} finally {
unlockKeyRoll();
}
}
public void waitForTokenEviction(TokenIdentifier tokenId)
throws InterruptedException, TimeoutException {
// Wait until token is not found on cache
GenericTestUtils.waitFor(() -> !this.currentTokens.containsKey(tokenId), 100, 5000);
}
public void removeExpiredStoredToken(TokenIdentifier tokenId) {
super.removeExpiredStoredToken((AbstractDelegationTokenIdentifier) tokenId);
}
public void storeToken(AbstractDelegationTokenIdentifier ident,
DelegationTokenInformation tokenInfo) throws IOException {
super.storeToken(ident, tokenInfo);
}
public void setReadOnly(boolean readOnly) {
((TestConnectionFactory) getConnectionFactory()).readOnly = readOnly;
}
}
static
|
TestDelegationTokenSecretManager
|
java
|
assertj__assertj-core
|
assertj-core/src/main/java/org/assertj/core/internal/TypeHolder.java
|
{
"start": 2657,
"end": 2917
}
|
class ____ which to find an entity
* @return the most relevant entity, or {@code null} if on entity could be found
*/
public T get(Class<?> clazz) {
return get(clazz, null);
}
/**
* This method returns the most relevant entity for the given
|
for
|
java
|
elastic__elasticsearch
|
modules/parent-join/src/internalClusterTest/java/org/elasticsearch/join/aggregations/ParentIT.java
|
{
"start": 1481,
"end": 13048
}
|
class ____ extends AbstractParentChildTestCase {
public void testSimpleParentAgg() {
long articlesWithComment = articleToControl.values()
.stream()
.filter(parentControl -> parentControl.commentIds.isEmpty() == false)
.count();
assertNoFailuresAndResponse(
prepareSearch("test").setSize(0).setQuery(matchQuery("randomized", true)).addAggregation(parent("to_article", "comment")),
response -> {
SingleBucketAggregation parentAgg = response.getAggregations().get("to_article");
assertThat("\nResponse: " + response + "\n", parentAgg.getDocCount(), equalTo(articlesWithComment));
}
);
}
public void testSimpleParentAggWithSubAgg() {
long articlesWithComment = articleToControl.values()
.stream()
.filter(parentControl -> parentControl.commentIds.isEmpty() == false)
.count();
long categoriesWithComments = categoryToControl.values().stream().filter(control -> control.commentIds.isEmpty() == false).count();
assertNoFailuresAndResponse(
prepareSearch("test").setSize(10000)
.setQuery(matchQuery("randomized", true))
.addAggregation(parent("to_article", "comment").subAggregation(terms("category").field("category").size(10000))),
response -> {
SingleBucketAggregation parentAgg = response.getAggregations().get("to_article");
assertThat("Response: " + response + "\n", parentAgg.getDocCount(), equalTo(articlesWithComment));
Terms categoryTerms = parentAgg.getAggregations().get("category");
assertThat(
"Buckets: "
+ categoryTerms.getBuckets()
.stream()
.map((Function<Terms.Bucket, String>) MultiBucketsAggregation.Bucket::getKeyAsString)
.collect(Collectors.toList())
+ "\nCategories: "
+ categoryToControl.keySet(),
(long) categoryTerms.getBuckets().size(),
equalTo(categoriesWithComments)
);
for (Map.Entry<String, Control> entry : categoryToControl.entrySet()) {
// no children for this category -> no entry in the child to parent-aggregation
if (entry.getValue().commentIds.isEmpty()) {
assertNull(categoryTerms.getBucketByKey(entry.getKey()));
continue;
}
final Terms.Bucket categoryBucket = categoryTerms.getBucketByKey(entry.getKey());
assertNotNull("Failed for category " + entry.getKey(), categoryBucket);
assertThat("Failed for category " + entry.getKey(), categoryBucket.getKeyAsString(), equalTo(entry.getKey()));
// count all articles in this category which have at least one comment
long articlesForCategory = articleToControl.values()
.stream()
// only articles with this category
.filter(parentControl -> parentControl.category.equals(entry.getKey()))
// only articles which have comments
.filter(parentControl -> parentControl.commentIds.isEmpty() == false)
.count();
assertThat("Failed for category " + entry.getKey(), categoryBucket.getDocCount(), equalTo(articlesForCategory));
}
}
);
}
public void testParentAggs() throws Exception {
assertNoFailuresAndResponse(
prepareSearch("test").setSize(10000)
.setQuery(matchQuery("randomized", true))
.addAggregation(
terms("to_commenter").field("commenter")
.size(10000)
.subAggregation(
parent("to_article", "comment").subAggregation(
terms("to_category").field("category").size(10000).subAggregation(topHits("top_category"))
)
)
),
response -> {
final Set<String> commenters = getCommenters();
final Map<String, Set<String>> commenterToComments = getCommenterToComments();
Terms categoryTerms = response.getAggregations().get("to_commenter");
assertThat("Response: " + response + "\n", categoryTerms.getBuckets().size(), equalTo(commenters.size()));
for (Terms.Bucket commenterBucket : categoryTerms.getBuckets()) {
Set<String> comments = commenterToComments.get(commenterBucket.getKeyAsString());
assertNotNull(comments);
assertThat(
"Failed for commenter " + commenterBucket.getKeyAsString(),
commenterBucket.getDocCount(),
equalTo((long) comments.size())
);
SingleBucketAggregation articleAgg = commenterBucket.getAggregations().get("to_article");
assertThat(articleAgg.getName(), equalTo("to_article"));
// find all articles for the comments for the current commenter
Set<String> articles = articleToControl.values()
.stream()
.flatMap(
(Function<ParentControl, Stream<String>>) parentControl -> parentControl.commentIds.stream()
.filter(comments::contains)
)
.collect(Collectors.toSet());
assertThat(articleAgg.getDocCount(), equalTo((long) articles.size()));
Terms categoryAgg = articleAgg.getAggregations().get("to_category");
assertNotNull(categoryAgg);
List<String> categories = categoryToControl.entrySet()
.stream()
.filter(entry -> entry.getValue().commenterToCommentId.containsKey(commenterBucket.getKeyAsString()))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
for (String category : categories) {
Terms.Bucket categoryBucket = categoryAgg.getBucketByKey(category);
assertNotNull(categoryBucket);
Aggregation topCategory = categoryBucket.getAggregations().get("top_category");
assertNotNull(topCategory);
}
}
for (String commenter : commenters) {
Terms.Bucket categoryBucket = categoryTerms.getBucketByKey(commenter);
assertThat(categoryBucket.getKeyAsString(), equalTo(commenter));
assertThat(categoryBucket.getDocCount(), equalTo((long) commenterToComments.get(commenter).size()));
SingleBucketAggregation childrenBucket = categoryBucket.getAggregations().get("to_article");
assertThat(childrenBucket.getName(), equalTo("to_article"));
}
}
);
}
private Set<String> getCommenters() {
return categoryToControl.values()
.stream()
.flatMap((Function<Control, Stream<String>>) control -> control.commenterToCommentId.keySet().stream())
.collect(Collectors.toSet());
}
private Map<String, Set<String>> getCommenterToComments() {
final Map<String, Set<String>> commenterToComments = new HashMap<>();
for (Control control : categoryToControl.values()) {
for (Map.Entry<String, Set<String>> entry : control.commenterToCommentId.entrySet()) {
final Set<String> comments = commenterToComments.computeIfAbsent(entry.getKey(), s -> new HashSet<>());
comments.addAll(entry.getValue());
}
}
return commenterToComments;
}
public void testNonExistingParentType() throws Exception {
assertNoFailuresAndResponse(prepareSearch("test").addAggregation(parent("non-existing", "xyz")), response -> {
SingleBucketAggregation parent = response.getAggregations().get("non-existing");
assertThat(parent.getName(), equalTo("non-existing"));
assertThat(parent.getDocCount(), equalTo(0L));
});
}
public void testTermsParentAggTerms() throws Exception {
assertNoFailuresAndResponse(
prepareSearch("test").setSize(10000)
.setQuery(matchQuery("randomized", true))
.addAggregation(
terms("to_commenter").field("commenter")
.size(10000)
.subAggregation(parent("to_article", "comment").subAggregation(terms("to_category").field("category").size(10000)))
),
response -> {
final Set<String> commenters = getCommenters();
final Map<String, Set<String>> commenterToComments = getCommenterToComments();
Terms commentersAgg = response.getAggregations().get("to_commenter");
assertThat("Response: " + response + "\n", commentersAgg.getBuckets().size(), equalTo(commenters.size()));
for (Terms.Bucket commenterBucket : commentersAgg.getBuckets()) {
Set<String> comments = commenterToComments.get(commenterBucket.getKeyAsString());
assertNotNull(comments);
assertThat(
"Failed for commenter " + commenterBucket.getKeyAsString(),
commenterBucket.getDocCount(),
equalTo((long) comments.size())
);
SingleBucketAggregation articleAgg = commenterBucket.getAggregations().get("to_article");
assertThat(articleAgg.getName(), equalTo("to_article"));
// find all articles for the comments for the current commenter
Set<String> articles = articleToControl.values()
.stream()
.flatMap(
(Function<ParentControl, Stream<String>>) parentControl -> parentControl.commentIds.stream()
.filter(comments::contains)
)
.collect(Collectors.toSet());
assertThat(articleAgg.getDocCount(), equalTo((long) articles.size()));
Terms categoryAgg = articleAgg.getAggregations().get("to_category");
assertNotNull(categoryAgg);
List<String> categories = categoryToControl.entrySet()
.stream()
.filter(entry -> entry.getValue().commenterToCommentId.containsKey(commenterBucket.getKeyAsString()))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
for (String category : categories) {
Terms.Bucket categoryBucket = categoryAgg.getBucketByKey(category);
assertNotNull(categoryBucket);
}
}
}
);
}
}
|
ParentIT
|
java
|
mockito__mockito
|
mockito-core/src/test/java/org/mockitousage/bugs/AtLeastMarksAllInvocationsVerified.java
|
{
"start": 629,
"end": 1656
}
|
class ____ {
public void allowedMethod() {}
public void disallowedMethod() {}
}
@Test
public void shouldFailBecauseDisallowedMethodWasCalled() {
SomeMethods someMethods = mock(SomeMethods.class);
someMethods.allowedMethod();
someMethods.disallowedMethod();
verify(someMethods, atLeast(1)).allowedMethod();
assertThatThrownBy(
() -> {
verifyNoMoreInteractions(someMethods);
})
.isInstanceOf(NoInteractionsWanted.class)
.hasMessageContainingAll(
"No interactions wanted here:",
"-> at ",
"But found this interaction on mock 'someMethods':",
"-> at ",
"For your reference, here is the list of all invocations ([?] - means unverified).",
"1. -> at ",
"2. [?]-> at ");
}
}
|
SomeMethods
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/http/codec/KotlinSerializationStringEncoder.java
|
{
"start": 2184,
"end": 6441
}
|
class ____<T extends StringFormat> extends KotlinSerializationSupport<T>
implements Encoder<Object> {
private static final byte[] NEWLINE_SEPARATOR = {'\n'};
protected static final byte[] EMPTY_BYTES = new byte[0];
// CharSequence encoding needed for now, see https://github.com/Kotlin/kotlinx.serialization/issues/204 for more details
private final CharSequenceEncoder charSequenceEncoder = CharSequenceEncoder.allMimeTypes();
private final Set<MimeType> streamingMediaTypes = new HashSet<>();
/**
* Creates a new instance with the given format and supported mime types
* which only encodes types annotated with
* {@link kotlinx.serialization.Serializable @Serializable} at type or
* generics level.
*/
protected KotlinSerializationStringEncoder(T format, MimeType... supportedMimeTypes) {
super(format, supportedMimeTypes);
}
/**
* Creates a new instance with the given format and supported mime types
* which only encodes types for which the specified predicate returns
* {@code true}.
* @since 7.0
*/
protected KotlinSerializationStringEncoder(T format, Predicate<ResolvableType> typePredicate, MimeType... supportedMimeTypes) {
super(format, typePredicate, supportedMimeTypes);
}
/**
* Set streaming {@link MediaType MediaTypes}.
* @param streamingMediaTypes streaming {@link MediaType MediaTypes}
* @since 6.1.4
*/
public void setStreamingMediaTypes(Collection<MediaType> streamingMediaTypes) {
this.streamingMediaTypes.clear();
this.streamingMediaTypes.addAll(streamingMediaTypes);
}
@Override
public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
return canSerialize(elementType, mimeType) && !String.class.isAssignableFrom(elementType.toClass());
}
@Override
public List<MimeType> getEncodableMimeTypes() {
return supportedMimeTypes();
}
@Override
public List<MimeType> getEncodableMimeTypes(ResolvableType elementType) {
return supportedMimeTypes();
}
@Override
public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory,
ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
if (inputStream instanceof Mono<?> mono) {
return mono
.map(value -> encodeValue(value, bufferFactory, elementType, mimeType, hints))
.flux();
}
if (mimeType != null && this.streamingMediaTypes.contains(mimeType)) {
return Flux.from(inputStream)
.map(value -> encodeStreamingValue(value, bufferFactory, elementType, mimeType, hints, EMPTY_BYTES,
NEWLINE_SEPARATOR));
}
return encodeNonStream(inputStream, bufferFactory, elementType, mimeType, hints);
}
protected DataBuffer encodeStreamingValue(Object value, DataBufferFactory bufferFactory,
ResolvableType valueType, @Nullable MimeType mimeType,
@Nullable Map<String, Object> hints, byte[] prefix, byte[] suffix) {
List<DataBuffer> buffers = new ArrayList<>(3);
if (prefix.length > 0) {
buffers.add(bufferFactory.allocateBuffer(prefix.length).write(prefix));
}
buffers.add(encodeValue(value, bufferFactory, valueType, mimeType, hints));
if (suffix.length > 0) {
buffers.add(bufferFactory.allocateBuffer(suffix.length).write(suffix));
}
return bufferFactory.join(buffers);
}
protected Flux<DataBuffer> encodeNonStream(Publisher<?> inputStream, DataBufferFactory bufferFactory,
ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType);
return Flux.from(inputStream)
.collectList()
.map(list -> encodeValue(list, bufferFactory, listType, mimeType, hints))
.flux();
}
@Override
public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory,
ResolvableType valueType, @Nullable MimeType mimeType,
@Nullable Map<String, Object> hints) {
KSerializer<Object> serializer = serializer(valueType);
if (serializer == null) {
throw new EncodingException("Could not find KSerializer for " + valueType);
}
String string = format().encodeToString(serializer, value);
return this.charSequenceEncoder.encodeValue(string, bufferFactory, valueType, mimeType, null);
}
}
|
KotlinSerializationStringEncoder
|
java
|
spring-projects__spring-security
|
web/src/main/java/org/springframework/security/web/csrf/InvalidCsrfTokenException.java
|
{
"start": 972,
"end": 1495
}
|
class ____ extends CsrfException {
@Serial
private static final long serialVersionUID = -7745955098435417418L;
/**
* @param expectedAccessToken
* @param actualAccessToken
*/
public InvalidCsrfTokenException(CsrfToken expectedAccessToken, @Nullable String actualAccessToken) {
super("Invalid CSRF Token '" + actualAccessToken + "' was found on the request parameter '"
+ expectedAccessToken.getParameterName() + "' or header '" + expectedAccessToken.getHeaderName()
+ "'.");
}
}
|
InvalidCsrfTokenException
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/index/engine/NoOpEngineRecoveryTests.java
|
{
"start": 927,
"end": 2177
}
|
class ____ extends IndexShardTestCase {
public void testRecoverFromNoOp() throws IOException {
final int nbDocs = scaledRandomIntBetween(1, 100);
final IndexShard indexShard = newStartedShard(true);
for (int i = 0; i < nbDocs; i++) {
indexDoc(indexShard, "_doc", String.valueOf(i));
}
flushAndCloseShardNoCheck(indexShard);
final ShardRouting shardRouting = indexShard.routingEntry();
IndexShard primary = reinitShard(
indexShard,
initWithSameId(shardRouting, ExistingStoreRecoverySource.INSTANCE),
indexShard.indexSettings().getIndexMetadata(),
NoOpEngine::new
);
recoverShardFromStore(primary);
assertEquals(primary.seqNoStats().getMaxSeqNo(), primary.getMaxSeqNoOfUpdatesOrDeletes());
assertEquals(nbDocs, primary.docStats().getCount());
IndexShard replica = newShard(false, Settings.EMPTY, NoOpEngine::new);
recoverReplica(replica, primary, true);
assertEquals(replica.seqNoStats().getMaxSeqNo(), replica.getMaxSeqNoOfUpdatesOrDeletes());
assertEquals(nbDocs, replica.docStats().getCount());
closeShards(primary, replica);
}
}
|
NoOpEngineRecoveryTests
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/ModuleFactoryGeneratorTest.java
|
{
"start": 49790,
"end": 50112
}
|
interface ____ {}");
@Test
public void providesMethodMultipleQualifiersOnMethod() {
Source moduleFile =
CompilerTests.javaSource("test.TestModule",
"package test;",
"",
"import dagger.Module;",
"import dagger.Provides;",
"",
"@Module",
"final
|
QualifierB
|
java
|
spring-projects__spring-framework
|
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ResponseBodyEmitterTests.java
|
{
"start": 1718,
"end": 9435
}
|
class ____ {
@Mock
private ResponseBodyEmitter.Handler handler;
private final ResponseBodyEmitter emitter = new ResponseBodyEmitter();
@Test
void sendBeforeHandlerInitialized() throws Exception {
this.emitter.send("foo", MediaType.TEXT_PLAIN);
this.emitter.send("bar", MediaType.TEXT_PLAIN);
this.emitter.complete();
verifyNoMoreInteractions(this.handler);
this.emitter.initialize(this.handler);
verify(this.handler).send(anySet());
verify(this.handler).complete();
verifyNoMoreInteractions(this.handler);
}
@Test
void sendDuplicateBeforeHandlerInitialized() throws Exception {
this.emitter.send("foo", MediaType.TEXT_PLAIN);
this.emitter.send("foo", MediaType.TEXT_PLAIN);
this.emitter.complete();
verifyNoMoreInteractions(this.handler);
this.emitter.initialize(this.handler);
verify(this.handler).send(anySet());
verify(this.handler).complete();
verifyNoMoreInteractions(this.handler);
}
@Test
void sendBeforeHandlerInitializedWithError() throws Exception {
IllegalStateException ex = new IllegalStateException();
this.emitter.send("foo", MediaType.TEXT_PLAIN);
this.emitter.send("bar", MediaType.TEXT_PLAIN);
this.emitter.completeWithError(ex);
verifyNoMoreInteractions(this.handler);
this.emitter.initialize(this.handler);
verify(this.handler).send(anySet());
verify(this.handler).completeWithError(ex);
verifyNoMoreInteractions(this.handler);
}
@Test
void sendFailsAfterComplete() {
this.emitter.complete();
assertThatIllegalStateException().isThrownBy(() -> this.emitter.send("foo"));
}
@Test
void sendAfterHandlerInitialized() throws Exception {
this.emitter.initialize(this.handler);
verify(this.handler).onTimeout(any());
verify(this.handler).onError(any());
verify(this.handler).onCompletion(any());
verifyNoMoreInteractions(this.handler);
this.emitter.send("foo", MediaType.TEXT_PLAIN);
this.emitter.send("bar", MediaType.TEXT_PLAIN);
this.emitter.complete();
verify(this.handler).send("foo", MediaType.TEXT_PLAIN);
verify(this.handler).send("bar", MediaType.TEXT_PLAIN);
verify(this.handler).complete();
verifyNoMoreInteractions(this.handler);
}
@Test
void sendAfterHandlerInitializedWithError() throws Exception {
this.emitter.initialize(this.handler);
verify(this.handler).onTimeout(any());
verify(this.handler).onError(any());
verify(this.handler).onCompletion(any());
verifyNoMoreInteractions(this.handler);
IllegalStateException ex = new IllegalStateException();
this.emitter.send("foo", MediaType.TEXT_PLAIN);
this.emitter.send("bar", MediaType.TEXT_PLAIN);
this.emitter.completeWithError(ex);
verify(this.handler).send("foo", MediaType.TEXT_PLAIN);
verify(this.handler).send("bar", MediaType.TEXT_PLAIN);
verify(this.handler).completeWithError(ex);
verifyNoMoreInteractions(this.handler);
}
@Test
void sendWithError() throws Exception {
this.emitter.initialize(this.handler);
verify(this.handler).onTimeout(any());
verify(this.handler).onError(any());
verify(this.handler).onCompletion(any());
verifyNoMoreInteractions(this.handler);
willThrow(new IOException()).given(this.handler).send("foo", MediaType.TEXT_PLAIN);
assertThatIOException().isThrownBy(() -> this.emitter.send("foo", MediaType.TEXT_PLAIN));
verify(this.handler).send("foo", MediaType.TEXT_PLAIN);
verifyNoMoreInteractions(this.handler);
}
@Test // gh-30687
void completeAfterNonIOException() throws Exception {
this.emitter.initialize(this.handler);
verify(this.handler).onTimeout(any());
verify(this.handler).onError(any());
verify(this.handler).onCompletion(any());
verifyNoMoreInteractions(this.handler);
willThrow(new IllegalStateException()).given(this.handler).send("foo", MediaType.TEXT_PLAIN);
assertThatIllegalStateException().isThrownBy(() -> this.emitter.send("foo", MediaType.TEXT_PLAIN));
verify(this.handler).send("foo", MediaType.TEXT_PLAIN);
verifyNoMoreInteractions(this.handler);
this.emitter.complete();
verify(this.handler).complete();
verifyNoMoreInteractions(this.handler);
}
@Test
void onTimeoutBeforeHandlerInitialized() throws Exception {
Runnable runnable = mock();
this.emitter.onTimeout(runnable);
this.emitter.initialize(this.handler);
ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
verify(this.handler).onTimeout(captor.capture());
verify(this.handler).onCompletion(any());
assertThat(captor.getValue()).isNotNull();
captor.getValue().run();
verify(runnable).run();
}
@Test
void onTimeoutAfterHandlerInitialized() throws Exception {
this.emitter.initialize(this.handler);
ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
verify(this.handler).onTimeout(captor.capture());
verify(this.handler).onCompletion(any());
Runnable runnable = mock();
this.emitter.onTimeout(runnable);
assertThat(captor.getValue()).isNotNull();
captor.getValue().run();
verify(runnable).run();
}
@Test
void multipleOnTimeoutCallbacks() throws Exception {
this.emitter.initialize(this.handler);
ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
verify(this.handler).onTimeout(captor.capture());
verify(this.handler).onCompletion(any());
Runnable first = mock();
Runnable second = mock();
this.emitter.onTimeout(first);
this.emitter.onTimeout(second);
assertThat(captor.getValue()).isNotNull();
captor.getValue().run();
verify(first).run();
verify(second).run();
}
@Test
void onCompletionBeforeHandlerInitialized() throws Exception {
Runnable runnable = mock();
this.emitter.onCompletion(runnable);
this.emitter.initialize(this.handler);
ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
verify(this.handler).onTimeout(any());
verify(this.handler).onCompletion(captor.capture());
assertThat(captor.getValue()).isNotNull();
captor.getValue().run();
verify(runnable).run();
}
@Test
void onCompletionAfterHandlerInitialized() throws Exception {
this.emitter.initialize(this.handler);
ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
verify(this.handler).onTimeout(any());
verify(this.handler).onCompletion(captor.capture());
Runnable runnable = mock();
this.emitter.onCompletion(runnable);
assertThat(captor.getValue()).isNotNull();
captor.getValue().run();
verify(runnable).run();
}
@Test
void multipleOnCompletionCallbacks() throws Exception {
this.emitter.initialize(this.handler);
ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class);
verify(this.handler).onTimeout(any());
verify(this.handler).onCompletion(captor.capture());
Runnable first = mock();
Runnable second = mock();
this.emitter.onCompletion(first);
this.emitter.onCompletion(second);
assertThat(captor.getValue()).isNotNull();
captor.getValue().run();
verify(first).run();
verify(second).run();
}
@Test
void multipleOnErrorCallbacks() throws Exception {
this.emitter.initialize(this.handler);
@SuppressWarnings({ "rawtypes", "unchecked" })
ArgumentCaptor<Consumer<Throwable>> captor = ArgumentCaptor.<Consumer<Throwable>, Consumer>forClass(Consumer.class);
verify(this.handler).onError(captor.capture());
Consumer<Throwable> first = mock();
Consumer<Throwable> second = mock();
this.emitter.onError(first);
this.emitter.onError(second);
assertThat(captor.getValue()).isNotNull();
IllegalStateException illegalStateException = new IllegalStateException();
captor.getValue().accept(illegalStateException);
verify(first).accept(eq(illegalStateException));
verify(second).accept(eq(illegalStateException));
}
}
|
ResponseBodyEmitterTests
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/collect/AbstractSequentialIteratorTest.java
|
{
"start": 4492,
"end": 4768
}
|
class ____ extends AbstractSequentialIterator<Object> {
BrokenAbstractSequentialIterator() {
super("UNUSED");
}
@Override
protected Object computeNext(Object previous) {
throw new SomeUncheckedException();
}
}
}
|
BrokenAbstractSequentialIterator
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.