language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/sampling/GetAllSampleConfigurationAction.java
{ "start": 4857, "end": 7644 }
class ____ extends ActionResponse implements ChunkedToXContentObject { private final Map<String, SamplingConfiguration> indexToSamplingConfigMap; /** * Constructs a new Response with the given index to sampling configuration map. * * @param indexToSamplingConfigMap the index to sampling configuration map */ public Response(Map<String, SamplingConfiguration> indexToSamplingConfigMap) { this.indexToSamplingConfigMap = indexToSamplingConfigMap; } /** * Constructs a new Response by deserializing from a StreamInput. * * @param in the stream input to read from * @throws IOException if an I/O error occurs during deserialization */ public Response(StreamInput in) throws IOException { this.indexToSamplingConfigMap = in.readMap(StreamInput::readString, SamplingConfiguration::new); } /** * Gets the index to sampling configuration map. * * @return the index to sampling configuration map, or an empty map if none exist */ public Map<String, SamplingConfiguration> getIndexToSamplingConfigMap() { return indexToSamplingConfigMap == null ? Map.of() : indexToSamplingConfigMap; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeMap(indexToSamplingConfigMap, StreamOutput::writeString, (o, v) -> v.writeTo(o)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Response that = (Response) o; return indexToSamplingConfigMap.equals(that.indexToSamplingConfigMap); } @Override public int hashCode() { return Objects.hash(indexToSamplingConfigMap); } @Override public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params params) { return Collections.singletonList((ToXContent) (builder, p) -> toXContent(builder, params)).iterator(); } private XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.startObject().startArray("configurations"); for (Map.Entry<String, SamplingConfiguration> entry : indexToSamplingConfigMap.entrySet()) { builder.startObject(); builder.field("index", entry.getKey()); builder.field("configuration", entry.getValue()); builder.endObject(); } builder.endArray(); builder.endObject(); return builder; } } }
Response
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/WritableName.java
{ "start": 2834, "end": 2984 }
class ____ a name. * Default is {@link Class#forName(String)}. * * @param name input name. * @param conf input configuration. * @return
for
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/UnitOfWorkFactory.java
{ "start": 1363, "end": 1747 }
interface ____ extends AfterPropertiesConfigured { /** * Creates a new {@link UnitOfWork} * * @param exchange the exchange * @return the created {@link UnitOfWork} */ UnitOfWork createUnitOfWork(Exchange exchange); @Override default void afterPropertiesConfigured(CamelContext camelContext) { // noop } }
UnitOfWorkFactory
java
apache__camel
components/camel-opensearch/src/test/java/org/apache/camel/component/opensearch/integration/OpensearchPingIT.java
{ "start": 1005, "end": 1548 }
class ____ extends OpensearchTestSupport { @Test void testPing() { boolean pingResult = template().requestBody("direct:ping", "test", Boolean.class); assertTrue(pingResult, "indexId should be set"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:ping") .to("opensearch://opensearch?operation=Ping"); } }; } }
OpensearchPingIT
java
google__error-prone
core/src/test/java/com/google/errorprone/refaster/testdata/input/EmitCommentBeforeTemplateExample.java
{ "start": 656, "end": 772 }
class ____ { public void example() { System.out.println("foobar".length()); } }
EmitCommentBeforeTemplateExample
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/JobConf.java
{ "start": 63693, "end": 64251 }
class ____ implements * {@link org.apache.hadoop.mapreduce.CustomJobEndNotifier} set through the * {@link org.apache.hadoop.mapreduce.MRJobConfig#MR_JOB_END_NOTIFICATION_CUSTOM_NOTIFIER_CLASS} * property * * @see JobConf#setJobEndNotificationCustomNotifierClass(java.lang.String) * @see org.apache.hadoop.mapreduce.MRJobConfig#MR_JOB_END_NOTIFICATION_CUSTOM_NOTIFIER_CLASS */ public String getJobEndNotificationCustomNotifierClass() { return get(JobContext.MR_JOB_END_NOTIFICATION_CUSTOM_NOTIFIER_CLASS); } /** * Sets the
which
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/jaxb/mapping/spi/db/JaxbCheckable.java
{ "start": 277, "end": 360 }
interface ____ { List<JaxbCheckConstraintImpl> getCheckConstraints(); }
JaxbCheckable
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/jpa/internal/JpaEntityNotFoundDelegate.java
{ "start": 318, "end": 755 }
class ____ implements EntityNotFoundDelegate, Serializable { /** * Singleton access */ public static final JpaEntityNotFoundDelegate INSTANCE = new JpaEntityNotFoundDelegate(); public void handleEntityNotFound(String entityName, Object identifier) { final var exception = new ObjectNotFoundException( entityName, identifier ); throw new EntityNotFoundException( exception.getMessage(), exception ); } }
JpaEntityNotFoundDelegate
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/main/java/org/apache/hadoop/mapred/ClientCache.java
{ "start": 1574, "end": 4010 }
class ____ { private final Configuration conf; private final ResourceMgrDelegate rm; private static final Logger LOG = LoggerFactory.getLogger(ClientCache.class); private Map<JobID, ClientServiceDelegate> cache = new HashMap<JobID, ClientServiceDelegate>(); private MRClientProtocol hsProxy; public ClientCache(Configuration conf, ResourceMgrDelegate rm) { this.conf = conf; this.rm = rm; } //TODO: evict from the cache on some threshold public synchronized ClientServiceDelegate getClient(JobID jobId) { if (hsProxy == null) { try { hsProxy = instantiateHistoryProxy(); } catch (IOException e) { LOG.warn("Could not connect to History server.", e); throw new YarnRuntimeException("Could not connect to History server.", e); } } ClientServiceDelegate client = cache.get(jobId); if (client == null) { client = new ClientServiceDelegate(conf, rm, jobId, hsProxy); cache.put(jobId, client); } return client; } protected synchronized MRClientProtocol getInitializedHSProxy() throws IOException { if (this.hsProxy == null) { hsProxy = instantiateHistoryProxy(); } return this.hsProxy; } protected MRClientProtocol instantiateHistoryProxy() throws IOException { final String serviceAddr = conf.get(JHAdminConfig.MR_HISTORY_ADDRESS); if (StringUtils.isEmpty(serviceAddr)) { return null; } LOG.debug("Connecting to HistoryServer at: " + serviceAddr); final YarnRPC rpc = YarnRPC.create(conf); LOG.debug("Connected to HistoryServer at: " + serviceAddr); UserGroupInformation currentUser = UserGroupInformation.getCurrentUser(); return currentUser.doAs(new PrivilegedAction<MRClientProtocol>() { @Override public MRClientProtocol run() { return (MRClientProtocol) rpc.getProxy(HSClientProtocol.class, NetUtils.createSocketAddr(serviceAddr), conf); } }); } public void close() throws IOException { if (rm != null) { rm.close(); } if (hsProxy != null) { RPC.stopProxy(hsProxy); hsProxy = null; } if (cache != null && !cache.isEmpty()) { for (ClientServiceDelegate delegate : cache.values()) { if (delegate != null) { delegate.close(); delegate = null; } } cache.clear(); cache = null; } } }
ClientCache
java
google__dagger
javatests/dagger/internal/codegen/ComponentShardTest.java
{ "start": 2905, "end": 4343 }
interface ____ {", " Binding1 binding1();", " Binding2 binding2();", " Binding3 binding3();", " Binding4 binding4();", " Binding5 binding5();", " Binding6 binding6();", " Binding7 binding7();", " Provider<Binding1> providerBinding1();", " Provider<Binding2> providerBinding2();", " Provider<Binding3> providerBinding3();", " Provider<Binding4> providerBinding4();", " Provider<Binding5> providerBinding5();", " Provider<Binding6> providerBinding6();", " Provider<Binding7> providerBinding7();", "}")); CompilerTests.daggerCompiler(sources.build()) .withProcessingOptions(compilerOptions()) .compile( subject -> { subject.hasErrorCount(0); subject.generatedSource( goldenFileRule.goldenSource("dagger/internal/codegen/DaggerTestComponent")); }); } @Test public void testNewShardCreatedWithDependencies() throws Exception { ImmutableList.Builder<Source> sources = ImmutableList.builder(); sources.add( createBinding("Binding1"), createBinding("Binding2"), CompilerTests.javaSource( "dagger.internal.codegen.Binding3", "package dagger.internal.codegen;", "", "
TestComponent
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/factories/TestFileFactory.java
{ "start": 2975, "end": 4510 }
class ____ implements DynamicTableSourceFactory, DynamicTableSinkFactory { // -------------------------------------------------------------------------------------------- // Factory // -------------------------------------------------------------------------------------------- private static final String IDENTIFIER = "test-file"; private static final ConfigOption<String> RUNTIME_SOURCE = ConfigOptions.key("runtime-source") .stringType() .defaultValue("Source"); // another is "DataStream" @Override public DynamicTableSource createDynamicTableSource(Context context) { Configuration conf = Configuration.fromMap(context.getCatalogTable().getOptions()); return new TestFileTableSource( new Path(conf.get(FileSystemConnectorOptions.PATH)), conf.get(RUNTIME_SOURCE)); } @Override public DynamicTableSink createDynamicTableSink(Context context) { Configuration conf = Configuration.fromMap(context.getCatalogTable().getOptions()); return new TestFileTableSink(new Path(conf.get(FileSystemConnectorOptions.PATH))); } @Override public String factoryIdentifier() { return IDENTIFIER; } @Override public Set<ConfigOption<?>> requiredOptions() { return new HashSet<>(); } @Override public Set<ConfigOption<?>> optionalOptions() { return new HashSet<>(Collections.singletonList(RUNTIME_SOURCE)); } private static
TestFileFactory
java
apache__camel
core/camel-core-reifier/src/main/java/org/apache/camel/reifier/loadbalancer/CustomLoadBalancerReifier.java
{ "start": 1121, "end": 1704 }
class ____ extends LoadBalancerReifier<CustomLoadBalancerDefinition> { public CustomLoadBalancerReifier(Route route, LoadBalancerDefinition definition) { super(route, (CustomLoadBalancerDefinition) definition); } @Override public LoadBalancer createLoadBalancer() { if (definition.getCustomLoadBalancer() != null) { return definition.getCustomLoadBalancer(); } StringHelper.notEmpty(definition.getRef(), "ref", this); return mandatoryLookup(definition.getRef(), LoadBalancer.class); } }
CustomLoadBalancerReifier
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/admin/cluster/node/shutdown/NodePrevalidateShardPathRequestSerializationTests.java
{ "start": 793, "end": 1616 }
class ____ extends AbstractWireSerializingTestCase<NodePrevalidateShardPathRequest> { @Override protected Writeable.Reader<NodePrevalidateShardPathRequest> instanceReader() { return NodePrevalidateShardPathRequest::new; } @Override protected NodePrevalidateShardPathRequest createTestInstance() { return new NodePrevalidateShardPathRequest(randomSet(0, 50, PrevalidateShardPathRequestSerializationTestUtils::randomShardId)); } @Override protected NodePrevalidateShardPathRequest mutateInstance(NodePrevalidateShardPathRequest request) { return new NodePrevalidateShardPathRequest( createSetMutation(request.getShardIds(), PrevalidateShardPathRequestSerializationTestUtils::randomShardId) ); } }
NodePrevalidateShardPathRequestSerializationTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/graph/GlobalStreamExchangeMode.java
{ "start": 1385, "end": 2423 }
enum ____ { /** Set all job edges to be {@link ResultPartitionType#BLOCKING}. */ ALL_EDGES_BLOCKING, /** * Set job edges with {@link ForwardPartitioner} to be {@link * ResultPartitionType#PIPELINED_BOUNDED} and other edges to be {@link * ResultPartitionType#BLOCKING}. */ FORWARD_EDGES_PIPELINED, /** * Set job edges with {@link ForwardPartitioner} or {@link RescalePartitioner} to be {@link * ResultPartitionType#PIPELINED_BOUNDED} and other edges to be {@link * ResultPartitionType#BLOCKING}. */ POINTWISE_EDGES_PIPELINED, /** Set all job edges {@link ResultPartitionType#PIPELINED_BOUNDED}. */ ALL_EDGES_PIPELINED, /** Set all job edges {@link ResultPartitionType#PIPELINED_APPROXIMATE}. */ ALL_EDGES_PIPELINED_APPROXIMATE, /** Set all job edges {@link ResultPartitionType#HYBRID_FULL}. */ ALL_EDGES_HYBRID_FULL, /** Set all job edges {@link ResultPartitionType#HYBRID_SELECTIVE}. */ ALL_EDGES_HYBRID_SELECTIVE }
GlobalStreamExchangeMode
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java
{ "start": 40325, "end": 40497 }
class ____ { private TestBean bean; public TestBean getBean() { return bean; } public void setBean(TestBean bean) { this.bean = bean; } } }
TestBeanWrapper
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnit4ClassUsedInJUnit3Test.java
{ "start": 1845, "end": 2474 }
class ____ { @Test public void testOne() { Assume.assumeTrue(true); } } """) .doTest(); } @Test public void negative_annotation_in_junit4() { compilationHelper .addSourceLines( "Foo.java", """ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import org.junit.Test; import org.junit.Ignore; @RunWith(JUnit4.class) public
Foo
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/LocalDateTimeWithTemporalTimeTest.java
{ "start": 603, "end": 1089 }
class ____ { @Test public void testLifecycle(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { DateEvent dateEvent = new DateEvent(LocalDateTime.now()); dateEvent.id = 1L; entityManager.persist(dateEvent); }); scope.inTransaction( entityManager -> { DateEvent dateEvent = entityManager.find(DateEvent.class, 1L); assertNotNull(dateEvent.getTimestamp()); }); } @Entity(name = "DateEvent") public static
LocalDateTimeWithTemporalTimeTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointCustomAsyncInterceptorTest.java
{ "start": 3259, "end": 4476 }
class ____ implements InterceptStrategy { private final AtomicInteger counter = new AtomicInteger(); @Override public Processor wrapProcessorInInterceptors( final CamelContext context, final NamedNode definition, final Processor target, final Processor nextTarget) { // use DelegateAsyncProcessor to ensure the interceptor works well // with the asynchronous routing // engine in Camel. // The target is the processor to continue routing to, which we must // provide // in the constructor of the DelegateAsyncProcessor return new DelegateAsyncProcessor(target) { @Override public boolean process(Exchange exchange, AsyncCallback callback) { // we just want to count number of interceptions counter.incrementAndGet(); // invoke processor to continue routing the message return processor.process(exchange, callback); } }; } public int getCounter() { return counter.get(); } } // END SNIPPET: e1 }
MyInterceptor
java
apache__camel
components/camel-pqc/src/main/java/org/apache/camel/component/pqc/lifecycle/KeyFormatConverter.java
{ "start": 1208, "end": 6633 }
class ____ { /** * Export a public key to the specified format */ public static byte[] exportPublicKey(PublicKey publicKey, KeyLifecycleManager.KeyFormat format) throws Exception { switch (format) { case PEM: return exportPublicKeyToPEM(publicKey); case DER: case X509: return publicKey.getEncoded(); // X.509 format (DER encoded) default: throw new IllegalArgumentException("Unsupported format for public key: " + format); } } /** * Export a private key to the specified format */ public static byte[] exportPrivateKey(PrivateKey privateKey, KeyLifecycleManager.KeyFormat format) throws Exception { switch (format) { case PEM: return exportPrivateKeyToPEM(privateKey); case DER: case PKCS8: return privateKey.getEncoded(); // PKCS#8 format (DER encoded) default: throw new IllegalArgumentException("Unsupported format for private key: " + format); } } /** * Export a key pair to the specified format */ public static byte[] exportKeyPair(KeyPair keyPair, KeyLifecycleManager.KeyFormat format, boolean includePrivate) throws Exception { if (includePrivate) { // Export both keys in a combined format byte[] publicKeyBytes = exportPublicKey(keyPair.getPublic(), format); byte[] privateKeyBytes = exportPrivateKey(keyPair.getPrivate(), format); // Concatenate with separator for PEM if (format == KeyLifecycleManager.KeyFormat.PEM) { return (new String(publicKeyBytes) + "\n" + new String(privateKeyBytes)).getBytes(); } else { // For DER, just return private key (contains public key info) return privateKeyBytes; } } else { return exportPublicKey(keyPair.getPublic(), format); } } /** * Import a public key from bytes */ public static PublicKey importPublicKey(byte[] keyData, KeyLifecycleManager.KeyFormat format, String algorithm) throws Exception { byte[] derBytes; if (format == KeyLifecycleManager.KeyFormat.PEM) { derBytes = parsePEMPublicKey(keyData); } else { derBytes = keyData; } X509EncodedKeySpec spec = new X509EncodedKeySpec(derBytes); KeyFactory keyFactory = KeyFactory.getInstance(algorithm); return keyFactory.generatePublic(spec); } /** * Import a private key from bytes */ public static PrivateKey importPrivateKey(byte[] keyData, KeyLifecycleManager.KeyFormat format, String algorithm) throws Exception { byte[] derBytes; if (format == KeyLifecycleManager.KeyFormat.PEM) { derBytes = parsePEMPrivateKey(keyData); } else { derBytes = keyData; } PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(derBytes); KeyFactory keyFactory = KeyFactory.getInstance(algorithm); return keyFactory.generatePrivate(spec); } /** * Export public key to PEM format */ private static byte[] exportPublicKeyToPEM(PublicKey publicKey) throws Exception { byte[] encoded = publicKey.getEncoded(); String base64 = Base64.getEncoder().encodeToString(encoded); // Format as PEM with line breaks every 64 characters StringBuilder pem = new StringBuilder(); pem.append("-----BEGIN PUBLIC KEY-----\n"); for (int i = 0; i < base64.length(); i += 64) { pem.append(base64, i, Math.min(i + 64, base64.length())).append("\n"); } pem.append("-----END PUBLIC KEY-----\n"); return pem.toString().getBytes(); } /** * Export private key to PEM format */ private static byte[] exportPrivateKeyToPEM(PrivateKey privateKey) throws Exception { byte[] encoded = privateKey.getEncoded(); String base64 = Base64.getEncoder().encodeToString(encoded); // Format as PEM with line breaks every 64 characters StringBuilder pem = new StringBuilder(); pem.append("-----BEGIN PRIVATE KEY-----\n"); for (int i = 0; i < base64.length(); i += 64) { pem.append(base64, i, Math.min(i + 64, base64.length())).append("\n"); } pem.append("-----END PRIVATE KEY-----\n"); return pem.toString().getBytes(); } /** * Parse PEM-encoded public key */ private static byte[] parsePEMPublicKey(byte[] pemData) throws Exception { String pemString = new String(pemData); pemString = pemString.replace("-----BEGIN PUBLIC KEY-----", "") .replace("-----END PUBLIC KEY-----", "") .replaceAll("\\s", ""); return Base64.getDecoder().decode(pemString); } /** * Parse PEM-encoded private key */ private static byte[] parsePEMPrivateKey(byte[] pemData) throws Exception { String pemString = new String(pemData); pemString = pemString.replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", "") .replaceAll("\\s", ""); return Base64.getDecoder().decode(pemString); } }
KeyFormatConverter
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/config/GatewayAutoConfigurationTests.java
{ "start": 23706, "end": 23994 }
class ____ { private final AtomicBoolean called = new AtomicBoolean(); @Bean HttpClientCustomizer myCustomCustomizer() { return httpClient -> { called.compareAndSet(false, true); return httpClient; }; } } @Configuration protected static
HttpClientCustomizedConfig
java
apache__flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/operators/GenericWriteAheadSink.java
{ "start": 2719, "end": 12918 }
class ____<IN> extends AbstractStreamOperator<IN> implements OneInputStreamOperator<IN, IN> { private static final long serialVersionUID = 1L; protected static final Logger LOG = LoggerFactory.getLogger(GenericWriteAheadSink.class); private final String id; private final CheckpointCommitter committer; protected final TypeSerializer<IN> serializer; private transient CheckpointStateOutputStream out; private transient CheckpointStorageWorkerView checkpointStorage; private transient ListState<PendingCheckpoint> checkpointedState; private final Set<PendingCheckpoint> pendingCheckpoints = new TreeSet<>(); public GenericWriteAheadSink( CheckpointCommitter committer, TypeSerializer<IN> serializer, String jobID) throws Exception { this.committer = Preconditions.checkNotNull(committer); this.serializer = Preconditions.checkNotNull(serializer); this.id = UUID.randomUUID().toString(); this.committer.setJobId(jobID); this.committer.createResource(); } @Override public void initializeState(StateInitializationContext context) throws Exception { super.initializeState(context); Preconditions.checkState( this.checkpointedState == null, "The reader state has already been initialized."); // We are using JavaSerializer from the flink-runtime module here. This is very naughty and // we shouldn't be doing it because ideally nothing in the API modules/connector depends // directly on flink-runtime. We are doing it here because we need to maintain backwards // compatibility with old state and because we will have to rework/remove this code soon. checkpointedState = context.getOperatorStateStore() .getListState( new ListStateDescriptor<>( "pending-checkpoints", new JavaSerializer<>())); int subtaskIdx = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(); if (context.isRestored()) { LOG.info("Restoring state for the GenericWriteAheadSink (taskIdx={}).", subtaskIdx); for (PendingCheckpoint pendingCheckpoint : checkpointedState.get()) { this.pendingCheckpoints.add(pendingCheckpoint); } if (LOG.isDebugEnabled()) { LOG.debug( "GenericWriteAheadSink idx {} restored {}.", subtaskIdx, this.pendingCheckpoints); } } else { LOG.info("No state to restore for the GenericWriteAheadSink (taskIdx={}).", subtaskIdx); } } @Override public void open() throws Exception { super.open(); committer.setOperatorId(id); committer.open(); checkpointStorage = getContainingTask().getCheckpointStorage(); cleanRestoredHandles(); } public void close() throws Exception { committer.close(); super.close(); } /** * Called when a checkpoint barrier arrives. It closes any open streams to the backend and marks * them as pending for committing to the external, third-party storage system. * * @param checkpointId the id of the latest received checkpoint. * @throws IOException in case something went wrong when handling the stream to the backend. */ private void saveHandleInState(final long checkpointId, final long timestamp) throws Exception { // only add handle if a new OperatorState was created since the last snapshot if (out != null) { int subtaskIdx = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(); StreamStateHandle handle = out.closeAndGetHandle(); PendingCheckpoint pendingCheckpoint = new PendingCheckpoint(checkpointId, subtaskIdx, timestamp, handle); if (pendingCheckpoints.contains(pendingCheckpoint)) { // we already have a checkpoint stored for that ID that may have been partially // written, // so we discard this "alternate version" and use the stored checkpoint handle.discardState(); } else { pendingCheckpoints.add(pendingCheckpoint); } out = null; } } @Override public void snapshotState(StateSnapshotContext context) throws Exception { super.snapshotState(context); Preconditions.checkState( this.checkpointedState != null, "The operator state has not been properly initialized."); saveHandleInState(context.getCheckpointId(), context.getCheckpointTimestamp()); try { // create a new partition for each entry. this.checkpointedState.update(new ArrayList<>(pendingCheckpoints)); } catch (Exception e) { checkpointedState.clear(); throw new Exception( "Could not add panding checkpoints to operator state " + "backend of operator " + getOperatorName() + '.', e); } int subtaskIdx = getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(); if (LOG.isDebugEnabled()) { LOG.debug( "{} (taskIdx= {}) checkpointed {}.", getClass().getSimpleName(), subtaskIdx, this.pendingCheckpoints); } } /** * Called at {@link #open()} to clean-up the pending handle list. It iterates over all restored * pending handles, checks which ones are already committed to the outside storage system and * removes them from the list. */ private void cleanRestoredHandles() throws Exception { synchronized (pendingCheckpoints) { Iterator<PendingCheckpoint> pendingCheckpointIt = pendingCheckpoints.iterator(); while (pendingCheckpointIt.hasNext()) { PendingCheckpoint pendingCheckpoint = pendingCheckpointIt.next(); if (committer.isCheckpointCommitted( pendingCheckpoint.subtaskId, pendingCheckpoint.checkpointId)) { pendingCheckpoint.stateHandle.discardState(); pendingCheckpointIt.remove(); } } } } @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { super.notifyCheckpointComplete(checkpointId); synchronized (pendingCheckpoints) { Iterator<PendingCheckpoint> pendingCheckpointIt = pendingCheckpoints.iterator(); while (pendingCheckpointIt.hasNext()) { PendingCheckpoint pendingCheckpoint = pendingCheckpointIt.next(); long pastCheckpointId = pendingCheckpoint.checkpointId; int subtaskId = pendingCheckpoint.subtaskId; long timestamp = pendingCheckpoint.timestamp; StreamStateHandle streamHandle = pendingCheckpoint.stateHandle; if (pastCheckpointId <= checkpointId) { try { if (!committer.isCheckpointCommitted(subtaskId, pastCheckpointId)) { try (FSDataInputStream in = streamHandle.openInputStream()) { boolean success = sendValues( new ReusingMutableToRegularIteratorWrapper<>( new InputViewIterator<>( new DataInputViewStreamWrapper(in), serializer), serializer), pastCheckpointId, timestamp); if (success) { // in case the checkpoint was successfully committed, // discard its state from the backend and mark it for removal // in case it failed, we retry on the next checkpoint committer.commitCheckpoint(subtaskId, pastCheckpointId); streamHandle.discardState(); pendingCheckpointIt.remove(); } } } else { streamHandle.discardState(); pendingCheckpointIt.remove(); } } catch (Exception e) { // we have to break here to prevent a new (later) checkpoint // from being committed before this one LOG.error("Could not commit checkpoint.", e); break; } } } } } /** * Write the given element into the backend. * * @param values The values to be written * @param checkpointId The checkpoint ID of the checkpoint to be written * @param timestamp The wall-clock timestamp of the checkpoint * @return true, if the sending was successful, false otherwise * @throws Exception */ protected abstract boolean sendValues(Iterable<IN> values, long checkpointId, long timestamp) throws Exception; @Override public void processElement(StreamRecord<IN> element) throws Exception { IN value = element.getValue(); // generate initial operator state if (out == null) { out = checkpointStorage.createTaskOwnedStateStream(); } serializer.serialize(value, new DataOutputViewStreamWrapper(out)); } private static final
GenericWriteAheadSink
java
google__dagger
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
{ "start": 60723, "end": 61087 }
interface ____ {}"); Source childModule = CompilerTests.javaSource( "test.ChildModule", "package test;", "", "import dagger.Module;", "import dagger.Provides;", "import java.util.Set;", "import java.util.HashSet;", "", "@Module", "
Child
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/reflect/TestReflectDatumReader.java
{ "start": 9384, "end": 10329 }
class ____ { private int id; private int[] relatedIds; public int getId() { return id; } public void setId(int id) { this.id = id; } public int[] getRelatedIds() { return relatedIds; } public void setRelatedIds(int[] relatedIds) { this.relatedIds = relatedIds; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; result = prime * result + Arrays.hashCode(relatedIds); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PojoWithArray other = (PojoWithArray) obj; if (id != other.id) return false; return Arrays.equals(relatedIds, other.relatedIds); } } public static
PojoWithArray
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/EmbeddableWithToOneAssociation2Test.java
{ "start": 4323, "end": 4788 }
class ____ { @Id int id; String garage; @OneToOne(mappedBy = "location.parkingSpot") Employee assignedTo; public ParkingSpot() { } public ParkingSpot(int id, String garage, Employee assignedTo) { this.id = id; this.garage = garage; this.assignedTo = assignedTo; } public int getId() { return id; } public String getGarage() { return garage; } public Employee getAssignedTo() { return assignedTo; } } }
ParkingSpot
java
quarkusio__quarkus
extensions/undertow/deployment/src/test/java/io/quarkus/undertow/test/ServletDestroyTestCase.java
{ "start": 333, "end": 1104 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(PreDestroyServlet.class)) .setAllowTestClassOutsideDeployment(true) .setAfterUndeployListener(() -> { try { Assertions.assertEquals("Servlet Destroyed", Messages.MESSAGES.poll(2, TimeUnit.SECONDS)); } catch (InterruptedException e) { throw new RuntimeException(e); } }); @Test public void testServlet() { RestAssured.when().get("/destroy").then() .statusCode(200) .body(is("pre destroy servlet")); } }
ServletDestroyTestCase
java
processing__processing4
app/src/processing/app/contrib/ManagerFrame.java
{ "start": 1093, "end": 1212 }
class ____ the main Contribution Manager Dialog. * It contains all the contributions tab and the update tab. */ public
is
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/CriteriaNoPredicateTest.java
{ "start": 3533, "end": 3918 }
class ____ { @Id private Integer id; private String code; @OneToMany private Collection<Deposit> deposits; public Account() { } public Account( Integer id, String code, Collection<Deposit> deposits) { this.id = id; this.code = code; this.deposits = deposits; } } @Entity(name = "Deposit") @Table(name = "DEPOSIT_TABLE") public static
Account
java
quarkusio__quarkus
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithMetricsTest.java
{ "start": 865, "end": 5632 }
class ____ { @RegisterExtension static final QuarkusProdModeTest config = new QuarkusProdModeTest() .withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class)) .setApplicationName("metrics") .setApplicationVersion("0.1-SNAPSHOT") .setRun(true) .setLogFileName("k8s.log") .overrideConfigKey("quarkus.http.port", "9090") .setForcedDependencies(List.of( Dependency.of("io.quarkus", "quarkus-smallrye-metrics", Version.getVersion()), Dependency.of("io.quarkus", "quarkus-kubernetes-client", Version.getVersion()))); @ProdBuildResults private ProdModeTestResults prodModeTestResults; @LogFile private Path logfile; @Test public void assertApplicationRuns() { assertThat(logfile).isRegularFile().hasFileName("k8s.log"); TestUtil.assertLogFileContents(logfile, "kubernetes", "metrics"); given() .when().get("/greeting") .then() .statusCode(200) .body(is("hello")); } @Test public void assertGeneratedResources() throws IOException { final Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes"); assertThat(kubernetesDir) .isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.json")) .isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.yml")); List<HasMetadata> kubernetesList = DeserializationUtil .deserializeAsList(kubernetesDir.resolve("kubernetes.yml")); assertThat(kubernetesList).filteredOn(h -> "Deployment".equals(h.getKind())).singleElement() .isInstanceOfSatisfying(Deployment.class, d -> { assertThat(d.getMetadata()).satisfies(m -> assertThat(m.getName()).isEqualTo("metrics")); assertThat(d.getSpec()).satisfies(deploymentSpec -> { assertThat(deploymentSpec.getTemplate()).satisfies(t -> { assertThat(t.getMetadata()).satisfies(meta -> { assertThat(meta.getAnnotations()).contains(entry("prometheus.io/scrape", "true"), entry("prometheus.io/path", "/q/metrics"), entry("prometheus.io/port", "9090"), entry("prometheus.io/scheme", "http")); }); }); }); }); assertThat(kubernetesList).filteredOn(h -> "Service".equals(h.getKind())).singleElement().satisfies(h -> { assertThat(h.getMetadata().getAnnotations()).contains(entry("prometheus.io/scrape", "true"), entry("prometheus.io/path", "/q/metrics"), entry("prometheus.io/port", "9090"), entry("prometheus.io/scheme", "http")); }); assertThat(kubernetesList).filteredOn(i -> i.getKind().equals("ServiceMonitor")).singleElement() .isInstanceOfSatisfying(ServiceMonitor.class, s -> { assertThat(s.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("metrics"); }); assertThat(s.getSpec()).satisfies(spec -> { assertThat(spec.getEndpoints()).hasSize(1); assertThat(spec.getEndpoints().get(0)).isInstanceOfSatisfying(Endpoint.class, e -> { assertThat(e.getScheme()).isEqualTo("http"); assertThat(e.getTargetPort().getStrVal()).isNull(); assertThat(e.getTargetPort().getIntVal()).isEqualTo(9090); assertThat(e.getPath()).isEqualTo("/q/metrics"); }); }); }); assertThat(kubernetesList).filteredOn(h -> "ServiceAccount".equals(h.getKind())).singleElement().satisfies(h -> { if (h.getMetadata().getAnnotations() != null) { assertThat(h.getMetadata().getAnnotations()).doesNotContainKeys("prometheus.io/scrape", "prometheus.io/path", "prometheus.io/port", "prometheus.io/scheme"); } }); assertThat(kubernetesList).filteredOn(h -> "RoleBinding".equals(h.getKind())).singleElement().satisfies(h -> { if (h.getMetadata().getAnnotations() != null) { assertThat(h.getMetadata().getAnnotations()).doesNotContainKeys("prometheus.io/scrape", "prometheus.io/path", "prometheus.io/port", "prometheus.io/scheme"); } }); } }
KubernetesWithMetricsTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/annotations/internal/NamedQueriesAnnotation.java
{ "start": 748, "end": 1717 }
class ____ implements NamedQueries, RepeatableContainer<NamedQuery> { private NamedQuery[] value; /** * Used in creating dynamic annotation instances (e.g. from XML) */ public NamedQueriesAnnotation(ModelsContext modelContext) { } /** * Used in creating annotation instances from JDK variant */ public NamedQueriesAnnotation(NamedQueries annotation, ModelsContext modelContext) { this.value = extractJdkValue( annotation, NAMED_QUERIES, "value", modelContext ); } /** * Used in creating annotation instances from Jandex variant */ public NamedQueriesAnnotation(Map<String, Object> attributeValues, ModelsContext modelContext) { this.value = (NamedQuery[]) attributeValues.get( "value" ); } @Override public Class<? extends Annotation> annotationType() { return NamedQueries.class; } @Override public NamedQuery[] value() { return value; } public void value(NamedQuery[] value) { this.value = value; } }
NamedQueriesAnnotation
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/testers/ListAddAtIndexTester.java
{ "start": 2252, "end": 5589 }
class ____<E> extends AbstractListTester<E> { @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAtIndex_supportedPresent() { getList().add(0, e0()); expectAdded(0, e0()); } @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) /* * absent = ZERO isn't required, since unmodList.add() must * throw regardless, but it keeps the method name accurate. */ public void testAddAtIndex_unsupportedPresent() { assertThrows(UnsupportedOperationException.class, () -> getList().add(0, e0())); expectUnchanged(); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_supportedNotPresent() { getList().add(0, e3()); expectAdded(0, e3()); } @CollectionFeature.Require(FAILS_FAST_ON_CONCURRENT_MODIFICATION) @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndexConcurrentWithIteration() { assertThrows( ConcurrentModificationException.class, () -> { Iterator<E> iterator = collection.iterator(); getList().add(0, e3()); iterator.next(); }); } @ListFeature.Require(absent = SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_unsupportedNotPresent() { assertThrows(UnsupportedOperationException.class, () -> getList().add(0, e3())); expectUnchanged(); expectMissing(e3()); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = {ZERO, ONE}) public void testAddAtIndex_middle() { getList().add(getNumElements() / 2, e3()); expectAdded(getNumElements() / 2, e3()); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionSize.Require(absent = ZERO) public void testAddAtIndex_end() { getList().add(getNumElements(), e3()); expectAdded(getNumElements(), e3()); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionFeature.Require(ALLOWS_NULL_VALUES) public void testAddAtIndex_nullSupported() { getList().add(0, null); expectAdded(0, (E) null); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) @CollectionFeature.Require(absent = ALLOWS_NULL_VALUES) public void testAddAtIndex_nullUnsupported() { assertThrows(NullPointerException.class, () -> getList().add(0, null)); expectUnchanged(); expectNullMissingWhenNullUnsupported("Should not contain null after unsupported add(n, null)"); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_negative() { assertThrows(IndexOutOfBoundsException.class, () -> getList().add(-1, e3())); expectUnchanged(); expectMissing(e3()); } @ListFeature.Require(SUPPORTS_ADD_WITH_INDEX) public void testAddAtIndex_tooLarge() { assertThrows(IndexOutOfBoundsException.class, () -> getList().add(getNumElements() + 1, e3())); expectUnchanged(); expectMissing(e3()); } /** * Returns the {@link Method} instance for {@link #testAddAtIndex_nullSupported()} so that tests * can suppress it. See {@link CollectionAddTester#getAddNullSupportedMethod()} for details. */ @J2ktIncompatible @GwtIncompatible // reflection public static Method getAddNullSupportedMethod() { return getMethod(ListAddAtIndexTester.class, "testAddAtIndex_nullSupported"); } }
ListAddAtIndexTester
java
apache__camel
core/camel-base/src/main/java/org/apache/camel/component/properties/DefaultPropertiesParser.java
{ "start": 3387, "end": 3447 }
class ____ replacing properties. */ private final
helps
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KTableKTableOuterJoin.java
{ "start": 1713, "end": 2519 }
class ____<K, V1, V2, VOut> extends KTableKTableAbstractJoin<K, V1, V2, VOut> { private static final Logger LOG = LoggerFactory.getLogger(KTableKTableOuterJoin.class); KTableKTableOuterJoin(final KTableImpl<K, ?, V1> table1, final KTableImpl<K, ?, V2> table2, final ValueJoiner<? super V1, ? super V2, ? extends VOut> joiner) { super(table1, table2, joiner); } @Override public Processor<K, Change<V1>, K, Change<VOut>> get() { return new KTableKTableOuterJoinProcessor(valueGetterSupplier2.get()); } @Override public KTableValueGetterSupplier<K, VOut> view() { return new KTableKTableOuterJoinValueGetterSupplier(valueGetterSupplier1, valueGetterSupplier2); } private
KTableKTableOuterJoin
java
spring-projects__spring-boot
module/spring-boot-micrometer-observation/src/main/java/org/springframework/boot/micrometer/observation/autoconfigure/ObservationAutoConfiguration.java
{ "start": 3675, "end": 4450 }
class ____ { @Bean @ConditionalOnMissingBean ObservedAspect observedAspect(ObservationRegistry observationRegistry, ObjectProvider<ObservationKeyValueAnnotationHandler> observationKeyValueAnnotationHandler) { ObservedAspect observedAspect = new ObservedAspect(observationRegistry); observationKeyValueAnnotationHandler.ifAvailable(observedAspect::setObservationKeyValueAnnotationHandler); return observedAspect; } @Bean @ConditionalOnMissingBean ObservationKeyValueAnnotationHandler observationKeyValueAnnotationHandler(BeanFactory beanFactory, ValueExpressionResolver valueExpressionResolver) { return new ObservationKeyValueAnnotationHandler(beanFactory::getBean, (ignored) -> valueExpressionResolver); } } }
ObservedAspectConfiguration
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/Display.java
{ "start": 4032, "end": 5866 }
class ____ extends Cat { public static final String NAME = "text"; public static final String USAGE = Cat.USAGE; public static final String DESCRIPTION = "Takes a source file and outputs the file in text format.\n" + "The allowed formats are zip and TextRecordInputStream and Avro."; @Override protected InputStream getInputStream(PathData item) throws IOException { FSDataInputStream i = (FSDataInputStream)super.getInputStream(item); // Handle 0 and 1-byte files short leadBytes; try { leadBytes = i.readShort(); } catch (EOFException e) { i.seek(0); return i; } // Check type of stream first switch(leadBytes) { case 0x1f8b: { // RFC 1952 // Must be gzip i.seek(0); return new GZIPInputStream(i); } case 0x5345: { // 'S' 'E' // Might be a SequenceFile if (i.readByte() == 'Q') { i.close(); return new TextRecordInputStream(item.stat); } } default: { // Check the type of compression instead, depending on Codec class's // own detection methods, based on the provided path. CompressionCodecFactory cf = new CompressionCodecFactory(getConf()); CompressionCodec codec = cf.getCodec(item.path); if (codec != null) { i.seek(0); return codec.createInputStream(i); } break; } case 0x4f62: { // 'O' 'b' if (i.readByte() == 'j') { i.close(); return new AvroFileInputStream(item.stat); } break; } } // File is non-compressed, or not a file container we know. i.seek(0); return i; } } public static
Text
java
quarkusio__quarkus
independent-projects/qute/core/src/main/java/io/quarkus/qute/SingleResultNode.java
{ "start": 255, "end": 1533 }
class ____ extends ResultNode { private final Object value; private final ExpressionNode node; public SingleResultNode(Object value) { this(value, null); } SingleResultNode(Object value, ExpressionNode expressionNode) { this.value = extractValue(value); this.node = expressionNode != null && expressionNode.hasEngineResultMappers() ? expressionNode : null; } private static Object extractValue(Object value) { if (value instanceof Optional) { return ((Optional<?>) value).orElse(null); } if (value instanceof OptionalInt) { return ((OptionalInt) value).orElse(0); } if (value instanceof OptionalDouble) { return ((OptionalDouble) value).orElse(0D); } if (value instanceof OptionalLong) { return ((OptionalLong) value).orElse(0L); } return value; } @Override public void process(Consumer<String> consumer) { if (value != null) { String result; if (node != null) { result = node.mapResult(value); } else { result = value.toString(); } consumer.accept(result); } } }
SingleResultNode
java
apache__flink
flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/NFASerializerUpgradeTest.java
{ "start": 13427, "end": 13835 }
class ____ implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<NFAState> { @Override public TypeSerializer<NFAState> createPriorSerializer() { return new NFAStateSerializer(); } @Override public NFAState createTestData() { return new NFAState(Collections.emptyList()); } } /** * This
NFAStateSerializerSetup
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/snapshot/FSImageFormatPBSnapshot.java
{ "start": 5082, "end": 18021 }
class ____ { private final FSNamesystem fsn; private final FSDirectory fsDir; private final FSImageFormatProtobuf.Loader parent; private final Map<Integer, Snapshot> snapshotMap; public Loader(FSNamesystem fsn, FSImageFormatProtobuf.Loader parent) { this.fsn = fsn; this.fsDir = fsn.getFSDirectory(); this.snapshotMap = new HashMap<Integer, Snapshot>(); this.parent = parent; } /** * The sequence of the ref node in refList must be strictly the same with * the sequence in fsimage */ public void loadINodeReferenceSection(InputStream in) throws IOException { final List<INodeReference> refList = parent.getLoaderContext() .getRefList(); while (true) { INodeReferenceSection.INodeReference e = INodeReferenceSection .INodeReference.parseDelimitedFrom(in); if (e == null) { break; } INodeReference ref = loadINodeReference(e); refList.add(ref); } } private INodeReference loadINodeReference( INodeReferenceSection.INodeReference r) { long referredId = r.getReferredId(); INode referred = fsDir.getInode(referredId); WithCount withCount = (WithCount) referred.getParentReference(); if (withCount == null) { withCount = new INodeReference.WithCount(null, referred); } final INodeReference ref; if (r.hasDstSnapshotId()) { // DstReference ref = new INodeReference.DstReference(null, withCount, r.getDstSnapshotId()); } else { ref = new INodeReference.WithName(null, withCount, r.getName() .toByteArray(), r.getLastSnapshotId()); } return ref; } /** * Load the snapshots section from fsimage. Also add snapshottable feature * to snapshottable directories. */ public void loadSnapshotSection(InputStream in) throws IOException { SnapshotManager sm = fsn.getSnapshotManager(); SnapshotSection section = SnapshotSection.parseDelimitedFrom(in); int snum = section.getNumSnapshots(); sm.setNumSnapshots(snum); sm.setSnapshotCounter(section.getSnapshotCounter()); for (long sdirId : section.getSnapshottableDirList()) { INodeDirectory dir = fsDir.getInode(sdirId).asDirectory(); if (!dir.isSnapshottable()) { dir.addSnapshottableFeature(); } else { // dir is root, and admin set root to snapshottable before dir.setSnapshotQuota( DirectorySnapshottableFeature.SNAPSHOT_QUOTA_DEFAULT); } sm.addSnapshottable(dir); } loadSnapshots(in, snum); } private void loadSnapshots(InputStream in, int size) throws IOException { for (int i = 0; i < size; i++) { SnapshotSection.Snapshot pbs = SnapshotSection.Snapshot .parseDelimitedFrom(in); INodeDirectory root = loadINodeDirectory(pbs.getRoot(), parent.getLoaderContext()); int sid = pbs.getSnapshotId(); INodeDirectory parent = fsDir.getInode(root.getId()).asDirectory(); Snapshot snapshot = new Snapshot(sid, root, parent); // add the snapshot to parent, since we follow the sequence of // snapshotsByNames when saving, we do not need to sort when loading parent.getDirectorySnapshottableFeature().addSnapshot(snapshot); snapshotMap.put(sid, snapshot); } } /** * Load the snapshot diff section from fsimage. */ public void loadSnapshotDiffSection(InputStream in) throws IOException { final List<INodeReference> refList = parent.getLoaderContext() .getRefList(); while (true) { SnapshotDiffSection.DiffEntry entry = SnapshotDiffSection.DiffEntry .parseDelimitedFrom(in); if (entry == null) { break; } long inodeId = entry.getInodeId(); INode inode = fsDir.getInode(inodeId); SnapshotDiffSection.DiffEntry.Type type = entry.getType(); switch (type) { case FILEDIFF: loadFileDiffList(in, inode.asFile(), entry.getNumOfDiff()); break; case DIRECTORYDIFF: loadDirectoryDiffList(in, inode.asDirectory(), entry.getNumOfDiff(), refList); break; } } } /** Load FileDiff list for a file with snapshot feature */ private void loadFileDiffList(InputStream in, INodeFile file, int size) throws IOException { final FileDiffList diffs = new FileDiffList(); final LoaderContext state = parent.getLoaderContext(); final BlockManager bm = fsn.getBlockManager(); for (int i = 0; i < size; i++) { SnapshotDiffSection.FileDiff pbf = SnapshotDiffSection.FileDiff .parseDelimitedFrom(in); INodeFileAttributes copy = null; if (pbf.hasSnapshotCopy()) { INodeSection.INodeFile fileInPb = pbf.getSnapshotCopy(); PermissionStatus permission = loadPermission( fileInPb.getPermission(), state.getStringTable()); AclFeature acl = null; if (fileInPb.hasAcl()) { int[] entries = AclEntryStatusFormat .toInt(FSImageFormatPBINode.Loader.loadAclEntries( fileInPb.getAcl(), state.getStringTable())); acl = new AclFeature(entries); } XAttrFeature xAttrs = null; if (fileInPb.hasXAttrs()) { xAttrs = new XAttrFeature(FSImageFormatPBINode.Loader.loadXAttrs( fileInPb.getXAttrs(), state.getStringTable())); } boolean isStriped = (fileInPb.getBlockType() == BlockTypeProto .STRIPED); Short replication = (!isStriped ? (short)fileInPb.getReplication() : null); Byte ecPolicyID = (isStriped ? (byte)fileInPb.getErasureCodingPolicyID() : null); copy = new INodeFileAttributes.SnapshotCopy(pbf.getName() .toByteArray(), permission, acl, fileInPb.getModificationTime(), fileInPb.getAccessTime(), replication, ecPolicyID, fileInPb.getPreferredBlockSize(), (byte)fileInPb.getStoragePolicyID(), xAttrs, PBHelperClient.convert(fileInPb.getBlockType())); } FileDiff diff = new FileDiff(pbf.getSnapshotId(), copy, null, pbf.getFileSize()); List<BlockProto> bpl = pbf.getBlocksList(); // in file diff there can only be contiguous blocks BlockInfo[] blocks = new BlockInfo[bpl.size()]; for(int j = 0, e = bpl.size(); j < e; ++j) { Block blk = PBHelperClient.convert(bpl.get(j)); BlockInfo storedBlock = bm.getStoredBlock(blk); if(storedBlock == null) { storedBlock = (BlockInfoContiguous) fsn.getBlockManager() .addBlockCollectionWithCheck(new BlockInfoContiguous(blk, copy.getFileReplication()), file); } blocks[j] = storedBlock; } if(blocks.length > 0) { diff.setBlocks(blocks); } diffs.addFirst(diff); } file.loadSnapshotFeature(diffs); short repl = file.getPreferredBlockReplication(); for (BlockInfo b : file.getBlocks()) { if (b.getReplication() < repl) { bm.setReplication(b.getReplication(), repl, b); } } } /** Load the created list in a DirectoryDiff */ private List<INode> loadCreatedList(InputStream in, INodeDirectory dir, int size) throws IOException { List<INode> clist = new ArrayList<INode>(size); for (long c = 0; c < size; c++) { CreatedListEntry entry = CreatedListEntry.parseDelimitedFrom(in); INode created = SnapshotFSImageFormat.loadCreated(entry.getName() .toByteArray(), dir); clist.add(created); } return clist; } private void addToDeletedList(INode dnode, INodeDirectory parent) { dnode.setParent(parent); if (dnode.isFile()) { updateBlocksMap(dnode.asFile(), fsn.getBlockManager()); } } /** * Load the deleted list in a DirectoryDiff */ private List<INode> loadDeletedList(final List<INodeReference> refList, InputStream in, INodeDirectory dir, List<Long> deletedNodes, List<Integer> deletedRefNodes) throws IOException { List<INode> dlist = new ArrayList<INode>(deletedRefNodes.size() + deletedNodes.size()); // load non-reference inodes for (long deletedId : deletedNodes) { INode deleted = fsDir.getInode(deletedId); dlist.add(deleted); addToDeletedList(deleted, dir); } // load reference nodes in the deleted list for (int refId : deletedRefNodes) { INodeReference deletedRef = refList.get(refId); dlist.add(deletedRef); addToDeletedList(deletedRef, dir); } Collections.sort(dlist, new Comparator<INode>() { @Override public int compare(INode n1, INode n2) { return n1.compareTo(n2.getLocalNameBytes()); } }); return dlist; } /** Load DirectoryDiff list for a directory with snapshot feature */ private void loadDirectoryDiffList(InputStream in, INodeDirectory dir, int size, final List<INodeReference> refList) throws IOException { if (!dir.isWithSnapshot()) { dir.addSnapshotFeature(null); } DirectoryDiffList diffs = dir.getDiffs(); final LoaderContext state = parent.getLoaderContext(); for (int i = 0; i < size; i++) { // load a directory diff SnapshotDiffSection.DirectoryDiff diffInPb = SnapshotDiffSection. DirectoryDiff.parseDelimitedFrom(in); final int snapshotId = diffInPb.getSnapshotId(); final Snapshot snapshot = snapshotMap.get(snapshotId); int childrenSize = diffInPb.getChildrenSize(); boolean useRoot = diffInPb.getIsSnapshotRoot(); INodeDirectoryAttributes copy = null; if (useRoot) { copy = snapshot.getRoot(); } else if (diffInPb.hasSnapshotCopy()) { INodeSection.INodeDirectory dirCopyInPb = diffInPb.getSnapshotCopy(); final byte[] name = diffInPb.getName().toByteArray(); PermissionStatus permission = loadPermission( dirCopyInPb.getPermission(), state.getStringTable()); AclFeature acl = null; if (dirCopyInPb.hasAcl()) { int[] entries = AclEntryStatusFormat .toInt(FSImageFormatPBINode.Loader.loadAclEntries( dirCopyInPb.getAcl(), state.getStringTable())); acl = new AclFeature(entries); } XAttrFeature xAttrs = null; if (dirCopyInPb.hasXAttrs()) { xAttrs = new XAttrFeature(FSImageFormatPBINode.Loader.loadXAttrs( dirCopyInPb.getXAttrs(), state.getStringTable())); } long modTime = dirCopyInPb.getModificationTime(); boolean noQuota = dirCopyInPb.getNsQuota() == -1 && dirCopyInPb.getDsQuota() == -1 && (!dirCopyInPb.hasTypeQuotas()); if (noQuota) { copy = new INodeDirectoryAttributes.SnapshotCopy(name, permission, acl, modTime, xAttrs); } else { EnumCounters<StorageType> typeQuotas = null; if (dirCopyInPb.hasTypeQuotas()) { ImmutableList<QuotaByStorageTypeEntry> qes = FSImageFormatPBINode.Loader.loadQuotaByStorageTypeEntries( dirCopyInPb.getTypeQuotas()); typeQuotas = new EnumCounters<StorageType>(StorageType.class, HdfsConstants.QUOTA_RESET); for (QuotaByStorageTypeEntry qe : qes) { if (qe.getQuota() >= 0 && qe.getStorageType() != null && qe.getStorageType().supportTypeQuota()) { typeQuotas.set(qe.getStorageType(), qe.getQuota()); } } } copy = new INodeDirectoryAttributes.CopyWithQuota(name, permission, acl, modTime, dirCopyInPb.getNsQuota(), dirCopyInPb.getDsQuota(), typeQuotas, xAttrs); } } // load created list List<INode> clist = loadCreatedList(in, dir, diffInPb.getCreatedListSize()); // load deleted list List<INode> dlist = loadDeletedList(refList, in, dir, diffInPb.getDeletedINodeList(), diffInPb.getDeletedINodeRefList()); // create the directory diff DirectoryDiff diff = new DirectoryDiff(snapshotId, copy, null, childrenSize, clist, dlist, useRoot); diffs.addFirst(diff); } } } /** * Saving snapshot related information to protobuf based FSImage */ public final static
Loader
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/impl/MockScheduledPollConsumer.java
{ "start": 1074, "end": 2053 }
class ____ extends ScheduledPollConsumer { private Exception exceptionToThrowOnPoll; public MockScheduledPollConsumer(DefaultEndpoint endpoint, Processor processor) { super(endpoint, processor); } // dummy constructor here - we just want to test the run() method, which // calls poll() public MockScheduledPollConsumer(Endpoint endpoint, Exception exceptionToThrowOnPoll) { super(endpoint, null, new ScheduledThreadPoolExecutor(1)); this.exceptionToThrowOnPoll = exceptionToThrowOnPoll; } @Override protected int poll() throws Exception { if (exceptionToThrowOnPoll != null) { throw exceptionToThrowOnPoll; } return 0; } public void setExceptionToThrowOnPoll(Exception exceptionToThrowOnPoll) { this.exceptionToThrowOnPoll = exceptionToThrowOnPoll; } @Override public String toString() { return "MockScheduled"; } }
MockScheduledPollConsumer
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/ids/ManyToOneIdNotAuditedTestEntity.java
{ "start": 391, "end": 1419 }
class ____ implements Serializable { @EmbeddedId private ManyToOneNotAuditedEmbId id; private String data; public ManyToOneIdNotAuditedTestEntity() { } public ManyToOneNotAuditedEmbId getId() { return id; } public void setId(ManyToOneNotAuditedEmbId id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } ManyToOneIdNotAuditedTestEntity that = (ManyToOneIdNotAuditedTestEntity) o; if ( data != null ? !data.equals( that.data ) : that.data != null ) { return false; } if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; } return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (data != null ? data.hashCode() : 0); return result; } }
ManyToOneIdNotAuditedTestEntity
java
spring-projects__spring-boot
module/spring-boot-micrometer-metrics/src/main/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/newrelic/NewRelicMetricsExportAutoConfiguration.java
{ "start": 2636, "end": 3725 }
class ____ { private final NewRelicProperties properties; NewRelicMetricsExportAutoConfiguration(NewRelicProperties properties) { this.properties = properties; } @Bean @ConditionalOnMissingBean NewRelicConfig newRelicConfig() { return new NewRelicPropertiesConfigAdapter(this.properties); } @Bean @ConditionalOnMissingBean NewRelicClientProvider newRelicClientProvider(NewRelicConfig newRelicConfig) { if (newRelicConfig.clientProviderType() == ClientProviderType.INSIGHTS_AGENT) { return new NewRelicInsightsAgentClientProvider(newRelicConfig); } return new NewRelicInsightsApiClientProvider(newRelicConfig, new HttpUrlConnectionSender(this.properties.getConnectTimeout(), this.properties.getReadTimeout())); } @Bean @ConditionalOnMissingBean NewRelicMeterRegistry newRelicMeterRegistry(NewRelicConfig newRelicConfig, Clock clock, NewRelicClientProvider newRelicClientProvider) { return NewRelicMeterRegistry.builder(newRelicConfig) .clock(clock) .clientProvider(newRelicClientProvider) .build(); } }
NewRelicMetricsExportAutoConfiguration
java
apache__camel
components/camel-influxdb2/src/main/java/org/apache/camel/component/influxdb2/InfluxDb2Constants.java
{ "start": 902, "end": 1675 }
class ____ { @Metadata(description = "The name of measurement", javaType = "String") public static final String MEASUREMENT = "CamelInfluxDB2MeasurementName"; @Metadata(description = "The string that defines the retention policy to the data created by the endpoint", javaType = "String") public static final String RETENTION_POLICY = "camelInfluxDB.RetentionPolicy"; public static final String ORG = "CamelInfluxDB2Org"; public static final String BUCKET = "CamelInfluxDB2Bucket"; @Metadata(description = "InfluxDb Write precision.", javaType = "com.influxdb.client.domain.WritePrecision") public static final String WRITE_PRECISION = "CamelInfluxDB2WritePrecision"; private InfluxDb2Constants() { } }
InfluxDb2Constants
java
apache__camel
components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddb/QueryCommand.java
{ "start": 1305, "end": 5325 }
class ____ extends AbstractDdbCommand { public QueryCommand(DynamoDbClient ddbClient, Ddb2Configuration configuration, Exchange exchange) { super(ddbClient, configuration, exchange); } @Override public void execute() { QueryRequest.Builder query = QueryRequest.builder().tableName(determineTableName()) .attributesToGet(determineAttributeNames()).consistentRead(determineConsistentRead()) .keyConditions(determineKeyConditions()).exclusiveStartKey(determineExclusiveStartKey()) .limit(determineLimit()).scanIndexForward(determineScanIndexForward()); // Check if we have set an Index Name if (exchange.getIn().getHeader(Ddb2Constants.INDEX_NAME, String.class) != null) { query.indexName(exchange.getIn().getHeader(Ddb2Constants.INDEX_NAME, String.class)); } //skip adding attribute-to-get from 'CamelAwsDdbAttributeNames' if the header is null or empty list. if (exchange.getIn().getHeader(Ddb2Constants.ATTRIBUTE_NAMES) != null && !exchange.getIn().getHeader(Ddb2Constants.ATTRIBUTE_NAMES, Collection.class).isEmpty()) { query.attributesToGet(determineAttributeNames()); } if (exchange.getIn().getHeader(Ddb2Constants.FILTER_EXPRESSION) != null && !exchange.getIn().getHeader(Ddb2Constants.FILTER_EXPRESSION, String.class).isEmpty()) { query.filterExpression(determineFilterExpression()); } if (exchange.getIn().getHeader(Ddb2Constants.FILTER_EXPRESSION_ATTRIBUTE_NAMES) != null && !exchange.getIn().getHeader(Ddb2Constants.FILTER_EXPRESSION_ATTRIBUTE_NAMES, Map.class).isEmpty()) { query.expressionAttributeNames(determineFilterExpressionAttributeNames()); } if (exchange.getIn().getHeader(Ddb2Constants.FILTER_EXPRESSION_ATTRIBUTE_VALUES) != null && !exchange.getIn().getHeader(Ddb2Constants.FILTER_EXPRESSION_ATTRIBUTE_VALUES, Map.class).isEmpty()) { query.expressionAttributeValues(determineFilterExpressionAttributeValues()); } if (exchange.getIn().getHeader(Ddb2Constants.PROJECT_EXPRESSION) != null && !exchange.getIn().getHeader(Ddb2Constants.PROJECT_EXPRESSION, Map.class).isEmpty()) { query.projectionExpression(determineProjectExpression()); } QueryResponse result = ddbClient.query(query.build()); Map<Object, Object> tmp = new HashMap<>(); tmp.put(Ddb2Constants.ITEMS, result.items()); tmp.put(Ddb2Constants.LAST_EVALUATED_KEY, result.hasLastEvaluatedKey() ? result.lastEvaluatedKey() : null); tmp.put(Ddb2Constants.CONSUMED_CAPACITY, result.consumedCapacity()); tmp.put(Ddb2Constants.COUNT, result.count()); addToResults(tmp); } private Boolean determineScanIndexForward() { return exchange.getIn().getHeader(Ddb2Constants.SCAN_INDEX_FORWARD, Boolean.class); } @SuppressWarnings("unchecked") private Map<String, Condition> determineKeyConditions() { return exchange.getIn().getHeader(Ddb2Constants.KEY_CONDITIONS, Map.class); } @SuppressWarnings("unchecked") private String determineFilterExpression() { return exchange.getIn().getHeader(Ddb2Constants.FILTER_EXPRESSION, String.class); } @SuppressWarnings("unchecked") private Map<String, String> determineFilterExpressionAttributeNames() { return exchange.getIn().getHeader(Ddb2Constants.FILTER_EXPRESSION_ATTRIBUTE_NAMES, Map.class); } @SuppressWarnings("unchecked") private Map<String, AttributeValue> determineFilterExpressionAttributeValues() { return exchange.getIn().getHeader(Ddb2Constants.FILTER_EXPRESSION_ATTRIBUTE_VALUES, Map.class); } @SuppressWarnings("unchecked") private String determineProjectExpression() { return exchange.getIn().getHeader(Ddb2Constants.PROJECT_EXPRESSION, String.class); } }
QueryCommand
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/spi/RuntimeConfiguration.java
{ "start": 452, "end": 540 }
interface ____ { List<String> fileContentTypes(); } }
MultiPart
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobImplementer.java
{ "start": 175, "end": 287 }
interface ____ non-contextually created {@link java.sql.Blob} instances. * * @author Steve Ebersole */ public
for
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/TestUtils.java
{ "start": 704, "end": 1575 }
class ____ { public static String randomAlphaString(int length) { StringBuilder builder = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = (char) (65 + 25 * Math.random()); builder.append(c); } return builder.toString(); } public static byte[] compressGzip(String source) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos); gos.write(source.getBytes()); gos.close(); return baos.toByteArray(); } public static byte[] decompressGzip(byte[] source) throws IOException { GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(source)); byte[] result = gis.readAllBytes(); gis.close(); return result; } }
TestUtils
java
spring-projects__spring-framework
spring-jms/src/main/java/org/springframework/jms/annotation/JmsBootstrapConfiguration.java
{ "start": 1695, "end": 2200 }
class ____ { @Bean(name = JmsListenerConfigUtils.JMS_LISTENER_ANNOTATION_PROCESSOR_BEAN_NAME) @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public JmsListenerAnnotationBeanPostProcessor jmsListenerAnnotationProcessor() { return new JmsListenerAnnotationBeanPostProcessor(); } @Bean(name = JmsListenerConfigUtils.JMS_LISTENER_ENDPOINT_REGISTRY_BEAN_NAME) public JmsListenerEndpointRegistry defaultJmsListenerEndpointRegistry() { return new JmsListenerEndpointRegistry(); } }
JmsBootstrapConfiguration
java
apache__rocketmq
common/src/main/java/org/apache/rocketmq/common/statistics/StatisticsItemScheduledIncrementPrinter.java
{ "start": 1042, "end": 7659 }
class ____ extends StatisticsItemScheduledPrinter { private String[] tpsItemNames; public static final int TPS_INITIAL_DELAY = 0; public static final int TPS_INTREVAL = 1000; public static final String SEPARATOR = "|"; /** * last snapshots of all scheduled items */ private final ConcurrentHashMap<String, ConcurrentHashMap<String, StatisticsItem>> lastItemSnapshots = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, ConcurrentHashMap<String, StatisticsItemSampleBrief>> sampleBriefs = new ConcurrentHashMap<>(); public StatisticsItemScheduledIncrementPrinter(String name, StatisticsItemPrinter printer, ScheduledExecutorService executor, InitialDelay initialDelay, long interval, String[] tpsItemNames, Valve valve) { super(name, printer, executor, initialDelay, interval, valve); this.tpsItemNames = tpsItemNames; } /** * schedule a StatisticsItem to print the Increments periodically */ @Override public void schedule(final StatisticsItem item) { setItemSampleBrief(item.getStatKind(), item.getStatObject(), new StatisticsItemSampleBrief(item, tpsItemNames)); // print log every ${interval} milliseconds ScheduledFuture future = executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (!enabled()) { return; } StatisticsItem snapshot = item.snapshot(); StatisticsItem lastSnapshot = getItemSnapshot(lastItemSnapshots, item.getStatKind(), item.getStatObject()); StatisticsItem increment = snapshot.subtract(lastSnapshot); Interceptor interceptor = item.getInterceptor(); String interceptorStr = formatInterceptor(interceptor); if (interceptor != null) { interceptor.reset(); } StatisticsItemSampleBrief brief = getSampleBrief(item.getStatKind(), item.getStatObject()); if (brief != null && (!increment.allZeros() || printZeroLine())) { printer.print(name, increment, interceptorStr, brief.toString()); } setItemSnapshot(lastItemSnapshots, snapshot); if (brief != null) { brief.reset(); } } }, getInitialDelay(), interval, TimeUnit.MILLISECONDS); addFuture(item, future); // sample every TPS_INTERVAL ScheduledFuture futureSample = executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { if (!enabled()) { return; } StatisticsItem snapshot = item.snapshot(); StatisticsItemSampleBrief brief = getSampleBrief(item.getStatKind(), item.getStatObject()); if (brief != null) { brief.sample(snapshot); } } }, TPS_INTREVAL, TPS_INTREVAL, TimeUnit.MILLISECONDS); addFuture(item, futureSample); } @Override public void remove(StatisticsItem item) { // remove task removeAllFuture(item); String kind = item.getStatKind(); String key = item.getStatObject(); ConcurrentHashMap<String, StatisticsItem> lastItemMap = lastItemSnapshots.get(kind); if (lastItemMap != null) { lastItemMap.remove(key); } ConcurrentHashMap<String, StatisticsItemSampleBrief> briefMap = sampleBriefs.get(kind); if (briefMap != null) { briefMap.remove(key); } } private StatisticsItem getItemSnapshot( ConcurrentHashMap<String, ConcurrentHashMap<String, StatisticsItem>> snapshots, String kind, String key) { ConcurrentHashMap<String, StatisticsItem> itemMap = snapshots.get(kind); return (itemMap != null) ? itemMap.get(key) : null; } private StatisticsItemSampleBrief getSampleBrief(String kind, String key) { ConcurrentHashMap<String, StatisticsItemSampleBrief> itemMap = sampleBriefs.get(kind); return (itemMap != null) ? itemMap.get(key) : null; } private void setItemSnapshot(ConcurrentHashMap<String, ConcurrentHashMap<String, StatisticsItem>> snapshots, StatisticsItem item) { String kind = item.getStatKind(); String key = item.getStatObject(); ConcurrentHashMap<String, StatisticsItem> itemMap = snapshots.get(kind); if (itemMap == null) { itemMap = new ConcurrentHashMap<>(); ConcurrentHashMap<String, StatisticsItem> oldItemMap = snapshots.putIfAbsent(kind, itemMap); if (oldItemMap != null) { itemMap = oldItemMap; } } itemMap.put(key, item); } private void setItemSampleBrief(String kind, String key, StatisticsItemSampleBrief brief) { ConcurrentHashMap<String, StatisticsItemSampleBrief> itemMap = sampleBriefs.get(kind); if (itemMap == null) { itemMap = new ConcurrentHashMap<>(); ConcurrentHashMap<String, StatisticsItemSampleBrief> oldItemMap = sampleBriefs.putIfAbsent(kind, itemMap); if (oldItemMap != null) { itemMap = oldItemMap; } } itemMap.put(key, brief); } private String formatInterceptor(Interceptor interceptor) { if (interceptor == null) { return ""; } if (interceptor instanceof StatisticsBriefInterceptor) { StringBuilder sb = new StringBuilder(); StatisticsBriefInterceptor briefInterceptor = (StatisticsBriefInterceptor)interceptor; for (StatisticsBrief brief : briefInterceptor.getStatisticsBriefs()) { long max = brief.getMax(); long tp999 = Math.min(brief.tp999(), max); //sb.append(SEPARATOR).append(brief.getTotal()); sb.append(SEPARATOR).append(max); //sb.append(SEPARATOR).append(brief.getMin()); sb.append(SEPARATOR).append(String.format("%.2f", brief.getAvg())); sb.append(SEPARATOR).append(tp999); } return sb.toString(); } return ""; } public static
StatisticsItemScheduledIncrementPrinter
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/RawKeyValueIterator.java
{ "start": 1287, "end": 2257 }
interface ____ { /** * Gets the current raw key. * * @return Gets the current raw key as a DataInputBuffer * @throws IOException */ DataInputBuffer getKey() throws IOException; /** * Gets the current raw value. * * @return Gets the current raw value as a DataInputBuffer * @throws IOException */ DataInputBuffer getValue() throws IOException; /** * Sets up the current key and value (for getKey and getValue). * * @return <code>true</code> if there exists a key/value, * <code>false</code> otherwise. * @throws IOException */ boolean next() throws IOException; /** * Closes the iterator so that the underlying streams can be closed. * * @throws IOException */ void close() throws IOException; /** Gets the Progress object; this has a float (0.0 - 1.0) * indicating the bytes processed by the iterator so far */ Progress getProgress(); }
RawKeyValueIterator
java
google__dagger
dagger-producers/main/java/dagger/producers/monitoring/TimingProductionComponentMonitor.java
{ "start": 1160, "end": 1782 }
class ____ extends ProductionComponentMonitor { private final ProductionComponentTimingRecorder recorder; private final Ticker ticker; private final Stopwatch stopwatch; TimingProductionComponentMonitor(ProductionComponentTimingRecorder recorder, Ticker ticker) { this.recorder = recorder; this.ticker = ticker; this.stopwatch = Stopwatch.createStarted(ticker); } @Override public ProducerMonitor producerMonitorFor(ProducerToken token) { return new TimingProducerMonitor(recorder.producerTimingRecorderFor(token), ticker, stopwatch); } public static final
TimingProductionComponentMonitor
java
spring-projects__spring-boot
module/spring-boot-graphql/src/test/java/org/springframework/boot/graphql/autoconfigure/observation/GraphQlObservationAutoConfigurationTests.java
{ "start": 4494, "end": 4642 }
class ____ extends DefaultDataLoaderObservationConvention { } @Configuration(proxyBeanMethods = false) static
CustomDataLoaderObservationConvention
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/rfc9562/EntitySeven.java
{ "start": 469, "end": 855 }
class ____ { @Id @UuidGenerator(algorithm = UuidVersion7Strategy.class) public UUID id; @Basic public String name; private EntitySeven() { // for Hibernate use } public EntitySeven(String name) { this.name = name; } public UUID getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
EntitySeven
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/configuration/injection/SpyOnInjectedFieldsHandler.java
{ "start": 834, "end": 2397 }
class ____ extends MockInjectionStrategy { private final MemberAccessor accessor = Plugins.getMemberAccessor(); @Override protected boolean processInjection(Field field, Object fieldOwner, Set<Object> mockCandidates) { FieldReader fieldReader = new FieldReader(fieldOwner, field); // TODO refactor : code duplicated in SpyAnnotationEngine if (!fieldReader.isNull() && field.isAnnotationPresent(Spy.class)) { try { Object instance = fieldReader.read(); if (MockUtil.isMock(instance)) { // A. instance has been spied earlier // B. protect against multiple use of MockitoAnnotations.openMocks() Mockito.reset(instance); } else { // TODO: Add mockMaker option for @Spy annotation (#2740) Object mock = Mockito.mock( instance.getClass(), withSettings() .spiedInstance(instance) .defaultAnswer(Mockito.CALLS_REAL_METHODS) .name(field.getName())); accessor.set(field, fieldOwner, mock); } } catch (Exception e) { throw new MockitoException("Problems initiating spied field " + field.getName(), e); } } return false; } }
SpyOnInjectedFieldsHandler
java
quarkusio__quarkus
extensions/reactive-routes/deployment/src/test/java/io/quarkus/vertx/web/mutiny/JsonMultiRouteWithContentTypeTest.java
{ "start": 2578, "end": 5227 }
class ____ { @Route(path = "hello", produces = ReactiveRoutes.APPLICATION_JSON) Multi<String> hello() { return Multi.createFrom().item("Hello world!"); } @Route(path = "hellos", produces = ReactiveRoutes.APPLICATION_JSON) Multi<String> hellos() { return Multi.createFrom().items("hello", "world", "!"); } @Route(path = "no-hello", produces = ReactiveRoutes.APPLICATION_JSON) Multi<String> noHello() { return Multi.createFrom().empty(); } @Route(path = "hello-and-fail", produces = ReactiveRoutes.APPLICATION_JSON) Multi<String> helloAndFail() { return Multi.createBy().concatenating().streams( Multi.createFrom().item("Hello"), Multi.createFrom().failure(new IOException("boom"))); } @Route(path = "buffers", produces = ReactiveRoutes.APPLICATION_JSON) Multi<Buffer> buffers() { return Multi.createFrom() .items(Buffer.buffer("Buffer"), Buffer.buffer(" Buffer"), Buffer.buffer(" Buffer.")); } @Route(path = "void", produces = ReactiveRoutes.APPLICATION_JSON) Multi<Void> multiVoid() { return Multi.createFrom().range(0, 200) .onItem().ignore(); } @Route(path = "/people", produces = ReactiveRoutes.APPLICATION_JSON) Multi<Person> people() { return Multi.createFrom().items( new Person("superman", 1), new Person("batman", 2), new Person("spiderman", 3)); } @Route(path = "/people-content-type", produces = ReactiveRoutes.APPLICATION_JSON) Multi<Person> peopleWithContentType(RoutingContext context) { context.response().putHeader("content-type", "application/json;charset=utf-8"); return Multi.createFrom().items( new Person("superman", 1), new Person("batman", 2), new Person("spiderman", 3)); } @Route(path = "/failure", produces = ReactiveRoutes.APPLICATION_JSON) Multi<Person> fail() { return Multi.createFrom().failure(new IOException("boom")); } @Route(path = "/sync-failure", produces = ReactiveRoutes.APPLICATION_JSON) Multi<Person> failSync() { throw new IllegalStateException("boom"); } @Route(path = "/null", produces = ReactiveRoutes.APPLICATION_JSON) Multi<String> uniNull() { return null; } } static
SimpleBean
java
quarkusio__quarkus
devtools/cli/src/main/java/io/quarkus/cli/config/Encrypt.java
{ "start": 4195, "end": 4250 }
enum ____ { base64, plain } }
KeyFormat
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-documentstore/src/test/java/org/apache/hadoop/yarn/server/timelineservice/documentstore/writer/cosmosdb/TestCosmosDBDocumentStoreWriter.java
{ "start": 1878, "end": 3953 }
class ____ { @BeforeEach public void setUp() { AsyncDocumentClient asyncDocumentClient = Mockito.mock(AsyncDocumentClient.class); Configuration conf = Mockito.mock(Configuration.class); mockStatic(DocumentStoreUtils.class); when(DocumentStoreUtils.getCosmosDBDatabaseName(conf)). thenReturn("FooBar"); when(DocumentStoreUtils.createCosmosDBAsyncClient(conf)). thenReturn(asyncDocumentClient); } @SuppressWarnings("unchecked") @Test public void applyingUpdatesOnPrevDocTest() throws IOException { MockedCosmosDBDocumentStoreWriter documentStoreWriter = new MockedCosmosDBDocumentStoreWriter(null); TimelineEntityDocument actualEntityDoc = new TimelineEntityDocument(); TimelineEntityDocument expectedEntityDoc = DocumentStoreTestUtils.bakeTimelineEntityDoc(); assertEquals(1, actualEntityDoc.getInfo().size()); assertEquals(0, actualEntityDoc.getMetrics().size()); assertEquals(0, actualEntityDoc.getEvents().size()); assertEquals(0, actualEntityDoc.getConfigs().size()); assertEquals(0, actualEntityDoc.getIsRelatedToEntities().size()); assertEquals(0, actualEntityDoc. getRelatesToEntities().size()); actualEntityDoc = (TimelineEntityDocument) documentStoreWriter .applyUpdatesOnPrevDoc(CollectionType.ENTITY, actualEntityDoc, null); assertEquals(expectedEntityDoc.getInfo().size(), actualEntityDoc.getInfo().size()); assertEquals(expectedEntityDoc.getMetrics().size(), actualEntityDoc.getMetrics().size()); assertEquals(expectedEntityDoc.getEvents().size(), actualEntityDoc.getEvents().size()); assertEquals(expectedEntityDoc.getConfigs().size(), actualEntityDoc.getConfigs().size()); assertEquals(expectedEntityDoc.getRelatesToEntities().size(), actualEntityDoc.getIsRelatedToEntities().size()); assertEquals(expectedEntityDoc.getRelatesToEntities().size(), actualEntityDoc.getRelatesToEntities().size()); } }
TestCosmosDBDocumentStoreWriter
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/rules/logical/promql/AutomatonUtils.java
{ "start": 861, "end": 4131 }
class ____ { /** * Maximum number of values to extract for IN clause optimization. * Beyond this threshold, fall back to regex matching. */ private static final int MAX_IN_VALUES = 256; /** * Maximum pattern length for string analysis. * Very long patterns are kept as-is to avoid excessive processing. */ private static final int MAX_PATTERN_LENGTH = 1000; private AutomatonUtils() { // Utility class } /** * Checks if the automaton matches all possible strings. * * @param automaton the automaton to check * @return true if it matches everything */ public static boolean matchesAll(Automaton automaton) { return Operations.isTotal(automaton); } /** * Checks if the automaton matches no strings. * * @param automaton the automaton to check * @return true if it matches nothing */ public static boolean matchesNone(Automaton automaton) { return Operations.isEmpty(automaton); } /** * Checks if the automaton matches the empty string. * * @param automaton the automaton to check * @return true if it matches the empty string */ public static boolean matchesEmpty(Automaton automaton) { return Operations.run(automaton, ""); } /** * Extracts an exact match if the automaton matches only a single string. * * @param automaton the automaton to analyze * @return the single matched string, or null if it matches zero or multiple strings */ public static String matchesExact(Automaton automaton) { if (automaton.getNumStates() == 0) { return null; // Empty automaton } IntsRef singleton = Operations.getSingleton(automaton); if (singleton == null) { return null; } return UnicodeUtil.newString(singleton.ints, singleton.offset, singleton.length); } /** * Checks if a string is a literal (no regex metacharacters). * * @param s the string to check * @return true if the string contains no regex metacharacters */ private static boolean isLiteral(String s) { if (s == null || s.isEmpty()) { return true; } for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '.': case '*': case '+': case '?': case '[': case ']': case '{': case '}': case '(': case ')': case '|': case '^': case '$': case '\\': return false; } } return true; } private static String removeStartingAnchor(String normalized) { return normalized.startsWith("^") ? normalized.substring(1) : normalized; } private static String removeEndingAnchor(String normalized) { return normalized.endsWith("$") ? normalized.substring(0, normalized.length() - 1) : normalized; } /** * Represents a pattern fragment that can be optimized. */ public static
AutomatonUtils
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/registry/ClearInferenceEndpointCacheAction.java
{ "start": 3060, "end": 6410 }
class ____ extends AcknowledgedTransportMasterNodeAction<ClearInferenceEndpointCacheAction.Request> { private static final Logger log = LogManager.getLogger(ClearInferenceEndpointCacheAction.class); private static final String NAME = "cluster:internal/xpack/inference/clear_inference_endpoint_cache"; public static final ActionType<AcknowledgedResponse> INSTANCE = new ActionType<>(NAME); private static final String TASK_QUEUE_NAME = "inference-endpoint-cache-management"; private static final TransportVersion ML_INFERENCE_ENDPOINT_CACHE = TransportVersion.fromName("ml_inference_endpoint_cache"); private final ProjectResolver projectResolver; private final InferenceEndpointRegistry inferenceEndpointRegistry; private final MasterServiceTaskQueue<RefreshCacheMetadataVersionTask> taskQueue; @Inject public ClearInferenceEndpointCacheAction( TransportService transportService, ClusterService clusterService, ThreadPool threadPool, ActionFilters actionFilters, ProjectResolver projectResolver, InferenceEndpointRegistry inferenceEndpointRegistry ) { super( NAME, transportService, clusterService, threadPool, actionFilters, ClearInferenceEndpointCacheAction.Request::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.projectResolver = projectResolver; this.inferenceEndpointRegistry = inferenceEndpointRegistry; this.taskQueue = clusterService.createTaskQueue(TASK_QUEUE_NAME, Priority.IMMEDIATE, new CacheMetadataUpdateTaskExecutor()); clusterService.addListener( event -> event.state() .metadata() .projects() .values() .stream() .map(ProjectMetadata::id) .filter(id -> event.customMetadataChanged(id, InvalidateCacheMetadata.NAME)) .peek(id -> log.trace("Inference endpoint cache on node [{}]", () -> event.state().nodes().getLocalNodeId())) .forEach(inferenceEndpointRegistry::invalidateAll) ); } @Override protected void doExecute(Task task, Request request, ActionListener<AcknowledgedResponse> listener) { if (inferenceEndpointRegistry.cacheEnabled() == false) { ActionListener.completeWith(listener, () -> AcknowledgedResponse.TRUE); return; } super.doExecute(task, request, listener); } @Override protected void masterOperation( Task task, ClearInferenceEndpointCacheAction.Request request, ClusterState state, ActionListener<AcknowledgedResponse> listener ) { if (inferenceEndpointRegistry.cacheEnabled()) { taskQueue.submitTask("invalidateAll", new RefreshCacheMetadataVersionTask(projectResolver.getProjectId(), listener), null); } else { listener.onResponse(AcknowledgedResponse.TRUE); } } @Override protected ClusterBlockException checkBlock(ClearInferenceEndpointCacheAction.Request request, ClusterState state) { return state.blocks().globalBlockedException(projectResolver.getProjectId(), ClusterBlockLevel.METADATA_WRITE); } public static
ClearInferenceEndpointCacheAction
java
grpc__grpc-java
api/src/test/java/io/grpc/ServiceProvidersTest.java
{ "start": 8375, "end": 9004 }
class ____ extends BaseProvider { private PrivateClass() { super(true, 5); } } try { ServiceProviders.getCandidatesViaHardCoded( ServiceProvidersTestAbstractProvider.class, Collections.<Class<?>>singletonList(PrivateClass.class)); fail("Expected exception"); } catch (ServiceConfigurationError expected) { assertTrue("Expected NoSuchMethodException cause: " + expected.getCause(), expected.getCause() instanceof NoSuchMethodException); } } @Test public void getCandidatesViaHardCoded_skipsWrongClassType() throws Exception {
PrivateClass
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptivebatch/AdaptiveExecutionPlanSchedulingContextTest.java
{ "start": 1872, "end": 7733 }
class ____ { @RegisterExtension private static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_RESOURCE = TestingUtils.defaultExecutorExtension(); @Test void testGetParallelismAndMaxParallelism() throws DynamicCodeLoadingException { int sinkParallelism = 4; int sinkMaxParallelism = 5; DefaultAdaptiveExecutionHandler adaptiveExecutionHandler = getDefaultAdaptiveExecutionHandler(sinkParallelism, sinkMaxParallelism); ExecutionPlanSchedulingContext schedulingContext = adaptiveExecutionHandler.createExecutionPlanSchedulingContext(100); JobGraph jobGraph = adaptiveExecutionHandler.getJobGraph(); JobVertex sourceVertex = jobGraph.getVerticesSortedTopologicallyFromSources().get(0); IntermediateDataSet sourceDataSet = sourceVertex.getProducedDataSets().get(0); assertThat(schedulingContext.getConsumersParallelism(id -> 123, sourceDataSet)) .isEqualTo(sinkParallelism); assertThat(schedulingContext.getConsumersMaxParallelism(id -> 456, sourceDataSet)) .isEqualTo(sinkMaxParallelism); // notify source finished, then the sink vertex will be created adaptiveExecutionHandler.handleJobEvent( new ExecutionJobVertexFinishedEvent(sourceVertex.getID(), Collections.emptyMap())); assertThat(schedulingContext.getConsumersParallelism(id -> 123, sourceDataSet)) .isEqualTo(123); assertThat(schedulingContext.getConsumersMaxParallelism(id -> 456, sourceDataSet)) .isEqualTo(456); } @Test void testGetDefaultMaxParallelismWhenParallelismGreaterThanZero() throws DynamicCodeLoadingException { int sinkParallelism = 4; int sinkMaxParallelism = -1; int defaultMaxParallelism = 100; DefaultAdaptiveExecutionHandler adaptiveExecutionHandler = getDefaultAdaptiveExecutionHandler(sinkParallelism, sinkMaxParallelism); ExecutionPlanSchedulingContext schedulingContext = adaptiveExecutionHandler.createExecutionPlanSchedulingContext( defaultMaxParallelism); JobGraph jobGraph = adaptiveExecutionHandler.getJobGraph(); JobVertex sourceVertex = jobGraph.getVerticesSortedTopologicallyFromSources().get(0); IntermediateDataSet dataSet = sourceVertex.getProducedDataSets().get(0); // the max parallelism will not fall back to the default max parallelism because its // parallelism is greater than zero. assertThat(schedulingContext.getConsumersMaxParallelism(id -> 123, dataSet)) .isEqualTo(getDefaultMaxParallelism(sinkParallelism)); } @Test void testGetDefaultMaxParallelismWhenParallelismLessThanZero() throws DynamicCodeLoadingException { int sinkParallelism = -1; int sinkMaxParallelism = -1; int defaultMaxParallelism = 100; DefaultAdaptiveExecutionHandler adaptiveExecutionHandler = getDefaultAdaptiveExecutionHandler(sinkParallelism, sinkMaxParallelism); ExecutionPlanSchedulingContext schedulingContext = adaptiveExecutionHandler.createExecutionPlanSchedulingContext( defaultMaxParallelism); JobGraph jobGraph = adaptiveExecutionHandler.getJobGraph(); JobVertex sourceVertex = jobGraph.getVerticesSortedTopologicallyFromSources().get(0); IntermediateDataSet dataSet = sourceVertex.getProducedDataSets().get(0); // the max parallelism will fall back to the default max parallelism because its // parallelism is less than zero. assertThat(schedulingContext.getConsumersMaxParallelism(id -> 123, dataSet)) .isEqualTo(defaultMaxParallelism); } @Test public void testGetPendingOperatorCount() throws DynamicCodeLoadingException { DefaultAdaptiveExecutionHandler adaptiveExecutionHandler = getDefaultAdaptiveExecutionHandler(); ExecutionPlanSchedulingContext schedulingContext = adaptiveExecutionHandler.createExecutionPlanSchedulingContext(1); assertThat(schedulingContext.getPendingOperatorCount()).isEqualTo(1); JobGraph jobGraph = adaptiveExecutionHandler.getJobGraph(); JobVertex source = jobGraph.getVertices().iterator().next(); adaptiveExecutionHandler.handleJobEvent( new ExecutionJobVertexFinishedEvent(source.getID(), Collections.emptyMap())); assertThat(schedulingContext.getPendingOperatorCount()).isEqualTo(0); } private static DefaultAdaptiveExecutionHandler getDefaultAdaptiveExecutionHandler() throws DynamicCodeLoadingException { return getDefaultAdaptiveExecutionHandler(2, 2); } private static DefaultAdaptiveExecutionHandler getDefaultAdaptiveExecutionHandler( int sinkParallelism, int sinkMaxParallelism) throws DynamicCodeLoadingException { StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.fromSequence(0L, 1L).disableChaining().print(); StreamGraph streamGraph = env.getStreamGraph(); for (StreamNode streamNode : streamGraph.getStreamNodes()) { if (streamNode.getOperatorName().contains("Sink")) { streamNode.setParallelism(sinkParallelism); if (sinkMaxParallelism > 0) { streamNode.setMaxParallelism(sinkMaxParallelism); } } } return new DefaultAdaptiveExecutionHandler( Thread.currentThread().getContextClassLoader(), streamGraph, EXECUTOR_RESOURCE.getExecutor()); } }
AdaptiveExecutionPlanSchedulingContextTest
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/fields/WithComparingSnakeOrCamelCaseFieldsIntrospectionStrategyBaseTest.java
{ "start": 897, "end": 1197 }
class ____ extends RecursiveComparisonAssert_BaseTest { @BeforeEach public void beforeEachTest() { super.beforeEachTest(); recursiveComparisonConfiguration.setIntrospectionStrategy(new ComparingSnakeOrCamelCaseFields()); } }
WithComparingSnakeOrCamelCaseFieldsIntrospectionStrategyBaseTest
java
apache__dubbo
dubbo-test/dubbo-test-spring/src/main/java/org/apache/dubbo/test/spring/context/MockSpringInitCustomizer.java
{ "start": 1582, "end": 2360 }
class ____ implements DubboSpringInitCustomizer { private List<DubboSpringInitContext> contexts = new ArrayList<>(); @Override public void customize(DubboSpringInitContext context) { this.contexts.add(context); // register post-processor bean, expecting the bean is loaded and invoked by spring container AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition( CustomBeanFactoryPostProcessor.class) .getBeanDefinition(); context.getRegistry().registerBeanDefinition(CustomBeanFactoryPostProcessor.class.getName(), beanDefinition); } public List<DubboSpringInitContext> getContexts() { return contexts; } private static
MockSpringInitCustomizer
java
grpc__grpc-java
api/src/main/java/io/grpc/InternalChannelz.java
{ "start": 30866, "end": 32236 }
class ____ { private final Map<String, String> others = new HashMap<>(); private TcpInfo tcpInfo; private Integer timeoutMillis; private Integer lingerSeconds; /** The value of {@link java.net.Socket#getSoTimeout()}. */ public Builder setSocketOptionTimeoutMillis(Integer timeoutMillis) { this.timeoutMillis = timeoutMillis; return this; } /** The value of {@link java.net.Socket#getSoLinger()}. * Note: SO_LINGER is typically expressed in seconds. */ public Builder setSocketOptionLingerSeconds(Integer lingerSeconds) { this.lingerSeconds = lingerSeconds; return this; } public Builder setTcpInfo(TcpInfo tcpInfo) { this.tcpInfo = tcpInfo; return this; } public Builder addOption(String name, String value) { others.put(name, checkNotNull(value)); return this; } public Builder addOption(String name, int value) { others.put(name, Integer.toString(value)); return this; } public Builder addOption(String name, boolean value) { others.put(name, Boolean.toString(value)); return this; } public SocketOptions build() { return new SocketOptions(timeoutMillis, lingerSeconds, tcpInfo, others); } } } /** * A data
Builder
java
apache__flink
flink-python/src/main/java/org/apache/flink/streaming/api/operators/python/embedded/EmbeddedPythonBatchKeyedCoBroadcastProcessOperator.java
{ "start": 1730, "end": 2896 }
class ____<K, IN1, IN2, OUT> extends EmbeddedPythonKeyedCoProcessOperator<K, IN1, IN2, OUT> implements BoundedMultiInput { private static final long serialVersionUID = 1L; private transient volatile boolean isBroadcastSideDone = false; public EmbeddedPythonBatchKeyedCoBroadcastProcessOperator( Configuration config, DataStreamPythonFunctionInfo pythonFunctionInfo, TypeInformation<IN1> inputTypeInfo1, TypeInformation<IN2> inputTypeInfo2, TypeInformation<OUT> outputTypeInfo) { super(config, pythonFunctionInfo, inputTypeInfo1, inputTypeInfo2, outputTypeInfo); } @Override public void endInput(int inputId) throws Exception { if (inputId == 2) { isBroadcastSideDone = true; } } @Override public void processElement1(StreamRecord<IN1> element) throws Exception { Preconditions.checkState( isBroadcastSideDone, "Should not process regular input before broadcast side is done."); super.processElement1(element); } }
EmbeddedPythonBatchKeyedCoBroadcastProcessOperator
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/authorization/method/PreFilterExpressionAttributeRegistry.java
{ "start": 2391, "end": 2713 }
class ____ extends ExpressionAttribute { private final String filterTarget; private PreFilterExpressionAttribute(Expression expression, String filterTarget) { super(expression); this.filterTarget = filterTarget; } String getFilterTarget() { return this.filterTarget; } } }
PreFilterExpressionAttribute
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/functional/RemoteIterators.java
{ "start": 12135, "end": 13206 }
class ____<T> implements RemoteIterator<T>, IOStatisticsSource, Closeable { /** * inner iterator.. */ private final Iterator<? extends T> source; private final Closeable sourceToClose; /** * Construct from an interator. * @param source source iterator. */ private WrappedJavaIterator(Iterator<? extends T> source) { this.source = requireNonNull(source); sourceToClose = new MaybeClose(source); } @Override public boolean hasNext() { return source.hasNext(); } @Override public T next() { return source.next(); } @Override public IOStatistics getIOStatistics() { return retrieveIOStatistics(source); } @Override public String toString() { return "FromIterator{" + source + '}'; } @Override public void close() throws IOException { sourceToClose.close(); } } /** * Wrapper of another remote iterator; IOStatistics * and Closeable methods are passed down if implemented. * This
WrappedJavaIterator
java
apache__dubbo
dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/CommandLineBuilder.java
{ "start": 920, "end": 991 }
class ____ build the command-line arguments of a java process. */ final
to
java
micronaut-projects__micronaut-core
function/src/main/java/io/micronaut/function/FunctionBean.java
{ "start": 2041, "end": 2209 }
class ____ is the function to invoke. The method should take no more than two arguments * * @return The method name */ String method() default ""; }
that
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/insertordering/InsertOrderingWithCascadeOnPersist.java
{ "start": 2656, "end": 3314 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "ID_TABLE") @TableGenerator(name = "ID_TABLE", pkColumnValue = "MarketBid", allocationSize = 10000) private Long id; private String bidNote; @ManyToOne(optional = false, cascade = CascadeType.PERSIST) private MarketBidGroup group; public Long getId() { return id; } public void setGroup(MarketBidGroup group) { this.group = group; } public String getBidNote() { return bidNote; } public void setBidNote(String bidNote) { this.bidNote = bidNote; } } @Entity(name = "MarketBidGroup") @Access(AccessType.FIELD) public static
MarketBid
java
quarkusio__quarkus
extensions/flyway/deployment/src/test/java/io/quarkus/flyway/test/FlywayExtensionCleanAndMigrateAtStartWithJavaMigrationTest.java
{ "start": 775, "end": 2169 }
class ____ { @Inject Flyway flyway; @Inject AgroalDataSource defaultDataSource; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(V1_0_1__Update.class, V1_0_2__Update.class, V9_9_9__Update.class) .addAsResource("db/migration/V1.0.0__Quarkus.sql") .addAsResource("clean-and-migrate-at-start-config.properties", "application.properties")); @Test @DisplayName("Clean and migrate at start correctly") public void testFlywayConfigInjection() throws SQLException { try (Connection connection = defaultDataSource.getConnection(); Statement stat = connection.createStatement()) { try (ResultSet countQuery = stat.executeQuery("select count(1) from quarked_flyway")) { assertTrue(countQuery.first()); assertEquals(2, countQuery.getInt(1), "Table 'quarked_flyway' does not contain the expected number of rows"); } } String currentVersion = flyway.info().current().getVersion().toString(); assertEquals("1.0.2", currentVersion, "Expected to be 1.0.2 as there is a SQL and two Java migration scripts"); } public static
FlywayExtensionCleanAndMigrateAtStartWithJavaMigrationTest
java
apache__spark
sql/core/src/test/java/test/org/apache/spark/sql/JavaDatasetSuite.java
{ "start": 66686, "end": 67839 }
class ____ implements Serializable { private ArrayList<Integer> arrayList; private LinkedList<Integer> linkedList; private List<Integer> list; public ArrayList<Integer> getArrayList() { return arrayList; } public void setArrayList(ArrayList<Integer> arrayList) { this.arrayList = arrayList; } public LinkedList<Integer> getLinkedList() { return linkedList; } public void setLinkedList(LinkedList<Integer> linkedList) { this.linkedList = linkedList; } public List<Integer> getList() { return list; } public void setList(List<Integer> list) { this.list = list; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SpecificListsBean that = (SpecificListsBean) o; return Objects.equals(arrayList, that.arrayList) && Objects.equals(linkedList, that.linkedList) && Objects.equals(list, that.list); } @Override public int hashCode() { return Objects.hash(arrayList, linkedList, list); } } }
SpecificListsBean
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java
{ "start": 38690, "end": 42242 }
class ____ extends BytesStream { private final BytesStreamOutput output = new BytesStreamOutput(); private final CountingStreamOutput counting = new CountingStreamOutput(); @Override public void writeByte(byte b) { output.writeByte(b); counting.writeByte(b); assertThat((long) output.size(), equalTo(counting.size())); } @Override public void writeBytes(byte[] b, int offset, int length) { output.writeBytes(b, offset, length); counting.writeBytes(b, offset, length); assertThat((long) output.size(), equalTo(counting.size())); } @Override public void writeInt(int i) throws IOException { output.writeInt(i); counting.writeInt(i); assertThat((long) output.size(), equalTo(counting.size())); } @Override public void writeIntArray(int[] values) throws IOException { output.writeIntArray(values); counting.writeIntArray(values); assertThat((long) output.size(), equalTo(counting.size())); } @Override public void writeLong(long i) throws IOException { output.writeLong(i); counting.writeLong(i); assertThat((long) output.size(), equalTo(counting.size())); } @Override public void writeLongArray(long[] values) throws IOException { output.writeLongArray(values); counting.writeLongArray(values); assertThat((long) output.size(), equalTo(counting.size())); } @Override public void writeFloat(float v) throws IOException { output.writeFloat(v); counting.writeFloat(v); assertThat((long) output.size(), equalTo(counting.size())); } @Override public void writeFloatArray(float[] values) throws IOException { output.writeFloatArray(values); counting.writeFloatArray(values); assertThat((long) output.size(), equalTo(counting.size())); } @Override public void writeDouble(double v) throws IOException { output.writeDouble(v); counting.writeDouble(v); assertThat((long) output.size(), equalTo(counting.size())); } @Override public void writeDoubleArray(double[] values) throws IOException { output.writeDoubleArray(values); counting.writeDoubleArray(values); assertThat((long) output.size(), equalTo(counting.size())); } @Override public BytesReference bytes() { BytesReference bytesReference = output.bytes(); assertThat((long) bytesReference.length(), equalTo(counting.size())); return bytesReference; } @Override public void seek(long position) { output.seek(position); } public int size() { int size = output.size(); assertThat((long) size, equalTo(counting.size())); return size; } @Override public void flush() { output.flush(); counting.flush(); assertThat((long) output.size(), equalTo(counting.size())); } @Override public void close() { assertThat((long) output.size(), equalTo(counting.size())); output.close(); counting.close(); } } }
TestStreamOutput
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/util/MRAsyncDiskService.java
{ "start": 1480, "end": 1958 }
class ____ a container of multiple thread pools, each for a volume, * so that we can schedule async disk operations easily. * * Examples of async disk operations are deletion of files. * We can move the files to a "toBeDeleted" folder before asychronously * deleting it, to make sure the caller can run it faster. * * Users should not write files into the "toBeDeleted" folder, otherwise * the files can be gone any time we restart the MRAsyncDiskService. * * This
is
java
apache__kafka
connect/runtime/src/test/resources/test-plugins/bad-packaging/test/plugins/InnocuousSinkConnector.java
{ "start": 1448, "end": 2032 }
class ____ extends SinkConnector { @Override public String version() { return "0.0.0"; } @Override public void start(Map<String, String> props) { } @Override public Class<? extends Task> taskClass() { return InnocuousSinkTask.class; } @Override public List<Map<String, String>> taskConfigs(int maxTasks) { return Collections.emptyList(); } @Override public void stop() { } @Override public ConfigDef config() { return new ConfigDef(); } public static
InnocuousSinkConnector
java
elastic__elasticsearch
modules/apm/src/main/java/org/elasticsearch/telemetry/apm/internal/MetricNameValidator.java
{ "start": 825, "end": 7616 }
class ____ { private static final Pattern ALLOWED_CHARACTERS = Pattern.compile("[a-z][a-z0-9_]*"); static final Set<String> ALLOWED_SUFFIXES = Set.of( "total", "current", "ratio", "status" /*a workaround for enums */, "usage", "size", "utilization", "histogram", "time" ); static final int MAX_METRIC_NAME_LENGTH = 255; static final int MAX_ELEMENT_LENGTH = 30; static final int MAX_NUMBER_OF_ELEMENTS = 10; static final Set<String> SKIP_VALIDATION_METRIC_NAMES_DUE_TO_BWC = Set.of( "searchable_snapshots_cache_fetch_async", "searchable_snapshots_cache_prewarming", "security-token-key", "security-crypto" ); // forbidden attributes known to cause issues due to mapping conflicts or high cardinality static final Predicate<String> FORBIDDEN_ATTRIBUTE_NAMES = Regex.simpleMatcher( "index", // below field names are typically mapped to a timestamp risking mapping errors at ingest time // if values are not valid timestamps (which would be of high cardinality, and not desired either) "*.timestamp", "*_timestamp", "created", "*.created", "*.creation_date", "ingested", "*.ingested", "*.start", "*.end" ); private MetricNameValidator() {} /** * Validates a metric name as per guidelines in Naming.md * * @param metricName metric name to be validated * @throws IllegalArgumentException an exception indicating an incorrect metric name */ public static String validate(String metricName) { Objects.requireNonNull(metricName); if (skipValidationToBWC(metricName)) { return metricName; } validateMaxMetricNameLength(metricName); String[] elements = metricName.split("\\."); hasESPrefix(elements, metricName); hasAtLeast3Elements(elements, metricName); hasNotBreachNumberOfElementsLimit(elements, metricName); lastElementIsFromAllowList(elements, metricName); perElementValidations(elements, metricName); return metricName; } public static boolean validateAttributeNames(Map<String, Object> attributes) { if (attributes == null && attributes.isEmpty()) { return true; } for (String attribute : attributes.keySet()) { if (FORBIDDEN_ATTRIBUTE_NAMES.test(attribute)) { LogManager.getLogger(MetricNameValidator.class) .warn("Attribute name [{}] is forbidden due to potential mapping conflicts or assumed high cardinality", attribute); return false; } } return true; } /** * Due to backwards compatibility some metric names would have to skip validation. * This is for instance where a threadpool name is too long, or contains `-` * We want to allow to easily find threadpools in code base that are alerting with a metric * as well as find thread pools metrics in dashboards with their codebase names. * Renaming a threadpool name would be a breaking change. * * NOTE: only allow skipping validation if a refactor in codebase would cause a breaking change */ private static boolean skipValidationToBWC(String metricName) { return SKIP_VALIDATION_METRIC_NAMES_DUE_TO_BWC.stream().anyMatch(m -> metricName.contains(m)); } private static void validateMaxMetricNameLength(String metricName) { if (metricName.length() > MAX_METRIC_NAME_LENGTH) { throw new IllegalArgumentException( "Metric name length " + metricName.length() + "is longer than max metric name length:" + MAX_METRIC_NAME_LENGTH + " Name was: " + metricName ); } } private static void lastElementIsFromAllowList(String[] elements, String name) { String lastElement = elements[elements.length - 1]; if (ALLOWED_SUFFIXES.contains(lastElement) == false) { throw new IllegalArgumentException( "Metric name should end with one of [" + ALLOWED_SUFFIXES.stream().collect(Collectors.joining(",")) + "] " + "Last element was: " + lastElement + ". " + "Name was: " + name ); } } private static void hasNotBreachNumberOfElementsLimit(String[] elements, String name) { if (elements.length > MAX_NUMBER_OF_ELEMENTS) { throw new IllegalArgumentException( "Metric name should have at most 10 elements. It had: " + elements.length + ". The name was: " + name ); } } private static void hasAtLeast3Elements(String[] elements, String name) { if (elements.length < 3) { throw new IllegalArgumentException( "Metric name consist of at least 3 elements. An es. prefix, group and a name. The name was: " + name ); } } private static void hasESPrefix(String[] elements, String name) { if (elements[0].equals("es") == false) { throw new IllegalArgumentException( "Metric name should start with \"es.\" prefix and use \".\" as a separator. Name was: " + name ); } } private static void perElementValidations(String[] elements, String name) { for (String element : elements) { hasOnlyAllowedCharacters(element, name); hasNotBreachLengthLimit(element, name); } } private static void hasNotBreachLengthLimit(String element, String name) { if (element.length() > MAX_ELEMENT_LENGTH) { throw new IllegalArgumentException( "Metric name's element should not be longer than " + MAX_ELEMENT_LENGTH + " characters. Was: " + element.length() + ". Name was: " + name ); } } private static void hasOnlyAllowedCharacters(String element, String name) { Matcher matcher = ALLOWED_CHARACTERS.matcher(element); if (matcher.matches() == false) { throw new IllegalArgumentException( "Metric name should only use [a-z][a-z0-9_]* characters. " + "Element does not match: \"" + element + "\". " + "Name was: " + name ); } } }
MetricNameValidator
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/client/RestTestClientTests.java
{ "start": 7726, "end": 7962 }
class ____ { @Test void testExpectCookie() { RestTestClientTests.this.client.get().uri("/test") .exchange() .expectCookie().value("session", v -> MatcherAssert.assertThat(v, equalTo("abc"))); } } @Nested
Expectations
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/objectid/TestObjectIdDeserialization.java
{ "start": 3325, "end": 3732 }
class ____ { protected Map<String, AnySetterObjectId> values = new HashMap<String, AnySetterObjectId>(); @JsonAnySetter public void anySet(String field, AnySetterObjectId value) { // Ensure that it is never called with null because of unresolved reference. assertNotNull(value); values.put(field, value); } } static
AnySetterObjectId
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/workload/GaussianTimestampRandomPayloadGenerator.java
{ "start": 1089, "end": 2359 }
class ____ identically to TimestampRandomPayloadGenerator, except the message size follows a gaussian * distribution. * * This should be used in conjunction with TimestampRecordProcessor in the Consumer to measure true end-to-end latency * of a system. * * `messageSizeAverage` - The average size in bytes of each message. * `messageSizeDeviation` - The standard deviation to use when calculating message size. * `messagesUntilSizeChange` - The number of messages to keep at the same size. * `seed` - Used to initialize Random() to remove some non-determinism. * * Here is an example spec: * * { * "type": "gaussianTimestampRandom", * "messageSizeAverage": 512, * "messageSizeDeviation": 100, * "messagesUntilSizeChange": 100 * } * * This will generate messages on a gaussian distribution with an average size each 512-bytes. The message sizes will * have a standard deviation of 100 bytes, and the size will only change every 100 messages. The distribution of * messages will be as follows: * * The average size of the messages are 512 bytes. * ~68% of the messages are between 412 and 612 bytes * ~95% of the messages are between 312 and 712 bytes * ~99% of the messages are between 212 and 812 bytes */ public
behaves
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client-jaxrs/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java
{ "start": 29493, "end": 29746 }
class ____ later used to create a new instance of the response type * and to provide {@link FieldFiller field fillers} that are responsible for setting values for each of the fields and * setters * * @param multipartResponseTypeInfo a
is
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/ExchangeAttribute.java
{ "start": 178, "end": 849 }
interface ____ { /** * Resolve the attribute from the HTTP server exchange. This may return null if the attribute is not present. * * @param exchange The exchange * @return The attribute */ String readAttribute(final RoutingContext exchange); /** * Sets a new value for the attribute. Not all attributes are writable. * * @param exchange The exchange * @param newValue The new value for the attribute * @throws ReadOnlyAttributeException when attribute cannot be written */ void writeAttribute(final RoutingContext exchange, final String newValue) throws ReadOnlyAttributeException; }
ExchangeAttribute
java
google__dagger
javatests/dagger/internal/codegen/InjectConstructorFactoryGeneratorTest.java
{ "start": 30025, "end": 30862 }
class ____ {", " @Inject CheckedExceptionClass() throws Exception {}", "}"); daggerCompiler(file) .withProcessingOptions(ImmutableMap.of("dagger.privateMemberValidation", "WARNING")) .compile( subject -> { subject.hasErrorCount(0); subject.hasWarningCount(1); subject.hasWarningContaining( "Dagger does not support checked exceptions on @Inject constructors") .onSource(file) .onLine(6); }); } @Test public void privateInjectClassError() { Source file = CompilerTests.javaSource( "test.OuterClass", "package test;", "", "import javax.inject.Inject;", "", "final
CheckedExceptionClass
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/text/WordUtils.java
{ "start": 1062, "end": 1549 }
class ____ to handle {@code null} input gracefully. * An exception will not be thrown for a {@code null} input. * Each method documents its behavior in more detail.</p> * * @since 2.0 * @deprecated As of <a href="https://commons.apache.org/proper/commons-lang/changes-report.html#a3.6">3.6</a>, use Apache Commons Text * <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/WordUtils.html"> * WordUtils</a>. */ @Deprecated public
tries
java
resilience4j__resilience4j
resilience4j-rxjava2/src/test/java/io/github/resilience4j/timelimiter/transformer/TimeLimiterTransformerObservableTest.java
{ "start": 1323, "end": 5031 }
class ____ { @Rule public final TestSchedulerRule testSchedulerRule = new TestSchedulerRule(); private final TestScheduler testScheduler = testSchedulerRule.getTestScheduler(); private final TimeLimiter timeLimiter = mock(TimeLimiter.class); @Test public void otherError() { given(timeLimiter.getTimeLimiterConfig()) .willReturn(toConfig(Duration.ZERO)); TestObserver<?> observer = Observable.error(new RuntimeException()) .compose(TimeLimiterTransformer.of(timeLimiter)) .test(); testScheduler.advanceTimeBy(1, TimeUnit.MINUTES); observer.assertError(RuntimeException.class); then(timeLimiter).should() .onError(any(RuntimeException.class)); } @Test public void timeout() { given(timeLimiter.getTimeLimiterConfig()) .willReturn(toConfig(Duration.ZERO)); TestObserver<?> observer = Observable.interval(1, TimeUnit.MINUTES) .compose(TimeLimiterTransformer.of(timeLimiter)) .test(); testScheduler.advanceTimeBy(1, TimeUnit.MINUTES); observer.assertError(TimeoutException.class); then(timeLimiter).should() .onError(any(TimeoutException.class)); } @Test public void timeoutEmpty() { given(timeLimiter.getTimeLimiterConfig()) .willReturn(toConfig(Duration.ZERO)); TestObserver<?> observer = Observable.empty() .delay(1, TimeUnit.MINUTES) .compose(TimeLimiterTransformer.of(timeLimiter)) .test(); testScheduler.advanceTimeBy(1, TimeUnit.MINUTES); observer.assertError(TimeoutException.class); then(timeLimiter).should() .onError(any(TimeoutException.class)); } @Test public void doNotTimeout() { given(timeLimiter.getTimeLimiterConfig()) .willReturn(toConfig(Duration.ofMinutes(1))); TestObserver<?> observer = Observable.interval(1, TimeUnit.SECONDS) .take(2) .compose(TimeLimiterTransformer.of(timeLimiter)) .test(); testScheduler.advanceTimeBy(1, TimeUnit.MINUTES); observer.assertValueCount(2) .assertComplete(); then(timeLimiter).should(times(3)) .onSuccess(); } @Test public void timeoutAfterInitial() throws InterruptedException { int timeout = 2; int initialDelay = 1; int periodDelay = 3; given(timeLimiter.getTimeLimiterConfig()) .willReturn(toConfig(Duration.ofSeconds(timeout))); TestObserver<?> observer = Observable.interval(initialDelay, periodDelay, TimeUnit.SECONDS) .compose(TimeLimiterTransformer.of(timeLimiter)) .test(); testScheduler.advanceTimeBy(1, TimeUnit.MINUTES); observer.await() .assertValueCount(1) .assertError(TimeoutException.class); then(timeLimiter).should() .onSuccess(); then(timeLimiter).should() .onError(any(TimeoutException.class)); } @Test public void doNotTimeoutEmpty() { given(timeLimiter.getTimeLimiterConfig()) .willReturn(toConfig(Duration.ofMinutes(1))); TestObserver<?> observer = Observable.empty() .compose(TimeLimiterTransformer.of(timeLimiter)) .test(); observer.assertComplete(); then(timeLimiter).should() .onSuccess(); } private TimeLimiterConfig toConfig(Duration timeout) { return TimeLimiterConfig.custom() .timeoutDuration(timeout) .build(); } }
TimeLimiterTransformerObservableTest
java
quarkusio__quarkus
extensions/spring-security/deployment/src/main/java/io/quarkus/spring/security/deployment/StringPropertyAccessorGenerator.java
{ "start": 1001, "end": 1083 }
class ____ the following: * * <pre> * &#64;Singleton * public
like
java
qos-ch__slf4j
slf4j-api/src/main/java/org/slf4j/MDC.java
{ "start": 1413, "end": 2357 }
class ____ and serves as a substitute for the underlying logging * system's MDC implementation. * * <p> * If the underlying logging system offers MDC functionality, then SLF4J's MDC, * i.e. this class, will delegate to the underlying system's MDC. Note that at * this time, only two logging systems, namely log4j and logback, offer MDC * functionality. For java.util.logging which does not support MDC, * {@link BasicMDCAdapter} will be used. For other systems, i.e. slf4j-simple * and slf4j-nop, {@link NOPMDCAdapter} will be used. * * <p> * Thus, as a SLF4J user, you can take advantage of MDC in the presence of log4j, * logback, or java.util.logging, but without forcing these systems as * dependencies upon your users. * * <p> * For more information on MDC please see the <a * href="http://logback.qos.ch/manual/mdc.html">chapter on MDC</a> in the * logback manual. * * <p> * Please note that all methods in this
hides
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/utils/PojoUtilsTest.java
{ "start": 45250, "end": 45506 }
class ____<T> implements Serializable { private List<T> list; public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } } public static
InnerPojo
java
quarkusio__quarkus
integration-tests/picocli/src/test/java/io/quarkus/it/picocli/TestTopCommand.java
{ "start": 279, "end": 713 }
class ____ { @RegisterExtension static final QuarkusProdModeTest config = createConfig("goodbye-app", GoodbyeCommand.class, EntryCommand.class) .setCommandLineParameters("goodbye"); @Test public void simpleTest() { Assertions.assertThat(config.getStartupConsoleOutput()).containsOnlyOnce("Goodbye was requested!"); Assertions.assertThat(config.getExitCode()).isZero(); } }
TestTopCommand
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/internal/util/collections/BoundedConcurrentHashMap.java
{ "start": 24219, "end": 31490 }
class ____<K, V> implements EvictionPolicy<K, V> { /** * The percentage of the cache which is dedicated to hot blocks. * See section 5.1 */ private static final float L_LIRS = 0.95f; /** * The owning segment */ private final Segment<K, V> segment; /** * The accessQueue for reducing lock contention * See "BP-Wrapper: a system framework making any replacement algorithms * (almost) lock contention free" * <p> * http://www.cse.ohio-state.edu/hpcs/WWW/HTML/publications/abs09-1.html */ private final ConcurrentLinkedQueue<LIRSHashEntry<K, V>> accessQueue; private final AtomicInteger accessQueueSize; /** * The maxBatchQueueSize * <p> * See "BP-Wrapper: a system framework making any replacement algorithms (almost) lock * contention free" */ private final int maxBatchQueueSize; /** * The number of LIRS entries in a segment */ private int size; private final float batchThresholdFactor; /** * This header encompasses two data structures: * <p> * <ul> * <li>The LIRS stack, S, which is maintains recency information. All hot * entries are on the stack. All cold and non-resident entries which are more * recent than the least recent hot entry are also stored in the stack (the * stack is always pruned such that the last entry is hot, and all entries * accessed more recently than the last hot entry are present in the stack). * The stack is ordered by recency, with its most recently accessed entry * at the top, and its least recently accessed entry at the bottom.</li> * <li>The LIRS queue, Q, which enqueues all cold entries for eviction. Cold * entries (by definition in the queue) may be absent from the stack (due to * pruning of the stack). Cold entries are added to the end of the queue * and entries are evicted from the front of the queue.</li> * </ul> */ private final LIRSHashEntry<K, V> header = new LIRSHashEntry<>( null, null, 0, null, null ); /** * The maximum number of hot entries (L_lirs in the paper). */ private final int maximumHotSize; /** * The maximum number of resident entries (L in the paper). */ private final int maximumSize; /** * The actual number of hot entries. */ private int hotSize; LIRS(Segment<K, V> s, int capacity, int maxBatchSize, float batchThresholdFactor) { this.segment = s; this.maximumSize = capacity; this.maximumHotSize = calculateLIRSize( capacity ); this.maxBatchQueueSize = Math.min( maxBatchSize, MAX_BATCH_SIZE ); this.batchThresholdFactor = batchThresholdFactor; this.accessQueue = new ConcurrentLinkedQueue<LIRSHashEntry<K, V>>(); this.accessQueueSize = new AtomicInteger(); } private static int calculateLIRSize(int maximumSize) { int result = (int) ( L_LIRS * maximumSize ); return ( result == maximumSize ) ? maximumSize - 1 : result; } @Override public void execute() { assert segment.isHeldByCurrentThread(); Set<HashEntry<K, V>> evicted = new HashSet<>(); int removed = 0; try { LIRSHashEntry<K, V> e; while ( (e = accessQueue.poll()) != null ) { removed++; if ( e.isResident() ) { e.hit( evicted ); } } removeFromSegment( evicted ); } finally { // guarantee that under OOM size won't be broken accessQueueSize.addAndGet(-removed); } } /** * Prunes HIR blocks in the bottom of the stack until an HOT block sits in * the stack bottom. If pruned blocks were resident, then they * remain in the queue; otherwise they are no longer referenced, and are thus * removed from the backing map. */ private void pruneStack(Set<HashEntry<K, V>> evicted) { // See section 3.3: // "We define an operation called "stack pruning" on the LIRS // stack S, which removes the HIR blocks in the bottom of // the stack until an LIR block sits in the stack bottom. This // operation serves for two purposes: (1) We ensure the block in // the bottom of the stack always belongs to the LIR block set. // (2) After the LIR block in the bottom is removed, those HIR // blocks contiguously located above it will not have chances to // change their status from HIR to LIR, because their recencies // are larger than the new maximum recency of LIR blocks." LIRSHashEntry<K, V> bottom = stackBottom(); while ( bottom != null && bottom.state != Recency.LIR_RESIDENT ) { bottom.removeFromStack(); if ( bottom.state == Recency.HIR_NONRESIDENT ) { evicted.add( bottom ); } bottom = stackBottom(); } } @Override public void onEntryMiss(HashEntry<K, V> en) { LIRSHashEntry<K, V> e = (LIRSHashEntry<K, V>) en; Set<HashEntry<K, V>> evicted = e.miss(); removeFromSegment( evicted ); } private void removeFromSegment(Set<HashEntry<K, V>> evicted) { for ( HashEntry<K, V> e : evicted ) { ( (LIRSHashEntry<K, V>) e ).evict(); segment.remove( e.key, e.hash, null ); } } /* * Invoked without holding a lock on Segment */ @Override public boolean onEntryHit(HashEntry<K, V> e) { accessQueue.add( (LIRSHashEntry<K, V>) e ); // counter-intuitive: // Why not placing this *before* appending the entry to the access queue? // we don't want the eviction to kick-in if the access queue doesn't contain enough entries. final int size = accessQueueSize.incrementAndGet(); return size >= maxBatchQueueSize * batchThresholdFactor; } /* * Invoked without holding a lock on Segment */ @Override public boolean thresholdExpired() { return accessQueueSize.get() >= maxBatchQueueSize; } @Override public void onEntryRemove(HashEntry<K, V> e) { assert segment.isHeldByCurrentThread(); ( (LIRSHashEntry<K, V>) e ).remove(); int removed = 0; // we could have multiple instances of e in accessQueue; remove them all while ( accessQueue.remove( e ) ) { removed++; } accessQueueSize.addAndGet(-removed); } @Override public void clear() { assert segment.isHeldByCurrentThread(); int removed = 0; while (accessQueue.poll() != null) { removed++; } accessQueueSize.addAndGet(-removed); } @Override public Eviction strategy() { return Eviction.LIRS; } /** * Returns the entry at the bottom of the stack. */ private LIRSHashEntry<K, V> stackBottom() { LIRSHashEntry<K, V> bottom = header.previousInStack; return ( bottom == header ) ? null : bottom; } /** * Returns the entry at the front of the queue. */ private LIRSHashEntry<K, V> queueFront() { LIRSHashEntry<K, V> front = header.nextInQueue; return ( front == header ) ? null : front; } /** * Returns the entry at the end of the queue. */ private LIRSHashEntry<K, V> queueEnd() { LIRSHashEntry<K, V> end = header.previousInQueue; return ( end == header ) ? null : end; } @Override public HashEntry<K, V> createNewEntry(K key, int hash, HashEntry<K, V> next, V value) { return new LIRSHashEntry<>( this, key, hash, next, value ); } } /** * Segments are specialized versions of hash tables. This * subclasses from ReentrantLock opportunistically, just to * simplify some locking and avoid separate construction. */ static final
LIRS
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/workload/SustainedConnectionWorker.java
{ "start": 2589, "end": 6297 }
class ____ implements TaskWorker { private static final Logger log = LoggerFactory.getLogger(SustainedConnectionWorker.class); // This is the metadata for the test itself. private final String id; private final SustainedConnectionSpec spec; // These variables are used to maintain the connections. private static final int BACKOFF_PERIOD_MS = 10; private ExecutorService workerExecutor; private final AtomicBoolean running = new AtomicBoolean(false); private KafkaFutureImpl<String> doneFuture; private ArrayList<SustainedConnection> connections; // These variables are used when tracking the reported status of the worker. private static final int REPORT_INTERVAL_MS = 5000; private WorkerStatusTracker status; private AtomicLong totalProducerConnections; private AtomicLong totalProducerFailedConnections; private AtomicLong totalConsumerConnections; private AtomicLong totalConsumerFailedConnections; private AtomicLong totalMetadataConnections; private AtomicLong totalMetadataFailedConnections; private AtomicLong totalAbortedThreads; private Future<?> statusUpdaterFuture; private ScheduledExecutorService statusUpdaterExecutor; public SustainedConnectionWorker(String id, SustainedConnectionSpec spec) { this.id = id; this.spec = spec; } @Override public void start(Platform platform, WorkerStatusTracker status, KafkaFutureImpl<String> doneFuture) throws Exception { if (!running.compareAndSet(false, true)) { throw new IllegalStateException("SustainedConnectionWorker is already running."); } log.info("{}: Activating SustainedConnectionWorker with {}", this.id, this.spec); this.doneFuture = doneFuture; this.status = status; this.connections = new ArrayList<>(); // Initialize all status reporting metrics to 0. this.totalProducerConnections = new AtomicLong(0); this.totalProducerFailedConnections = new AtomicLong(0); this.totalConsumerConnections = new AtomicLong(0); this.totalConsumerFailedConnections = new AtomicLong(0); this.totalMetadataConnections = new AtomicLong(0); this.totalMetadataFailedConnections = new AtomicLong(0); this.totalAbortedThreads = new AtomicLong(0); // Create the worker classes and add them to the list of items to act on. for (int i = 0; i < this.spec.producerConnectionCount(); i++) { this.connections.add(new ProducerSustainedConnection()); } for (int i = 0; i < this.spec.consumerConnectionCount(); i++) { this.connections.add(new ConsumerSustainedConnection()); } for (int i = 0; i < this.spec.metadataConnectionCount(); i++) { this.connections.add(new MetadataSustainedConnection()); } // Create the status reporter thread and schedule it. this.statusUpdaterExecutor = Executors.newScheduledThreadPool(1, ThreadUtils.createThreadFactory("StatusUpdaterWorkerThread%d", false)); this.statusUpdaterFuture = this.statusUpdaterExecutor.scheduleAtFixedRate( new StatusUpdater(), 0, REPORT_INTERVAL_MS, TimeUnit.MILLISECONDS); // Create the maintainer pool, add all the maintainer threads, then start it. this.workerExecutor = Executors.newFixedThreadPool(spec.numThreads(), ThreadUtils.createThreadFactory("SustainedConnectionWorkerThread%d", false)); for (int i = 0; i < this.spec.numThreads(); i++) { this.workerExecutor.submit(new MaintainLoop()); } } private
SustainedConnectionWorker
java
spring-projects__spring-boot
module/spring-boot-jersey/src/main/java/org/springframework/boot/jersey/autoconfigure/actuate/web/JerseyManagementContextConfiguration.java
{ "start": 1226, "end": 1556 }
class ____ { @Bean ServletRegistrationBean<ServletContainer> jerseyServletRegistration(JerseyApplicationPath jerseyApplicationPath, ResourceConfig resourceConfig) { return new ServletRegistrationBean<>(new ServletContainer(resourceConfig), jerseyApplicationPath.getUrlMapping()); } }
JerseyManagementContextConfiguration
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/authorization/method/PreAuthorizeAuthorizationManagerTests.java
{ "start": 9506, "end": 9622 }
interface ____ { @PreAuthorize("hasRole('USER')") void inheritedAnnotations(); } public
InterfaceAnnotationsTwo
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/InterfaceWithOnlyStaticsTest.java
{ "start": 3964, "end": 4200 }
interface ____ { int foo = 42; static int bar() { return 1; } } """) .addOutputLines( "Test.java", """ final
Test
java
apache__avro
lang/java/perf/src/main/java/org/apache/avro/perf/test/reflect/ReflectLongArrayTest.java
{ "start": 3347, "end": 4695 }
class ____ extends BasicArrayState { private final Schema schema; private byte[] testData; private Decoder decoder; public TestStateDecode() { super(ARRAY_SIZE); final String jsonText = ReflectData.get().getSchema(long[].class).toString(); this.schema = new Schema.Parser().parse(jsonText); } /** * Generate test data. * * @throws IOException Could not setup test data */ @Setup(Level.Trial) public void doSetupTrial() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Encoder encoder = super.newEncoder(true, baos); ReflectDatumWriter<long[]> writer = new ReflectDatumWriter<>(schema); for (int i = 0; i < getBatchSize(); i++) { final long[] r = populateDoubleArray(getRandom(), getArraySize()); writer.write(r, encoder); } this.testData = baos.toByteArray(); } @Setup(Level.Invocation) public void doSetupInvocation() throws Exception { this.decoder = DecoderFactory.get().validatingDecoder(schema, super.newDecoder(this.testData)); } } static long[] populateDoubleArray(final Random r, final int size) { long[] result = new long[size]; for (int i = 0; i < result.length; i++) { result[i] = r.nextLong(); } return result; } }
TestStateDecode
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/TopicPartitionInfo.java
{ "start": 1051, "end": 1335 }
class ____ { private final int partition; private final Node leader; private final List<Node> replicas; private final List<Node> isr; private final List<Node> elr; private final List<Node> lastKnownElr; /** * Create an instance of this
TopicPartitionInfo
java
google__guava
android/guava/src/com/google/common/collect/Maps.java
{ "start": 157021, "end": 161405 }
class ____ extends EntrySet<K, V> { @Override Map<K, V> map() { return DescendingMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return entryIterator(); } } return new EntrySetImpl(); } @Override public Set<K> keySet() { return navigableKeySet(); } @LazyInit private transient @Nullable NavigableSet<K> navigableKeySet; @Override public NavigableSet<K> navigableKeySet() { NavigableSet<K> result = navigableKeySet; return (result == null) ? navigableKeySet = new NavigableKeySet<>(this) : result; } @Override public NavigableSet<K> descendingKeySet() { return forward().navigableKeySet(); } @Override public NavigableMap<K, V> subMap( @ParametricNullness K fromKey, boolean fromInclusive, @ParametricNullness K toKey, boolean toInclusive) { return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap(); } @Override public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { return subMap(fromKey, true, toKey, false); } @Override public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) { return forward().tailMap(toKey, inclusive).descendingMap(); } @Override public SortedMap<K, V> headMap(@ParametricNullness K toKey) { return headMap(toKey, false); } @Override public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) { return forward().headMap(fromKey, inclusive).descendingMap(); } @Override public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) { return tailMap(fromKey, true); } @Override public Collection<V> values() { return new Values<>(this); } @Override public String toString() { return standardToString(); } } /** Returns a map from the ith element of list to i. */ static <E> ImmutableMap<E, Integer> indexMap(Collection<E> list) { ImmutableMap.Builder<E, Integer> builder = new ImmutableMap.Builder<>(list.size()); int i = 0; for (E e : list) { builder.put(e, i++); } return builder.buildOrThrow(); } /** * Returns a view of the portion of {@code map} whose keys are contained by {@code range}. * * <p>This method delegates to the appropriate methods of {@link NavigableMap} (namely {@link * NavigableMap#subMap(Object, boolean, Object, boolean) subMap()}, {@link * NavigableMap#tailMap(Object, boolean) tailMap()}, and {@link NavigableMap#headMap(Object, * boolean) headMap()}) to actually construct the view. Consult these methods for a full * description of the returned view's behavior. * * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural * ordering. {@code NavigableMap} on the other hand can specify a custom ordering via a {@link * Comparator}, which can violate the natural ordering. Using this method (or in general using * {@code Range}) with unnaturally-ordered maps can lead to unexpected and undefined behavior. * * @since 20.0 */ @GwtIncompatible // NavigableMap public static <K extends Comparable<? super K>, V extends @Nullable Object> NavigableMap<K, V> subMap(NavigableMap<K, V> map, Range<K> range) { if (map.comparator() != null && map.comparator() != Ordering.natural() && range.hasLowerBound() && range.hasUpperBound()) { checkArgument( map.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0, "map is using a custom comparator which is inconsistent with the natural ordering."); } if (range.hasLowerBound() && range.hasUpperBound()) { return map.subMap( range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED, range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED); } else if (range.hasLowerBound()) { return map.tailMap(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED); } else if (range.hasUpperBound()) { return map.headMap(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED); } return checkNotNull(map); } }
EntrySetImpl
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/ttl/TtlStateContext.java
{ "start": 978, "end": 1860 }
class ____<T, SV> { /** Wrapped original state handler. */ public final T original; public final StateTtlConfig config; public final TtlTimeProvider timeProvider; /** Serializer of original user stored value without timestamp. */ public final TypeSerializer<SV> valueSerializer; /** This registered callback is to be called whenever state is accessed for read or write. */ public final Runnable accessCallback; public TtlStateContext( T original, StateTtlConfig config, TtlTimeProvider timeProvider, TypeSerializer<SV> valueSerializer, Runnable accessCallback) { this.original = original; this.config = config; this.timeProvider = timeProvider; this.valueSerializer = valueSerializer; this.accessCallback = accessCallback; } }
TtlStateContext
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/api/operators/windowing/functions/InternalWindowFunctionTest.java
{ "start": 28199, "end": 28909 }
class ____ extends ProcessWindowFunction<Map<Long, Long>, String, Long, TimeWindow> implements OutputTypeConfigurable<String> { private static final long serialVersionUID = 1L; @Override public void setOutputType( TypeInformation<String> outTypeInfo, ExecutionConfig executionConfig) {} @Override public void process( Long aLong, ProcessWindowFunction<Map<Long, Long>, String, Long, TimeWindow>.Context context, Iterable<Map<Long, Long>> elements, Collector<String> out) throws Exception {} } private static
AggregateProcessWindowFunctionMock
java
apache__camel
core/camel-core-reifier/src/main/java/org/apache/camel/reifier/language/MethodCallExpressionReifier.java
{ "start": 1100, "end": 2394 }
class ____ extends TypedExpressionReifier<MethodCallExpression> { public MethodCallExpressionReifier(CamelContext camelContext, ExpressionDefinition definition) { super(camelContext, definition); } @Override protected Object[] createProperties() { Object[] properties = new Object[7]; properties[0] = asResultType(); properties[1] = definition.getInstance(); properties[2] = parseString(definition.getMethod()); properties[3] = definition.getBeanType(); properties[4] = parseString(definition.getRef()); properties[5] = parseString(definition.getScope()); properties[6] = parseString(definition.getValidate()); return properties; } @Override protected void configureLanguage(Language language) { super.configureLanguage(language); if (definition.getBeanType() == null && definition.getBeanTypeName() != null) { try { Class<?> clazz = camelContext.getClassResolver().resolveMandatoryClass(definition.getBeanTypeName()); definition.setBeanType(clazz); } catch (ClassNotFoundException e) { throw RuntimeCamelException.wrapRuntimeException(e); } } } }
MethodCallExpressionReifier
java
spring-projects__spring-boot
module/spring-boot-hazelcast/src/test/java/org/springframework/boot/hazelcast/testcontainers/HazelcastContainerConnectionDetailsFactoryTests.java
{ "start": 1157, "end": 1461 }
class ____ { @Test void shouldRegisterHints() { RuntimeHints hints = ContainerConnectionDetailsFactoryHints.getRegisteredHints(getClass().getClassLoader()); assertThat(RuntimeHintsPredicates.reflection().onType(ClientConfig.class)).accepts(hints); } }
HazelcastContainerConnectionDetailsFactoryTests
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/support/DirtiesContextTestExecutionListenerTests.java
{ "start": 18524, "end": 18669 }
class ____ { void test() { } } @NestedTestConfiguration(OVERRIDE) @DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
InheritedConfig
java
micronaut-projects__micronaut-core
http/src/test/java/io/micronaut/http/util/HtmlEntityEncodingHtmlSanitizerTest.java
{ "start": 273, "end": 1648 }
class ____ { @Test void sanitize() { HtmlEntityEncodingHtmlSanitizer sanitizer = new HtmlEntityEncodingHtmlSanitizer(); String html = sanitizer.sanitize("<b>Hello, World!</b>"); assertEquals("&lt;b&gt;Hello, World!&lt;/b&gt;", html); html = sanitizer.sanitize("\"Hello, World!\""); assertEquals("&quot;Hello, World!&quot;", html); html = sanitizer.sanitize("'Hello, World!'"); assertEquals("&#x27;Hello, World!&#x27;", html); assertEquals("", sanitizer.sanitize(null)); } @Test void beanOfHtmlSanitizerExistsAndItDefaultsToHtmlEntityEncodingHtmlSanitizer() { try (ApplicationContext ctx = ApplicationContext.run()) { assertTrue(ctx.containsBean(HtmlSanitizer.class)); assertTrue(ctx.getBean(HtmlSanitizer.class) instanceof HtmlEntityEncodingHtmlSanitizer); } } @Test void itIsEasyToProvideYourOwnBeanOfTypeHtmlSanitizer() { try (ApplicationContext ctx = ApplicationContext.run(Map.of("spec.name", "HtmlSanitizerReplacement"))) { assertTrue(ctx.containsBean(HtmlSanitizer.class)); assertTrue(ctx.getBean(HtmlSanitizer.class) instanceof BogusHtmlSanitizer); } } @Singleton @Requires(property = "spec.name", value = "HtmlSanitizerReplacement") static
HtmlEntityEncodingHtmlSanitizerTest