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
alibaba__nacos
naming/src/test/java/com/alibaba/nacos/naming/controllers/v2/CatalogControllerV2Test.java
{ "start": 1841, "end": 3603 }
class ____ extends BaseTest { List instances; @Mock private CatalogServiceV2Impl catalogServiceV2; @InjectMocks private CatalogControllerV2 catalogControllerV2; private MockMvc mockmvc; @BeforeEach public void before() { Instance instance = new Instance(); instance.setIp("1.1.1.1"); instance.setPort(1234); instance.setClusterName(TEST_CLUSTER_NAME); instance.setServiceName(TEST_SERVICE_NAME); instance.setEnabled(false); instances = new ArrayList<>(1); instances.add(instance); mockmvc = MockMvcBuilders.standaloneSetup(catalogControllerV2).build(); } @Test void testInstanceList() throws Exception { String serviceNameWithoutGroup = NamingUtils.getServiceName(TEST_SERVICE_NAME); String groupName = NamingUtils.getGroupName(TEST_SERVICE_NAME); when(catalogServiceV2.listAllInstances(Constants.DEFAULT_NAMESPACE_ID, groupName, serviceNameWithoutGroup)).thenReturn(instances); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get( UtilsAndCommons.DEFAULT_NACOS_NAMING_CONTEXT_V2 + UtilsAndCommons.NACOS_NAMING_CATALOG_CONTEXT + "/instances") .param("namespaceId", Constants.DEFAULT_NAMESPACE_ID).param("serviceName", TEST_SERVICE_NAME).param("pageNo", "1") .param("pageSize", "100"); MockHttpServletResponse response = mockmvc.perform(builder).andReturn().getResponse(); assertEquals(200, response.getStatus()); JsonNode data = JacksonUtils.toObj(response.getContentAsString()).get("data").get("instances"); assertEquals(instances.size(), data.size()); } }
CatalogControllerV2Test
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ComparableType.java
{ "start": 1667, "end": 2846 }
class ____ extends BugChecker implements ClassTreeMatcher { @Override public Description matchClass(ClassTree tree, VisitorState state) { Type comparableType = state.getSymtab().comparableType; return tree.getImplementsClause().stream() .filter(impl -> isSameType(getType(impl), comparableType, state)) .findAny() .map(impl -> match(tree, impl, state)) .orElse(NO_MATCH); } Description match(ClassTree tree, Tree impl, VisitorState state) { Type implType = getType(impl); ClassType type = getType(tree); if (implType.getTypeArguments().isEmpty()) { return buildDescription(tree).setMessage("Comparable should not be raw").build(); } Type comparableTypeArgument = getOnlyElement(implType.getTypeArguments()); if (!isSameType(type, comparableTypeArgument, state)) { return buildDescription(tree) .setMessage( String.format( "Type of Comparable (%s) is not the same as implementing class (%s).", Signatures.prettyType(comparableTypeArgument), Signatures.prettyType(type))) .build(); } return NO_MATCH; } }
ComparableType
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/RemoteMethod.java
{ "start": 1272, "end": 7838 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(RemoteMethod.class); /** List of parameters: static and dynamic values, matching types. */ private final Object[] params; /** List of method parameters types, matches parameters. */ private final Class<?>[] types; /** Class of the protocol for the method. */ private final Class<?> protocol; /** String name of the ClientProtocol method. */ private final String methodName; /** * Create a remote method generator for the ClientProtocol with no parameters. * * @param method The string name of the protocol method. */ public RemoteMethod(String method) { this(ClientProtocol.class, method); } /** * Create a method with no parameters. * * @param proto Protocol of the method. * @param method The string name of the ClientProtocol method. */ public RemoteMethod(Class<?> proto, String method) { this.params = null; this.types = null; this.methodName = method; this.protocol = proto; } /** * Create a remote method generator for the ClientProtocol. * * @param method The string name of the ClientProtocol method. * @param pTypes A list of types to use to locate the specific method. * @param pParams A list of parameters for the method. The order of the * parameter list must match the order and number of the types. * Parameters are grouped into 2 categories: * <ul> * <li>Static parameters that are immutable across locations. * <li>Dynamic parameters that are determined for each location by a * RemoteParam object. To specify a dynamic parameter, pass an * instance of RemoteParam in place of the parameter value. * </ul> * @throws IOException If the types and parameter lists are not valid. */ public RemoteMethod(String method, Class<?>[] pTypes, Object... pParams) throws IOException { this(ClientProtocol.class, method, pTypes, pParams); } /** * Creates a remote method generator. * * @param proto Protocol of the method. * @param method The string name of the ClientProtocol method. * @param pTypes A list of types to use to locate the specific method. * @param pParams A list of parameters for the method. The order of the * parameter list must match the order and number of the types. * Parameters are grouped into 2 categories: * <ul> * <li>Static parameters that are immutable across locations. * <li>Dynamic parameters that are determined for each location by a * RemoteParam object. To specify a dynamic parameter, pass an * instance of RemoteParam in place of the parameter value. * </ul> * @throws IOException If the types and parameter lists are not valid. */ public RemoteMethod(Class<?> proto, String method, Class<?>[] pTypes, Object... pParams) throws IOException { if (pParams.length != pTypes.length) { throw new IOException("Invalid parameters for method " + method); } this.protocol = proto; this.params = pParams; this.types = Arrays.copyOf(pTypes, pTypes.length); this.methodName = method; } /** * Get the interface/protocol for this method. For example, ClientProtocol or * NamenodeProtocol. * * @return Protocol for this method. */ public Class<?> getProtocol() { return this.protocol; } /** * Get the represented java method. * * @return {@link Method} * @throws IOException If the method cannot be found. */ public Method getMethod() throws IOException { try { if (types != null) { return protocol.getDeclaredMethod(methodName, types); } else { return protocol.getDeclaredMethod(methodName); } } catch (NoSuchMethodException e) { // Re-throw as an IOException LOG.error("Cannot get method {} with types {} from {}", methodName, Arrays.toString(types), protocol.getSimpleName(), e); throw new IOException(e); } catch (SecurityException e) { LOG.error("Cannot access method {} with types {} from {}", methodName, Arrays.toString(types), protocol.getSimpleName(), e); throw new IOException(e); } } /** * Get the calling types for this method. * * @return An array of calling types. */ public Class<?>[] getTypes() { return Arrays.copyOf(this.types, this.types.length); } /** * Generate a list of parameters for this specific location using no context. * * @return A list of parameters for the method customized for the location. */ public Object[] getParams() { return this.getParams(null); } /** * Get the name of the method. * * @return Name of the method. */ public String getMethodName() { return this.methodName; } /** * Generate a list of parameters for this specific location. Parameters are * grouped into 2 categories: * <ul> * <li>Static parameters that are immutable across locations. * <li>Dynamic parameters that are determined for each location by a * RemoteParam object. * </ul> * * @param context The context identifying the location. * @return A list of parameters for the method customized for the location. */ public Object[] getParams(RemoteLocationContext context) { if (this.params == null) { return new Object[] {}; } Object[] objList = new Object[this.params.length]; for (int i = 0; i < this.params.length; i++) { Object currentObj = this.params[i]; if (currentObj instanceof RemoteParam) { RemoteParam paramGetter = (RemoteParam) currentObj; // Map the parameter using the context if (this.types[i] == CacheDirectiveInfo.class) { CacheDirectiveInfo path = (CacheDirectiveInfo) paramGetter.getParameterForContext(context); objList[i] = new CacheDirectiveInfo.Builder(path) .setPath(new Path(context.getDest())).build(); } else { objList[i] = paramGetter.getParameterForContext(context); } } else { objList[i] = currentObj; } } return objList; } @Override public String toString() { return new StringBuilder() .append(this.protocol.getSimpleName()) .append("#") .append(this.methodName) .append("(") .append(Arrays.deepToString(this.params)) .append(")") .toString(); } }
RemoteMethod
java
netty__netty
codec-http2/src/test/java/io/netty/handler/codec/http2/Http2MultiplexCodecBuilderTest.java
{ "start": 2192, "end": 9411 }
class ____ { private static EventLoopGroup group; private Channel serverChannel; private volatile Channel serverConnectedChannel; private Channel clientChannel; private LastInboundHandler serverLastInboundHandler; @BeforeAll public static void init() { group = new DefaultEventLoop(); } @BeforeEach public void setUp() throws InterruptedException { final CountDownLatch serverChannelLatch = new CountDownLatch(1); LocalAddress serverAddress = new LocalAddress(getClass()); serverLastInboundHandler = new SharableLastInboundHandler(); ServerBootstrap sb = new ServerBootstrap() .channel(LocalServerChannel.class) .group(group) .childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { serverConnectedChannel = ch; ch.pipeline().addLast(new Http2MultiplexCodecBuilder(true, new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { private boolean writable; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { writable |= ctx.channel().isWritable(); super.channelActive(ctx); } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { writable |= ctx.channel().isWritable(); super.channelWritabilityChanged(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { assertTrue(writable); super.channelInactive(ctx); } }); ch.pipeline().addLast(serverLastInboundHandler); } }).build()); serverChannelLatch.countDown(); } }); serverChannel = sb.bind(serverAddress).sync().channel(); Bootstrap cb = new Bootstrap() .channel(LocalChannel.class) .group(group) .handler(new Http2MultiplexCodecBuilder(false, new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { fail("Should not be called for outbound streams"); } }).build()); clientChannel = cb.connect(serverAddress).sync().channel(); assertTrue(serverChannelLatch.await(5, SECONDS)); } @AfterAll public static void shutdown() { group.shutdownGracefully(0, 5, SECONDS); } @AfterEach public void tearDown() throws Exception { if (clientChannel != null) { clientChannel.close().syncUninterruptibly(); clientChannel = null; } if (serverChannel != null) { serverChannel.close().syncUninterruptibly(); serverChannel = null; } final Channel serverConnectedChannel = this.serverConnectedChannel; if (serverConnectedChannel != null) { serverConnectedChannel.close().syncUninterruptibly(); this.serverConnectedChannel = null; } } private Http2StreamChannel newOutboundStream(ChannelHandler handler) { return new Http2StreamChannelBootstrap(clientChannel).handler(handler).open().syncUninterruptibly().getNow(); } @Test public void multipleOutboundStreams() throws Exception { Http2StreamChannel childChannel1 = newOutboundStream(new TestChannelInitializer()); assertTrue(childChannel1.isActive()); assertFalse(isStreamIdValid(childChannel1.stream().id())); Http2StreamChannel childChannel2 = newOutboundStream(new TestChannelInitializer()); assertTrue(childChannel2.isActive()); assertFalse(isStreamIdValid(childChannel2.stream().id())); Http2Headers headers1 = new DefaultHttp2Headers(); Http2Headers headers2 = new DefaultHttp2Headers(); // Test that streams can be made active (headers sent) in different order than the corresponding channels // have been created. childChannel2.writeAndFlush(new DefaultHttp2HeadersFrame(headers2)); childChannel1.writeAndFlush(new DefaultHttp2HeadersFrame(headers1)); Http2HeadersFrame headersFrame2 = serverLastInboundHandler.blockingReadInbound(); assertNotNull(headersFrame2); assertEquals(3, headersFrame2.stream().id()); Http2HeadersFrame headersFrame1 = serverLastInboundHandler.blockingReadInbound(); assertNotNull(headersFrame1); assertEquals(5, headersFrame1.stream().id()); assertEquals(3, childChannel2.stream().id()); assertEquals(5, childChannel1.stream().id()); childChannel1.close(); childChannel2.close(); serverLastInboundHandler.checkException(); } @Test public void createOutboundStream() throws Exception { Channel childChannel = newOutboundStream(new TestChannelInitializer()); assertTrue(childChannel.isRegistered()); assertTrue(childChannel.isActive()); Http2Headers headers = new DefaultHttp2Headers(); childChannel.writeAndFlush(new DefaultHttp2HeadersFrame(headers)); ByteBuf data = Unpooled.buffer(100).writeZero(100); try { childChannel.writeAndFlush(new DefaultHttp2DataFrame(data.retainedDuplicate(), true)); Http2HeadersFrame headersFrame = serverLastInboundHandler.blockingReadInbound(); assertNotNull(headersFrame); assertEquals(3, headersFrame.stream().id()); assertEquals(headers, headersFrame.headers()); Http2DataFrame dataFrame = serverLastInboundHandler.blockingReadInbound(); assertNotNull(dataFrame); assertEquals(3, dataFrame.stream().id()); assertEquals(data, dataFrame.content()); assertTrue(dataFrame.isEndStream()); dataFrame.release(); childChannel.close(); Http2ResetFrame rstFrame = serverLastInboundHandler.blockingReadInbound(); assertNotNull(rstFrame); assertEquals(3, rstFrame.stream().id()); serverLastInboundHandler.checkException(); } finally { data.release(); } } @Sharable private static
Http2MultiplexCodecBuilderTest
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/GetBucketActionResponseTests.java
{ "start": 857, "end": 3902 }
class ____ extends AbstractWireSerializingTestCase<Response> { @Override protected Response createTestInstance() { int listSize = randomInt(10); List<Bucket> hits = new ArrayList<>(listSize); for (int j = 0; j < listSize; j++) { String jobId = "foo"; Bucket bucket = new Bucket(jobId, new Date(randomLong()), randomNonNegativeLong()); if (randomBoolean()) { bucket.setAnomalyScore(randomDouble()); } if (randomBoolean()) { int size = randomInt(10); List<BucketInfluencer> bucketInfluencers = new ArrayList<>(size); for (int i = 0; i < size; i++) { BucketInfluencer bucketInfluencer = new BucketInfluencer("foo", bucket.getTimestamp(), bucket.getBucketSpan()); bucketInfluencer.setAnomalyScore(randomDouble()); bucketInfluencer.setInfluencerFieldName(randomAlphaOfLengthBetween(1, 20)); bucketInfluencer.setInitialAnomalyScore(randomDouble()); bucketInfluencer.setProbability(randomDouble()); bucketInfluencer.setRawAnomalyScore(randomDouble()); bucketInfluencers.add(bucketInfluencer); } bucket.setBucketInfluencers(bucketInfluencers); } if (randomBoolean()) { bucket.setEventCount(randomNonNegativeLong()); } if (randomBoolean()) { bucket.setInitialAnomalyScore(randomDouble()); } if (randomBoolean()) { bucket.setInterim(randomBoolean()); } if (randomBoolean()) { bucket.setProcessingTimeMs(randomLong()); } if (randomBoolean()) { int size = randomInt(10); List<AnomalyRecord> records = new ArrayList<>(size); for (int i = 0; i < size; i++) { AnomalyRecord anomalyRecord = new AnomalyRecord(jobId, new Date(randomLong()), randomNonNegativeLong()); anomalyRecord.setActual(Collections.singletonList(randomDouble())); anomalyRecord.setTypical(Collections.singletonList(randomDouble())); anomalyRecord.setProbability(randomDouble()); anomalyRecord.setInterim(randomBoolean()); records.add(anomalyRecord); } bucket.setRecords(records); } hits.add(bucket); } QueryPage<Bucket> buckets = new QueryPage<>(hits, listSize, Bucket.RESULTS_FIELD); return new Response(buckets); } @Override protected Response mutateInstance(Response instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Writeable.Reader<Response> instanceReader() { return Response::new; } }
GetBucketActionResponseTests
java
spring-projects__spring-boot
test-support/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathExtension.java
{ "start": 2014, "end": 2090 }
class ____ while the test is being run. * * @author Christoph Dreis */
loader
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ser/BasicSerializerFactory.java
{ "start": 2364, "end": 9540 }
class ____ be instantiated. */ protected BasicSerializerFactory(SerializerFactoryConfig config) { _factoryConfig = (config == null) ? new SerializerFactoryConfig() : config; } /** * Method used for creating a new instance of this factory, but with different * configuration. Reason for specifying factory method (instead of plain constructor) * is to allow proper sub-classing of factories. *<p> * Note that custom sub-classes generally <b>must override</b> implementation * of this method, as it usually requires instantiating a new instance of * factory type. Check out javadocs for * {@link tools.jackson.databind.ser.BeanSerializerFactory} for more details. */ protected abstract SerializerFactory withConfig(SerializerFactoryConfig config); /** * Convenience method for creating a new factory instance with an additional * serializer provider. */ @Override public final SerializerFactory withAdditionalSerializers(Serializers additional) { return withConfig(_factoryConfig.withAdditionalSerializers(additional)); } /** * Convenience method for creating a new factory instance with an additional * key serializer provider. */ @Override public final SerializerFactory withAdditionalKeySerializers(Serializers additional) { return withConfig(_factoryConfig.withAdditionalKeySerializers(additional)); } /** * Convenience method for creating a new factory instance with additional bean * serializer modifier. */ @Override public final SerializerFactory withSerializerModifier(ValueSerializerModifier modifier) { return withConfig(_factoryConfig.withSerializerModifier(modifier)); } @Override public final SerializerFactory withNullValueSerializer(ValueSerializer<?> nvs) { return withConfig(_factoryConfig.withNullValueSerializer(nvs)); } @Override public final SerializerFactory withNullKeySerializer(ValueSerializer<?> nks) { return withConfig(_factoryConfig.withNullKeySerializer(nks)); } /* /********************************************************************** /* `SerializerFactory` impl /********************************************************************** */ // Implemented by sub-classes // public abstract ValueSerializer<Object> createSerializer(SerializationContext ctxt, ....) @Override @SuppressWarnings("unchecked") public ValueSerializer<Object> createKeySerializer(SerializationContext ctxt, JavaType keyType) { BeanDescription.Supplier beanDescRef = ctxt.lazyIntrospectBeanDescription(keyType); final SerializationConfig config = ctxt.getConfig(); ValueSerializer<?> ser = null; // Minor optimization: to avoid constructing beanDesc, bail out if none registered if (_factoryConfig.hasKeySerializers()) { // Only thing we have here are module-provided key serializers: for (Serializers serializers : _factoryConfig.keySerializers()) { ser = serializers.findSerializer(config, keyType, beanDescRef, null); if (ser != null) { break; } } } if (ser == null) { // [databind#2503]: Support `@Json[De]Serialize(keyUsing)` on key type too ser = _findKeySerializer(ctxt, beanDescRef.getClassInfo()); if (ser == null) { // If no explicit serializer, see if type is JDK one for which there is // explicit deserializer: if so, can avoid further annotation lookups: ser = JDKKeySerializers.getStdKeySerializer(config, keyType.getRawClass(), false); if (ser == null) { final BeanDescription beanDesc = beanDescRef.get(); // Check `@JsonKey` and `@JsonValue`, in this order AnnotatedMember acc = beanDesc.findJsonKeyAccessor(); if (acc == null) { acc = beanDesc.findJsonValueAccessor(); } if (acc != null) { ValueSerializer<?> delegate = createKeySerializer(ctxt, acc.getType()); if (config.canOverrideAccessModifiers()) { ClassUtil.checkAndFixAccess(acc.getMember(), config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS)); } // need to pass both type of key Object (on which accessor called), and actual // value type that `JsonType`-annotated accessor returns (or contains, in case of field) ser = JsonValueSerializer.construct(config, keyType, acc.getType(), false, null, delegate, acc); } else { ser = JDKKeySerializers.getFallbackKeySerializer(config, keyType.getRawClass(), beanDesc.getClassInfo()); } } } } // [databind#120]: Allow post-processing if (_factoryConfig.hasSerializerModifiers()) { for (ValueSerializerModifier mod : _factoryConfig.serializerModifiers()) { ser = mod.modifyKeySerializer(config, keyType, beanDescRef, ser); } } return (ValueSerializer<Object>) ser; } @Override public ValueSerializer<Object> getDefaultNullKeySerializer() { return _factoryConfig.getNullKeySerializer(); } @Override public ValueSerializer<Object> getDefaultNullValueSerializer() { return _factoryConfig.getNullValueSerializer(); } /* /********************************************************************** /* Additional API for other core classes /********************************************************************** */ protected Iterable<Serializers> customSerializers() { return _factoryConfig.serializers(); } /** * Method called to create a type information serializer for values of given * container property * if one is needed. If not needed (no polymorphic handling configured), should * return null. * * @param containerType Declared type of the container to use as the base type for type information serializer * * @return Type serializer to use for property value contents, if one is needed; null if not. */ public TypeSerializer findPropertyContentTypeSerializer(SerializationContext ctxt, JavaType containerType, AnnotatedMember accessor) { return ctxt.getConfig().getTypeResolverProvider() .findPropertyContentTypeSerializer(ctxt, accessor, containerType); } /* /********************************************************************** /* Secondary serializer accessor methods /********************************************************************** */ /** * Method called to see if one of primary per-
will
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/PreUpdateNewUnidirectionalIdBagTest.java
{ "start": 2453, "end": 3117 }
class ____ { @Id private int id; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private Instant lastUpdatedAt; public Instant getLastUpdatedAt() { return lastUpdatedAt; } public void setLastUpdatedAt(Instant lastUpdatedAt) { this.lastUpdatedAt = lastUpdatedAt; } @CollectionId( column = @Column(name = "n_key_tag"), generator = "increment" ) @CollectionIdJdbcTypeCode( Types.BIGINT ) @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Collection<Tag> tags = new ArrayList<Tag>(); } @Entity(name = "Tag") public static
Person
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/visitor/functions/Char.java
{ "start": 930, "end": 1988 }
class ____ implements Function { public static final Char instance = new Char(); public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) { if (x.getArguments().isEmpty()) { return SQLEvalVisitor.EVAL_ERROR; } StringBuilder buf = new StringBuilder(x.getArguments().size()); for (SQLExpr param : x.getArguments()) { param.accept(visitor); Object paramValue = param.getAttributes().get(EVAL_VALUE); if (paramValue instanceof Number) { int charCode = ((Number) paramValue).intValue(); buf.append((char) charCode); } else if (paramValue instanceof String) { try { int charCode = new BigDecimal((String) paramValue).intValue(); buf.append((char) charCode); } catch (NumberFormatException e) { } } else { return SQLEvalVisitor.EVAL_ERROR; } } return buf.toString(); } }
Char
java
apache__kafka
tools/src/main/java/org/apache/kafka/tools/ConsumerPerformance.java
{ "start": 2121, "end": 11440 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(ConsumerPerformance.class); private static final Random RND = new Random(); public static void main(String[] args) { run(args, KafkaConsumer::new); } static void run(String[] args, Function<Properties, Consumer<byte[], byte[]>> consumerCreator) { try { LOG.info("Starting consumer..."); ConsumerPerfOptions options = new ConsumerPerfOptions(args); AtomicLong totalRecordsRead = new AtomicLong(0); AtomicLong totalBytesRead = new AtomicLong(0); AtomicLong joinTimeMs = new AtomicLong(0); AtomicLong joinTimeMsInSingleRound = new AtomicLong(0); if (!options.hideHeader()) printHeader(options.showDetailedStats()); try (Consumer<byte[], byte[]> consumer = consumerCreator.apply(options.props())) { long bytesRead = 0L; long recordsRead = 0L; long lastBytesRead = 0L; long lastRecordsRead = 0L; long currentTimeMs = System.currentTimeMillis(); long joinStartMs = currentTimeMs; long startMs = currentTimeMs; consume(consumer, options, totalRecordsRead, totalBytesRead, joinTimeMs, bytesRead, recordsRead, lastBytesRead, lastRecordsRead, joinStartMs, joinTimeMsInSingleRound); long endMs = System.currentTimeMillis(); // print final stats double elapsedSec = (endMs - startMs) / 1_000.0; long fetchTimeInMs = (endMs - startMs) - joinTimeMs.get(); if (!options.showDetailedStats()) { double totalMbRead = (totalBytesRead.get() * 1.0) / (1024 * 1024); System.out.printf("%s, %s, %.4f, %.4f, %d, %.4f, %d, %d, %.4f, %.4f%n", options.dateFormat().format(startMs), options.dateFormat().format(endMs), totalMbRead, totalMbRead / elapsedSec, totalRecordsRead.get(), totalRecordsRead.get() / elapsedSec, joinTimeMs.get(), fetchTimeInMs, totalMbRead / (fetchTimeInMs / 1000.0), totalRecordsRead.get() / (fetchTimeInMs / 1000.0) ); } if (options.printMetrics()) { ToolsUtils.printMetrics(consumer.metrics()); } } } catch (Throwable e) { System.err.println(e.getMessage()); System.err.println(Utils.stackTrace(e)); Exit.exit(1); } } protected static void printHeader(boolean showDetailedStats) { String newFieldsInHeader = ", rebalance.time.ms, fetch.time.ms, fetch.MB.sec, fetch.nMsg.sec"; if (!showDetailedStats) System.out.printf("start.time, end.time, data.consumed.in.MB, MB.sec, data.consumed.in.nMsg, nMsg.sec%s%n", newFieldsInHeader); else System.out.printf("time, threadId, data.consumed.in.MB, MB.sec, data.consumed.in.nMsg, nMsg.sec%s%n", newFieldsInHeader); } private static void consume(Consumer<byte[], byte[]> consumer, ConsumerPerfOptions options, AtomicLong totalRecordsRead, AtomicLong totalBytesRead, AtomicLong joinTimeMs, long bytesRead, long recordsRead, long lastBytesRead, long lastRecordsRead, long joinStartMs, AtomicLong joinTimeMsInSingleRound) { long numRecords = options.numRecords(); long recordFetchTimeoutMs = options.recordFetchTimeoutMs(); long reportingIntervalMs = options.reportingIntervalMs(); boolean showDetailedStats = options.showDetailedStats(); SimpleDateFormat dateFormat = options.dateFormat(); ConsumerPerfRebListener listener = new ConsumerPerfRebListener(joinTimeMs, joinStartMs, joinTimeMsInSingleRound); if (options.topic().isPresent()) { consumer.subscribe(options.topic().get(), listener); } else { consumer.subscribe(options.include().get(), listener); } // now start the benchmark long currentTimeMs = System.currentTimeMillis(); long lastReportTimeMs = currentTimeMs; long lastConsumedTimeMs = currentTimeMs; while (recordsRead < numRecords && currentTimeMs - lastConsumedTimeMs <= recordFetchTimeoutMs) { ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(100)); currentTimeMs = System.currentTimeMillis(); if (!records.isEmpty()) lastConsumedTimeMs = currentTimeMs; for (ConsumerRecord<byte[], byte[]> record : records) { recordsRead += 1; if (record.key() != null) bytesRead += record.key().length; if (record.value() != null) bytesRead += record.value().length; if (currentTimeMs - lastReportTimeMs >= reportingIntervalMs) { if (showDetailedStats) printConsumerProgress(0, bytesRead, lastBytesRead, recordsRead, lastRecordsRead, lastReportTimeMs, currentTimeMs, dateFormat, joinTimeMsInSingleRound.get()); joinTimeMsInSingleRound.set(0); lastReportTimeMs = currentTimeMs; lastRecordsRead = recordsRead; lastBytesRead = bytesRead; } } } if (recordsRead < numRecords) System.out.printf("WARNING: Exiting before consuming the expected number of records: timeout (%d ms) exceeded. " + "You can use the --timeout option to increase the timeout.%n", recordFetchTimeoutMs); totalRecordsRead.set(recordsRead); totalBytesRead.set(bytesRead); } protected static void printConsumerProgress(int id, long bytesRead, long lastBytesRead, long recordsRead, long lastRecordsRead, long startMs, long endMs, SimpleDateFormat dateFormat, long joinTimeMsInSingleRound) { printBasicProgress(id, bytesRead, lastBytesRead, recordsRead, lastRecordsRead, startMs, endMs, dateFormat); printExtendedProgress(bytesRead, lastBytesRead, recordsRead, lastRecordsRead, startMs, endMs, joinTimeMsInSingleRound); System.out.println(); } private static void printBasicProgress(int id, long bytesRead, long lastBytesRead, long recordsRead, long lastRecordsRead, long startMs, long endMs, SimpleDateFormat dateFormat) { double elapsedMs = endMs - startMs; double totalMbRead = (bytesRead * 1.0) / (1024 * 1024); double intervalMbRead = ((bytesRead - lastBytesRead) * 1.0) / (1024 * 1024); double intervalMbPerSec = 1000.0 * intervalMbRead / elapsedMs; double intervalRecordsPerSec = ((recordsRead - lastRecordsRead) / elapsedMs) * 1000.0; System.out.printf("%s, %d, %.4f, %.4f, %d, %.4f", dateFormat.format(endMs), id, totalMbRead, intervalMbPerSec, recordsRead, intervalRecordsPerSec); } private static void printExtendedProgress(long bytesRead, long lastBytesRead, long recordsRead, long lastRecordsRead, long startMs, long endMs, long joinTimeMsInSingleRound) { long fetchTimeMs = endMs - startMs - joinTimeMsInSingleRound; double intervalMbRead = ((bytesRead - lastBytesRead) * 1.0) / (1024 * 1024); long intervalRecordsRead = recordsRead - lastRecordsRead; double intervalMbPerSec = (fetchTimeMs <= 0) ? 0.0 : 1000.0 * intervalMbRead / fetchTimeMs; double intervalRecordsPerSec = (fetchTimeMs <= 0) ? 0.0 : 1000.0 * intervalRecordsRead / fetchTimeMs; System.out.printf(", %d, %d, %.4f, %.4f", joinTimeMsInSingleRound, fetchTimeMs, intervalMbPerSec, intervalRecordsPerSec); } public static
ConsumerPerformance
java
spring-projects__spring-boot
module/spring-boot-hibernate/src/test/java/org/springframework/boot/hibernate/autoconfigure/HibernateJpaAutoConfigurationTests.java
{ "start": 51930, "end": 52699 }
class ____ implements JtaPlatform { @Override public TransactionManager retrieveTransactionManager() { return mock(TransactionManager.class); } @Override public UserTransaction retrieveUserTransaction() { throw new UnsupportedOperationException(); } @Override public Object getTransactionIdentifier(Transaction transaction) { throw new UnsupportedOperationException(); } @Override public boolean canRegisterSynchronization() { throw new UnsupportedOperationException(); } @Override public void registerSynchronization(Synchronization synchronization) { throw new UnsupportedOperationException(); } @Override public int getCurrentStatus() { throw new UnsupportedOperationException(); } } static
TestJtaPlatform
java
quarkusio__quarkus
extensions/info/deployment/src/main/java/io/quarkus/info/deployment/InfoBuildTimeConfig.java
{ "start": 430, "end": 974 }
interface ____ { /** * Whether the info endpoint will be enabled */ @WithDefault("true") boolean enabled(); /** * The path under which the info endpoint will be located */ @WithDefault("info") String path(); /** * Git related configuration */ Git git(); /** * Build related configuration */ Build build(); /** * Build related configuration */ Os os(); /** * Build related configuration */ Java java();
InfoBuildTimeConfig
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/BeanConfigInject.java
{ "start": 1362, "end": 1473 }
interface ____ { /** * Name of the root property (prefix) */ String value(); }
BeanConfigInject
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ConcurrentReferenceHashMap.java
{ "start": 7110, "end": 10415 }
enum ____ { /** * Indicates that referential-equality (== instead of .equals()) should * be used when locating keys. This offers similar behavior to {@link java.util.IdentityHashMap} */ IDENTITY_COMPARISONS } /* ---------------- Constants -------------- */ static final ReferenceType DEFAULT_KEY_TYPE = ReferenceType.WEAK; static final ReferenceType DEFAULT_VALUE_TYPE = ReferenceType.STRONG; /** * The default initial capacity for this table, * used when not otherwise specified in a constructor. */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * The default load factor for this table, used when not * otherwise specified in a constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The default concurrency level for this table, used when not * otherwise specified in a constructor. */ static final int DEFAULT_CONCURRENCY_LEVEL = 16; /** * The maximum capacity, used if a higher value is implicitly * specified by either of the constructors with arguments. MUST * be a power of two <= 1<<30 to ensure that entries are indexable * using ints. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The maximum number of segments to allow; used to bound * constructor arguments. */ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative /** * Number of unsynchronized retries in size and containsValue * methods before resorting to locking. This is used to avoid * unbounded retries if tables undergo continuous modification * which would make it impossible to obtain an accurate result. */ static final int RETRIES_BEFORE_LOCK = 2; /* ---------------- Fields -------------- */ /** * Mask value for indexing into segments. The upper bits of a * key's hash code are used to choose the segment. */ final int segmentMask; /** * Shift value for indexing within segments. */ final int segmentShift; /** * The segments, each of which is a specialized hash table */ final Segment<K, V>[] segments; boolean identityComparisons; transient Set<K> keySet; transient Set<Entry<K, V>> entrySet; transient Collection<V> values; /* ---------------- Small Utilities -------------- */ /** * Applies a supplemental hash function to a given hashCode, which * defends against poor quality hash functions. This is critical * because ConcurrentReferenceHashMap uses power-of-two length hash tables, * that otherwise encounter collisions for hashCodes that do not * differ in lower or upper bits. */ private static int hash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. h += ( h << 15 ) ^ 0xffffcd7d; h ^= ( h >>> 10 ); h += ( h << 3 ); h ^= ( h >>> 6 ); h += ( h << 2 ) + ( h << 14 ); return h ^ ( h >>> 16 ); } /** * Returns the segment that should be used for key with given hash * * @param hash the hash code for the key * * @return the segment */ final Segment<K, V> segmentFor(int hash) { return segments[( hash >>> segmentShift ) & segmentMask]; } private int hashOf(Object key) { return hash( identityComparisons ? System.identityHashCode( key ) : key.hashCode() ); } /* ---------------- Inner Classes -------------- */
Option
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test3.java
{ "start": 191, "end": 747 }
class ____ extends TestCase { public void test_jsonpath_leve_1() throws Exception { Map<String, Object> root = new HashMap<String, Object>(); JSONPath.set(root, "/id", 1001); Assert.assertEquals(1001, JSONPath.eval(root, "/id")); } public void test_jsonpath() throws Exception { Map<String, Object> root = new HashMap<String, Object>(); JSONPath.set(root, "/a/b/id", 1001); Assert.assertEquals(1001, JSONPath.eval(root, "a/b/id")); } }
JSONPath_set_test3
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/InjectableValues.java
{ "start": 207, "end": 347 }
class ____ defines API for objects that provide value to * "inject" during deserialization. An instance of this object */ public abstract
that
java
quarkusio__quarkus
integration-tests/opentelemetry-vertx-exporter/src/test/java/io/quarkus/it/opentelemetry/vertx/exporter/Logs.java
{ "start": 209, "end": 479 }
class ____ { private final List<ExportLogsServiceRequest> logsRequests = new CopyOnWriteArrayList<>(); public List<ExportLogsServiceRequest> getLogsRequests() { return logsRequests; } public void reset() { logsRequests.clear(); } }
Logs
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderMockMvcTests.java
{ "start": 1930, "end": 2568 }
class ____ { @Autowired private WebApplicationContext context; @Autowired private ServletContext servletContext; private MockMvcTester mvc; @BeforeEach void setUp() { this.mvc = MockMvcTester.from(this.context); } @Test void testMockHttpEndpoint() { assertThat(this.mvc.get().uri("/")).hasStatusOk().hasBodyTextEqualTo("Hello World"); } @Test void validateWebApplicationContextIsSet() { assertThat(this.context).isSameAs(WebApplicationContextUtils.getWebApplicationContext(this.servletContext)); } @Configuration(proxyBeanMethods = false) @EnableWebMvc @RestController static
SpringBootContextLoaderMockMvcTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/records/RecordNestedEmbeddedWithASecondaryTableTest.java
{ "start": 2357, "end": 2482 }
class ____ map to the same table" ); } } @Entity @Table(name = "UserEntity") @SecondaryTable(name = "Person") static
must
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/TupleConverterUnitTests.java
{ "start": 8813, "end": 8870 }
class ____ { String one, two, three; } static
DomainType
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/partitioner/RowDataCustomStreamPartitioner.java
{ "start": 1496, "end": 2948 }
class ____ extends StreamPartitioner<RowData> { private final InputDataPartitioner partitioner; private final RowDataKeySelector keySelector; public RowDataCustomStreamPartitioner( InputDataPartitioner partitioner, RowDataKeySelector keySelector) { this.partitioner = partitioner; this.keySelector = keySelector; } @Override public int selectChannel(SerializationDelegate<StreamRecord<RowData>> record) { RowData key; try { key = keySelector.getKey(record.getInstance().getValue()); } catch (Exception e) { throw new RuntimeException( "Could not extract key from " + record.getInstance().getValue(), e); } int partition = partitioner.partition(key, numberOfChannels); Preconditions.checkState( partition < numberOfChannels, "The partition computed by custom partitioner is out of range, please check the logic of custom partitioner."); return partition; } @Override public StreamPartitioner<RowData> copy() { return this; } @Override public SubtaskStateMapper getDownstreamSubtaskStateMapper() { return SubtaskStateMapper.ARBITRARY; } @Override public boolean isPointwise() { return false; } @Override public String toString() { return "CUSTOM"; } }
RowDataCustomStreamPartitioner
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java
{ "start": 1247, "end": 10475 }
class ____ extends AbstractEntityInsertAction { private Object version; private Object cacheEntry; /** * Constructs an EntityInsertAction. * @param id The entity identifier * @param state The current (extracted) entity state * @param instance The entity instance * @param version The current entity version value * @param persister The entity's persister * @param isVersionIncrementDisabled Whether version incrementing is disabled. * @param session The session */ public EntityInsertAction( final Object id, final Object[] state, final Object instance, final Object version, final EntityPersister persister, final boolean isVersionIncrementDisabled, final EventSource session) { super( id, state, instance, isVersionIncrementDisabled, persister, session ); this.version = version; } public Object getVersion() { return version; } public void setVersion(Object version) { this.version = version; } protected Object getCacheEntry() { return cacheEntry; } protected void setCacheEntry(Object cacheEntry) { this.cacheEntry = cacheEntry; } @Override public boolean isEarlyInsert() { return false; } @Override protected Object getRowId() { return null ; } @Override protected EntityKey getEntityKey() { return getSession().generateEntityKey( getId(), getPersister() ); } @Override public void execute() throws HibernateException { nullifyTransientReferencesIfNotAlready(); // Don't need to lock the cache here, since if someone // else inserted the same pk first, the insert would fail final var session = getSession(); final Object id = getId(); final boolean veto = preInsert(); if ( !veto ) { final var persister = getPersister(); final Object instance = getInstance(); final var eventMonitor = session.getEventMonitor(); final var event = eventMonitor.beginEntityInsertEvent(); boolean success = false; final GeneratedValues generatedValues; try { generatedValues = persister.getInsertCoordinator().insert( instance, id, getState(), session ); success = true; } finally { eventMonitor.completeEntityInsertEvent( event, id, persister.getEntityName(), success, session ); } final var persistenceContext = session.getPersistenceContextInternal(); final var entry = persistenceContext.getEntry( instance ); if ( entry == null ) { throw new AssertionFailure( "possible non-threadsafe access to session" ); } entry.postInsert( getState() ); handleGeneratedProperties( entry, generatedValues, persistenceContext ); persistenceContext.registerInsertedKey( persister, id ); addCollectionsByKeyToPersistenceContext( persistenceContext, getState() ); } putCacheIfNecessary(); handleNaturalIdPostSaveNotifications( id ); postInsert(); final var statistics = session.getFactory().getStatistics(); if ( statistics.isStatisticsEnabled() && !veto ) { statistics.insertEntity( getPersister().getEntityName() ); } markExecuted(); } private void handleGeneratedProperties( EntityEntry entry, GeneratedValues generatedValues, PersistenceContext persistenceContext) { final var persister = getPersister(); final Object[] state = getState(); if ( persister.hasInsertGeneratedProperties() ) { final Object instance = getInstance(); persister.processInsertGeneratedProperties( getId(), instance, state, generatedValues, getSession() ); if ( persister.isVersionPropertyGenerated() ) { version = Versioning.getVersion( state, persister ); } entry.postUpdate( instance, state, version ); } else if ( persister.isVersionPropertyGenerated() ) { version = Versioning.getVersion( state, persister ); entry.postInsert( version ); } // Process row-id values when available early by replacing the entity entry if ( generatedValues != null && persister.getRowIdMapping() != null ) { final Object rowId = generatedValues.getGeneratedValue( persister.getRowIdMapping() ); if ( rowId != null ) { persistenceContext.replaceEntityEntryRowId( getInstance(), rowId ); } } } protected void putCacheIfNecessary() { final var persister = getPersister(); final var session = getSession(); if ( isCachePutEnabled( persister, session ) ) { final var factory = session.getFactory(); cacheEntry = buildStructuredCacheEntry( getInstance(), version, getState(), persister, session ); final var cache = persister.getCacheAccessStrategy(); final Object cacheKey = cache.generateCacheKey( getId(), persister, factory, session.getTenantIdentifier() ); final boolean put = cacheInsert( persister, cacheKey ); final var statistics = factory.getStatistics(); if ( put && statistics.isStatisticsEnabled() ) { statistics.entityCachePut( StatsHelper.getRootEntityRole( persister ), cache.getRegion().getName() ); } } } protected boolean cacheInsert(EntityPersister persister, Object cacheKey) { final var session = getSession(); final var eventMonitor = session.getEventMonitor(); final var cachePutEvent = eventMonitor.beginCachePutEvent(); final var cacheAccessStrategy = persister.getCacheAccessStrategy(); final var eventListenerManager = session.getEventListenerManager(); boolean insert = false; try { eventListenerManager.cachePutStart(); insert = cacheAccessStrategy.insert( session, cacheKey, cacheEntry, version ); return insert; } finally { eventMonitor.completeCachePutEvent( cachePutEvent, session, cacheAccessStrategy, getPersister(), insert, EventMonitor.CacheActionDescription.ENTITY_INSERT ); eventListenerManager.cachePutEnd(); } } protected void postInsert() { getEventListenerGroups() .eventListenerGroup_POST_INSERT .fireLazyEventOnEachListener( this::newPostInsertEvent, PostInsertEventListener::onPostInsert ); } private PostInsertEvent newPostInsertEvent() { return new PostInsertEvent( getInstance(), getId(), getState(), getPersister(), eventSource() ); } protected void postCommitInsert(boolean success) { getEventListenerGroups().eventListenerGroup_POST_COMMIT_INSERT .fireLazyEventOnEachListener( this::newPostInsertEvent, success ? PostInsertEventListener::onPostInsert : this::postCommitOnFailure ); } private void postCommitOnFailure(PostInsertEventListener listener, PostInsertEvent event) { if ( listener instanceof PostCommitInsertEventListener postCommitInsertEventListener ) { postCommitInsertEventListener.onPostInsertCommitFailed( event ); } else { //default to the legacy implementation that always fires the event listener.onPostInsert( event ); } } protected boolean preInsert() { final var listenerGroup = getEventListenerGroups().eventListenerGroup_PRE_INSERT; if ( listenerGroup.isEmpty() ) { return false; } else { boolean veto = false; final PreInsertEvent event = new PreInsertEvent( getInstance(), getId(), getState(), getPersister(), eventSource() ); for ( var listener : listenerGroup.listeners() ) { veto |= listener.onPreInsert( event ); } return veto; } } @Override public void doAfterTransactionCompletion(boolean success, SharedSessionContractImplementor session) throws HibernateException { final var persister = getPersister(); if ( success && isCachePutEnabled( persister, getSession() ) ) { final var cache = persister.getCacheAccessStrategy(); final var factory = session.getFactory(); final Object cacheKey = cache.generateCacheKey( getId(), persister, factory, session.getTenantIdentifier() ); final boolean put = cacheAfterInsert( cache, cacheKey ); final var statistics = factory.getStatistics(); if ( put && statistics.isStatisticsEnabled() ) { statistics.entityCachePut( StatsHelper.getRootEntityRole( persister ), cache.getRegion().getName() ); } } postCommitInsert( success ); } protected boolean cacheAfterInsert(EntityDataAccess cache, Object cacheKey) { final var session = getSession(); final var eventListenerManager = session.getEventListenerManager(); final var eventMonitor = session.getEventMonitor(); final var cachePutEvent = eventMonitor.beginCachePutEvent(); boolean afterInsert = false; try { eventListenerManager.cachePutStart(); afterInsert = cache.afterInsert( session, cacheKey, cacheEntry, version ); return afterInsert; } finally { eventMonitor.completeCachePutEvent( cachePutEvent, session, cache, getPersister(), afterInsert, EventMonitor.CacheActionDescription.ENTITY_AFTER_INSERT ); eventListenerManager.cachePutEnd(); } } @Override protected boolean hasPostCommitEventListeners() { final var group = getEventListenerGroups().eventListenerGroup_POST_COMMIT_INSERT; for ( var listener : group.listeners() ) { if ( listener.requiresPostCommitHandling( getPersister() ) ) { return true; } } return false; } protected boolean isCachePutEnabled(EntityPersister persister, SharedSessionContractImplementor session) { return persister.canWriteToCache() && !persister.isCacheInvalidationRequired() && session.getCacheMode().isPutEnabled(); } }
EntityInsertAction
java
google__guava
android/guava/src/com/google/common/hash/BloomFilter.java
{ "start": 3563, "end": 23607 }
interface ____ extends Serializable { /** * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element. * * <p>Returns whether any bits changed as a result of this operation. */ <T extends @Nullable Object> boolean put( @ParametricNullness T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits); /** * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element; * returns {@code true} if and only if all selected bits are set. */ <T extends @Nullable Object> boolean mightContain( @ParametricNullness T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits); /** * Identifier used to encode this strategy, when marshalled as part of a BloomFilter. Only * values in the [-128, 127] range are valid for the compact serial form. Non-negative values * are reserved for enums defined in BloomFilterStrategies; negative values are reserved for any * custom, stateful strategy we may define (e.g. any kind of strategy that would depend on user * input). */ int ordinal(); } /** The bit set of the BloomFilter (not necessarily power of 2!) */ private final LockFreeBitArray bits; /** Number of hashes per element */ private final int numHashFunctions; /** The funnel to translate Ts to bytes */ private final Funnel<? super T> funnel; /** The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. */ private final Strategy strategy; /** Natural logarithm of 2, used to optimize calculations in Bloom filter sizing. */ private static final double LOG_TWO = Math.log(2); /** Square of the natural logarithm of 2, reused to optimize the bit size calculation. */ private static final double SQUARED_LOG_TWO = LOG_TWO * LOG_TWO; /** Creates a BloomFilter. */ private BloomFilter( LockFreeBitArray bits, int numHashFunctions, Funnel<? super T> funnel, Strategy strategy) { checkArgument(numHashFunctions > 0, "numHashFunctions (%s) must be > 0", numHashFunctions); checkArgument( numHashFunctions <= 255, "numHashFunctions (%s) must be <= 255", numHashFunctions); this.bits = checkNotNull(bits); this.numHashFunctions = numHashFunctions; this.funnel = checkNotNull(funnel); this.strategy = checkNotNull(strategy); } /** * Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to * this instance but shares no mutable state. * * @since 12.0 */ public BloomFilter<T> copy() { return new BloomFilter<>(bits.copy(), numHashFunctions, funnel, strategy); } /** * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter, {@code * false} if this is <i>definitely</i> not the case. */ public boolean mightContain(@ParametricNullness T object) { return strategy.mightContain(object, funnel, numHashFunctions, bits); } /** * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #mightContain} * instead. */ @InlineMe(replacement = "this.mightContain(input)") @Deprecated @Override public boolean apply(@ParametricNullness T input) { return mightContain(input); } /** * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of {@link * #mightContain(Object)} with the same element will always return {@code true}. * * @return true if the Bloom filter's bits changed as a result of this operation. If the bits * changed, this is <i>definitely</i> the first time {@code object} has been added to the * filter. If the bits haven't changed, this <i>might</i> be the first time {@code object} has * been added to the filter. Note that {@code put(t)} always returns the <i>opposite</i> * result to what {@code mightContain(t)} would have returned at the time it is called. * @since 12.0 (present in 11.0 with {@code void} return type}) */ @CanIgnoreReturnValue public boolean put(@ParametricNullness T object) { return strategy.put(object, funnel, numHashFunctions, bits); } /** * Returns the probability that {@linkplain #mightContain(Object)} will erroneously return {@code * true} for an object that has not actually been put in the {@code BloomFilter}. * * <p>Ideally, this number should be close to the {@code fpp} parameter passed in {@linkplain * #create(Funnel, int, double)}, or smaller. If it is significantly higher, it is usually the * case that too many elements (more than expected) have been put in the {@code BloomFilter}, * degenerating it. * * @since 14.0 (since 11.0 as expectedFalsePositiveProbability()) */ public double expectedFpp() { return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions); } /** * Returns an estimate for the total number of distinct elements that have been added to this * Bloom filter. This approximation is reasonably accurate if it does not exceed the value of * {@code expectedInsertions} that was used when constructing the filter. * * @since 22.0 */ public long approximateElementCount() { long bitSize = bits.bitSize(); long bitCount = bits.bitCount(); /* * Each insertion is expected to reduce the # of clear bits by a factor of * `numHashFunctions/bitSize`. So, after n insertions, expected bitCount is `bitSize * (1 - (1 - * numHashFunctions/bitSize)^n)`. Solving that for n, and approximating `ln x` as `x - 1` when x * is close to 1 (why?), gives the following formula. */ double fractionOfBitsSet = (double) bitCount / bitSize; return DoubleMath.roundToLong( -Math.log1p(-fractionOfBitsSet) * bitSize / numHashFunctions, RoundingMode.HALF_UP); } /** Returns the number of bits in the underlying bit array. */ @VisibleForTesting long bitSize() { return bits.bitSize(); } /** * Determines whether a given Bloom filter is compatible with this Bloom filter. For two Bloom * filters to be compatible, they must: * * <ul> * <li>not be the same instance * <li>have the same number of hash functions * <li>have the same bit size * <li>have the same strategy * <li>have equal funnels * </ul> * * @param that The Bloom filter to check for compatibility. * @since 15.0 */ public boolean isCompatible(BloomFilter<T> that) { checkNotNull(that); return this != that && this.numHashFunctions == that.numHashFunctions && this.bitSize() == that.bitSize() && this.strategy.equals(that.strategy) && this.funnel.equals(that.funnel); } /** * Combines this Bloom filter with another Bloom filter by performing a bitwise OR of the * underlying data. The mutations happen to <b>this</b> instance. Callers must ensure the Bloom * filters are appropriately sized to avoid saturating them. * * @param that The Bloom filter to combine this Bloom filter with. It is not mutated. * @throws IllegalArgumentException if {@code isCompatible(that) == false} * @since 15.0 */ public void putAll(BloomFilter<T> that) { checkNotNull(that); checkArgument(this != that, "Cannot combine a BloomFilter with itself."); checkArgument( this.numHashFunctions == that.numHashFunctions, "BloomFilters must have the same number of hash functions (%s != %s)", this.numHashFunctions, that.numHashFunctions); checkArgument( this.bitSize() == that.bitSize(), "BloomFilters must have the same size underlying bit arrays (%s != %s)", this.bitSize(), that.bitSize()); checkArgument( this.strategy.equals(that.strategy), "BloomFilters must have equal strategies (%s != %s)", this.strategy, that.strategy); checkArgument( this.funnel.equals(that.funnel), "BloomFilters must have equal funnels (%s != %s)", this.funnel, that.funnel); this.bits.putAll(that.bits); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof BloomFilter) { BloomFilter<?> that = (BloomFilter<?>) object; return this.numHashFunctions == that.numHashFunctions && this.funnel.equals(that.funnel) && this.bits.equals(that.bits) && this.strategy.equals(that.strategy); } return false; } @Override public int hashCode() { return Objects.hash(numHashFunctions, funnel, strategy, bits); } /** * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link * BloomFilter} with false positive probability 3%. * * <p>Note that if the {@code Collector} receives significantly more elements than specified, the * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive * probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @return a {@code Collector} generating a {@code BloomFilter} of the received elements * @since 33.4.0 (but since 23.0 in the JRE flavor) */ @IgnoreJRERequirement // Users will use this only if they're already using streams. public static <T extends @Nullable Object> Collector<T, ?, BloomFilter<T>> toBloomFilter( Funnel<? super T> funnel, long expectedInsertions) { return toBloomFilter(funnel, expectedInsertions, 0.03); } /** * Returns a {@code Collector} expecting the specified number of insertions, and yielding a {@link * BloomFilter} with the specified expected false positive probability. * * <p>Note that if the {@code Collector} receives significantly more elements than specified, the * resulting {@code BloomFilter} will suffer a sharp deterioration of its false positive * probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code Collector} generating a {@code BloomFilter} of the received elements * @since 33.4.0 (but since 23.0 in the JRE flavor) */ @IgnoreJRERequirement // Users will use this only if they're already using streams. public static <T extends @Nullable Object> Collector<T, ?, BloomFilter<T>> toBloomFilter( Funnel<? super T> funnel, long expectedInsertions, double fpp) { checkNotNull(funnel); checkArgument( expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); return Collector.of( () -> BloomFilter.create(funnel, expectedInsertions, fpp), BloomFilter::put, (bf1, bf2) -> { bf1.putAll(bf2); return bf1; }, Collector.Characteristics.UNORDERED, Collector.Characteristics.CONCURRENT); } /** * Creates a {@link BloomFilter} with the expected number of insertions and expected false * positive probability. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code BloomFilter} */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, int expectedInsertions, double fpp) { return create(funnel, (long) expectedInsertions, fpp); } /** * Creates a {@link BloomFilter} with the expected number of insertions and expected false * positive probability. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @param fpp the desired false positive probability (must be positive and less than 1.0) * @return a {@code BloomFilter} * @since 19.0 */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, long expectedInsertions, double fpp) { return create(funnel, expectedInsertions, fpp, BloomFilterStrategies.MURMUR128_MITZ_64); } @VisibleForTesting static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, long expectedInsertions, double fpp, Strategy strategy) { checkNotNull(funnel); checkArgument( expectedInsertions >= 0, "Expected insertions (%s) must be >= 0", expectedInsertions); checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp); checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp); checkNotNull(strategy); if (expectedInsertions == 0) { expectedInsertions = 1; } /* * TODO(user): Put a warning in the javadoc about tiny fpp values, since the resulting size * is proportional to -log(p), but there is not much of a point after all, e.g. * optimalM(1000, 0.0000000000000001) = 76680 which is less than 10kb. Who cares! */ long numBits = optimalNumOfBits(expectedInsertions, fpp); int numHashFunctions = optimalNumOfHashFunctions(fpp); try { return new BloomFilter<>(new LockFreeBitArray(numBits), numHashFunctions, funnel, strategy); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e); } } /** * Creates a {@link BloomFilter} with the expected number of insertions and a default expected * false positive probability of 3%. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @return a {@code BloomFilter} */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, int expectedInsertions) { return create(funnel, (long) expectedInsertions); } /** * Creates a {@link BloomFilter} with the expected number of insertions and a default expected * false positive probability of 3%. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements than specified, * will result in its saturation, and a sharp deterioration of its false positive probability. * * <p>The constructed {@code BloomFilter} will be serializable if the provided {@code Funnel<T>} * is. * * <p>It is recommended that the funnel be implemented as a Java enum. This has the benefit of * ensuring proper serialization and deserialization, which is important since {@link #equals} * also relies on object identity of funnels. * * @param funnel the funnel of T's that the constructed {@code BloomFilter} will use * @param expectedInsertions the number of expected insertions to the constructed {@code * BloomFilter}; must be positive * @return a {@code BloomFilter} * @since 19.0 */ public static <T extends @Nullable Object> BloomFilter<T> create( Funnel<? super T> funnel, long expectedInsertions) { return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions } // Cheat sheet: // // m: total bits // n: expected insertions // b: m/n, bits per insertion // p: expected false positive probability // // 1) Optimal k = b * ln2 // 2) p = (1 - e ^ (-kn/m))^k // 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b // 4) For optimal k: m = -nlnp / ((ln2) ^ 2) /** * Computes the optimal number of hash functions (k) for a given false positive probability (p). * * <p>See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. * * @param p desired false positive probability (must be between 0 and 1, exclusive) */ @VisibleForTesting static int optimalNumOfHashFunctions(double p) { // -log(p) / log(2), ensuring the result is rounded to avoid truncation. return max(1, (int) Math.round(-Math.log(p) / LOG_TWO)); } /** * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified * expected insertions, the required false positive probability. * * <p>See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the * formula. * * @param n expected insertions (must be positive) * @param p false positive rate (must be 0 < p < 1) */ @VisibleForTesting static long optimalNumOfBits(long n, double p) { if (p == 0) { p = Double.MIN_VALUE; } return (long) (-n * Math.log(p) / SQUARED_LOG_TWO); } private Object writeReplace() { return new SerialForm<T>(this); } private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } private static final
Strategy
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/AnnotationBasedAuthMechanismSelectionTest.java
{ "start": 17906, "end": 18236 }
class ____ auth mechanism is going to be used return super.defaultImplementedClassLevelInterfaceMethod(); } @Path("overridden-parent-class-endpoint") @GET @Override public String overriddenParentClassEndpoint() { // here we repeated Path annotation, therefore this
http
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/metrics/dump/MetricDump.java
{ "start": 2290, "end": 2747 }
class ____ extends MetricDump { public final long count; public CounterDump(QueryScopeInfo scopeInfo, String name, long count) { super(scopeInfo, name); this.count = count; } @Override public byte getCategory() { return METRIC_CATEGORY_COUNTER; } } /** Container for the value of a {@link org.apache.flink.metrics.Gauge} as a string. */ public static
CounterDump
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/logs/OtelLogsHandlerDisabledTest.java
{ "start": 842, "end": 2471 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addClasses(JBossLoggingBean.class) .addClasses(InMemoryLogRecordExporter.class, InMemoryLogRecordExporterProvider.class) .addAsResource(new StringAsset(InMemoryLogRecordExporterProvider.class.getCanonicalName()), "META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider") .add(new StringAsset( "quarkus.otel.logs.enabled=true\n" + "quarkus.otel.logs.handler.enabled=false\n" + "quarkus.otel.traces.enabled=false\n"), "application.properties")); @Inject InMemoryLogRecordExporter logRecordExporter; @Inject JBossLoggingBean jBossLoggingBean; @BeforeEach void setup() { logRecordExporter.reset(); } @Test public void testLoggingData() { final String message = "Logging handler disabled"; assertEquals("hello", jBossLoggingBean.hello(message)); List<LogRecordData> finishedLogRecordItems = logRecordExporter .getFinishedLogRecordItemsWithWait(Duration.ofMillis(1000)); assertEquals(0, finishedLogRecordItems.size()); } @ApplicationScoped public static
OtelLogsHandlerDisabledTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/internal/UserTypeJavaTypeWrapper.java
{ "start": 5275, "end": 7542 }
class ____ implements MutabilityPlan<J> { private final UserType<J> userType; public MutabilityPlanWrapper(UserType<J> userType) { this.userType = userType; } @Override public boolean isMutable() { return userType.isMutable(); } @Override public J deepCopy(J value) { return userType.deepCopy( value ); } @Override public Serializable disassemble(J value, SharedSessionContract session) { final Serializable disassembled = userType.disassemble( value ); // Since UserType#disassemble is an optional operation, // we have to handle the fact that it could produce a null value, // in which case we will try to use a converter for disassembling, // or if that doesn't exist, simply use the domain value as is return disassembled == null && value != null ? disassemble( value, customType.getValueConverter(), session ) : disassembled; } private <R> Serializable disassemble(J value, BasicValueConverter<J, R> converter, SharedSessionContract session) { if ( converter == null ) { return (Serializable) value; } else { final Object converted = customType.convertToRelationalValue( value ); return converter.getRelationalJavaType().getMutabilityPlan() .disassemble( (R) converted, session ); } } @Override public J assemble(Serializable cached, SharedSessionContract session) { final J assembled = userType.assemble( cached, null ); // Since UserType#assemble is an optional operation, // we have to handle the fact that it could produce a null value, // in which case we will try to use a converter for assembling, // or if that doesn't exist, simply use the relational value as is return assembled == null && cached != null ? disassemble( cached, customType.getValueConverter(), session ) : assembled; } private J disassemble(Serializable cached, BasicValueConverter<J, ?> converter, SharedSessionContract session) { if ( converter == null ) { //noinspection unchecked return (J) cached; } else { final Object assembled = converter.getRelationalJavaType().getMutabilityPlan() .assemble( cached, session ); return (J) customType.convertToDomainValue( assembled ); } } } }
MutabilityPlanWrapper
java
apache__camel
components/camel-file/src/main/java/org/apache/camel/component/file/strategy/FileIdempotentChangedRepositoryReadLockStrategy.java
{ "start": 2104, "end": 13326 }
class ____ extends ServiceSupport implements GenericFileExclusiveReadLockStrategy<File>, CamelContextAware { private static final Logger LOG = LoggerFactory.getLogger(FileIdempotentChangedRepositoryReadLockStrategy.class); private final FileChangedExclusiveReadLockStrategy changed; private GenericFileEndpoint<File> endpoint; private LoggingLevel readLockLoggingLevel = LoggingLevel.DEBUG; private CamelContext camelContext; private IdempotentRepository idempotentRepository; private boolean removeOnRollback = true; private boolean removeOnCommit; private int readLockIdempotentReleaseDelay; private boolean readLockIdempotentReleaseAsync; private int readLockIdempotentReleaseAsyncPoolSize; private ScheduledExecutorService readLockIdempotentReleaseExecutorService; private boolean shutdownExecutorService; public FileIdempotentChangedRepositoryReadLockStrategy() { this.changed = new FileChangedExclusiveReadLockStrategy(); // no need to use marker file as idempotent ensures exclusive read-lock this.changed.setMarkerFiler(false); this.changed.setDeleteOrphanLockFiles(false); } @Override public void prepareOnStartup(GenericFileOperations<File> operations, GenericFileEndpoint<File> endpoint) throws Exception { this.endpoint = endpoint; LOG.info("Using FileIdempotentRepositoryReadLockStrategy: {} on endpoint: {}", idempotentRepository, endpoint); changed.prepareOnStartup(operations, endpoint); } @Override public boolean acquireExclusiveReadLock(GenericFileOperations<File> operations, GenericFile<File> file, Exchange exchange) throws Exception { // in clustered mode then another node may have processed the file so we // must check here again if the file exists File path = file.getFile(); if (!path.exists()) { return false; } // check if we can begin on this file String key = asKey(exchange, file); boolean answer = false; try { answer = idempotentRepository.add(exchange, key); } catch (Exception e) { if (LOG.isTraceEnabled()) { LOG.trace("Cannot acquire read lock due to {}. Will skip the file: {}", e.getMessage(), file, e); } } if (!answer) { // another node is processing the file so skip CamelLogger.log(LOG, readLockLoggingLevel, "Cannot acquire read lock. Will skip the file: " + file); } if (answer) { // if we acquired during idempotent then check changed also answer = changed.acquireExclusiveReadLock(operations, file, exchange); if (!answer) { // remove from idempotent as we did not acquire it from changed idempotentRepository.remove(exchange, key); } } return answer; } @Override public void releaseExclusiveReadLockOnAbort( GenericFileOperations<File> operations, GenericFile<File> file, Exchange exchange) throws Exception { changed.releaseExclusiveReadLockOnAbort(operations, file, exchange); } @Override public void releaseExclusiveReadLockOnRollback( GenericFileOperations<File> operations, GenericFile<File> file, Exchange exchange) throws Exception { String key = asKey(exchange, file); Runnable r = () -> { if (removeOnRollback) { idempotentRepository.remove(exchange, key); } else { // okay we should not remove then confirm instead idempotentRepository.confirm(exchange, key); } try { changed.releaseExclusiveReadLockOnRollback(operations, file, exchange); } catch (Exception e) { LOG.warn("Error during releasing exclusive read lock on rollback. This exception is ignored.", e); } }; delayOrScheduleLockRelease(r); } private void delayOrScheduleLockRelease(Runnable r) throws InterruptedException { if (readLockIdempotentReleaseDelay > 0 && readLockIdempotentReleaseExecutorService != null) { LOG.debug("Scheduling read lock release task to run asynchronous delayed after {} millis", readLockIdempotentReleaseDelay); readLockIdempotentReleaseExecutorService.schedule(r, readLockIdempotentReleaseDelay, TimeUnit.MILLISECONDS); } else if (readLockIdempotentReleaseDelay > 0) { LOG.debug("Delaying read lock release task {} millis", readLockIdempotentReleaseDelay); Thread.sleep(readLockIdempotentReleaseDelay); r.run(); } else { r.run(); } } @Override public void releaseExclusiveReadLockOnCommit( GenericFileOperations<File> operations, GenericFile<File> file, Exchange exchange) throws Exception { String key = asKey(exchange, file); Runnable r = () -> { if (removeOnCommit) { idempotentRepository.remove(exchange, key); } else { // confirm on commit idempotentRepository.confirm(exchange, key); } try { changed.releaseExclusiveReadLockOnCommit(operations, file, exchange); } catch (Exception e) { LOG.warn("Error during releasing exclusive read lock on rollback. This exception is ignored.", e); } }; delayOrScheduleLockRelease(r); } @Override public void setTimeout(long timeout) { changed.setTimeout(timeout); } @Override public void setCheckInterval(long checkInterval) { changed.setCheckInterval(checkInterval); } @Override public void setReadLockLoggingLevel(LoggingLevel readLockLoggingLevel) { this.readLockLoggingLevel = readLockLoggingLevel; changed.setReadLockLoggingLevel(readLockLoggingLevel); } @Override public void setMarkerFiler(boolean markerFile) { // we do not use marker files } @Override public void setDeleteOrphanLockFiles(boolean deleteOrphanLockFiles) { // we do not use marker files } public void setMinLength(long minLength) { changed.setMinLength(minLength); } public void setMinAge(long minAge) { changed.setMinAge(minAge); } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } /** * The idempotent repository to use as the store for the read locks. */ public IdempotentRepository getIdempotentRepository() { return idempotentRepository; } /** * The idempotent repository to use as the store for the read locks. */ public void setIdempotentRepository(IdempotentRepository idempotentRepository) { this.idempotentRepository = idempotentRepository; } /** * Whether to remove the file from the idempotent repository when doing a rollback. * <p/> * By default this is true. */ public boolean isRemoveOnRollback() { return removeOnRollback; } /** * Whether to remove the file from the idempotent repository when doing a rollback. * <p/> * By default this is true. */ public void setRemoveOnRollback(boolean removeOnRollback) { this.removeOnRollback = removeOnRollback; } /** * Whether to remove the file from the idempotent repository when doing a commit. * <p/> * By default this is false. */ public boolean isRemoveOnCommit() { return removeOnCommit; } /** * Whether to remove the file from the idempotent repository when doing a commit. * <p/> * By default this is false. */ public void setRemoveOnCommit(boolean removeOnCommit) { this.removeOnCommit = removeOnCommit; } /** * Whether to delay the release task for a period of millis. */ public void setReadLockIdempotentReleaseDelay(int readLockIdempotentReleaseDelay) { this.readLockIdempotentReleaseDelay = readLockIdempotentReleaseDelay; } public boolean isReadLockIdempotentReleaseAsync() { return readLockIdempotentReleaseAsync; } /** * Whether the delayed release task should be synchronous or asynchronous. */ public void setReadLockIdempotentReleaseAsync(boolean readLockIdempotentReleaseAsync) { this.readLockIdempotentReleaseAsync = readLockIdempotentReleaseAsync; } public int getReadLockIdempotentReleaseAsyncPoolSize() { return readLockIdempotentReleaseAsyncPoolSize; } /** * The number of threads in the scheduled thread pool when using asynchronous release tasks. */ public void setReadLockIdempotentReleaseAsyncPoolSize(int readLockIdempotentReleaseAsyncPoolSize) { this.readLockIdempotentReleaseAsyncPoolSize = readLockIdempotentReleaseAsyncPoolSize; } public ScheduledExecutorService getReadLockIdempotentReleaseExecutorService() { return readLockIdempotentReleaseExecutorService; } /** * To use a custom and shared thread pool for asynchronous release tasks. */ public void setReadLockIdempotentReleaseExecutorService(ScheduledExecutorService readLockIdempotentReleaseExecutorService) { this.readLockIdempotentReleaseExecutorService = readLockIdempotentReleaseExecutorService; } protected String asKey(Exchange exchange, GenericFile<File> file) { // use absolute file path as default key, but evaluate if an expression // key was configured String key = file.getAbsoluteFilePath(); if (endpoint.getIdempotentKey() != null) { Exchange dummy = GenericFileHelper.createDummy(endpoint, exchange, () -> file); key = endpoint.getIdempotentKey().evaluate(dummy, String.class); } return key; } @Override protected void doStart() throws Exception { ObjectHelper.notNull(camelContext, "camelContext", this); ObjectHelper.notNull(idempotentRepository, "idempotentRepository", this); if (readLockIdempotentReleaseAsync && readLockIdempotentReleaseExecutorService == null) { readLockIdempotentReleaseExecutorService = camelContext.getExecutorServiceManager().newScheduledThreadPool(this, "ReadLockChangedIdempotentReleaseTask", readLockIdempotentReleaseAsyncPoolSize); shutdownExecutorService = true; } } @Override protected void doStop() throws Exception { if (shutdownExecutorService && readLockIdempotentReleaseExecutorService != null) { camelContext.getExecutorServiceManager().shutdownGraceful(readLockIdempotentReleaseExecutorService, 30000); readLockIdempotentReleaseExecutorService = null; } } }
FileIdempotentChangedRepositoryReadLockStrategy
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/support/EnvironmentPostProcessorApplicationListenerTests.java
{ "start": 7194, "end": 7679 }
class ____ implements EnvironmentPostProcessor { TestEnvironmentPostProcessor(DeferredLogFactory logFactory, BootstrapRegistry bootstrapRegistry) { assertThat(logFactory).isNotNull(); assertThat(bootstrapRegistry).isNotNull(); } @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { ((MockEnvironment) environment).setProperty("processed", "true"); } } } @Nested
TestEnvironmentPostProcessor
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ConstantPatternCompileTest.java
{ "start": 1567, "end": 1913 }
class ____ { boolean isCar(String input) { return Pattern.compile("car").matcher(input).matches(); } } """) .addOutputLines( "in/Test.java", """ import java.util.regex.Matcher; import java.util.regex.Pattern;
Test
java
quarkusio__quarkus
independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/classloading/QuarkusClassLoader.java
{ "start": 31291, "end": 31819 }
class ____ %s", this); } List<Runnable> tasks; synchronized (closeTasks) { tasks = new ArrayList<>(closeTasks); } for (Runnable i : tasks) { try { i.run(); } catch (Throwable t) { log.error("Failed to run close task", t); } } if (driverLoaded) { //DriverManager only lets you remove drivers with the same CL as the caller //so we need do define the cleaner in this
loader
java
redisson__redisson
redisson/src/test/java/org/redisson/BaseMapTest.java
{ "start": 4990, "end": 19794 }
class ____ implements Serializable { private String name; public MyClass(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MyClass myClass = (MyClass) o; return Objects.equals(name, myClass.name); } @Override public int hashCode() { return Objects.hash(name); } @Override public String toString() { return "MyClass{" + "name='" + name + '\'' + '}'; } } @Test public void testComputeIfPresentMutable() { RMap<String, MyClass> map = getMap("map"); map.put("1", new MyClass("value1")); map.computeIfPresent("1", (key, value) -> { assertThat(value).isEqualTo(new MyClass("value1")); value.setName("value2"); return value; }); assertThat(map.get("1")).isEqualTo(new MyClass("value2")); } @Test public void testComputeIfAbsent() { RMap<String, String> map = getMap("map"); map.computeIfAbsent("1", (key) -> { assertThat(key).isEqualTo("1"); return "12"; }); assertThat(map.get("1")).isEqualTo("12"); map.computeIfAbsent("1", (key) -> { assertThat(key).isEqualTo("1"); return "13"; }); assertThat(map.get("1")).isEqualTo("12"); } @Test public void testMerge() { RMap<String, String> map = getMap("map"); map.merge("1", "2", (key, oldValue) -> { return "12"; }); assertThat(map.get("1")).isEqualTo("2"); map.merge("1", "2", (key, oldValue) -> { return "12"; }); assertThat(map.get("1")).isEqualTo("12"); map.merge("1", "2", (key, oldValue) -> { return null; }); assertThat(map.get("1")).isNull(); } @Test public void testCompute() { RMap<String, String> map = getMap("map"); map.compute("1", (key, oldValue) -> { return "12"; }); assertThat(map.get("1")).isEqualTo("12"); map.compute("1", (key, oldValue) -> { return (oldValue == null) ? "12" : oldValue.concat("34"); }); assertThat(map.get("1")).isEqualTo("1234"); map.compute("1", (key, oldValue) -> { return null; }); assertThat(map.get("1")).isNull(); } @Test public void testComputeAsync() { RMap<String, String> map = getMap("mapAsync"); RFuture<String> res1 = map.computeAsync("1", (key, oldValue) -> { return "12"; }); assertThat(res1.toCompletableFuture().join()).isEqualTo("12"); assertThat(map.get("1")).isEqualTo("12"); RFuture<String> res2 = map.computeAsync("1", (key, oldValue) -> { return (oldValue == null) ? "12" : oldValue.concat("34"); }); assertThat(res2.toCompletableFuture().join()).isEqualTo("1234"); assertThat(map.get("1")).isEqualTo("1234"); RFuture<String> res3 = map.computeAsync("1", (key, oldValue) -> { return null; }); assertThat(res3.toCompletableFuture().join()).isNull(); assertThat(map.get("1")).isNull(); } @Test public void testGetAllWithStringKeys() { RMap<String, Integer> map = getMap("getAllStrings"); map.put("A", 100); map.put("B", 200); map.put("C", 300); map.put("D", 400); Map<String, Integer> filtered = map.getAll(new HashSet<String>(Arrays.asList("B", "C", "E"))); Map<String, Integer> expectedMap = new HashMap<String, Integer>(); expectedMap.put("B", 200); expectedMap.put("C", 300); assertThat(filtered).isEqualTo(expectedMap); destroy(map); } @Test public void testStringCodec() { Config config = createConfig(); config.setCodec(StringCodec.INSTANCE); RedissonClient redisson = Redisson.create(config); RMap<String, String> rmap = redisson.getMap("TestRMap01"); rmap.put("A", "1"); rmap.put("B", "2"); for (Entry<String, String> next : rmap.entrySet()) { assertThat(next).isIn(new AbstractMap.SimpleEntry("A", "1"), new AbstractMap.SimpleEntry("B", "2")); } destroy(rmap); redisson.shutdown(); } @Test public void testInteger() { RMap<Integer, Integer> map = getMap("test_int"); map.put(1, 2); map.put(3, 4); assertThat(map.size()).isEqualTo(2); Integer val = map.get(1); assertThat(val).isEqualTo(2); Integer val2 = map.get(3); assertThat(val2).isEqualTo(4); destroy(map); } @Test public void testLong() { RMap<Long, Long> map = getMap("test_long"); map.put(1L, 2L); map.put(3L, 4L); assertThat(map.size()).isEqualTo(2); Long val = map.get(1L); assertThat(val).isEqualTo(2); Long val2 = map.get(3L); assertThat(val2).isEqualTo(4); destroy(map); } @Test public void testIterator() { RMap<Integer, Integer> rMap = getMap("123"); int size = 1000; for (int i = 0; i < size; i++) { rMap.put(i, i); } assertThat(rMap.size()).isEqualTo(1000); int counter = 0; for (Integer key : rMap.keySet()) { counter++; } assertThat(counter).isEqualTo(size); counter = 0; for (Integer value : rMap.values()) { counter++; } assertThat(counter).isEqualTo(size); counter = 0; for (Entry<Integer, Integer> entry : rMap.entrySet()) { counter++; } assertThat(counter).isEqualTo(size); destroy(rMap); } @Test public void testOrdering() { Map<String, String> map = new LinkedHashMap<String, String>(); // General player data map.put("name", "123"); map.put("ip", "4124"); map.put("rank", "none"); map.put("tokens", "0"); map.put("coins", "0"); // Arsenal player statistics map.put("ar_score", "0"); map.put("ar_gameswon", "0"); map.put("ar_gameslost", "0"); map.put("ar_kills", "0"); map.put("ar_deaths", "0"); RMap<String, String> rmap = getMap("123"); Assumptions.assumeTrue(!(rmap instanceof RLocalCachedMap)); rmap.putAll(map); assertThat(rmap.keySet()).containsExactlyElementsOf(map.keySet()); assertThat(rmap.readAllKeySet()).containsExactlyElementsOf(map.keySet()); assertThat(rmap.values()).containsExactlyElementsOf(map.values()); assertThat(rmap.readAllValues()).containsExactlyElementsOf(map.values()); assertThat(rmap.entrySet()).containsExactlyElementsOf(map.entrySet()); assertThat(rmap.readAllEntrySet()).containsExactlyElementsOf(map.entrySet()); destroy(rmap); } @Test public void testNullValue() { Assertions.assertThrows(NullPointerException.class, () -> { RMap<Integer, String> map = getMap("simple12"); destroy(map); map.put(1, null); }); } @Test public void testNullKey() { Assertions.assertThrows(NullPointerException.class, () -> { RMap<Integer, String> map = getMap("simple12"); destroy(map); map.put(null, "1"); }); } @Test public void testSize() { RMap<SimpleKey, SimpleValue> map = getMap("simple"); map.put(new SimpleKey("1"), new SimpleValue("2")); map.put(new SimpleKey("3"), new SimpleValue("4")); map.put(new SimpleKey("5"), new SimpleValue("6")); assertThat(map.size()).isEqualTo(3); map.put(new SimpleKey("1"), new SimpleValue("2")); map.put(new SimpleKey("3"), new SimpleValue("4")); assertThat(map.size()).isEqualTo(3); map.put(new SimpleKey("1"), new SimpleValue("21")); map.put(new SimpleKey("3"), new SimpleValue("41")); assertThat(map.size()).isEqualTo(3); map.put(new SimpleKey("51"), new SimpleValue("6")); assertThat(map.size()).isEqualTo(4); map.remove(new SimpleKey("3")); assertThat(map.size()).isEqualTo(3); destroy(map); } @Test public void testEmptyRemove() { RMap<Integer, Integer> map = getMap("simple"); assertThat(map.remove(1, 3)).isFalse(); map.put(4, 5); assertThat(map.remove(4, 5)).isTrue(); destroy(map); } @Test public void testFastPutIfAbsent() throws Exception { RMap<SimpleKey, SimpleValue> map = getMap("simple"); SimpleKey key = new SimpleKey("1"); SimpleValue value = new SimpleValue("2"); map.put(key, value); assertThat(map.fastPutIfAbsent(key, new SimpleValue("3"))).isFalse(); assertThat(map.get(key)).isEqualTo(value); SimpleKey key1 = new SimpleKey("2"); SimpleValue value1 = new SimpleValue("4"); assertThat(map.fastPutIfAbsent(key1, value1)).isTrue(); assertThat(map.get(key1)).isEqualTo(value1); destroy(map); } @Test public void testPutAll() { RMap<Integer, String> map = getMap("simple"); map.put(1, "1"); map.put(2, "2"); map.put(3, "3"); Map<Integer, String> joinMap = new HashMap<Integer, String>(); joinMap.put(4, "4"); joinMap.put(5, "5"); joinMap.put(6, "6"); map.putAll(joinMap); assertThat(map.keySet()).containsOnly(1, 2, 3, 4, 5, 6); destroy(map); } @Test public void testPutAllBatched() { RMap<Integer, String> map = getMap("simple"); map.put(1, "1"); map.put(2, "2"); map.put(3, "3"); Map<Integer, String> joinMap = new HashMap<Integer, String>(); joinMap.put(4, "4"); joinMap.put(5, "5"); joinMap.put(6, "6"); map.putAll(joinMap, 5); assertThat(map.keySet()).containsOnly(1, 2, 3, 4, 5, 6); Map<Integer, String> joinMap2 = new HashMap<Integer, String>(); joinMap2.put(7, "7"); joinMap2.put(8, "8"); joinMap2.put(9, "9"); joinMap2.put(10, "10"); joinMap2.put(11, "11"); map.putAll(joinMap2, 5); assertThat(map.keySet()).containsOnly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); Map<Integer, String> joinMap3 = new HashMap<Integer, String>(); joinMap3.put(12, "12"); joinMap3.put(13, "13"); joinMap3.put(14, "14"); joinMap3.put(15, "15"); joinMap3.put(16, "16"); joinMap3.put(17, "17"); joinMap3.put(18, "18"); map.putAll(joinMap3, 5); assertThat(map.keySet()).containsOnly(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18); destroy(map); } @Test public void testPutAllBig() { Map<Integer, String> joinMap = new HashMap<Integer, String>(); for (int i = 0; i < 100000; i++) { joinMap.put(i, "" + i); } RMap<Integer, String> map = getMap("simple"); map.putAll(joinMap); assertThat(map.size()).isEqualTo(joinMap.size()); destroy(map); } @Test public void testPutGet() { RMap<SimpleKey, SimpleValue> map = getMap("simple"); map.put(new SimpleKey("1"), new SimpleValue("2")); map.put(new SimpleKey("33"), new SimpleValue("44")); map.put(new SimpleKey("5"), new SimpleValue("6")); SimpleValue val1 = map.get(new SimpleKey("33")); assertThat(val1.getValue()).isEqualTo("44"); SimpleValue val2 = map.get(new SimpleKey("5")); assertThat(val2.getValue()).isEqualTo("6"); destroy(map); } @Test public void testPutIfAbsent() throws Exception { RMap<SimpleKey, SimpleValue> map = getMap("simple"); SimpleKey key = new SimpleKey("1"); SimpleValue value = new SimpleValue("2"); map.put(key, value); assertThat(map.putIfAbsent(key, new SimpleValue("3"))).isEqualTo(value); assertThat(map.get(key)).isEqualTo(value); SimpleKey key1 = new SimpleKey("2"); SimpleValue value1 = new SimpleValue("4"); assertThat(map.putIfAbsent(key1, value1)).isNull(); assertThat(map.get(key1)).isEqualTo(value1); destroy(map); } @Test public void testFastPutIfExists() throws Exception { RMap<SimpleKey, SimpleValue> map = getMap("simple"); SimpleKey key = new SimpleKey("1"); SimpleValue value = new SimpleValue("2"); assertThat(map.fastPutIfExists(key, new SimpleValue("3"))).isFalse(); assertThat(map.get(key)).isNull(); map.put(key, value); assertThat(map.fastPutIfExists(key, new SimpleValue("3"))).isTrue(); Thread.sleep(50); assertThat(map.get(key)).isEqualTo(new SimpleValue("3")); destroy(map); } @Test public void testPutIfExists() throws Exception { RMap<SimpleKey, SimpleValue> map = getMap("simple"); SimpleKey key = new SimpleKey("1"); SimpleValue value = new SimpleValue("2"); assertThat(map.putIfExists(key, new SimpleValue("3"))).isNull(); assertThat(map.get(key)).isNull(); map.put(key, value); assertThat(map.putIfExists(key, new SimpleValue("3"))).isEqualTo(value); assertThat(map.get(key)).isEqualTo(new SimpleValue("3")); destroy(map); } @Test @Timeout(5) public void testDeserializationErrorReturnsErrorImmediately() { RMap<String, SimpleObjectWithoutDefaultConstructor> map = getMap("deserializationFailure", new JsonJacksonCodec()); Assumptions.assumeTrue(!(map instanceof RLocalCachedMap)); SimpleObjectWithoutDefaultConstructor object = new SimpleObjectWithoutDefaultConstructor("test-val"); assertThat(object.getTestField()).isEqualTo("test-val"); map.put("test-key", object); try { map.get("test-key"); Assertions.fail("Expected exception from map.get() call"); } catch (Exception e) { e.printStackTrace(); } destroy(map); } public static
MyClass
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/annotation/MergedAnnotation.java
{ "start": 13312, "end": 23409 }
enum ____ * @throws NoSuchElementException if there is no matching attribute */ <E extends Enum<E>> E[] getEnumArray(String attributeName, Class<E> type) throws NoSuchElementException; /** * Get a required annotation attribute value from the annotation. * @param attributeName the attribute name * @param type the annotation type * @return the value as a {@link MergedAnnotation} * @throws NoSuchElementException if there is no matching attribute */ <T extends Annotation> MergedAnnotation<T> getAnnotation(String attributeName, Class<T> type) throws NoSuchElementException; /** * Get a required annotation array attribute value from the annotation. * @param attributeName the attribute name * @param type the annotation type * @return the value as a {@link MergedAnnotation} array * @throws NoSuchElementException if there is no matching attribute */ <T extends Annotation> MergedAnnotation<T>[] getAnnotationArray(String attributeName, Class<T> type) throws NoSuchElementException; /** * Get an optional attribute value from the annotation. * @param attributeName the attribute name * @return an optional value or {@link Optional#empty()} if there is no * matching attribute */ Optional<Object> getValue(String attributeName); /** * Get an optional attribute value from the annotation. * @param attributeName the attribute name * @param type the attribute type. Must be compatible with the underlying * attribute type or {@code Object.class}. * @return an optional value or {@link Optional#empty()} if there is no * matching attribute */ <T> Optional<T> getValue(String attributeName, Class<T> type); /** * Get the default attribute value from the annotation as specified in * the annotation declaration. * @param attributeName the attribute name * @return an optional of the default value or {@link Optional#empty()} if * there is no matching attribute or no defined default */ Optional<Object> getDefaultValue(String attributeName); /** * Get the default attribute value from the annotation as specified in * the annotation declaration. * @param attributeName the attribute name * @param type the attribute type. Must be compatible with the underlying * attribute type or {@code Object.class}. * @return an optional of the default value or {@link Optional#empty()} if * there is no matching attribute or no defined default */ <T> Optional<T> getDefaultValue(String attributeName, Class<T> type); /** * Create a new view of the annotation with all attributes that have default * values removed. * @return a filtered view of the annotation without any attributes that * have a default value * @see #filterAttributes(Predicate) */ MergedAnnotation<A> filterDefaultValues(); /** * Create a new view of the annotation with only attributes that match the * given predicate. * @param predicate a predicate used to filter attribute names * @return a filtered view of the annotation * @see #filterDefaultValues() * @see MergedAnnotationPredicates */ MergedAnnotation<A> filterAttributes(Predicate<String> predicate); /** * Create a new view of the annotation that exposes non-merged attribute values. * <p>Methods from this view will return attribute values with only alias mirroring * rules applied. Aliases to {@link #getMetaSource() meta-source} attributes will * not be applied. * @return a non-merged view of the annotation */ MergedAnnotation<A> withNonMergedAttributes(); /** * Create a new mutable {@link AnnotationAttributes} instance from this * merged annotation. * <p>The {@link Adapt adaptations} may be used to change the way that values * are added. * @param adaptations the adaptations that should be applied to the annotation values * @return an immutable map containing the attributes and values */ AnnotationAttributes asAnnotationAttributes(Adapt... adaptations); /** * Get an immutable {@link Map} that contains all the annotation attributes. * <p>The {@link Adapt adaptations} may be used to change the way that values are added. * @param adaptations the adaptations that should be applied to the annotation values * @return an immutable map containing the attributes and values */ Map<String, Object> asMap(Adapt... adaptations); /** * Create a new {@link Map} instance of the given type that contains all the annotation * attributes. * <p>The {@link Adapt adaptations} may be used to change the way that values are added. * @param factory a map factory * @param adaptations the adaptations that should be applied to the annotation values * @return a map containing the attributes and values */ <T extends Map<String, Object>> T asMap(Function<MergedAnnotation<?>, T> factory, Adapt... adaptations); /** * Create a type-safe synthesized version of this merged annotation that can * be used directly in code. * <p>The result is synthesized using a JDK {@link java.lang.reflect.Proxy Proxy} * and as a result may incur a computational cost when first invoked. * <p>If this merged annotation was created {@linkplain #of(AnnotatedElement, Class, Map) * from} a map of annotation attributes or default attribute values, those * attributes will always be synthesized into an annotation instance. * <p>If this merged annotation was created {@linkplain #from(Annotation) from} * an annotation instance, that annotation will be returned unmodified if it is * not <em>synthesizable</em>. An annotation is considered synthesizable if * it has not already been synthesized and one of the following is true. * <ul> * <li>The annotation declares attributes annotated with {@link AliasFor @AliasFor}.</li> * <li>The annotation declares attributes that are annotations or arrays of * annotations that are themselves synthesizable.</li> * </ul> * @return a synthesized version of the annotation or the original annotation * unmodified * @throws NoSuchElementException on a missing annotation */ A synthesize() throws NoSuchElementException; /** * Optionally create a type-safe synthesized version of this annotation based * on a condition predicate. * <p>The result is synthesized using a JDK {@link java.lang.reflect.Proxy Proxy} * and as a result may incur a computational cost when first invoked. * <p>Consult the documentation for {@link #synthesize()} for an explanation * of what is considered synthesizable. * @param condition the test to determine if the annotation can be synthesized * @return an optional containing the synthesized version of the annotation or * an empty optional if the condition doesn't match * @throws NoSuchElementException on a missing annotation * @see MergedAnnotationPredicates */ Optional<A> synthesize(Predicate<? super MergedAnnotation<A>> condition) throws NoSuchElementException; /** * Create a {@link MergedAnnotation} that represents a missing annotation * (i.e. one that is not present). * @return an instance representing a missing annotation */ static <A extends Annotation> MergedAnnotation<A> missing() { return MissingMergedAnnotation.getInstance(); } /** * Create a new {@link MergedAnnotation} instance from the specified * annotation. * @param annotation the annotation to include * @return a {@link MergedAnnotation} instance containing the annotation */ static <A extends Annotation> MergedAnnotation<A> from(A annotation) { return from(null, annotation); } /** * Create a new {@link MergedAnnotation} instance from the specified * annotation. * @param source the source for the annotation. This source is used only for * information and logging. It does not need to <em>actually</em> contain * the specified annotations, and it will not be searched. * @param annotation the annotation to include * @return a {@link MergedAnnotation} instance for the annotation */ static <A extends Annotation> MergedAnnotation<A> from(@Nullable Object source, A annotation) { return TypeMappedAnnotation.from(source, annotation); } /** * Create a new {@link MergedAnnotation} instance of the specified * annotation type. The resulting annotation will not have any attribute * values but may still be used to query default values. * @param annotationType the annotation type * @return a {@link MergedAnnotation} instance for the annotation */ static <A extends Annotation> MergedAnnotation<A> of(Class<A> annotationType) { return of(null, annotationType, null); } /** * Create a new {@link MergedAnnotation} instance of the specified * annotation type with attribute values supplied by a map. * @param annotationType the annotation type * @param attributes the annotation attributes or {@code null} if just default * values should be used * @return a {@link MergedAnnotation} instance for the annotation and attributes * @see #of(AnnotatedElement, Class, Map) */ static <A extends Annotation> MergedAnnotation<A> of( Class<A> annotationType, @Nullable Map<String, ?> attributes) { return of(null, annotationType, attributes); } /** * Create a new {@link MergedAnnotation} instance of the specified * annotation type with attribute values supplied by a map. * @param source the source for the annotation. This source is used only for * information and logging. It does not need to <em>actually</em> contain * the specified annotations and it will not be searched. * @param annotationType the annotation type * @param attributes the annotation attributes or {@code null} if just default * values should be used * @return a {@link MergedAnnotation} instance for the annotation and attributes */ static <A extends Annotation> MergedAnnotation<A> of( @Nullable AnnotatedElement source, Class<A> annotationType, @Nullable Map<String, ?> attributes) { return of(null, source, annotationType, attributes); } /** * Create a new {@link MergedAnnotation} instance of the specified * annotation type with attribute values supplied by a map. * @param classLoader the
array
java
quarkusio__quarkus
extensions/resteasy-classic/rest-client-config/runtime/src/main/java/io/quarkus/restclient/config/RestClientsBuildTimeConfig.java
{ "start": 1019, "end": 1228 }
class ____ of a CDI * scope annotation (such as "jakarta.enterprise.context.ApplicationScoped") or its simple name (such as * "ApplicationScoped"). * By default, this is not set which means the
name
java
apache__camel
components/camel-jsonpath/src/test/java/org/apache/camel/jsonpath/JsonPathTransformTest.java
{ "start": 1142, "end": 2038 }
class ____ extends CamelTestSupport { @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .transform().jsonpath("$.store.book[*].author") .to("mock:authors"); } }; } @Test public void testAuthors() throws Exception { getMockEndpoint("mock:authors").expectedMessageCount(1); template.sendBody("direct:start", new File("src/test/resources/books.json")); MockEndpoint.assertIsSatisfied(context); List<?> authors = getMockEndpoint("mock:authors").getReceivedExchanges().get(0).getIn().getBody(List.class); assertEquals("Nigel Rees", authors.get(0)); assertEquals("Evelyn Waugh", authors.get(1)); } }
JsonPathTransformTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/fair/TestSchedulingPolicy.java
{ "start": 4590, "end": 5146 }
class ____ responsible for testing the transitivity of * {@link FairSharePolicy.FairShareComparator}. We will generate * a lot of triples(each triple contains three {@link Schedulable}), * and then we verify transitivity by using each triple. * * <p>How to generate:</p> * For each field in {@link Schedulable} we all have a data collection. We * combine these data to construct a {@link Schedulable}, and generate all * cases of triple by DFS(depth first search algorithm). We can get 100% code * coverage by DFS. */ private
is
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/jdk8/TestOptionalWithPolymorphic.java
{ "start": 674, "end": 1130 }
class ____ { @JsonProperty private Optional<String> name = Optional.empty(); @JsonProperty private Strategy strategy = null; } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(name = "Foo", value = Foo.class), @JsonSubTypes.Type(name = "Bar", value = Bar.class), @JsonSubTypes.Type(name = "Baz", value = Baz.class) })
ContainerB
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/ConcurrentReferenceHashMap.java
{ "start": 36413, "end": 37143 }
class ____<K, V> extends SoftReference<Entry<K, V>> implements Reference<K, V> { private final int hash; private final @Nullable Reference<K, V> nextReference; public SoftEntryReference(Entry<K, V> entry, int hash, @Nullable Reference<K, V> next, ReferenceQueue<Entry<K, V>> queue) { super(entry, queue); this.hash = hash; this.nextReference = next; } @Override public int getHash() { return this.hash; } @Override public @Nullable Reference<K, V> getNext() { return this.nextReference; } @Override public void release() { enqueue(); } } /** * Internal {@link Reference} implementation for {@link WeakReference WeakReferences}. */ private static final
SoftEntryReference
java
elastic__elasticsearch
x-pack/plugin/ml/qa/no-bootstrap-tests/src/test/java/org/elasticsearch/xpack/ml/utils/NamedPipeHelperNoBootstrapTests.java
{ "start": 1703, "end": 2719 }
class ____ extends LuceneTestCase { private static final NamedPipeHelper NAMED_PIPE_HELPER = new NamedPipeHelper(); private static final String HELLO_WORLD = "Hello, world!"; private static final String GOODBYE_WORLD = "Goodbye, world!"; private static final int BUFFER_SIZE = 4096; private static final long PIPE_ACCESS_OUTBOUND = 2; private static final long PIPE_ACCESS_INBOUND = 1; private static final long PIPE_TYPE_BYTE = 0; private static final long PIPE_WAIT = 0; private static final long PIPE_REJECT_REMOTE_CLIENTS = 8; private static final long NMPWAIT_USE_DEFAULT_WAIT = 0; private static final int ERROR_PIPE_CONNECTED = 535; private static final Pointer INVALID_HANDLE_VALUE = Pointer.createConstant(Native.POINTER_SIZE == 8 ? -1 : 0xFFFFFFFFL); static { // Have to use JNA for Windows named pipes if (Constants.WINDOWS) { Native.register("kernel32"); } } public static
NamedPipeHelperNoBootstrapTests
java
grpc__grpc-java
rls/src/main/java/io/grpc/rls/CachingRlsLbClient.java
{ "start": 33692, "end": 35708 }
class ____ { private Helper helper; private LbPolicyConfiguration lbPolicyConfig; private Throttler throttler = new HappyThrottler(); private ResolvedAddressFactory resolvedAddressFactory; private Ticker ticker = Ticker.systemTicker(); private EvictionListener<RouteLookupRequestKey, CacheEntry> evictionListener; private BackoffPolicy.Provider backoffProvider = new ExponentialBackoffPolicy.Provider(); Builder setHelper(Helper helper) { this.helper = checkNotNull(helper, "helper"); return this; } Builder setLbPolicyConfig(LbPolicyConfiguration lbPolicyConfig) { this.lbPolicyConfig = checkNotNull(lbPolicyConfig, "lbPolicyConfig"); return this; } Builder setThrottler(Throttler throttler) { this.throttler = checkNotNull(throttler, "throttler"); return this; } /** * Sets a factory to create {@link ResolvedAddresses} for child load balancer. */ Builder setResolvedAddressesFactory( ResolvedAddressFactory resolvedAddressFactory) { this.resolvedAddressFactory = checkNotNull(resolvedAddressFactory, "resolvedAddressFactory"); return this; } Builder setTicker(Ticker ticker) { this.ticker = checkNotNull(ticker, "ticker"); return this; } Builder setEvictionListener( @Nullable EvictionListener<RouteLookupRequestKey, CacheEntry> evictionListener) { this.evictionListener = evictionListener; return this; } Builder setBackoffProvider(BackoffPolicy.Provider provider) { this.backoffProvider = checkNotNull(provider, "provider"); return this; } CachingRlsLbClient build() { CachingRlsLbClient client = new CachingRlsLbClient(this); client.init(); return client; } } /** * When any {@link CacheEntry} is evicted from {@link LruCache}, it performs {@link * CacheEntry#cleanup()} after original {@link EvictionListener} is finished. */ private static final
Builder
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceUrlProviderTests.java
{ "start": 6829, "end": 6980 }
class ____ { @Bean public ResourceUrlProvider resourceUrlProvider() { return new ResourceUrlProvider(); } } }
ParentHandlerMappingConfiguration
java
google__dagger
javatests/dagger/functional/membersinject/MembersInjectModule.java
{ "start": 701, "end": 1046 }
class ____ { @Provides String[] provideStringArray() { return new String[10]; } @Provides int[] provideIntArray() { return new int[10]; } @SuppressWarnings({"unchecked", "rawtypes"}) @Provides MembersInjectGenericParent<String[]>[] provideFooArrayOfStringArray() { return new MembersInjectGenericParent[10]; } }
MembersInjectModule
java
apache__dubbo
dubbo-rpc/dubbo-rpc-dubbo/src/test/java/org/apache/dubbo/rpc/protocol/dubbo/managemode/ChannelHandlersTest.java
{ "start": 1248, "end": 2021 }
class ____ { @Test void test() { ChannelHandlers instance1 = ChannelHandlers.getInstance(); ChannelHandlers instance2 = ChannelHandlers.getInstance(); Assertions.assertEquals(instance1, instance2); ChannelHandler channelHandler = Mockito.mock(ChannelHandler.class); URL url = new ServiceConfigURL("dubbo", "127.0.0.1", 9999); ChannelHandler wrappedHandler = ChannelHandlers.wrap(channelHandler, url); Assertions.assertTrue(wrappedHandler instanceof MultiMessageHandler); MultiMessageHandler multiMessageHandler = (MultiMessageHandler) wrappedHandler; ChannelHandler handler = multiMessageHandler.getHandler(); Assertions.assertEquals(channelHandler, handler); } }
ChannelHandlersTest
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/config/GatewayMetricsAutoConfigurationTests.java
{ "start": 6354, "end": 6518 }
class ____ implements GatewayTagsProvider { @Override public Tags apply(ServerWebExchange exchange) { return Tags.empty(); } } } }
EmptyTagsProvider
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/parser/AbstractBuilder.java
{ "start": 648, "end": 4727 }
class ____ extends EqlBaseBaseVisitor<Object> { @Override public Object visit(ParseTree tree) { return ParserUtils.visit(super::visit, tree); } protected LogicalPlan plan(ParseTree ctx) { return ParserUtils.typedParsing(this, ctx, LogicalPlan.class); } protected List<LogicalPlan> plans(List<? extends ParserRuleContext> ctxs) { return ParserUtils.visitList(this, ctxs, LogicalPlan.class); } public static String unquoteString(Source source) { // remove leading and trailing ' for strings and also eliminate escaped single quotes String text = source.text(); if (text == null) { return null; } // catch old method of ?" and ?' to define unescaped strings if (text.startsWith("?")) { throw new ParsingException( source, "Use triple double quotes [\"\"\"] to define unescaped string literals, not [?{}]", text.charAt(1) ); } // unescaped strings can be interpreted directly if (text.startsWith("\"\"\"")) { return text.substring(3, text.length() - 3); } checkForSingleQuotedString(source, text, 0); text = text.substring(1, text.length() - 1); StringBuilder sb = new StringBuilder(); for (int i = 0; i < text.length();) { if (text.charAt(i) == '\\') { // ANTLR4 Grammar guarantees there is always a character after the `\` switch (text.charAt(++i)) { case 't' -> sb.append('\t'); case 'b' -> sb.append('\b'); case 'f' -> sb.append('\f'); case 'n' -> sb.append('\n'); case 'r' -> sb.append('\r'); case '"' -> sb.append('\"'); case '\'' -> sb.append('\''); case 'u' -> i = handleUnicodePoints(source, sb, text, ++i); case '\\' -> sb.append('\\'); // will be interpreted as regex, so we have to escape it default -> // unknown escape sequence, pass through as-is, e.g: `...\w...` sb.append('\\').append(text.charAt(i)); } i++; } else { sb.append(text.charAt(i++)); } } return sb.toString(); } private static int handleUnicodePoints(Source source, StringBuilder sb, String text, int i) { String unicodeSequence; int startIdx = i + 1; int endIdx = text.indexOf('}', startIdx); unicodeSequence = text.substring(startIdx, endIdx); int length = unicodeSequence.length(); if (length < 2 || length > 8) { throw new ParsingException( source, "Unicode sequence should use [2-8] hex digits, [{}] has [{}]", text.substring(startIdx - 3, endIdx + 1), length ); } sb.append(hexToUnicode(source, unicodeSequence)); return endIdx; } private static String hexToUnicode(Source source, String hex) { try { int code = Integer.parseInt(hex, 16); // U+D800—U+DFFF can only be used as surrogate pairs and therefore are not valid character codes if (code >= 0xD800 && code <= 0xDFFF) { throw new ParsingException(source, "Invalid unicode character code, [{}] is a surrogate code", hex); } return String.valueOf(Character.toChars(code)); } catch (IllegalArgumentException e) { throw new ParsingException(source, "Invalid unicode character code [{}]", hex); } } private static void checkForSingleQuotedString(Source source, String text, int i) { if (text.charAt(i) == '\'') { throw new ParsingException(source, "Use double quotes [\"] to define string literals, not single quotes [']"); } } }
AbstractBuilder
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/operators/Keys.java
{ "start": 20691, "end": 21260 }
class ____ extends Exception { private static final long serialVersionUID = 1L; public static final String SIZE_MISMATCH_MESSAGE = "The number of specified keys is different."; public IncompatibleKeysException(String message) { super(message); } public IncompatibleKeysException( TypeInformation<?> typeInformation, TypeInformation<?> typeInformation2) { super(typeInformation + " and " + typeInformation2 + " are not compatible"); } } }
IncompatibleKeysException
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionWrappedExceptionTest.java
{ "start": 1227, "end": 2277 }
class ____ extends ContextTestSupport { @Test public void testWrappedException() throws Exception { getMockEndpoint("mock:error").expectedMessageCount(0); getMockEndpoint("mock:wrapped").expectedMessageCount(1); getMockEndpoint("mock:end").expectedMessageCount(0); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.getTypeConverterRegistry().addTypeConverter(LocalDateTime.class, String.class, new MyLocalDateTimeConverter()); errorHandler(deadLetterChannel("mock:error")); onException(IllegalArgumentException.class).handled(true).to("mock:wrapped"); from("direct:start").convertBodyTo(LocalDateTime.class).to("mock:end"); } }; } public static
OnExceptionWrappedExceptionTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/resources/HttpOpParam.java
{ "start": 1961, "end": 3835 }
class ____ implements Op { static final TemporaryRedirectOp CREATE = new TemporaryRedirectOp( PutOpParam.Op.CREATE); static final TemporaryRedirectOp APPEND = new TemporaryRedirectOp( PostOpParam.Op.APPEND); static final TemporaryRedirectOp OPEN = new TemporaryRedirectOp( GetOpParam.Op.OPEN); static final TemporaryRedirectOp GETFILECHECKSUM = new TemporaryRedirectOp( GetOpParam.Op.GETFILECHECKSUM); static final List<TemporaryRedirectOp> values = Collections.unmodifiableList(Arrays.asList(CREATE, APPEND, OPEN, GETFILECHECKSUM)); /** Get an object for the given op. */ public static TemporaryRedirectOp valueOf(final Op op) { for(TemporaryRedirectOp t : values) { if (op == t.op) { return t; } } throw new IllegalArgumentException(op + " not found."); } private final Op op; private TemporaryRedirectOp(final Op op) { this.op = op; } @Override public Type getType() { return op.getType(); } @Override public boolean getRequireAuth() { return op.getRequireAuth(); } @Override public boolean getDoOutput() { return false; } @Override public boolean getRedirect() { return false; } /** Override the original expected response with "Temporary Redirect". */ @Override public int getExpectedHttpResponseCode() { return Response.Status.TEMPORARY_REDIRECT.getStatusCode(); } @Override public String toQueryString() { return op.toQueryString(); } } /** @return the parameter value as a string */ @Override public String getValueString() { return value.toString(); } HttpOpParam(final Domain<E> domain, final E value) { super(domain, value); } }
TemporaryRedirectOp
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/util/NonReusingMutableToRegularIteratorWrapper.java
{ "start": 1303, "end": 2844 }
class ____<T> implements Iterator<T>, Iterable<T> { private final MutableObjectIterator<T> source; private T current; private boolean currentIsAvailable; private boolean iteratorAvailable = true; public NonReusingMutableToRegularIteratorWrapper( MutableObjectIterator<T> source, TypeSerializer<T> serializer) { this.source = source; this.current = null; } @Override public boolean hasNext() { if (currentIsAvailable) { return true; } else { try { if ((current = source.next()) != null) { currentIsAvailable = true; return true; } else { return false; } } catch (IOException ioex) { throw new RuntimeException("Error reading next record: " + ioex.getMessage(), ioex); } } } @Override public T next() { if (currentIsAvailable || hasNext()) { currentIsAvailable = false; return current; } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException(); } @Override public Iterator<T> iterator() { if (iteratorAvailable) { iteratorAvailable = false; return this; } else { throw new TraversableOnceException(); } } }
NonReusingMutableToRegularIteratorWrapper
java
apache__kafka
server-common/src/main/java/org/apache/kafka/server/share/persister/ReadShareGroupStateSummaryParameters.java
{ "start": 1118, "end": 2363 }
class ____ implements PersisterParameters { private final GroupTopicPartitionData<PartitionIdLeaderEpochData> groupTopicPartitionData; private ReadShareGroupStateSummaryParameters(GroupTopicPartitionData<PartitionIdLeaderEpochData> groupTopicPartitionData) { this.groupTopicPartitionData = groupTopicPartitionData; } public GroupTopicPartitionData<PartitionIdLeaderEpochData> groupTopicPartitionData() { return groupTopicPartitionData; } public static ReadShareGroupStateSummaryParameters from(ReadShareGroupStateSummaryRequestData data) { return new Builder() .setGroupTopicPartitionData(new GroupTopicPartitionData<>(data.groupId(), data.topics().stream() .map(topicData -> new TopicData<>(topicData.topicId(), topicData.partitions().stream() .map(partitionData -> PartitionFactory.newPartitionIdLeaderEpochData(partitionData.partition(), partitionData.leaderEpoch())) .collect(Collectors.toList()))) .collect(Collectors.toList()))) .build(); } public static
ReadShareGroupStateSummaryParameters
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/CodeTemplates.java
{ "start": 6942, "end": 7264 }
class ____ { @Advice.OnMethodEnter static void $$_hibernate_clearDirtyAttributes( @Advice.FieldValue(value = EnhancerConstants.TRACKER_FIELD_NAME) DirtyTracker $$_hibernate_tracker) { if ( $$_hibernate_tracker != null ) { $$_hibernate_tracker.clear(); } } } static
ClearDirtyAttributesWithoutCollections
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conversion/_enum/EnumToIntegerEnum.java
{ "start": 204, "end": 334 }
enum ____ { ARBITRARY_VALUE_ZERO, ARBITRARY_VALUE_ONE, ARBITRARY_VALUE_TWO, ARBITRARY_VALUE_THREE }
EnumToIntegerEnum
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLRevokeStatement.java
{ "start": 755, "end": 1373 }
class ____ extends SQLPrivilegeStatement { private boolean grantOption; public SQLRevokeStatement() { } public SQLRevokeStatement(DbType dbType) { super(dbType); } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, resource); acceptChild(visitor, users); } visitor.endVisit(this); } public boolean isGrantOption() { return grantOption; } public void setGrantOption(boolean grantOption) { this.grantOption = grantOption; } }
SQLRevokeStatement
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/SharedSlotTest.java
{ "start": 2203, "end": 14520 }
class ____ { private static final ExecutionVertexID EV1 = createRandomExecutionVertexId(); private static final ExecutionVertexID EV2 = createRandomExecutionVertexId(); private static final ExecutionSlotSharingGroup SG = createExecutionSlotSharingGroup(EV1, EV2); private static final SlotRequestId PHYSICAL_SLOT_REQUEST_ID = new SlotRequestId(); private static final ResourceProfile RP = ResourceProfile.newBuilder().setCpuCores(2.0).build(); @Test void testCreation() { SharedSlot sharedSlot = SharedSlotBuilder.newBuilder().slotWillBeOccupiedIndefinitely().build(); assertThat(sharedSlot.getPhysicalSlotRequestId()).isEqualTo(PHYSICAL_SLOT_REQUEST_ID); assertThat(sharedSlot.getPhysicalSlotResourceProfile()).isEqualTo(RP); assertThat(sharedSlot.willOccupySlotIndefinitely()).isTrue(); assertThat(sharedSlot.isEmpty()).isTrue(); } @Test void testAssignAsPayloadToPhysicalSlot() { CompletableFuture<PhysicalSlot> slotContextFuture = new CompletableFuture<>(); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder().withSlotContextFuture(slotContextFuture).build(); TestingPhysicalSlot physicalSlot = new TestingPhysicalSlot(RP, new AllocationID()); slotContextFuture.complete(physicalSlot); assertThat(physicalSlot.getPayload()).isEqualTo(sharedSlot); } @Test void testLogicalSlotAllocation() { CompletableFuture<PhysicalSlot> slotContextFuture = new CompletableFuture<>(); CompletableFuture<ExecutionSlotSharingGroup> released = new CompletableFuture<>(); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder() .withSlotContextFuture(slotContextFuture) .slotWillBeOccupiedIndefinitely() .withExternalReleaseCallback(released::complete) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = sharedSlot.allocateLogicalSlot(EV1); assertThatFuture(logicalSlotFuture).isNotDone(); AllocationID allocationId = new AllocationID(); LocalTaskManagerLocation taskManagerLocation = new LocalTaskManagerLocation(); SimpleAckingTaskManagerGateway taskManagerGateway = new SimpleAckingTaskManagerGateway(); slotContextFuture.complete( new TestingPhysicalSlot( allocationId, taskManagerLocation, 3, taskManagerGateway, RP)); assertThat(sharedSlot.isEmpty()).isFalse(); assertThatFuture(released).isNotDone(); assertThat(logicalSlotFuture).isDone(); LogicalSlot logicalSlot = logicalSlotFuture.join(); assertThat(logicalSlot.getAllocationId()).isEqualTo(allocationId); assertThat(logicalSlot.getTaskManagerLocation()).isEqualTo(taskManagerLocation); assertThat(logicalSlot.getTaskManagerGateway()).isEqualTo(taskManagerGateway); assertThat(logicalSlot.getLocality()).isEqualTo(Locality.UNKNOWN); } @Test void testLogicalSlotFailureDueToPhysicalSlotFailure() { CompletableFuture<PhysicalSlot> slotContextFuture = new CompletableFuture<>(); CompletableFuture<ExecutionSlotSharingGroup> released = new CompletableFuture<>(); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder() .withSlotContextFuture(slotContextFuture) .withExternalReleaseCallback(released::complete) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = sharedSlot.allocateLogicalSlot(EV1); Throwable cause = new Throwable(); slotContextFuture.completeExceptionally(cause); assertThat(logicalSlotFuture.isCompletedExceptionally()).isTrue(); assertThatThrownBy(logicalSlotFuture::get) .isInstanceOf(ExecutionException.class) .hasCause(cause); assertThat(sharedSlot.isEmpty()).isTrue(); assertThat(released).isDone(); } @Test void testCancelCompletedLogicalSlotRequest() { CompletableFuture<PhysicalSlot> slotContextFuture = new CompletableFuture<>(); CompletableFuture<ExecutionSlotSharingGroup> released = new CompletableFuture<>(); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder() .withSlotContextFuture(slotContextFuture) .withExternalReleaseCallback(released::complete) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = sharedSlot.allocateLogicalSlot(EV1); slotContextFuture.complete(new TestingPhysicalSlot(RP, new AllocationID())); sharedSlot.cancelLogicalSlotRequest(EV1, new Throwable()); assertThatFuture(logicalSlotFuture).isNotCompletedExceptionally(); assertThat(sharedSlot.isEmpty()).isFalse(); assertThat(released).isNotDone(); } @Test void testCancelPendingLogicalSlotRequest() { CompletableFuture<ExecutionSlotSharingGroup> released = new CompletableFuture<>(); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder() .withExternalReleaseCallback(released::complete) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = sharedSlot.allocateLogicalSlot(EV1); Throwable cause = new Throwable(); sharedSlot.cancelLogicalSlotRequest(EV1, cause); assertThat(logicalSlotFuture.isCompletedExceptionally()).isTrue(); assertThatThrownBy(logicalSlotFuture::get) .isInstanceOf(ExecutionException.class) .hasCause(cause); assertThat(sharedSlot.isEmpty()).isTrue(); assertThatFuture(released).isDone(); } @Test void testReturnAllocatedLogicalSlot() { CompletableFuture<PhysicalSlot> slotContextFuture = new CompletableFuture<>(); CompletableFuture<ExecutionSlotSharingGroup> released = new CompletableFuture<>(); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder() .withSlotContextFuture(slotContextFuture) .withExternalReleaseCallback(released::complete) .build(); CompletableFuture<LogicalSlot> logicalSlotFuture = sharedSlot.allocateLogicalSlot(EV1); slotContextFuture.complete(new TestingPhysicalSlot(RP, new AllocationID())); sharedSlot.returnLogicalSlot(logicalSlotFuture.join()); assertThat(sharedSlot.isEmpty()).isTrue(); assertThatFuture(released).isDone(); } @Test void testReleaseIfPhysicalSlotRequestIsIncomplete() { CompletableFuture<PhysicalSlot> slotContextFuture = new CompletableFuture<>(); CompletableFuture<ExecutionSlotSharingGroup> released = new CompletableFuture<>(); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder() .withSlotContextFuture(slotContextFuture) .withExternalReleaseCallback(released::complete) .build(); sharedSlot.allocateLogicalSlot(EV1); assertThatThrownBy(() -> sharedSlot.release(new Throwable())) .withFailMessage( "IllegalStateException is expected trying to release a shared slot with incomplete physical slot request") .isInstanceOf(IllegalStateException.class); assertThat(sharedSlot.isEmpty()).isFalse(); assertThatFuture(released).isNotDone(); } @Test void testReleaseIfPhysicalSlotIsAllocated() { CompletableFuture<PhysicalSlot> slotContextFuture = CompletableFuture.completedFuture(new TestingPhysicalSlot(RP, new AllocationID())); CompletableFuture<ExecutionSlotSharingGroup> released = new CompletableFuture<>(); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder() .withSlotContextFuture(slotContextFuture) .withExternalReleaseCallback(released::complete) .build(); LogicalSlot logicalSlot = sharedSlot.allocateLogicalSlot(EV1).join(); CompletableFuture<Object> terminalFuture = new CompletableFuture<>(); logicalSlot.tryAssignPayload(new DummyPayload(terminalFuture)); assertThatFuture(terminalFuture).isNotDone(); sharedSlot.release(new Throwable()); assertThatFuture(terminalFuture).isDone(); assertThat(sharedSlot.isEmpty()).isTrue(); assertThatFuture(released).isDone(); } @Test void tesDuplicatedReturnLogicalSlotFails() { CompletableFuture<PhysicalSlot> slotContextFuture = CompletableFuture.completedFuture(new TestingPhysicalSlot(RP, new AllocationID())); AtomicInteger released = new AtomicInteger(0); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder() .withSlotContextFuture(slotContextFuture) .withExternalReleaseCallback(g -> released.incrementAndGet()) .build(); LogicalSlot logicalSlot = sharedSlot.allocateLogicalSlot(EV1).join(); sharedSlot.returnLogicalSlot(logicalSlot); assertThatThrownBy(() -> sharedSlot.returnLogicalSlot(logicalSlot)) .withFailMessage( "Duplicated 'returnLogicalSlot' call should fail with IllegalStateException") .isInstanceOf(IllegalStateException.class); } @Test void testReleaseEmptyDoesNotCallAllocatorReleaseBack() { CompletableFuture<PhysicalSlot> slotContextFuture = CompletableFuture.completedFuture(new TestingPhysicalSlot(RP, new AllocationID())); CompletableFuture<SharedSlot> sharedSlotReleaseFuture = new CompletableFuture<>(); AtomicInteger released = new AtomicInteger(0); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder() .withSlotContextFuture(slotContextFuture) .withExternalReleaseCallback( g -> { // checks that release -> externalReleaseCallback -> release // does not lead to infinite recursion // due to SharedSlot.state.RELEASED check sharedSlotReleaseFuture.join().release(new Throwable()); released.incrementAndGet(); }) .build(); sharedSlotReleaseFuture.complete(sharedSlot); LogicalSlot logicalSlot = sharedSlot.allocateLogicalSlot(EV1).join(); assertThat(released).hasValue(0); // returns the only and last slot, calling the external release callback sharedSlot.returnLogicalSlot(logicalSlot); assertThat(released).hasValue(1); // slot is already released, it should not get released again sharedSlot.release(new Throwable()); assertThat(released).hasValue(1); } @Test void testReturnLogicalSlotWhileReleasingDoesNotCauseConcurrentModificationException() { CompletableFuture<PhysicalSlot> slotContextFuture = CompletableFuture.completedFuture(new TestingPhysicalSlot(RP, new AllocationID())); SharedSlot sharedSlot = SharedSlotBuilder.newBuilder().withSlotContextFuture(slotContextFuture).build(); LogicalSlot logicalSlot1 = sharedSlot.allocateLogicalSlot(EV1).join(); LogicalSlot logicalSlot2 = sharedSlot.allocateLogicalSlot(EV2).join(); logicalSlot1.tryAssignPayload( new LogicalSlot.Payload() { @Override public void fail(Throwable cause) { sharedSlot.returnLogicalSlot(logicalSlot2); } @Override public CompletableFuture<?> getTerminalStateFuture() { return CompletableFuture.completedFuture(null); } }); sharedSlot.release(new Throwable()); } private static
SharedSlotTest
java
apache__camel
test-infra/camel-test-infra-cli/src/test/java/org/apache/camel/test/infra/cli/it/AbstractTestSupport.java
{ "start": 1029, "end": 1384 }
class ____ { protected void execute(Consumer<CliService> consumer) { try (CliService containerService = CliServiceFactory.createService()) { containerService.beforeAll(null); consumer.accept(containerService); } catch (Exception e) { throw new RuntimeException(e); } } }
AbstractTestSupport
java
quarkusio__quarkus
extensions/picocli/runtime/src/main/java/io/quarkus/picocli/runtime/PicocliConfiguration.java
{ "start": 300, "end": 452 }
interface ____ { /** * Name of bean annotated with {@link io.quarkus.picocli.runtime.annotations.TopCommand} * or FQCN of
PicocliConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobCharArrayTest.java
{ "start": 1392, "end": 2022 }
class ____ { @Id private Integer id; private String name; @Lob private char[] warranty; //Getters and setters are omitted for brevity //end::basic-clob-char-array-example[] public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public char[] getWarranty() { return warranty; } public void setWarranty(char[] warranty) { this.warranty = warranty; } //tag::basic-clob-char-array-example[] } //end::basic-clob-char-array-example[] }
Product
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CheckReturnValueWellKnownLibrariesTest.java
{ "start": 10308, "end": 10569 }
class ____ { void go(Lib lib) { lib.b(); } } """) .addOutputLines( "Test.java", """ import static com.google.common.base.Verify.verify;
Test
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/SQLObjectImpl.java
{ "start": 1151, "end": 8494 }
class ____ implements SQLObject { protected SQLObject parent; protected Map<String, Object> attributes; protected SQLCommentHint hint; protected int sourceLine; protected int sourceColumn; public SQLObjectImpl() { } protected void cloneTo(SQLObjectImpl x) { x.parent = this.parent; if (this.attributes != null) { x.attributes = new HashMap<>(attributes); } x.sourceLine = this.sourceLine; x.sourceColumn = this.sourceColumn; } public final void accept(SQLASTVisitor visitor) { if (visitor == null) { throw new IllegalArgumentException(); } visitor.preVisit(this); accept0(visitor); visitor.postVisit(this); } protected abstract void accept0(SQLASTVisitor v); protected final void acceptChild(SQLASTVisitor visitor, List<? extends SQLObject> children) { if (children == null) { return; } for (int i = 0; i < children.size(); i++) { acceptChild(visitor, children.get(i)); } } protected final void acceptChild(SQLASTVisitor visitor, SQLObject child) { if (child == null) { return; } child.accept(visitor); } public void output(StringBuilder buf) { DbType dbType = null; if (this instanceof OracleSQLObject) { dbType = DbType.oracle; } else if (this instanceof MySqlObject) { dbType = DbType.mysql; } else if (this instanceof PGSQLObject) { dbType = DbType.postgresql; } else if (this instanceof SQLServerObject) { dbType = DbType.sqlserver; } else if (this instanceof SQLDbTypedObject) { dbType = ((SQLDbTypedObject) this).getDbType(); } accept( SQLUtils.createOutputVisitor(buf, dbType) ); } public String toString() { StringBuilder buf = new StringBuilder(); output(buf); return buf.toString(); } public SQLObject getParent() { return parent; } public SQLObject getParent(int level) { if (level <= 0) { throw new IllegalArgumentException("Get parent level should be greater than 0."); } SQLObject parent = this; while (level-- > 0) { if (parent == null) { return null; } parent = parent.getParent(); } return parent; } public void setParent(SQLObject parent) { this.parent = parent; } public Map<String, Object> getAttributes() { if (attributes == null) { attributes = new HashMap<String, Object>(1); } return attributes; } public Object getAttribute(String name) { if (attributes == null) { return null; } return attributes.get(name); } public boolean containsAttribute(String name) { if (attributes == null) { return false; } return attributes.containsKey(name); } public void putAttribute(String name, Object value) { if (attributes == null) { attributes = new HashMap<String, Object>(1); } attributes.put(name, value); } public Map<String, Object> getAttributesDirect() { return attributes; } @SuppressWarnings("unchecked") public void addBeforeComment(String comment) { if (comment == null) { return; } if (attributes == null) { attributes = new HashMap<String, Object>(1); } List<String> comments = (List<String>) attributes.get("rowFormat.before_comment"); if (comments == null) { comments = new ArrayList<String>(2); attributes.put("rowFormat.before_comment", comments); } comments.add(comment); } @SuppressWarnings("unchecked") public void addBeforeComment(List<String> comments) { if (comments == null) { return; } if (attributes == null) { attributes = new HashMap<String, Object>(1); } List<String> attrComments = (List<String>) attributes.get("rowFormat.before_comment"); if (attrComments == null) { attributes.put("rowFormat.before_comment", comments); } else { attrComments.addAll(comments); } } @SuppressWarnings("unchecked") public List<String> getBeforeCommentsDirect() { if (attributes == null) { return null; } return (List<String>) attributes.get("rowFormat.before_comment"); } @SuppressWarnings("unchecked") public void addAfterComment(String comment) { if (comment == null) { return; } if (attributes == null) { attributes = new HashMap<String, Object>(1); } List<String> comments = (List<String>) attributes.get("rowFormat.after_comment"); if (comments == null) { comments = new ArrayList<String>(2); attributes.put("rowFormat.after_comment", comments); } comments.add(comment); } @SuppressWarnings("unchecked") public void addAfterComment(List<String> comments) { if (comments == null) { return; } if (attributes == null) { attributes = new HashMap<String, Object>(1); } List<String> attrComments = (List<String>) attributes.get("rowFormat.after_comment"); if (attrComments == null) { attributes.put("rowFormat.after_comment", comments); } else { attrComments.addAll(comments); } } @SuppressWarnings("unchecked") public List<String> getAfterCommentsDirect() { if (attributes == null) { return null; } return (List<String>) attributes.get("rowFormat.after_comment"); } public boolean hasBeforeComment() { if (attributes == null) { return false; } List<String> comments = (List<String>) attributes.get("rowFormat.before_comment"); if (comments == null) { return false; } return !comments.isEmpty(); } public boolean hasAfterComment() { if (attributes == null) { return false; } List<String> comments = (List<String>) attributes.get("rowFormat.after_comment"); if (comments == null) { return false; } return !comments.isEmpty(); } public SQLObject clone() { throw new UnsupportedOperationException(this.getClass().getName()); } public SQLDataType computeDataType() { return null; } public int getSourceLine() { return sourceLine; } public void setSourceLine(int sourceLine) { this.sourceLine = sourceLine; } public int getSourceColumn() { return sourceColumn; } public void setSource(int line, int column) { this.sourceLine = line; this.sourceColumn = column; } public SQLCommentHint getHint() { return hint; } public void setHint(SQLCommentHint hint) { this.hint = hint; } }
SQLObjectImpl
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/javadoc/UnrecognisedJavadocTagTest.java
{ "start": 1643, "end": 1922 }
class ____ {} """) .doTest(); } @Test public void link() { helper .addSourceLines( "Test.java", """ /** * // BUG: Diagnostic contains: * {@link Test) */
Test
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/TransformCommand.java
{ "start": 1114, "end": 1377 }
class ____ extends CamelCommand { public TransformCommand(CamelJBangMain main) { super(main); } @Override public Integer doCall() throws Exception { new CommandLine(this).execute("--help"); return 0; } }
TransformCommand
java
processing__processing4
core/src/processing/core/PFont.java
{ "start": 14242, "end": 29873 }
class ____ handle closing * the stream when finished. */ public void save(OutputStream output) throws IOException { DataOutputStream os = new DataOutputStream(output); os.writeInt(glyphCount); if ((name == null) || (psname == null)) { name = ""; psname = ""; } os.writeInt(11); // formerly numBits, now used for version number os.writeInt(size); // formerly mboxX (was 64, now 48) os.writeInt(0); // formerly mboxY, now ignored os.writeInt(ascent); // formerly baseHt (was ignored) os.writeInt(descent); // formerly struct padding for c version for (int i = 0; i < glyphCount; i++) { glyphs[i].writeHeader(os); } for (int i = 0; i < glyphCount; i++) { glyphs[i].writeBitmap(os); } // version 11 os.writeUTF(name); os.writeUTF(psname); os.writeBoolean(smooth); os.flush(); } /** * Create a new glyph, and add the character to the current font. * @param c character to create an image for. */ protected void addGlyph(char c) { Glyph glyph = new Glyph(c); if (glyphCount == glyphs.length) { glyphs = (Glyph[]) PApplet.expand(glyphs); } if (glyphCount == 0) { glyph.index = 0; glyphs[glyphCount] = glyph; if (glyph.value < 128) { ascii[glyph.value] = 0; } } else if (glyphs[glyphCount-1].value < glyph.value) { glyphs[glyphCount] = glyph; if (glyph.value < 128) { ascii[glyph.value] = glyphCount; } } else { for (int i = 0; i < glyphCount; i++) { if (glyphs[i].value > c) { for (int j = glyphCount; j > i; --j) { glyphs[j] = glyphs[j-1]; if (glyphs[j].value < 128) { ascii[glyphs[j].value] = j; } } glyph.index = i; glyphs[i] = glyph; // cache locations of the ascii charset if (c < 128) ascii[c] = i; break; } } } glyphCount++; } public String getName() { return name; } public String getPostScriptName() { return psname; } /** * Set the native complement of this font. Might be set internally via the * findFont() function, or externally by a deriveFont() call if the font * is resized by PGraphicsJava2D. */ public void setNative(Object font) { this.font = (Font) font; } /** * Use the getNative() method instead, which allows library interfaces to be * written in a cross-platform fashion for desktop, Android, and others. */ @Deprecated public Font getFont() { return font; } /** * Return the native java.awt.Font associated with this PFont (if any). */ public Object getNative() { if (subsetting) { return null; // don't return the font for use } return font; } /** * Return size of this font. */ public int getSize() { return size; } // public void setDefaultSize(int size) { // defaultSize = size; // } /** * Returns the size that will be used when textFont(font) is called. * When drawing with 2x pixel density, bitmap fonts in OpenGL need to be * created (behind the scenes) at double the requested size. This ensures * that they're shown at half on displays (so folks don't have to change * their sketch code). */ public int getDefaultSize() { //return defaultSize; return size / density; } public boolean isSmooth() { return smooth; } public boolean isStream() { return stream; } public void setSubsetting() { subsetting = true; } /** * Attempt to find the native version of this font. * (Public so that it can be used by OpenGL or other renderers.) */ public Object findNative() { if (font == null) { if (!fontSearched) { // this font may or may not be installed font = new Font(name, Font.PLAIN, size); // if the ps name matches, then we're in fine shape if (!font.getPSName().equals(psname)) { // on osx java 1.4 (not 1.3.. ugh), you can specify the ps name // of the font, so try that in case this .vlw font was created on pc // and the name is different, but the ps name is found on the // java 1.4 mac that's currently running this sketch. font = new Font(psname, Font.PLAIN, size); } // check again, and if still bad, screw em if (!font.getPSName().equals(psname)) { font = null; } fontSearched = true; } } return font; } public Glyph getGlyph(char c) { int index = index(c); return (index == -1) ? null : glyphs[index]; } /** * Get index for the character. * @return index into arrays or -1 if not found */ protected int index(char c) { if (lazy) { int index = indexActual(c); if (index != -1) { return index; } if (font != null && font.canDisplay(c)) { // create the glyph addGlyph(c); // now where did i put that? return indexActual(c); } else { return -1; } } else { return indexActual(c); } } protected int indexActual(char c) { // degenerate case, but the find function will have trouble // if there are somehow zero chars in the lookup //if (value.length == 0) return -1; if (glyphCount == 0) return -1; // quicker lookup for the ascii fellers if (c < 128) return ascii[c]; // some other unicode char, hunt it out //return index_hunt(c, 0, value.length-1); return indexHunt(c, 0, glyphCount-1); } protected int indexHunt(int c, int start, int stop) { int pivot = (start + stop) / 2; // if this is the char, then return it if (c == glyphs[pivot].value) return pivot; // char doesn't exist, otherwise would have been the pivot //if (start == stop) return -1; if (start >= stop) return -1; // if it's in the lower half, continue searching that if (c < glyphs[pivot].value) return indexHunt(c, start, pivot-1); // if it's in the upper half, continue there return indexHunt(c, pivot+1, stop); } /** * Currently un-implemented for .vlw fonts, * but honored for layout in case subclasses use it. */ public float kern(char a, char b) { return 0; } /** * Returns the ascent of this font from the baseline. * The value is based on a font of size 1. */ public float ascent() { return ((float) ascent / (float) size); } /** * Returns how far this font descends from the baseline. * The value is based on a font size of 1. */ public float descent() { return ((float) descent / (float) size); } /** * Width of this character for a font of size 1. */ public float width(char c) { if (c == 32) return width('i'); int cc = index(c); if (cc == -1) return 0; return ((float) glyphs[cc].setWidth / (float) size); } ////////////////////////////////////////////////////////////// public int getGlyphCount() { return glyphCount; } public Glyph getGlyph(int i) { return glyphs[i]; } public PShape getShape(char ch) { return getShape(ch, 0); } public PShape getShape(char ch, float detail) { Font font = (Font) getNative(); if (font == null) { throw new IllegalArgumentException("getShape() only works on fonts loaded with createFont()"); } PShape s = new PShape(PShape.PATH); // six element array received from the Java2D path iterator float[] iterPoints = new float[6]; // array passed to createGlyphVector char[] textArray = { ch }; //Graphics2D graphics = (Graphics2D) this.getGraphics(); //FontRenderContext frc = graphics.getFontRenderContext(); @SuppressWarnings("deprecation") FontRenderContext frc = Toolkit.getDefaultToolkit().getFontMetrics(font).getFontRenderContext(); GlyphVector gv = font.createGlyphVector(frc, textArray); Shape shp = gv.getOutline(); // make everything into moveto and lineto PathIterator iter = (detail == 0) ? shp.getPathIterator(null) : // maintain curves shp.getPathIterator(null, detail); // convert to line segments int contours = 0; s.beginShape(); s.noStroke(); s.fill(0); while (!iter.isDone()) { int type = iter.currentSegment(iterPoints); switch (type) { case PathIterator.SEG_MOVETO: // 1 point (2 vars) in textPoints if (contours > 0) { s.beginContour(); } ++contours; s.vertex(iterPoints[0], iterPoints[1]); break; case PathIterator.SEG_LINETO: // 1 point s.vertex(iterPoints[0], iterPoints[1]); break; case PathIterator.SEG_QUADTO: // 2 points s.quadraticVertex(iterPoints[0], iterPoints[1], iterPoints[2], iterPoints[3]); break; case PathIterator.SEG_CUBICTO: // 3 points s.bezierVertex(iterPoints[0], iterPoints[1], iterPoints[2], iterPoints[3], iterPoints[4], iterPoints[5]); break; case PathIterator.SEG_CLOSE: if (contours > 1) { s.endContour(); } break; } iter.next(); } s.endShape(CLOSE); return s; } ////////////////////////////////////////////////////////////// static final char[] EXTRA_CHARS = { 0x0080, 0x0081, 0x0082, 0x0083, 0x0084, 0x0085, 0x0086, 0x0087, 0x0088, 0x0089, 0x008A, 0x008B, 0x008C, 0x008D, 0x008E, 0x008F, 0x0090, 0x0091, 0x0092, 0x0093, 0x0094, 0x0095, 0x0096, 0x0097, 0x0098, 0x0099, 0x009A, 0x009B, 0x009C, 0x009D, 0x009E, 0x009F, 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, 0x00B0, 0x00B1, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x00BA, 0x00BB, 0x00BF, 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DF, 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FF, 0x0102, 0x0103, 0x0104, 0x0105, 0x0106, 0x0107, 0x010C, 0x010D, 0x010E, 0x010F, 0x0110, 0x0111, 0x0118, 0x0119, 0x011A, 0x011B, 0x0131, 0x0139, 0x013A, 0x013D, 0x013E, 0x0141, 0x0142, 0x0143, 0x0144, 0x0147, 0x0148, 0x0150, 0x0151, 0x0152, 0x0153, 0x0154, 0x0155, 0x0158, 0x0159, 0x015A, 0x015B, 0x015E, 0x015F, 0x0160, 0x0161, 0x0162, 0x0163, 0x0164, 0x0165, 0x016E, 0x016F, 0x0170, 0x0171, 0x0178, 0x0179, 0x017A, 0x017B, 0x017C, 0x017D, 0x017E, 0x0192, 0x02C6, 0x02C7, 0x02D8, 0x02D9, 0x02DA, 0x02DB, 0x02DC, 0x02DD, 0x03A9, 0x03C0, 0x2013, 0x2014, 0x2018, 0x2019, 0x201A, 0x201C, 0x201D, 0x201E, 0x2020, 0x2021, 0x2022, 0x2026, 0x2030, 0x2039, 0x203A, 0x2044, 0x20AC, 0x2122, 0x2202, 0x2206, 0x220F, 0x2211, 0x221A, 0x221E, 0x222B, 0x2248, 0x2260, 0x2264, 0x2265, 0x25CA, 0xF8FF, 0xFB01, 0xFB02 }; /** * The default Processing character set. * <P> * This is the union of the Mac Roman and Windows ANSI (CP1250) * character sets. ISO 8859-1 Latin 1 is Unicode characters 0x80 -> 0xFF, * and would seem a good standard, but in practice, most P5 users would * rather have characters that they expect from their platform's fonts. * <P> * This is more of an interim solution until a much better * font solution can be determined. (i.e. create fonts on * the fly from some sort of vector format). * <P> * Not that I expect that to happen. */ static public char[] CHARSET; static { CHARSET = new char[126-33+1 + EXTRA_CHARS.length]; int index = 0; for (int i = 33; i <= 126; i++) { CHARSET[index++] = (char)i; } for (char extraChar : EXTRA_CHARS) { CHARSET[index++] = extraChar; } } /** * * Gets a list of the fonts installed on the system. The data is returned as a * String array. This list provides the names of each font for input into * <b>createFont()</b>, which allows Processing to dynamically format fonts. * * * @webref pfont * @webBrief Gets a list of the fonts installed on the system * @usage application * @brief Gets a list of the fonts installed on the system */ static public String[] list() { loadFonts(); String[] list = new String[fonts.length]; for (int i = 0; i < list.length; i++) { list[i] = fonts[i].getName(); } return list; } /** * Make an internal list of all installed fonts. * * This can take a while with a lot of fonts installed, but running it on * a separate thread may not help much. As of the commit that's adding this * note, loadFonts() will only be called by PFont.list() and when loading a * font by name, both of which are occasions when we'd need to block until * this was finished anyway. It's also possible that running getAllFonts() * on a non-EDT thread could cause graphics system issues. Further, the first * fonts are usually loaded at the beginning of a sketch, meaning that sketch * startup time will still be affected, even with threading in place. * * Where we're getting killed on font performance is due to this bug: * https://bugs.openjdk.java.net/browse/JDK-8179209 */ static public void loadFonts() { if (fonts == null) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); fonts = ge.getAllFonts(); if (PApplet.platform == PConstants.MACOS) { fontDifferent = new HashMap<>(); for (Font font : fonts) { // No need to use getPSName() anymore because getName() // returns the PostScript name on OS X 10.6 w/ Java 6. fontDifferent.put(font.getName(), font); } } } } /** * Starting with Java 1.5, Apple broke the ability to specify most fonts. * This bug was filed years ago as #4769141 at bugreporter.apple.com. More: * <a href="https://download.processing.org/bugzilla/407.html">Bug 407</a>. * <br> * This function displays a warning when the font is not found * and Java's system font is used. * See: <a href="https://github.com/processing/processing/issues/5481">issue #5481</a> */ static public Font findFont(String name) { if (PApplet.platform == PConstants.MACOS) { loadFonts(); Font maybe = fontDifferent.get(name); if (maybe != null) { return maybe; } } Font font = new Font(name, Font.PLAIN, 1); // make sure we have the name of the system fallback font if (systemFontName == null) { // Figure out what the font is named when things fail systemFontName = new Font("", Font.PLAIN, 1).getFontName(); } // warn the user if they didn't get the font they want if (!name.equals(systemFontName) && font.getFontName().equals(systemFontName)) { PGraphics.showWarning("\"" + name + "\" is not available, " + "so another font will be used. " + "Use PFont.list() to show available fonts."); } return font; } ////////////////////////////////////////////////////////////// /** * A single character, and its visage. */ public
will
java
redisson__redisson
redisson/src/main/java/org/redisson/api/search/query/Document.java
{ "start": 772, "end": 2289 }
class ____ { private final String id; private Map<String, Object> attributes; private byte[] payload; private Double score; public Document(String id) { this.id = id; } public Document(String id, Map<String, Object> attributes) { this.id = id; this.attributes = attributes; } /** * Returns document id * * @return document id */ public String getId() { return id; } /** * Returns document attributes * * @return document attributes */ public Map<String, Object> getAttributes() { return attributes; } /** * Returns document payload * * @return document payload */ public byte[] getPayload() { return payload; } /** * Returns document score * * @return document score */ public Double getScore() { return score; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Document document = (Document) o; return Objects.equals(id, document.id) && Objects.equals(attributes, document.attributes) && Arrays.equals(payload, document.payload) && Objects.equals(score, document.score); } @Override public int hashCode() { int result = Objects.hash(id, attributes, score); result = 31 * result + Arrays.hashCode(payload); return result; } }
Document
java
apache__spark
common/network-common/src/main/java/org/apache/spark/network/util/CryptoUtils.java
{ "start": 967, "end": 1800 }
class ____ { // The prefix for the configurations passing to Apache Commons Crypto library. public static final String COMMONS_CRYPTO_CONFIG_PREFIX = "commons.crypto."; /** * Extract the commons-crypto configuration embedded in a list of config values. * * @param prefix Prefix in the given configuration that identifies the commons-crypto configs. * @param conf List of configuration values. */ public static Properties toCryptoConf(String prefix, Iterable<Map.Entry<String, String>> conf) { Properties props = new Properties(); for (Map.Entry<String, String> e : conf) { String key = e.getKey(); if (key.startsWith(prefix)) { props.setProperty(COMMONS_CRYPTO_CONFIG_PREFIX + key.substring(prefix.length()), e.getValue()); } } return props; } }
CryptoUtils
java
quarkusio__quarkus
extensions/hibernate-envers/deployment/src/main/java/io/quarkus/hibernate/envers/deployment/HibernateEnversProcessor.java
{ "start": 1232, "end": 4786 }
class ____ { static final String HIBERNATE_ENVERS = "Hibernate Envers"; @BuildStep List<AdditionalJpaModelBuildItem> addJpaModelClasses() { return Arrays.asList( // These are added to specific PUs at static init using org.hibernate.boot.spi.AdditionalMappingContributor, // so we pass empty sets of PUs. // The build items tell the Hibernate extension to process the classes at build time: // add to Jandex index, bytecode enhancement, proxy generation, ... new AdditionalJpaModelBuildItem("org.hibernate.envers.DefaultRevisionEntity", Set.of()), new AdditionalJpaModelBuildItem("org.hibernate.envers.DefaultTrackingModifiedEntitiesRevisionEntity", Set.of()), new AdditionalJpaModelBuildItem("org.hibernate.envers.RevisionMapping", Set.of()), new AdditionalJpaModelBuildItem("org.hibernate.envers.TrackingModifiedEntitiesRevisionMapping", Set.of())); } @BuildStep public void registerEnversReflections(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, HibernateEnversBuildTimeConfig buildTimeConfig) { // This is necessary because these classes are added to the model conditionally at static init, // so they don't get processed by HibernateOrmProcessor and in particular don't get reflection enabled. reflectiveClass.produce(ReflectiveClassBuildItem.builder( "org.hibernate.envers.DefaultRevisionEntity", "org.hibernate.envers.DefaultTrackingModifiedEntitiesRevisionEntity", "org.hibernate.envers.RevisionMapping", "org.hibernate.envers.TrackingModifiedEntitiesRevisionMapping") .reason(getClass().getName()) .methods().build()); List<String> classes = new ArrayList<>(buildTimeConfig.persistenceUnits().size() * 2); for (HibernateEnversBuildTimeConfigPersistenceUnit pu : buildTimeConfig.persistenceUnits().values()) { pu.revisionListener().ifPresent(classes::add); pu.auditStrategy().ifPresent(classes::add); } reflectiveClass.produce(ReflectiveClassBuildItem.builder(classes.toArray(new String[0])) .reason("Configured Envers listeners and audit strategies") .methods().fields().build()); } @BuildStep(onlyIf = NativeOrNativeSourcesBuild.class) NativeImageFeatureBuildItem nativeImageFeature() { return new NativeImageFeatureBuildItem(DisableLoggingFeature.class); } @BuildStep @Record(ExecutionTime.STATIC_INIT) public void applyStaticConfig(HibernateEnversRecorder recorder, HibernateEnversBuildTimeConfig buildTimeConfig, List<PersistenceUnitDescriptorBuildItem> persistenceUnitDescriptorBuildItems, BuildProducer<HibernateOrmIntegrationStaticConfiguredBuildItem> integrationProducer) { for (PersistenceUnitDescriptorBuildItem puDescriptor : persistenceUnitDescriptorBuildItems) { String puName = puDescriptor.getPersistenceUnitName(); integrationProducer.produce( new HibernateOrmIntegrationStaticConfiguredBuildItem(HIBERNATE_ENVERS, puName) .setInitListener(recorder.createStaticInitListener(buildTimeConfig, puName)) .setXmlMappingRequired(true)); } } }
HibernateEnversProcessor
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerDslTest.java
{ "start": 1157, "end": 2413 }
class ____ extends ContextTestSupport { @Test public void testDuplicateMessages() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("one", "two", "three"); template.sendBodyAndHeader("direct:start", "one", "messageId", "1"); template.sendBodyAndHeader("direct:start", "two", "messageId", "2"); template.sendBodyAndHeader("direct:start", "one", "messageId", "1"); template.sendBodyAndHeader("direct:start", "two", "messageId", "2"); template.sendBodyAndHeader("direct:start", "one", "messageId", "1"); template.sendBodyAndHeader("direct:start", "three", "messageId", "3"); mock.assertIsSatisfied(); } public IdempotentRepository createRepo() { return MemoryIdempotentRepository.memoryIdempotentRepository(200); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").idempotentConsumer().message(m -> m.getHeader("messageId")) .idempotentRepository(createRepo()).to("mock:result"); } }; } }
IdempotentConsumerDslTest
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ext/javatime/deser/JSR310StringParsableDeserializer.java
{ "start": 1571, "end": 7050 }
class ____ extends JSR310DeserializerBase<Object> { protected final static int TYPE_PERIOD = 1; protected final static int TYPE_ZONE_ID = 2; protected final static int TYPE_ZONE_OFFSET = 3; public static final ValueDeserializer<Period> PERIOD = createDeserializer(Period.class, TYPE_PERIOD); public static final ValueDeserializer<ZoneId> ZONE_ID = createDeserializer(ZoneId.class, TYPE_ZONE_ID); public static final ValueDeserializer<ZoneOffset> ZONE_OFFSET = createDeserializer(ZoneOffset.class, TYPE_ZONE_OFFSET); protected final int _typeSelector; @SuppressWarnings("unchecked") protected JSR310StringParsableDeserializer(Class<?> supportedType, int typeSelector) { super((Class<Object>)supportedType); _typeSelector = typeSelector; } protected JSR310StringParsableDeserializer(JSR310StringParsableDeserializer base, Boolean leniency) { super(base, leniency); _typeSelector = base._typeSelector; } @SuppressWarnings("unchecked") protected static <T> ValueDeserializer<T> createDeserializer(Class<T> type, int typeId) { return (ValueDeserializer<T>) new JSR310StringParsableDeserializer(type, typeId); } @Override protected JSR310StringParsableDeserializer withLeniency(Boolean leniency) { if (_isLenient == !Boolean.FALSE.equals(leniency)) { return this; } // TODO: or should this be casting as above in createDeserializer? But then in createContext, we need to // call the withLeniency method in this class. (See if we can follow InstantDeser convention here?) return new JSR310StringParsableDeserializer(this, leniency); } @Override public ValueDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) { JsonFormat.Value format = findFormatOverrides(ctxt, property, handledType()); JSR310StringParsableDeserializer deser = this; if (format != null) { if (format.hasLenient()) { Boolean leniency = format.getLenient(); if (leniency != null) { deser = this.withLeniency(leniency); } } } return deser; } @Override public Object deserialize(JsonParser p, DeserializationContext ctxt) throws JacksonException { if (p.hasToken(JsonToken.VALUE_STRING)) { return _fromString(p, ctxt, p.getString()); } // 30-Sep-2020, tatu: New! "Scalar from Object" (mostly for XML) if (p.isExpectedStartObjectToken()) { final String str = ctxt.extractScalarFromObject(p, this, handledType()); // 17-May-2025, tatu: [databind#4656] need to check for `null` if (str != null) { return _fromString(p, ctxt, str); } // fall through } else if (p.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) { // 20-Apr-2016, tatu: Related to [databind#1208], can try supporting embedded // values quite easily return p.getEmbeddedObject(); } else if (p.isExpectedStartArrayToken()) { return _deserializeFromArray(p, ctxt); } throw ctxt.wrongTokenException(p, handledType(), JsonToken.VALUE_STRING, null); } @Override public Object deserializeWithType(JsonParser p, DeserializationContext context, TypeDeserializer deserializer) throws JacksonException { // This is a nasty kludge right here, working around issues like // [datatype-jsr310#24]. But should work better than not having the work-around. JsonToken t = p.currentToken(); if ((t != null) && t.isScalarValue()) { return deserialize(p, context); } return deserializer.deserializeTypedFromAny(p, context); } protected Object _fromString(JsonParser p, DeserializationContext ctxt, String string) throws JacksonException { string = string.trim(); if (string.length() == 0) { CoercionAction act = ctxt.findCoercionAction(logicalType(), _valueClass, CoercionInputShape.EmptyString); if (act == CoercionAction.Fail) { ctxt.reportInputMismatch(this, "Cannot coerce empty String (\"\") to %s (but could if enabling coercion using `CoercionConfig`)", _coercedTypeDesc()); } // 21-Jun-2020, tatu: As of 2.12, leniency considered legacy setting, // but still supported. if (!isLenient()) { return _failForNotLenient(p, ctxt, JsonToken.VALUE_STRING); } if (act == CoercionAction.AsEmpty) { return getEmptyValue(ctxt); } // None of the types has specific null value return null; } try { switch (_typeSelector) { case TYPE_PERIOD: return Period.parse(string); case TYPE_ZONE_ID: return ZoneId.of(string); case TYPE_ZONE_OFFSET: return ZoneOffset.of(string); } } catch (DateTimeException e) { return _handleDateTimeFormatException(ctxt, e, null, string); } VersionUtil.throwInternal(); return null; } }
JSR310StringParsableDeserializer
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/value/PropertyNotFoundException.java
{ "start": 739, "end": 1050 }
class ____ extends ValueException { /** * Constructor. * @param name name * @param type type */ public PropertyNotFoundException(String name, Class<?> type) { super("No property found for name [" + name + "] and type [" + type.getName() + "]"); } }
PropertyNotFoundException
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/subjects/SerializedSubject.java
{ "start": 1160, "end": 5944 }
class ____<T> extends Subject<T> implements NonThrowingPredicate<Object> { /** The actual subscriber to serialize Subscriber calls to. */ final Subject<T> actual; /** Indicates an emission is going on, guarded by this. */ boolean emitting; /** If not null, it holds the missed NotificationLite events. */ AppendOnlyLinkedArrayList<Object> queue; /** Indicates a terminal event has been received and all further events will be dropped. */ volatile boolean done; /** * Constructor that wraps an actual subject. * @param actual the subject wrapped */ SerializedSubject(final Subject<T> actual) { this.actual = actual; } @Override protected void subscribeActual(Observer<? super T> observer) { actual.subscribe(observer); } @Override public void onSubscribe(Disposable d) { boolean cancel; if (!done) { synchronized (this) { if (done) { cancel = true; } else { if (emitting) { AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(4); queue = q; } q.add(NotificationLite.disposable(d)); return; } emitting = true; cancel = false; } } } else { cancel = true; } if (cancel) { d.dispose(); } else { actual.onSubscribe(d); emitLoop(); } } @Override public void onNext(T t) { if (done) { return; } synchronized (this) { if (done) { return; } if (emitting) { AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(4); queue = q; } q.add(NotificationLite.next(t)); return; } emitting = true; } actual.onNext(t); emitLoop(); } @Override public void onError(Throwable t) { if (done) { RxJavaPlugins.onError(t); return; } boolean reportError; synchronized (this) { if (done) { reportError = true; } else { done = true; if (emitting) { AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(4); queue = q; } q.setFirst(NotificationLite.error(t)); return; } reportError = false; emitting = true; } } if (reportError) { RxJavaPlugins.onError(t); return; } actual.onError(t); } @Override public void onComplete() { if (done) { return; } synchronized (this) { if (done) { return; } done = true; if (emitting) { AppendOnlyLinkedArrayList<Object> q = queue; if (q == null) { q = new AppendOnlyLinkedArrayList<>(4); queue = q; } q.add(NotificationLite.complete()); return; } emitting = true; } actual.onComplete(); } /** Loops until all notifications in the queue has been processed. */ void emitLoop() { for (;;) { AppendOnlyLinkedArrayList<Object> q; synchronized (this) { q = queue; if (q == null) { emitting = false; return; } queue = null; } q.forEachWhile(this); } } @Override public boolean test(Object o) { return NotificationLite.acceptFull(o, actual); } @Override public boolean hasObservers() { return actual.hasObservers(); } @Override public boolean hasThrowable() { return actual.hasThrowable(); } @Override @Nullable public Throwable getThrowable() { return actual.getThrowable(); } @Override public boolean hasComplete() { return actual.hasComplete(); } }
SerializedSubject
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/MethodParameter.java
{ "start": 14979, "end": 18234 }
class ____ * @see #getDeclaringClass() */ public Class<?> getContainingClass() { Class<?> containingClass = this.containingClass; return (containingClass != null ? containingClass : getDeclaringClass()); } /** * Set a resolved (generic) parameter type. */ @Deprecated(since = "5.2") void setParameterType(@Nullable Class<?> parameterType) { this.parameterType = parameterType; } /** * Return the type of the method/constructor parameter. * @return the parameter type (never {@code null}) */ public Class<?> getParameterType() { Class<?> paramType = this.parameterType; if (paramType != null) { return paramType; } if (getContainingClass() != getDeclaringClass()) { paramType = ResolvableType.forMethodParameter(this, null, 1).resolve(); } if (paramType == null) { paramType = computeParameterType(); } this.parameterType = paramType; return paramType; } /** * Return the generic type of the method/constructor parameter. * @return the parameter type (never {@code null}) * @since 3.0 */ public Type getGenericParameterType() { Type paramType = this.genericParameterType; if (paramType == null) { if (this.parameterIndex < 0) { Method method = getMethod(); paramType = (method != null ? (KOTLIN_REFLECT_PRESENT && KotlinDetector.isKotlinType(getContainingClass()) ? KotlinDelegate.getGenericReturnType(method) : method.getGenericReturnType()) : void.class); } else { Type[] genericParameterTypes = this.executable.getGenericParameterTypes(); int index = this.parameterIndex; if (this.executable instanceof Constructor && ClassUtils.isInnerClass(this.executable.getDeclaringClass()) && genericParameterTypes.length == this.executable.getParameterCount() - 1) { // Bug in javac: type array excludes enclosing instance parameter // for inner classes with at least one generic constructor parameter, // so access it with the actual parameter index lowered by 1 index = this.parameterIndex - 1; } paramType = (index >= 0 && index < genericParameterTypes.length ? genericParameterTypes[index] : computeParameterType()); } this.genericParameterType = paramType; } return paramType; } private Class<?> computeParameterType() { if (this.parameterIndex < 0) { Method method = getMethod(); if (method == null) { return void.class; } if (KOTLIN_REFLECT_PRESENT && KotlinDetector.isKotlinType(getContainingClass())) { return KotlinDelegate.getReturnType(method); } return method.getReturnType(); } return this.executable.getParameterTypes()[this.parameterIndex]; } /** * Return the nested type of the method/constructor parameter. * @return the parameter type (never {@code null}) * @since 3.1 * @see #getNestingLevel() */ public Class<?> getNestedParameterType() { if (this.nestingLevel > 1) { Type type = getGenericParameterType(); for (int i = 2; i <= this.nestingLevel; i++) { if (type instanceof ParameterizedType parameterizedType) { Type[] args = parameterizedType.getActualTypeArguments(); Integer index = getTypeIndexForLevel(i); type = args[index != null ? index : args.length - 1]; } // TODO: Object.
itself
java
apache__camel
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/HttpFilterNoCamelHeadersTest.java
{ "start": 1181, "end": 3024 }
class ____ extends BaseJettyTest { @Test public void testFilterCamelHeaders() throws Exception { // the Camel file name header should be preserved during routing // but should not be sent over HTTP // and jetty should not send back CamelDummy header getMockEndpoint("mock:input").expectedMessageCount(1); getMockEndpoint("mock:input").message(0).header("bar").isEqualTo(123); getMockEndpoint("mock:input").message(0).header(Exchange.FILE_NAME).isNull(); getMockEndpoint("mock:result").expectedMessageCount(1); getMockEndpoint("mock:result").message(0).header("bar").isEqualTo(123); getMockEndpoint("mock:result").message(0).header(Exchange.FILE_NAME).isEqualTo("test.txt"); getMockEndpoint("mock:result").message(0).header("CamelDummy").isNull(); Exchange out = template.request("direct:start", new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody("World"); exchange.getIn().setHeader("bar", 123); } }); assertNotNull(out); assertEquals("Bye World", out.getMessage().getBody(String.class)); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").setHeader(Exchange.FILE_NAME, constant("test.txt")) .to("http://localhost:{{port}}/test/filter").to("mock:result"); from("jetty:http://localhost:{{port}}/test/filter").to("mock:input").setHeader("CamelDummy", constant("dummy")) .transform(simple("Bye ${body}")); } }; } }
HttpFilterNoCamelHeadersTest
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/factories/TestCatalogFactory.java
{ "start": 3708, "end": 14905 }
class ____ implements Catalog { private final String name; private final Map<String, String> options; public TestCatalog(String name, Map<String, String> options) { this.name = name; this.options = options; } public String getName() { return name; } public Map<String, String> getOptions() { return options; } @Override public void open() throws CatalogException {} @Override public void close() throws CatalogException {} @Override public String getDefaultDatabase() throws CatalogException { throw new UnsupportedOperationException(); } @Override public List<String> listDatabases() throws CatalogException { throw new UnsupportedOperationException(); } @Override public CatalogDatabase getDatabase(String databaseName) throws DatabaseNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public boolean databaseExists(String databaseName) throws CatalogException { throw new UnsupportedOperationException(); } @Override public void createDatabase(String name, CatalogDatabase database, boolean ignoreIfExists) throws DatabaseAlreadyExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public void dropDatabase(String name, boolean ignoreIfNotExists, boolean cascade) throws DatabaseNotExistException, DatabaseNotEmptyException, CatalogException { throw new UnsupportedOperationException(); } @Override public void alterDatabase( String name, CatalogDatabase newDatabase, boolean ignoreIfNotExists) throws DatabaseNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public List<String> listTables(String databaseName) throws DatabaseNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public List<String> listViews(String databaseName) throws DatabaseNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public CatalogBaseTable getTable(ObjectPath tablePath) throws TableNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public boolean tableExists(ObjectPath tablePath) throws CatalogException { throw new UnsupportedOperationException(); } @Override public void dropTable(ObjectPath tablePath, boolean ignoreIfNotExists) throws TableNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public void renameTable( ObjectPath tablePath, String newTableName, boolean ignoreIfNotExists) throws TableNotExistException, TableAlreadyExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public void createTable( ObjectPath tablePath, CatalogBaseTable table, boolean ignoreIfExists) throws TableAlreadyExistException, DatabaseNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public void alterTable( ObjectPath tablePath, CatalogBaseTable newTable, boolean ignoreIfNotExists) throws TableNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public List<CatalogPartitionSpec> listPartitions(ObjectPath tablePath) throws TableNotExistException, TableNotPartitionedException, CatalogException { throw new UnsupportedOperationException(); } @Override public List<CatalogPartitionSpec> listPartitions( ObjectPath tablePath, CatalogPartitionSpec partitionSpec) throws TableNotExistException, TableNotPartitionedException, PartitionSpecInvalidException, CatalogException { throw new UnsupportedOperationException(); } @Override public List<CatalogPartitionSpec> listPartitionsByFilter( ObjectPath tablePath, List<Expression> filters) throws TableNotExistException, TableNotPartitionedException, CatalogException { throw new UnsupportedOperationException(); } @Override public CatalogPartition getPartition( ObjectPath tablePath, CatalogPartitionSpec partitionSpec) throws PartitionNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public boolean partitionExists(ObjectPath tablePath, CatalogPartitionSpec partitionSpec) throws CatalogException { throw new UnsupportedOperationException(); } @Override public void createPartition( ObjectPath tablePath, CatalogPartitionSpec partitionSpec, CatalogPartition partition, boolean ignoreIfExists) throws TableNotExistException, TableNotPartitionedException, PartitionSpecInvalidException, PartitionAlreadyExistsException, CatalogException { throw new UnsupportedOperationException(); } @Override public void dropPartition( ObjectPath tablePath, CatalogPartitionSpec partitionSpec, boolean ignoreIfNotExists) throws PartitionNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public void alterPartition( ObjectPath tablePath, CatalogPartitionSpec partitionSpec, CatalogPartition newPartition, boolean ignoreIfNotExists) throws PartitionNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public List<String> listFunctions(String dbName) throws DatabaseNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public CatalogFunction getFunction(ObjectPath functionPath) throws FunctionNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public boolean functionExists(ObjectPath functionPath) throws CatalogException { throw new UnsupportedOperationException(); } @Override public void createFunction( ObjectPath functionPath, CatalogFunction function, boolean ignoreIfExists) throws FunctionAlreadyExistException, DatabaseNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public void alterFunction( ObjectPath functionPath, CatalogFunction newFunction, boolean ignoreIfNotExists) throws FunctionNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public void dropFunction(ObjectPath functionPath, boolean ignoreIfNotExists) throws FunctionNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public CatalogTableStatistics getTableStatistics(ObjectPath tablePath) throws TableNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public CatalogColumnStatistics getTableColumnStatistics(ObjectPath tablePath) throws TableNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public CatalogTableStatistics getPartitionStatistics( ObjectPath tablePath, CatalogPartitionSpec partitionSpec) throws CatalogException { throw new UnsupportedOperationException(); } @Override public List<CatalogTableStatistics> bulkGetPartitionStatistics( ObjectPath tablePath, List<CatalogPartitionSpec> partitionSpecs) throws CatalogException { throw new UnsupportedOperationException(); } @Override public CatalogColumnStatistics getPartitionColumnStatistics( ObjectPath tablePath, CatalogPartitionSpec partitionSpec) throws PartitionNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public List<CatalogColumnStatistics> bulkGetPartitionColumnStatistics( ObjectPath tablePath, List<CatalogPartitionSpec> partitionSpecs) throws PartitionNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public void alterTableStatistics( ObjectPath tablePath, CatalogTableStatistics tableStatistics, boolean ignoreIfNotExists) throws TableNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public void alterTableColumnStatistics( ObjectPath tablePath, CatalogColumnStatistics columnStatistics, boolean ignoreIfNotExists) throws TableNotExistException, CatalogException, TablePartitionedException { throw new UnsupportedOperationException(); } @Override public void alterPartitionStatistics( ObjectPath tablePath, CatalogPartitionSpec partitionSpec, CatalogTableStatistics partitionStatistics, boolean ignoreIfNotExists) throws PartitionNotExistException, CatalogException { throw new UnsupportedOperationException(); } @Override public void alterPartitionColumnStatistics( ObjectPath tablePath, CatalogPartitionSpec partitionSpec, CatalogColumnStatistics columnStatistics, boolean ignoreIfNotExists) throws PartitionNotExistException, CatalogException { throw new UnsupportedOperationException(); } } }
TestCatalog
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/protocol/CommandType.java
{ "start": 5517, "end": 6181 }
enum ____ as command name. */ CommandType() { command = name(); bytes = name().getBytes(StandardCharsets.US_ASCII); } /** * Complex commands (comprised of other symbols besides letters) get the command name as a parameter. * * @param name the command name, must not be {@literal null}. */ CommandType(String name) { command = name; bytes = name.getBytes(StandardCharsets.US_ASCII); } /** * * @return name of the command. */ public String toString() { return command; } @Override public byte[] getBytes() { return bytes; } }
constant
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/records/impl/pb/SubClusterDeregisterRequestPBImpl.java
{ "start": 1850, "end": 4869 }
class ____ extends SubClusterDeregisterRequest { private SubClusterDeregisterRequestProto proto = SubClusterDeregisterRequestProto.getDefaultInstance(); private SubClusterDeregisterRequestProto.Builder builder = null; private boolean viaProto = false; public SubClusterDeregisterRequestPBImpl() { builder = SubClusterDeregisterRequestProto.newBuilder(); } public SubClusterDeregisterRequestPBImpl( SubClusterDeregisterRequestProto proto) { this.proto = proto; viaProto = true; } public SubClusterDeregisterRequestProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } private void mergeLocalToProto() { if (viaProto) { maybeInitBuilder(); } mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = SubClusterDeregisterRequestProto.newBuilder(proto); } viaProto = false; } private void mergeLocalToBuilder() { } @Override public int hashCode() { return getProto().hashCode(); } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other.getClass().isAssignableFrom(this.getClass())) { return this.getProto().equals(this.getClass().cast(other).getProto()); } return false; } @Override public String toString() { return TextFormat.shortDebugString(getProto()); } @Override public SubClusterId getSubClusterId() { SubClusterDeregisterRequestProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasSubClusterId()) { return null; } return convertFromProtoFormat(p.getSubClusterId()); } @Override public void setSubClusterId(SubClusterId subClusterId) { maybeInitBuilder(); if (subClusterId == null) { builder.clearSubClusterId(); return; } builder.setSubClusterId(convertToProtoFormat(subClusterId)); } @Override public SubClusterState getState() { SubClusterDeregisterRequestProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasState()) { return null; } return convertFromProtoFormat(p.getState()); } @Override public void setState(SubClusterState state) { maybeInitBuilder(); if (state == null) { builder.clearState(); return; } builder.setState(convertToProtoFormat(state)); } private SubClusterId convertFromProtoFormat(SubClusterIdProto sc) { return new SubClusterIdPBImpl(sc); } private SubClusterIdProto convertToProtoFormat(SubClusterId sc) { return ((SubClusterIdPBImpl) sc).getProto(); } private SubClusterState convertFromProtoFormat(SubClusterStateProto state) { return SubClusterState.valueOf(state.name()); } private SubClusterStateProto convertToProtoFormat(SubClusterState state) { return SubClusterStateProto.valueOf(state.name()); } }
SubClusterDeregisterRequestPBImpl
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/Operator.java
{ "start": 3829, "end": 4368 }
interface ____ extends ToXContentObject, VersionedNamedWriteable { /** * The number of documents found by this operator. Most operators * don't find documents and will return {@code 0} here. */ default long documentsFound() { return 0; } /** * The number of values loaded by this operator. Most operators * don't load values and will return {@code 0} here. */ default long valuesLoaded() { return 0; } } }
Status
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/input/simple/SimpleInput.java
{ "start": 2433, "end": 2736 }
class ____ implements Input.Builder<SimpleInput> { private final Payload payload; private Builder(Payload payload) { this.payload = payload; } @Override public SimpleInput build() { return new SimpleInput(payload); } } }
Builder
java
quarkusio__quarkus
extensions/reactive-mssql-client/deployment/src/test/java/io/quarkus/reactive/mssql/client/CredentialsTestResource.java
{ "start": 365, "end": 856 }
class ____ { @Inject Pool client; @GET @Produces(MediaType.TEXT_PLAIN) public CompletionStage<String> connect() { return client.query("SELECT 1").execute() .map(mssqlRowSet -> { assertEquals(1, mssqlRowSet.size()); assertEquals(1, mssqlRowSet.iterator().next().getInteger(0)); return "OK"; }) .subscribeAsCompletionStage(); } }
CredentialsTestResource
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/InjectableDecorator.java
{ "start": 311, "end": 590 }
interface ____<T> extends InjectableBean<T>, Decorator<T> { @Override default Kind getKind() { return Kind.DECORATOR; } @Override default Set<Annotation> getDelegateQualifiers() { return Qualifiers.DEFAULT_QUALIFIERS; } }
InjectableDecorator
java
apache__flink
flink-connectors/flink-connector-files/src/test/java/org/apache/flink/connector/file/src/testutils/TestingFileEnumerator.java
{ "start": 1256, "end": 1995 }
class ____ implements FileEnumerator { private final ArrayDeque<FileSourceSplit> splits = new ArrayDeque<>(); public TestingFileEnumerator(FileSourceSplit... initialSplits) { addSplits(initialSplits); } @Override public Collection<FileSourceSplit> enumerateSplits(Path[] paths, int minDesiredSplits) throws IOException { synchronized (splits) { final ArrayList<FileSourceSplit> currentSplits = new ArrayList<>(splits); splits.clear(); return currentSplits; } } public void addSplits(FileSourceSplit... newSplits) { synchronized (splits) { splits.addAll(Arrays.asList(newSplits)); } } }
TestingFileEnumerator
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/inference/action/UpdateInferenceModelAction.java
{ "start": 2141, "end": 10226 }
class ____ extends AcknowledgedRequest<Request> { private final String inferenceEntityId; private final BytesReference content; private final XContentType contentType; private final TaskType taskType; private Settings settings; public Request(String inferenceEntityId, BytesReference content, XContentType contentType, TaskType taskType, TimeValue timeout) { super(timeout, DEFAULT_ACK_TIMEOUT); this.inferenceEntityId = inferenceEntityId; this.content = content; this.contentType = contentType; this.taskType = taskType; } public Request(StreamInput in) throws IOException { super(in); this.inferenceEntityId = in.readString(); this.taskType = TaskType.fromStream(in); this.content = in.readBytesReference(); this.contentType = in.readEnum(XContentType.class); } public String getInferenceEntityId() { return inferenceEntityId; } public TaskType getTaskType() { return taskType; } /** * The body of the request. * For in-cluster models, this is expected to contain some of the following: * "number_of_allocations": `an integer` * * For third-party services, this is expected to contain: * "service_settings": { * "api_key": `a string` // service settings can only contain an api key * } * "task_settings": { a map of settings } * */ public BytesReference getContent() { return content; } /** * The body of the request as a map. * The map is validated such that only allowed fields are present. * If any fields in the body are not on the allow list, this function will throw an exception. */ public Settings getContentAsSettings() { if (settings == null) { // settings is deterministic on content, so we only need to compute it once Map<String, Object> unvalidatedMap = XContentHelper.convertToMap(content, false, contentType).v2(); Map<String, Object> serviceSettings = new HashMap<>(); Map<String, Object> taskSettings = new HashMap<>(); TaskType taskType = null; if (unvalidatedMap.isEmpty()) { throw new ElasticsearchStatusException("Request body is empty", RestStatus.BAD_REQUEST); } if (unvalidatedMap.containsKey("task_type")) { if (unvalidatedMap.get("task_type") instanceof String taskTypeString) { taskType = TaskType.fromStringOrStatusException(taskTypeString); } else { throw new ElasticsearchStatusException( "Failed to parse [task_type] in update request [{}]", RestStatus.INTERNAL_SERVER_ERROR, unvalidatedMap.toString() ); } unvalidatedMap.remove("task_type"); } if (unvalidatedMap.containsKey(SERVICE_SETTINGS)) { if (unvalidatedMap.get(SERVICE_SETTINGS) instanceof Map<?, ?> tempMap) { for (Map.Entry<?, ?> entry : (tempMap).entrySet()) { if (entry.getKey() instanceof String key && entry.getValue() instanceof Object value) { serviceSettings.put(key, value); } else { throw new ElasticsearchStatusException( "Failed to parse update request [{}]", RestStatus.INTERNAL_SERVER_ERROR, unvalidatedMap.toString() ); } } unvalidatedMap.remove(SERVICE_SETTINGS); } else { throw new ElasticsearchStatusException( "Unable to parse service settings in the request [{}]", RestStatus.BAD_REQUEST, unvalidatedMap.toString() ); } } if (unvalidatedMap.containsKey(TASK_SETTINGS)) { if (unvalidatedMap.get(TASK_SETTINGS) instanceof Map<?, ?> tempMap) { for (Map.Entry<?, ?> entry : (tempMap).entrySet()) { if (entry.getKey() instanceof String key && entry.getValue() instanceof Object value) { taskSettings.put(key, value); } else { throw new ElasticsearchStatusException( "Failed to parse update request [{}]", RestStatus.INTERNAL_SERVER_ERROR, unvalidatedMap.toString() ); } } unvalidatedMap.remove(TASK_SETTINGS); } else { throw new ElasticsearchStatusException( "Unable to parse task settings in the request [{}]", RestStatus.BAD_REQUEST, unvalidatedMap.toString() ); } } if (unvalidatedMap.isEmpty() == false) { throw new ElasticsearchStatusException( "Request contained fields which cannot be updated, remove these fields and try again [{}]", RestStatus.BAD_REQUEST, unvalidatedMap.toString() ); } this.settings = new Settings( serviceSettings.isEmpty() == false ? Collections.unmodifiableMap(serviceSettings) : null, taskSettings.isEmpty() == false ? Collections.unmodifiableMap(taskSettings) : null, taskType ); } return this.settings; } public XContentType getContentType() { return contentType; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(inferenceEntityId); taskType.writeTo(out); out.writeBytesReference(content); XContentHelper.writeTo(out, contentType); } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = new ActionRequestValidationException(); if (MlStrings.isValidId(this.inferenceEntityId) == false) { validationException.addValidationError(Messages.getMessage(Messages.INVALID_ID, "inference_id", this.inferenceEntityId)); } if (validationException.validationErrors().isEmpty() == false) { return validationException; } else { return null; } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Request request = (Request) o; return Objects.equals(inferenceEntityId, request.inferenceEntityId) && Objects.equals(content, request.content) && contentType == request.contentType && taskType == request.taskType; } @Override public int hashCode() { return Objects.hash(inferenceEntityId, content, contentType, taskType); } } public static
Request
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/struct/TestPOJOAsArrayAdvanced.java
{ "start": 1480, "end": 1740 }
class ____ { @JsonView(ViewA.class) public int a; @JsonView(ViewB.class) public int b; public int c; } @JsonFormat(shape=JsonFormat.Shape.ARRAY) @JsonPropertyOrder(alphabetic=true) static
AsArrayWithView
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/array/FloatPrimitiveArraySerializer.java
{ "start": 1324, "end": 3579 }
class ____ extends TypeSerializerSingleton<float[]> { private static final long serialVersionUID = 1L; private static final float[] EMPTY = new float[0]; public static final FloatPrimitiveArraySerializer INSTANCE = new FloatPrimitiveArraySerializer(); @Override public boolean isImmutableType() { return false; } @Override public float[] createInstance() { return EMPTY; } @Override public float[] copy(float[] from) { float[] copy = new float[from.length]; System.arraycopy(from, 0, copy, 0, from.length); return copy; } @Override public float[] copy(float[] from, float[] reuse) { return copy(from); } @Override public int getLength() { return -1; } @Override public void serialize(float[] record, DataOutputView target) throws IOException { if (record == null) { throw new IllegalArgumentException("The record must not be null."); } final int len = record.length; target.writeInt(len); for (int i = 0; i < len; i++) { target.writeFloat(record[i]); } } @Override public float[] deserialize(DataInputView source) throws IOException { final int len = source.readInt(); float[] result = new float[len]; for (int i = 0; i < len; i++) { result[i] = source.readFloat(); } return result; } @Override public float[] deserialize(float[] reuse, DataInputView source) throws IOException { return deserialize(source); } @Override public void copy(DataInputView source, DataOutputView target) throws IOException { final int len = source.readInt(); target.writeInt(len); target.write(source, len * 4); } @Override public TypeSerializerSnapshot<float[]> snapshotConfiguration() { return new FloatPrimitiveArraySerializerSnapshot(); } // ------------------------------------------------------------------------ /** Serializer configuration snapshot for compatibility and format evolution. */ @SuppressWarnings("WeakerAccess") public static final
FloatPrimitiveArraySerializer
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/document/DocumentActionsIT.java
{ "start": 2140, "end": 13213 }
class ____ extends ESIntegTestCase { protected void createIndex() { ElasticsearchAssertions.assertAcked(prepareCreate(getConcreteIndexName()).setMapping("name", "type=keyword,store=true")); } protected String getConcreteIndexName() { return "test"; } public void testIndexActions() throws Exception { createIndex(); NumShards numShards = getNumShards(getConcreteIndexName()); logger.info("Running Cluster Health"); ensureGreen(); logger.info("Indexing [type1/1]"); DocWriteResponse indexResponse = prepareIndex("test").setId("1") .setSource(source("1", "test")) .setRefreshPolicy(RefreshPolicy.IMMEDIATE) .get(); assertThat(indexResponse.getIndex(), equalTo(getConcreteIndexName())); assertThat(indexResponse.getId(), equalTo("1")); logger.info("Refreshing"); BroadcastResponse refreshResponse = refresh(); assertThat(refreshResponse.getSuccessfulShards(), equalTo(numShards.totalNumShards)); logger.info("--> index exists?"); assertThat(indexExists(getConcreteIndexName()), equalTo(true)); logger.info("--> index exists?, fake index"); assertThat(indexExists("test1234565"), equalTo(false)); logger.info("Clearing cache"); BroadcastResponse clearIndicesCacheResponse = indicesAdmin().clearCache( new ClearIndicesCacheRequest("test").fieldDataCache(true).queryCache(true) ).actionGet(); assertNoFailures(clearIndicesCacheResponse); assertThat(clearIndicesCacheResponse.getSuccessfulShards(), equalTo(numShards.totalNumShards)); logger.info("Force Merging"); waitForRelocation(ClusterHealthStatus.GREEN); BaseBroadcastResponse mergeResponse = forceMerge(); assertThat(mergeResponse.getSuccessfulShards(), equalTo(numShards.totalNumShards)); GetResponse getResult; logger.info("Get [type1/1]"); for (int i = 0; i < 5; i++) { getResult = client().prepareGet("test", "1").get(); assertThat(getResult.getIndex(), equalTo(getConcreteIndexName())); assertThat("cycle #" + i, getResult.getSourceAsString(), equalTo(Strings.toString(source("1", "test")))); assertThat("cycle(map) #" + i, (String) getResult.getSourceAsMap().get("name"), equalTo("test")); getResult = client().get(new GetRequest("test").id("1")).actionGet(); assertThat("cycle #" + i, getResult.getSourceAsString(), equalTo(Strings.toString(source("1", "test")))); assertThat(getResult.getIndex(), equalTo(getConcreteIndexName())); } logger.info("Get [type1/1] with script"); for (int i = 0; i < 5; i++) { getResult = client().prepareGet("test", "1").setStoredFields("name").get(); assertThat(getResult.getIndex(), equalTo(getConcreteIndexName())); assertThat(getResult.isExists(), equalTo(true)); assertThat(getResult.getSourceAsBytesRef(), nullValue()); assertThat(getResult.getField("name").getValues().get(0).toString(), equalTo("test")); } logger.info("Get [type1/2] (should be empty)"); for (int i = 0; i < 5; i++) { getResult = client().get(new GetRequest("test").id("2")).actionGet(); assertThat(getResult.isExists(), equalTo(false)); } logger.info("Delete [type1/1]"); DeleteResponse deleteResponse = client().prepareDelete("test", "1").get(); assertThat(deleteResponse.getIndex(), equalTo(getConcreteIndexName())); assertThat(deleteResponse.getId(), equalTo("1")); logger.info("Refreshing"); indicesAdmin().refresh(new RefreshRequest("test")).actionGet(); logger.info("Get [type1/1] (should be empty)"); for (int i = 0; i < 5; i++) { getResult = client().get(new GetRequest("test").id("1")).actionGet(); assertThat(getResult.isExists(), equalTo(false)); } logger.info("Index [type1/1]"); client().index(new IndexRequest("test").id("1").source(source("1", "test"))).actionGet(); logger.info("Index [type1/2]"); client().index(new IndexRequest("test").id("2").source(source("2", "test2"))).actionGet(); logger.info("Flushing"); BroadcastResponse flushResult = indicesAdmin().prepareFlush("test").get(); assertThat(flushResult.getSuccessfulShards(), equalTo(numShards.totalNumShards)); assertThat(flushResult.getFailedShards(), equalTo(0)); logger.info("Refreshing"); indicesAdmin().refresh(new RefreshRequest("test")).actionGet(); logger.info("Get [type1/1] and [type1/2]"); for (int i = 0; i < 5; i++) { getResult = client().get(new GetRequest("test").id("1")).actionGet(); assertThat(getResult.getIndex(), equalTo(getConcreteIndexName())); assertThat("cycle #" + i, getResult.getSourceAsString(), equalTo(Strings.toString(source("1", "test")))); getResult = client().get(new GetRequest("test").id("2")).actionGet(); String ste1 = getResult.getSourceAsString(); String ste2 = Strings.toString(source("2", "test2")); assertThat("cycle #" + i, ste1, equalTo(ste2)); assertThat(getResult.getIndex(), equalTo(getConcreteIndexName())); } logger.info("Count"); // check count for (int i = 0; i < 5; i++) { // test successful assertNoFailuresAndResponse(prepareSearch("test").setSize(0).setQuery(matchAllQuery()), countResponse -> { assertThat(countResponse.getHits().getTotalHits().value(), equalTo(2L)); assertThat(countResponse.getSuccessfulShards(), equalTo(numShards.numPrimaries)); assertThat(countResponse.getFailedShards(), equalTo(0)); }); // count with no query is a match all one assertNoFailuresAndResponse(prepareSearch("test").setSize(0), countResponse -> { assertThat( "Failures " + countResponse.getShardFailures(), countResponse.getShardFailures() == null ? 0 : countResponse.getShardFailures().length, equalTo(0) ); assertThat(countResponse.getHits().getTotalHits().value(), equalTo(2L)); assertThat(countResponse.getSuccessfulShards(), equalTo(numShards.numPrimaries)); assertThat(countResponse.getFailedShards(), equalTo(0)); }); } } public void testBulk() throws Exception { createIndex(); NumShards numShards = getNumShards(getConcreteIndexName()); logger.info("-> running Cluster Health"); ensureGreen(); BulkResponse bulkResponse = client().prepareBulk() .add(prepareIndex("test").setId("1").setSource(source("1", "test"))) .add(prepareIndex("test").setId("2").setSource(source("2", "test")).setCreate(true)) .add(prepareIndex("test").setSource(source("3", "test"))) .add(prepareIndex("test").setCreate(true).setSource(source("4", "test"))) .add(client().prepareDelete().setIndex("test").setId("1")) .add(prepareIndex("test").setSource("{ xxx }", XContentType.JSON)) // failure .get(); assertThat(bulkResponse.hasFailures(), equalTo(true)); assertThat(bulkResponse.getItems().length, equalTo(6)); assertThat(bulkResponse.getItems()[0].isFailed(), equalTo(false)); assertThat(bulkResponse.getItems()[0].getOpType(), equalTo(OpType.INDEX)); assertThat(bulkResponse.getItems()[0].getIndex(), equalTo(getConcreteIndexName())); assertThat(bulkResponse.getItems()[0].getId(), equalTo("1")); assertThat(bulkResponse.getItems()[1].isFailed(), equalTo(false)); assertThat(bulkResponse.getItems()[1].getOpType(), equalTo(OpType.CREATE)); assertThat(bulkResponse.getItems()[1].getIndex(), equalTo(getConcreteIndexName())); assertThat(bulkResponse.getItems()[1].getId(), equalTo("2")); assertThat(bulkResponse.getItems()[2].isFailed(), equalTo(false)); assertThat(bulkResponse.getItems()[2].getOpType(), equalTo(OpType.INDEX)); assertThat(bulkResponse.getItems()[2].getIndex(), equalTo(getConcreteIndexName())); String generatedId3 = bulkResponse.getItems()[2].getId(); assertThat(bulkResponse.getItems()[3].isFailed(), equalTo(false)); assertThat(bulkResponse.getItems()[3].getOpType(), equalTo(OpType.CREATE)); assertThat(bulkResponse.getItems()[3].getIndex(), equalTo(getConcreteIndexName())); String generatedId4 = bulkResponse.getItems()[3].getId(); assertThat(bulkResponse.getItems()[4].isFailed(), equalTo(false)); assertThat(bulkResponse.getItems()[4].getOpType(), equalTo(OpType.DELETE)); assertThat(bulkResponse.getItems()[4].getIndex(), equalTo(getConcreteIndexName())); assertThat(bulkResponse.getItems()[4].getId(), equalTo("1")); assertThat(bulkResponse.getItems()[5].isFailed(), equalTo(true)); assertThat(bulkResponse.getItems()[5].getOpType(), equalTo(OpType.INDEX)); assertThat(bulkResponse.getItems()[5].getIndex(), equalTo(getConcreteIndexName())); waitForRelocation(ClusterHealthStatus.GREEN); BroadcastResponse refreshResponse = indicesAdmin().prepareRefresh("test").get(); assertNoFailures(refreshResponse); assertThat(refreshResponse.getSuccessfulShards(), equalTo(numShards.totalNumShards)); for (int i = 0; i < 5; i++) { GetResponse getResult = client().get(new GetRequest("test").id("1")).actionGet(); assertThat(getResult.getIndex(), equalTo(getConcreteIndexName())); assertThat("cycle #" + i, getResult.isExists(), equalTo(false)); getResult = client().get(new GetRequest("test").id("2")).actionGet(); assertThat("cycle #" + i, getResult.getSourceAsString(), equalTo(Strings.toString(source("2", "test")))); assertThat(getResult.getIndex(), equalTo(getConcreteIndexName())); getResult = client().get(new GetRequest("test").id(generatedId3)).actionGet(); assertThat("cycle #" + i, getResult.getSourceAsString(), equalTo(Strings.toString(source("3", "test")))); assertThat(getResult.getIndex(), equalTo(getConcreteIndexName())); getResult = client().get(new GetRequest("test").id(generatedId4)).actionGet(); assertThat("cycle #" + i, getResult.getSourceAsString(), equalTo(Strings.toString(source("4", "test")))); assertThat(getResult.getIndex(), equalTo(getConcreteIndexName())); } } private XContentBuilder source(String id, String nameValue) throws IOException { return XContentFactory.jsonBuilder().startObject().field("id", id).field("name", nameValue).endObject(); } }
DocumentActionsIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/collection/multisession/MultipleSessionCollectionTest.java
{ "start": 1728, "end": 12504 }
class ____ { @Test @JiraKey(value = "HHH-9518") public void testCopyPersistentCollectionReferenceBeforeFlush(SessionFactoryScope scope) { Parent parent = new Parent(); Child c = new Child(); parent.children.add( c ); scope.inTransaction( s1 -> { s1.persist( parent ); // Copy p.children into a different Parent before flush and try to save in new session. Parent pWithSameChildren = new Parent(); pWithSameChildren.children = parent.children; scope.inSession( s2 -> { s2.getTransaction().begin(); try { s2.merge( pWithSameChildren ); s2.getTransaction().commit(); fail( "should have thrown HibernateException" ); } catch (OptimisticLockException ex) { // expected s2.getTransaction().rollback(); } } ); } ); scope.inTransaction( session -> { Parent pGet = session.get( Parent.class, parent.id ); assertEquals( c.id, pGet.children.iterator().next().id ); session.remove( pGet ); } ); } @Test @JiraKey("HHH-9518") @SkipForDialect(dialectClass = HSQLDialect.class, reason = "The select triggered by the merge just hang without any exception") @SkipForDialect(dialectClass = CockroachDialect.class, reason = "The merge in the second session causes a deadlock") public void testCopyPersistentCollectionReferenceAfterFlush(SessionFactoryScope scope) { Parent p = new Parent(); Child c = new Child(); p.children.add( c ); scope.inTransaction( s1 -> { s1.persist( p ); s1.flush(); // Copy p.children into a different Parent after flush and try to merge in new session. Parent pWithSameChildren = new Parent(); pWithSameChildren.children = p.children; scope.inSession( s2 -> { s2.getTransaction().begin(); try { s2.merge( pWithSameChildren ); s2.getTransaction().commit(); fail( "should have thrown HibernateException" ); } catch (OptimisticLockException | PessimisticLockException | LockTimeoutException ex) { // expected s2.getTransaction().rollback(); } } ); } ); scope.inTransaction( session -> { Parent pGet = session.get( Parent.class, p.id ); assertEquals( c.id, pGet.children.iterator().next().id ); session.remove( pGet ); } ); } @Test @JiraKey(value = "HHH-9518") public void testCopyUninitializedCollectionReferenceAfterGet(SessionFactoryScope scope) { Parent parent = new Parent(); Child c = new Child(); parent.children.add( c ); scope.inTransaction( session -> session.persist( parent ) ); scope.inTransaction( s1 -> { Parent p = s1.get( Parent.class, parent.id ); assertFalse( Hibernate.isInitialized( p.children ) ); // Copy p.children (uninitialized) into a different Parent and try to save in new session. Parent pWithSameChildren = new Parent(); pWithSameChildren.children = p.children; scope.inTransaction( s2 -> { Parent merged = s2.merge( pWithSameChildren ); assertThat( merged.children ).isNotSameAs( p.children ); } ); } ); scope.inTransaction( session -> { Parent pGet = session.get( Parent.class, parent.id ); assertEquals( c.id, pGet.children.iterator().next().id ); session.remove( pGet ); } ); } @Test @JiraKey(value = "HHH-9518") public void testCopyInitializedCollectionReferenceAfterGet(SessionFactoryScope scope) { Parent parent = new Parent(); Child c = new Child(); parent.children.add( c ); scope.inTransaction( session -> session.persist( parent ) ); Parent pMerged = scope.fromTransaction( s1 -> { Parent p = s1.get( Parent.class, parent.id ); Hibernate.initialize( p.children ); // Copy p.children (initialized) into a different Parent.children and try to save in new session. Parent pWithSameChildren = new Parent(); pWithSameChildren.children = p.children; return scope.fromTransaction( s2 -> { Parent merged = s2.merge( pWithSameChildren ); assertThat( merged.children ).isNotSameAs( p.children ); assertThat( merged.children ).isNotSameAs( pWithSameChildren.children ); return merged; } ); } ); scope.inTransaction( session -> { Parent pGet = session.get( Parent.class, parent.id ); assertThat( pGet.children.size() ).isEqualTo( 0 ); pGet = session.get( Parent.class, pMerged.id ); assertEquals( c.id, pGet.children.iterator().next().id ); session.remove( pGet ); } ); } @Test @JiraKey(value = "HHH-9518") public void testCopyInitializedCollectionReferenceToNewEntityCollectionRoleAfterGet(SessionFactoryScope scope) { Parent parent = new Parent(); Child c = new Child(); parent.children.add( c ); scope.inTransaction( session -> session.persist( parent ) ); Parent mParent = scope.fromTransaction( s1 -> { Parent p = s1.get( Parent.class, parent.id ); Hibernate.initialize( p.children ); // Copy p.children (initialized) into a different Parent.oldChildren (note different collection role) // and try to save in new session. Parent pWithSameChildren = new Parent(); pWithSameChildren.oldChildren = p.children; return scope.fromTransaction( s2 -> { Parent merged = s2.merge( pWithSameChildren ); assertThat( merged.oldChildren ).isNotSameAs( p.children ); assertThat( merged.oldChildren ).isNotSameAs( pWithSameChildren.children ); assertThat( merged.oldChildren ).isNotSameAs( p.oldChildren ); assertThat( merged.oldChildren ).isNotSameAs( pWithSameChildren.oldChildren ); return merged; } ); } ); scope.inTransaction( session -> { Parent pGet = session.get( Parent.class, parent.id ); assertEquals( c.id, pGet.children.iterator().next().id ); Parent pGet1 = session.get( Parent.class, mParent.id ); assertEquals( c.id, pGet1.oldChildren.iterator().next().id ); session.remove( pGet ); session.remove( pGet1 ); } ); } @Test @JiraKey(value = "HHH-9518") public void testDeleteCommitCopyToNewOwnerInNewSession(SessionFactoryScope scope) { Parent p1 = new Parent(); p1.nickNames.add( "nick" ); Parent p2 = new Parent(); scope.inTransaction( session -> { session.persist( p1 ); session.persist( p2 ); } ); scope.inSession( s1 -> { s1.getTransaction().begin(); s1.remove( p1 ); s1.flush(); s1.getTransaction().commit(); // need to commit after flushing; otherwise, will get lock failure when try to move the collection below assertNull( s1.getPersistenceContext().getEntry( p1 ) ); CollectionEntry ceChildren = s1.getPersistenceContext() .getCollectionEntry( (PersistentCollection) p1.children ); CollectionEntry ceNickNames = s1.getPersistenceContext() .getCollectionEntry( (PersistentCollection) p1.nickNames ); assertNull( ceChildren ); assertNull( ceNickNames ); assertNull( ( (AbstractPersistentCollection) p1.children ).getSession() ); assertNull( ( (AbstractPersistentCollection) p1.oldChildren ).getSession() ); assertNull( ( (AbstractPersistentCollection) p1.nickNames ).getSession() ); assertNull( ( (AbstractPersistentCollection) p1.oldNickNames ).getSession() ); // Assign the deleted collection to a different entity with same collection role (p2.nickNames) p2.nickNames = p1.nickNames; scope.inTransaction( s2 -> s2.merge( p2 ) ); } ); } @Test @JiraKey(value = "HHH-9518") public void testDeleteCommitCopyToNewOwnerNewCollectionRoleInNewSession(SessionFactoryScope scope) { Parent p1 = new Parent(); p1.nickNames.add( "nick" ); Parent p2 = new Parent(); scope.inTransaction( session -> { session.persist( p1 ); session.persist( p2 ); } ); scope.inSession( s1 -> { s1.getTransaction().begin(); s1.remove( p1 ); s1.flush(); s1.getTransaction().commit(); // need to commit after flushing; otherwise, will get lock failure when try to move the collection below assertNull( s1.getPersistenceContext().getEntry( p1 ) ); CollectionEntry ceChildren = s1.getPersistenceContext() .getCollectionEntry( (PersistentCollection) p1.children ); CollectionEntry ceNickNames = s1.getPersistenceContext() .getCollectionEntry( (PersistentCollection) p1.nickNames ); assertNull( ceChildren ); assertNull( ceNickNames ); assertNull( ( (AbstractPersistentCollection) p1.children ).getSession() ); assertNull( ( (AbstractPersistentCollection) p1.oldChildren ).getSession() ); assertNull( ( (AbstractPersistentCollection) p1.nickNames ).getSession() ); assertNull( ( (AbstractPersistentCollection) p1.oldNickNames ).getSession() ); // Assign the deleted collection to a different entity with different collection role (p2.oldNickNames) p2.oldNickNames = p1.nickNames; scope.inTransaction( s2 -> s2.merge( p2 ) ); } ); } @Test @JiraKey(value = "HHH-9518") public void testDeleteCopyToNewOwnerInNewSessionBeforeFlush(SessionFactoryScope scope) { Parent p1 = new Parent(); p1.nickNames.add( "nick" ); Parent p2 = new Parent(); scope.inTransaction( session -> { session.persist( p1 ); session.persist( p2 ); } ); scope.inTransaction( s1 -> { s1.remove( p1 ); // Assign the deleted collection to a different entity with same collection role (p2.nickNames) // before committing delete. p2.nickNames = p1.nickNames; scope.inTransaction( s2 -> { Parent merged = s2.merge( p2 ); assertThat( merged.nickNames ).isNotSameAs( p2.nickNames ); } ); } ); } @Test @JiraKey(value = "HHH-9518") public void testDeleteCopyToNewOwnerNewCollectionRoleInNewSessionBeforeFlush(SessionFactoryScope scope) { Parent p1 = new Parent(); p1.nickNames.add( "nick" ); Parent p2 = new Parent(); scope.inTransaction( session -> { session.persist( p1 ); session.persist( p2 ); } ); scope.inTransaction( s1 -> { s1.remove( p1 ); // Assign the deleted collection to a different entity with different collection role (p2.oldNickNames) // before committing delete. p2.oldNickNames = p1.nickNames; scope.inTransaction( s2 -> { Parent merged = s2.merge( p2 ); assertThat( merged.oldNickNames ).isNotSameAs( p2.oldNickNames ); } ); } ); } @Entity(name = "Parent") public static
MultipleSessionCollectionTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/DefinitionPolicyPerProcessorTest.java
{ "start": 2764, "end": 3720 }
class ____ implements Policy { private final String name; private int invoked; public MyPolicy(String name) { this.name = name; } public int getInvoked() { return invoked; } @Override public void beforeWrap(Route route, NamedNode definition) { SetBodyDefinition bodyDef = (SetBodyDefinition) ((ProcessorDefinition<?>) definition).getOutputs().get(0); bodyDef.setExpression(new ConstantExpression("body was altered")); } @Override public Processor wrap(final Route route, final Processor processor) { return new Processor() { public void process(Exchange exchange) throws Exception { invoked++; exchange.getIn().setHeader(name, "was wrapped"); processor.process(exchange); } }; } } }
MyPolicy
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/expr/SQLSizeExpr.java
{ "start": 932, "end": 2156 }
class ____ extends SQLExprImpl { private SQLExpr value; private Unit unit; public SQLSizeExpr() { } public SQLSizeExpr(String value, char unit) { this.unit = Unit.valueOf(Character.toString(unit).toUpperCase()); if (value.indexOf('.') == -1) { this.value = new SQLIntegerExpr(Integer.parseInt(value)); } else { this.value = new SQLNumberExpr(new BigDecimal(value)); } } public SQLSizeExpr(SQLExpr value, Unit unit) { super(); this.value = value; this.unit = unit; } @Override public void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { if (this.value != null) { this.value.accept(visitor); } } visitor.endVisit(this); } public List<SQLObject> getChildren() { return Collections.<SQLObject>singletonList(value); } public SQLExpr getValue() { return value; } public void setValue(SQLExpr value) { this.value = value; } public Unit getUnit() { return unit; } public void setUnit(Unit unit) { this.unit = unit; } public static
SQLSizeExpr
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateShouldSkipFilteredExchangesTest.java
{ "start": 1246, "end": 2511 }
class ____ extends ContextTestSupport { @Test public void testAggregateWithFilter() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Hello World,Bye World"); MockEndpoint filtered = getMockEndpoint("mock:filtered"); filtered.expectedBodiesReceived("Hello World", "Bye World"); template.sendBodyAndHeader("direct:start", "Hello World", "id", 1); template.sendBodyAndHeader("direct:start", "Hi there", "id", 1); template.sendBodyAndHeader("direct:start", "Bye World", "id", 1); template.sendBodyAndHeader("direct:start", "How do you do?", "id", 1); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { Predicate goodWord = body().contains("World"); from("direct:start").filter(goodWord).to("mock:filtered").aggregate(header("id"), new MyAggregationStrategy()) .completionTimeout(1000).to("mock:result").end() .end(); } }; } private static
AggregateShouldSkipFilteredExchangesTest
java
apache__camel
components/camel-grape/src/main/java/org/apache/camel/component/grape/GrapeEndpoint.java
{ "start": 1690, "end": 3787 }
class ____ extends DefaultEndpoint { @UriPath(description = "Maven coordinates to use as default to grab if the message body is empty.") @Metadata(required = true) private final String defaultCoordinates; public GrapeEndpoint(String endpointUri, String defaultCoordinates, GrapeComponent component) { super(endpointUri, component); this.defaultCoordinates = defaultCoordinates; } public static List<String> loadPatches(CamelContext camelContext) { final ClassLoader classLoader = camelContext.getApplicationContextClassLoader(); PatchesRepository patchesRepository = camelContext.getComponent("grape", GrapeComponent.class).getPatchesRepository(); return DefaultGroovyMethods.each(patchesRepository.listPatches(), new Closure<Object>(null, null) { public void doCall(String it) { MavenCoordinates coordinates = MavenCoordinates.parseMavenCoordinates(it); LinkedHashMap<String, Object> map = new LinkedHashMap<>(5); map.put("classLoader", classLoader); map.put("group", coordinates.getGroupId()); map.put("module", coordinates.getArtifactId()); map.put("version", coordinates.getVersion()); map.put("classifier", coordinates.getClassifier()); Grape.grab(map); } public void doCall() { doCall(null); } }); } @Override public boolean isRemote() { return false; } @Override public Producer createProducer() { return new GrapeProducer(this); } @Override public Consumer createConsumer(Processor processor) { throw new UnsupportedOperationException("Grape component supports only the producer side of the route."); } public String getDefaultCoordinates() { return defaultCoordinates; } @Override public GrapeComponent getComponent() { return DefaultGroovyMethods.asType(super.getComponent(), GrapeComponent.class); } }
GrapeEndpoint
java
apache__flink
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/generated/GeneratedCollectorWrapper.java
{ "start": 961, "end": 1048 }
class ____ of generated code in it. It * is only used for easy testing. */ public
instead
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/util/ResolverUtilCustomProtocolTest.java
{ "start": 8409, "end": 9263 }
class ____"); } } @Test void testFindInPackageFromVfsJarURL() throws Exception { final File tmpDir = new File(DIR, "resolverutil4"); try (final URLClassLoader cl = ResolverUtilTest.compileJarAndCreateClassLoader(tmpDir, "4")) { final ResolverUtil resolverUtil = new ResolverUtil(); resolverUtil.setClassLoader( new SingleURLClassLoader(new URL("vfs:/" + tmpDir + "/customplugin4.jar/customplugin4/"), cl)); resolverUtil.findInPackage(new PluginTest(), "customplugin4"); assertEquals(1, resolverUtil.getClasses().size(), "Class not found in packages"); assertEquals( cl.loadClass("customplugin4.FixedString4Layout"), resolverUtil.getClasses().iterator().next(), "Unexpected
resolved
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/blockaliasmap/impl/LevelDBFileRegionAliasMap.java
{ "start": 5304, "end": 5423 }
class ____ extends Reader<FileRegion> { /** * Options for {@link LevelDBReader}. */ public
LevelDBReader
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/MockFilterConfig.java
{ "start": 888, "end": 1651 }
class ____ implements FilterConfig { private Map map = new HashMap(); @Override public String getFilterName() { throw new UnsupportedOperationException("mock method not implemented"); } @Override public String getInitParameter(String arg0) { Object result = this.map.get(arg0); if (result != null) { return (String) result; } else { return null; } } @Override public Enumeration getInitParameterNames() { throw new UnsupportedOperationException("mock method not implemented"); } @Override public ServletContext getServletContext() { throw new UnsupportedOperationException("mock method not implemented"); } public void setInitParmeter(String parameter, String value) { this.map.put(parameter, value); } }
MockFilterConfig
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/internals/graph/TableSourceNode.java
{ "start": 5468, "end": 7299 }
class ____<K, V> { private String nodeName; private String sourceName; private String topic; private ConsumedInternal<K, V> consumedInternal; private ProcessorParameters<K, V, ?, ?> processorParameters; private boolean isGlobalKTable = false; private TableSourceNodeBuilder() { } public TableSourceNodeBuilder<K, V> withSourceName(final String sourceName) { this.sourceName = sourceName; return this; } public TableSourceNodeBuilder<K, V> withTopic(final String topic) { this.topic = topic; return this; } public TableSourceNodeBuilder<K, V> withConsumedInternal(final ConsumedInternal<K, V> consumedInternal) { this.consumedInternal = consumedInternal; return this; } public TableSourceNodeBuilder<K, V> withProcessorParameters(final ProcessorParameters<K, V, ?, ?> processorParameters) { this.processorParameters = processorParameters; return this; } public TableSourceNodeBuilder<K, V> withNodeName(final String nodeName) { this.nodeName = nodeName; return this; } public TableSourceNodeBuilder<K, V> isGlobalKTable(final boolean isGlobalKTable) { this.isGlobalKTable = isGlobalKTable; return this; } public TableSourceNode<K, V> build() { return new TableSourceNode<>(nodeName, sourceName, topic, consumedInternal, processorParameters, isGlobalKTable); } } }
TableSourceNodeBuilder
java
google__dagger
javatests/dagger/internal/codegen/bindinggraphvalidation/NullableBindingValidationKotlinTest.java
{ "start": 15233, "end": 16073 }
class ____ {", " @Binds abstract fun bindObject(string: String): Object", "", " companion object {", " @Provides fun nullableString():String? = null", " }", "}"); CompilerTests.daggerCompiler(module) .withProcessingOptions( ImmutableMap.<String, String>builder() .putAll(compilerMode.processorOptions()) .put("dagger.fullBindingGraphValidation", "ERROR") .buildOrThrow()) .compile( subject -> { subject.hasErrorCount(1); subject.hasErrorContaining( nullableToNonNullable( "String", "@Provides @Nullable String TestModule.Companion.nullableString()")); }); } }
TestModule
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/watcher/ResourceWatcherService.java
{ "start": 5506, "end": 6387 }
class ____ implements Runnable { final TimeValue interval; final Frequency frequency; final Set<ResourceWatcher> watchers = new CopyOnWriteArraySet<>(); private ResourceMonitor(TimeValue interval, Frequency frequency) { this.interval = interval; this.frequency = frequency; } private <W extends ResourceWatcher> WatcherHandle<W> add(W watcher) { watchers.add(watcher); return new WatcherHandle<>(this, watcher); } @Override public synchronized void run() { for (ResourceWatcher watcher : watchers) { try { watcher.checkAndNotify(); } catch (IOException e) { logger.trace("failed to check resource watcher", e); } } } } }
ResourceMonitor
java
eclipse-vertx__vert.x
vertx-core/src/main/generated/io/vertx/core/eventbus/EventBusOptionsConverter.java
{ "start": 346, "end": 4168 }
class ____ { static void fromJson(Iterable<java.util.Map.Entry<String, Object>> json, EventBusOptions obj) { for (java.util.Map.Entry<String, Object> member : json) { switch (member.getKey()) { case "clientAuth": if (member.getValue() instanceof String) { obj.setClientAuth(io.vertx.core.http.ClientAuth.valueOf((String)member.getValue())); } break; case "acceptBacklog": if (member.getValue() instanceof Number) { obj.setAcceptBacklog(((Number)member.getValue()).intValue()); } break; case "host": if (member.getValue() instanceof String) { obj.setHost((String)member.getValue()); } break; case "port": if (member.getValue() instanceof Number) { obj.setPort(((Number)member.getValue()).intValue()); } break; case "reconnectAttempts": if (member.getValue() instanceof Number) { obj.setReconnectAttempts(((Number)member.getValue()).intValue()); } break; case "reconnectInterval": if (member.getValue() instanceof Number) { obj.setReconnectInterval(((Number)member.getValue()).longValue()); } break; case "trustAll": if (member.getValue() instanceof Boolean) { obj.setTrustAll((Boolean)member.getValue()); } break; case "connectTimeout": if (member.getValue() instanceof Number) { obj.setConnectTimeout(((Number)member.getValue()).intValue()); } break; case "clusterPingInterval": if (member.getValue() instanceof Number) { obj.setClusterPingInterval(((Number)member.getValue()).longValue()); } break; case "clusterPingReplyInterval": if (member.getValue() instanceof Number) { obj.setClusterPingReplyInterval(((Number)member.getValue()).longValue()); } break; case "clusterPublicHost": if (member.getValue() instanceof String) { obj.setClusterPublicHost((String)member.getValue()); } break; case "clusterPublicPort": if (member.getValue() instanceof Number) { obj.setClusterPublicPort(((Number)member.getValue()).intValue()); } break; case "clusterNodeMetadata": if (member.getValue() instanceof JsonObject) { obj.setClusterNodeMetadata(((JsonObject)member.getValue()).copy()); } break; } } } static void toJson(EventBusOptions obj, JsonObject json) { toJson(obj, json.getMap()); } static void toJson(EventBusOptions obj, java.util.Map<String, Object> json) { if (obj.getClientAuth() != null) { json.put("clientAuth", obj.getClientAuth().name()); } json.put("acceptBacklog", obj.getAcceptBacklog()); if (obj.getHost() != null) { json.put("host", obj.getHost()); } json.put("port", obj.getPort()); json.put("reconnectAttempts", obj.getReconnectAttempts()); json.put("reconnectInterval", obj.getReconnectInterval()); json.put("trustAll", obj.isTrustAll()); json.put("connectTimeout", obj.getConnectTimeout()); json.put("clusterPingInterval", obj.getClusterPingInterval()); json.put("clusterPingReplyInterval", obj.getClusterPingReplyInterval()); if (obj.getClusterPublicHost() != null) { json.put("clusterPublicHost", obj.getClusterPublicHost()); } json.put("clusterPublicPort", obj.getClusterPublicPort()); if (obj.getClusterNodeMetadata() != null) { json.put("clusterNodeMetadata", obj.getClusterNodeMetadata()); } } }
EventBusOptionsConverter
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/form/FormWithConverterTest.java
{ "start": 2024, "end": 2772 }
class ____ implements ParamConverterProvider { @SuppressWarnings("unchecked") @Override public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { if (rawType == Input.class) { return (ParamConverter<T>) new ParamConverter<Input>() { @Override public Input fromString(String value) { return new Input(value); } @Override public String toString(Input value) { return value.value; } }; } return null; } } }
InputParamConverterProvider
java
spring-projects__spring-boot
module/spring-boot-devtools/src/test/java/org/springframework/boot/devtools/restart/classloader/Sample.java
{ "start": 706, "end": 774 }
class ____ to test reloading. * * @author Phillip Webb */ public
used
java
micronaut-projects__micronaut-core
management/src/main/java/io/micronaut/management/endpoint/threads/ThreadDumpEndpoint.java
{ "start": 1045, "end": 1602 }
class ____ { private final ThreadInfoMapper<?> threadInfoMapper; /** * Constructor. * * @param threadInfoMapper The mapper */ ThreadDumpEndpoint(ThreadInfoMapper<?> threadInfoMapper) { this.threadInfoMapper = threadInfoMapper; } /** * @return A publisher containing the thread information */ @Read Publisher getThreadDump() { return threadInfoMapper.mapThreadInfo( Flux.fromArray(ManagementFactory.getThreadMXBean().dumpAllThreads(true, true))); } }
ThreadDumpEndpoint
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/SqlTypedMapping.java
{ "start": 362, "end": 1048 }
interface ____ { @Nullable String getColumnDefinition(); @Nullable Long getLength(); @Nullable Integer getArrayLength(); @Nullable Integer getPrecision(); @Nullable Integer getScale(); @Nullable Integer getTemporalPrecision(); default boolean isLob() { return getJdbcMapping().getJdbcType().isLob(); } JdbcMapping getJdbcMapping(); default Size toSize() { final Size size = new Size(); size.setArrayLength( getArrayLength() ); size.setLength( getLength() ); if ( getTemporalPrecision() != null ) { size.setPrecision( getTemporalPrecision() ); } else { size.setPrecision( getPrecision() ); } size.setScale( getScale() ); return size; } }
SqlTypedMapping