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
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/tool/schema/spi/SchemaFilter.java
{ "start": 470, "end": 1651 }
interface ____ { /** * Should the given namespace (catalog+schema) be included? If {@code true}, the * namespace will be further processed; if {@code false}, processing will skip this * namespace. * * @param namespace The namespace to check for inclusion. * * @return {@code true} to include the namespace; {@code false} otherwise */ boolean includeNamespace(Namespace namespace); /** * Should the given table be included? If {@code true}, the * table will be further processed; if {@code false}, processing will skip this * table. * * @param table The table to check for inclusion * * @return {@code true} to include the table; {@code false} otherwise */ boolean includeTable(Table table); /** * Should the given sequence be included? If {@code true}, the * sequence will be further processed; if {@code false}, processing will skip this * sequence. * * @param sequence The sequence to check for inclusion * * @return {@code true} to include the sequence; {@code false} otherwise */ boolean includeSequence(Sequence sequence); /** * Matches everything */ SchemaFilter ALL = DefaultSchemaFilter.INSTANCE; }
SchemaFilter
java
resilience4j__resilience4j
resilience4j-spring-boot2/src/main/java/io/github/resilience4j/fallback/autoconfigure/FallbackConfigurationOnMissingBean.java
{ "start": 1721, "end": 3492 }
class ____ { private final FallbackConfiguration fallbackConfiguration; public FallbackConfigurationOnMissingBean() { this.fallbackConfiguration = new FallbackConfiguration(); } @Bean @ConditionalOnMissingBean @Conditional(value = {AspectJOnClasspathCondition.class}) public FallbackDecorators fallbackDecorators(@Autowired(required = false) List<FallbackDecorator> fallbackDecorators) { return fallbackConfiguration.fallbackDecorators(fallbackDecorators); } @Bean @ConditionalOnMissingBean @Conditional(value = {AspectJOnClasspathCondition.class}) public FallbackExecutor fallbackExecutor(SpelResolver spelResolver, FallbackDecorators fallbackDecorators) { return fallbackConfiguration.fallbackExecutor(spelResolver, fallbackDecorators); } @Bean @Conditional(value = {RxJava2OnClasspathCondition.class}) @ConditionalOnMissingBean public RxJava2FallbackDecorator rxJava2FallbackDecorator() { return fallbackConfiguration.rxJava2FallbackDecorator(); } @Bean @Conditional(value = {RxJava3OnClasspathCondition.class}) @ConditionalOnMissingBean public RxJava3FallbackDecorator rxJava3FallbackDecorator() { return fallbackConfiguration.rxJava3FallbackDecorator(); } @Bean @Conditional(value = {ReactorOnClasspathCondition.class}) @ConditionalOnMissingBean public ReactorFallbackDecorator reactorFallbackDecorator() { return fallbackConfiguration.reactorFallbackDecorator(); } @Bean @ConditionalOnMissingBean public CompletionStageFallbackDecorator completionStageFallbackDecorator() { return fallbackConfiguration.completionStageFallbackDecorator(); } }
FallbackConfigurationOnMissingBean
java
apache__camel
components/camel-test/camel-test-main-junit5/src/test/java/org/apache/camel/test/main/junit5/annotation/TestInstancePerMethodTest.java
{ "start": 1428, "end": 1654 }
class ____ that a new camel context is created for each test method. */ @CamelMainTest(mainClass = MyMainClass.class) @TestInstance(TestInstance.Lifecycle.PER_METHOD) @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
ensuring
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/DelegationTokenRenewer.java
{ "start": 10980, "end": 12973 }
class ____ { public final Token<?> token; public final Collection<ApplicationId> referringAppIds; public final Configuration conf; public long expirationDate; public RenewalTimerTask timerTask; public volatile boolean shouldCancelAtEnd; public long maxDate; public String user; public DelegationTokenToRenew(Collection<ApplicationId> applicationIds, Token<?> token, Configuration conf, long expirationDate, boolean shouldCancelAtEnd, String user) { this.token = token; this.user = user; if (token.getKind().equals(HDFS_DELEGATION_KIND)) { try { AbstractDelegationTokenIdentifier identifier = (AbstractDelegationTokenIdentifier) token.decodeIdentifier(); maxDate = identifier.getMaxDate(); } catch (IOException e) { throw new YarnRuntimeException(e); } } this.referringAppIds = Collections.synchronizedSet( new HashSet<ApplicationId>(applicationIds)); this.conf = conf; this.expirationDate = expirationDate; this.timerTask = null; this.shouldCancelAtEnd = shouldCancelAtEnd | alwaysCancelDelegationTokens; } public void setTimerTask(RenewalTimerTask tTask) { timerTask = tTask; } @VisibleForTesting public void cancelTimer() { if (timerTask != null) { timerTask.cancel(); } } @VisibleForTesting public boolean isTimerCancelled() { return (timerTask != null) && timerTask.cancelled.get(); } @Override public String toString() { return token + ";exp=" + expirationDate + "; apps=" + referringAppIds; } @Override public boolean equals(Object obj) { return obj instanceof DelegationTokenToRenew && token.equals(((DelegationTokenToRenew)obj).token); } @Override public int hashCode() { return token.hashCode(); } } private static
DelegationTokenToRenew
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/ui/ExtendedModelMap.java
{ "start": 1288, "end": 2181 }
class ____ extends ModelMap implements Model { @Override public ExtendedModelMap addAttribute(String attributeName, @Nullable Object attributeValue) { super.addAttribute(attributeName, attributeValue); return this; } @Override public ExtendedModelMap addAttribute(Object attributeValue) { super.addAttribute(attributeValue); return this; } @Override public ExtendedModelMap addAllAttributes(@Nullable Collection<?> attributeValues) { super.addAllAttributes(attributeValues); return this; } @Override public ExtendedModelMap addAllAttributes(@Nullable Map<String, ?> attributes) { super.addAllAttributes(attributes); return this; } @Override public ExtendedModelMap mergeAttributes(@Nullable Map<String, ?> attributes) { super.mergeAttributes(attributes); return this; } @Override public Map<String, Object> asMap() { return this; } }
ExtendedModelMap
java
grpc__grpc-java
binder/src/test/java/io/grpc/binder/PeerUidsTest.java
{ "start": 4406, "end": 4916 }
class ____ implements MethodDescriptor.Marshaller<String> { public static final StringMarshaller INSTANCE = new StringMarshaller(); @Override public InputStream stream(String value) { return new ByteArrayInputStream(value.getBytes(UTF_8)); } @Override public String parse(InputStream stream) { try { return new String(ByteStreams.toByteArray(stream), UTF_8); } catch (IOException ex) { throw new RuntimeException(ex); } } } }
StringMarshaller
java
apache__camel
components/camel-resilience4j/src/main/java/org/apache/camel/component/resilience4j/ResilienceProcessor.java
{ "start": 24285, "end": 31631 }
class ____ implements PooledExchangeTask, Function<Throwable, Exchange> { private Exchange exchange; @Override public void prepare(Exchange exchange, AsyncCallback callback) { this.exchange = exchange; // callback not in use } @Override public void reset() { this.exchange = null; } @Override public void run() { // not in use } @Override public Exchange apply(Throwable throwable) { String state = circuitBreaker.getState().name(); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_STATE, state); // check again if we should ignore or not record the throw exception as a failure if (ignorePredicate != null && ignorePredicate.test(throwable)) { if (LOG.isTraceEnabled()) { LOG.trace("Processing exchange: {} recover task using circuit breaker ({}):{} ignored exception: {}", exchange.getExchangeId(), state, id, throwable); } // exception should be ignored exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_IGNORED, true); exchange.setException(null); return exchange; } if (recordPredicate != null && !recordPredicate.test(throwable)) { if (LOG.isTraceEnabled()) { LOG.trace("Processing exchange: {} recover task using circuit breaker ({}):{} success exception: {}", exchange.getExchangeId(), state, id, throwable); } // exception is a success exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, true); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, false); exchange.setException(null); return exchange; } if (LOG.isTraceEnabled()) { LOG.trace("Processing exchange: {} recover task using circuit breaker ({}):{} failed exception: {}", exchange.getExchangeId(), state, id, throwable); } if (fallback == null) { if (throwable instanceof TimeoutException) { // the circuit breaker triggered a timeout (and there is no // fallback) so lets mark the exchange as failed exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_TIMED_OUT, true); exchange.setException(throwable); return exchange; } else if (throwable instanceof CallNotPermittedException) { // the circuit breaker triggered a call rejected exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, true); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_REJECTED, true); if (throwExceptionWhenHalfOpenOrOpenState) { exchange.setException(throwable); } return exchange; } else if (throwable instanceof BulkheadFullException) { // the circuit breaker bulkhead is full exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, true); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_REJECTED, true); exchange.setException(throwable); return exchange; } else { // other kind of exception exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, true); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_REJECTED, true); exchange.setException(throwable); return exchange; } } // fallback route is handling the exception so its short-circuited exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SUCCESSFUL_EXECUTION, false); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_FROM_FALLBACK, true); exchange.setProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_SHORT_CIRCUITED, true); // store the last to endpoint as the failure endpoint if (exchange.getProperty(ExchangePropertyKey.FAILURE_ENDPOINT) == null) { exchange.setProperty(ExchangePropertyKey.FAILURE_ENDPOINT, exchange.getProperty(ExchangePropertyKey.TO_ENDPOINT)); } // give the rest of the pipeline another chance exchange.setProperty(ExchangePropertyKey.EXCEPTION_HANDLED, true); exchange.setProperty(ExchangePropertyKey.EXCEPTION_CAUGHT, exchange.getException()); exchange.setRouteStop(false); exchange.setException(null); // and we should not be regarded as exhausted as we are in a try .. // catch block exchange.getExchangeExtension().setRedeliveryExhausted(false); // run the fallback processor try { if (LOG.isTraceEnabled()) { LOG.trace("Processing exchange: {} using circuit breaker ({}):{} with fallback: {}", exchange.getExchangeId(), state, id, fallback); } // process the fallback until its fully done fallback.process(exchange); } catch (Throwable e) { exchange.setException(e); } return exchange; } } }
CircuitBreakerFallbackTask
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/ott/OneTimeTokenLoginConfigurerTests.java
{ "start": 15329, "end": 15525 }
class ____ { @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager(PasswordEncodedUser.user(), PasswordEncodedUser.admin()); } } }
UserDetailsServiceConfig
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AzureDFSIngressHandler.java
{ "start": 1657, "end": 11572 }
class ____ extends AzureIngressHandler { private static final Logger LOG = LoggerFactory.getLogger( AbfsOutputStream.class); private AzureDFSBlockManager dfsBlockManager; private final AbfsDfsClient dfsClient; private String eTag; /** * Constructs an AzureDFSIngressHandler. * * @param abfsOutputStream the AbfsOutputStream instance. * @param clientHandler the AbfsClientHandler instance. */ public AzureDFSIngressHandler(AbfsOutputStream abfsOutputStream, AbfsClientHandler clientHandler) { super(abfsOutputStream); this.dfsClient = clientHandler.getDfsClient(); } /** * Constructs an AzureDFSIngressHandler with specified parameters. * * @param abfsOutputStream the AbfsOutputStream. * @param blockFactory the block factory. * @param bufferSize the buffer size. * @param eTag the eTag. * @param clientHandler the client handler. */ public AzureDFSIngressHandler(AbfsOutputStream abfsOutputStream, DataBlocks.BlockFactory blockFactory, int bufferSize, String eTag, AbfsClientHandler clientHandler) { this(abfsOutputStream, clientHandler); this.eTag = eTag; this.dfsBlockManager = new AzureDFSBlockManager(abfsOutputStream, blockFactory, bufferSize); LOG.trace( "Created a new DFSIngress Handler for AbfsOutputStream instance {} for path {}", abfsOutputStream.getStreamID(), abfsOutputStream.getPath()); } /** * Buffers data into the specified block. * * @param block the block to buffer data into. * @param data the data to be buffered. * @param off the start offset in the data. * @param length the number of bytes to buffer. * @return the number of bytes buffered. * @throws IOException if an I/O error occurs. */ @Override public int bufferData(AbfsBlock block, final byte[] data, final int off, final int length) throws IOException { LOG.trace("Buffering data of length {} to block at offset {}", length, off); return block.write(data, off, length); } /** * Performs a remote write operation. * * @param blockToUpload the block to upload. * @param uploadData the data to upload. * @param reqParams the request parameters. * @param tracingContext the tracing context. * @return the resulting AbfsRestOperation. * @throws IOException if an I/O error occurs. */ @Override protected AbfsRestOperation remoteWrite(AbfsBlock blockToUpload, DataBlocks.BlockUploadData uploadData, AppendRequestParameters reqParams, TracingContext tracingContext) throws IOException { TracingContext tracingContextAppend = new TracingContext(tracingContext); String threadIdStr = String.valueOf(Thread.currentThread().getId()); if (tracingContextAppend.getIngressHandler().equals(EMPTY_STRING)) { tracingContextAppend.setIngressHandler(DFS_APPEND + " T " + threadIdStr); tracingContextAppend.setPosition( String.valueOf(blockToUpload.getOffset())); } LOG.trace("Starting remote write for block with offset {} and path {}", blockToUpload.getOffset(), getAbfsOutputStream().getPath()); return getClient().append(getAbfsOutputStream().getPath(), uploadData.toByteArray(), reqParams, getAbfsOutputStream().getCachedSasTokenString(), getAbfsOutputStream().getContextEncryptionAdapter(), tracingContextAppend); } /** * Method to perform a remote write operation for appending data to an append blob in Azure Blob Storage. * * <p>This method is intended to be implemented by subclasses to handle the specific * case of appending data to an append blob. It takes in the path of the append blob, * the data to be uploaded, the block of data, and additional parameters required for * the append operation.</p> * * @param path The path of the append blob to which data is to be appended. * @param uploadData The data to be uploaded as part of the append operation. * @param block The block of data to append. * @param reqParams The additional parameters required for the append operation. * @param tracingContext The tracing context for the operation. * @return An {@link AbfsRestOperation} object representing the remote write operation. * @throws IOException If an I/O error occurs during the append operation. */ @Override protected AbfsRestOperation remoteAppendBlobWrite(String path, DataBlocks.BlockUploadData uploadData, AbfsBlock block, AppendRequestParameters reqParams, TracingContext tracingContext) throws IOException { return remoteWrite(block, uploadData, reqParams, tracingContext); } /** * Flushes data to the remote store. * * @param offset the offset to flush. * @param retainUncommitedData whether to retain uncommitted data. * @param isClose whether this is a close operation. * @param leaseId the lease ID. * @param tracingContext the tracing context. * @return the resulting AbfsRestOperation. * @throws IOException if an I/O error occurs. */ @Override protected synchronized AbfsRestOperation remoteFlush(final long offset, final boolean retainUncommitedData, final boolean isClose, final String leaseId, TracingContext tracingContext) throws IOException { TracingContext tracingContextFlush = new TracingContext(tracingContext); if (tracingContextFlush.getIngressHandler().equals(EMPTY_STRING)) { tracingContextFlush.setIngressHandler(DFS_FLUSH); tracingContextFlush.setPosition(String.valueOf(offset)); } String fullBlobMd5 = null; if (getClient().isFullBlobChecksumValidationEnabled()) { fullBlobMd5 = computeFullBlobMd5(); } LOG.trace("Flushing data at offset {} and path {}", offset, getAbfsOutputStream().getPath()); AbfsRestOperation op; try { op = getClient() .flush(getAbfsOutputStream().getPath(), offset, retainUncommitedData, isClose, getAbfsOutputStream().getCachedSasTokenString(), leaseId, getAbfsOutputStream().getContextEncryptionAdapter(), tracingContextFlush, fullBlobMd5); } catch (AbfsRestOperationException ex) { LOG.error("Error in remote flush for path {} and offset {}", getAbfsOutputStream().getPath(), offset, ex); throw ex; } finally { if (getClient().isFullBlobChecksumValidationEnabled()) { getAbfsOutputStream().getFullBlobContentMd5().reset(); } } return op; } /** * Appending the current active data block to the service. Clearing the active * data block and releasing all buffered data. * * @throws IOException if there is any failure while starting an upload for * the data block or while closing the BlockUploadData. */ @Override protected void writeAppendBlobCurrentBufferToService() throws IOException { AbfsBlock activeBlock = dfsBlockManager.getActiveBlock(); // No data, return immediately. if (!getAbfsOutputStream().hasActiveBlockDataToUpload()) { return; } // Prepare data for upload. final int bytesLength = activeBlock.dataSize(); DataBlocks.BlockUploadData uploadData = activeBlock.startUpload(); // Clear active block and update statistics. if (dfsBlockManager.hasActiveBlock()) { dfsBlockManager.clearActiveBlock(); } getAbfsOutputStream().getOutputStreamStatistics().writeCurrentBuffer(); getAbfsOutputStream().getOutputStreamStatistics().bytesToUpload(bytesLength); // Update the stream position. final long offset = getAbfsOutputStream().getPosition(); getAbfsOutputStream().setPosition(offset + bytesLength); // Perform the upload within a performance tracking context. try (AbfsPerfInfo perfInfo = new AbfsPerfInfo( dfsClient.getAbfsPerfTracker(), "writeCurrentBufferToService", APPEND_ACTION)) { LOG.trace("Writing current buffer to service at offset {} and path {}", offset, getAbfsOutputStream().getPath()); AppendRequestParameters reqParams = new AppendRequestParameters( offset, 0, bytesLength, AppendRequestParameters.Mode.APPEND_MODE, true, getAbfsOutputStream().getLeaseId(), getAbfsOutputStream().isExpectHeaderEnabled(), getAbfsOutputStream().getMd5()); // Perform the remote write operation. AbfsRestOperation op = remoteWrite(activeBlock, uploadData, reqParams, new TracingContext(getAbfsOutputStream().getTracingContext())); // Update the SAS token and log the successful upload. getAbfsOutputStream().getCachedSasToken().update(op.getSasToken()); getAbfsOutputStream().getOutputStreamStatistics().uploadSuccessful(bytesLength); // Register performance information. perfInfo.registerResult(op.getResult()); perfInfo.registerSuccess(true); } catch (Exception ex) { LOG.error("Failed to upload current buffer of length {} and path {}", bytesLength, getAbfsOutputStream().getPath(), ex); getAbfsOutputStream().getOutputStreamStatistics().uploadFailed(bytesLength); getAbfsOutputStream().failureWhileSubmit(ex); } finally { // Ensure the upload data stream is closed. IOUtils.closeStreams(uploadData, activeBlock); } } /** * Gets the block manager. * * @return the block manager. */ @Override public AzureBlockManager getBlockManager() { return dfsBlockManager; } /** * Gets the dfs client. * * @return the dfs client. */ @Override public AbfsDfsClient getClient() { return dfsClient; } /** * Gets the eTag value of the blob. * * @return the eTag. */ @Override public String getETag() { return eTag; } }
AzureDFSIngressHandler
java
quarkusio__quarkus
integration-tests/jaxp/src/test/java/io/quarkus/it/jaxp/JaxpTest.java
{ "start": 204, "end": 1160 }
class ____ { @Test public void domBuilder() { RestAssured.given() .contentType("text/xml") .body("<foo>bar</foo>") .post("/jaxp/dom-builder") .then() .statusCode(200) .body(is("bar")); } @Test public void transformer() { RestAssured.given() .contentType("text/xml") .body("<foo>bar</foo>") .post("/jaxp/transformer") .then() .statusCode(200) .body(is("bar")); } @Test public void xPath() { RestAssured.given() .contentType("text/xml") .param("input", "<foo><bar>baz</bar></foo>") .param("xpath", "/foo/bar/text()") .get("/jaxp/xpath") .then() .statusCode(200) .body(is("baz")); } }
JaxpTest
java
alibaba__nacos
api/src/test/java/com/alibaba/nacos/api/config/remote/request/ConfigChangeNotifyRequestTest.java
{ "start": 975, "end": 2584 }
class ____ extends BasedConfigRequestTest { ConfigChangeNotifyRequest configChangeNotifyRequest; String requestId; @BeforeEach void before() { configChangeNotifyRequest = ConfigChangeNotifyRequest.build(DATA_ID, GROUP, TENANT); configChangeNotifyRequest.putAllHeader(HEADERS); requestId = injectRequestUuId(configChangeNotifyRequest); } @Override @Test public void testSerialize() throws JsonProcessingException { String json = mapper.writeValueAsString(configChangeNotifyRequest); assertTrue(json.contains("\"module\":\"" + Constants.Config.CONFIG_MODULE)); assertTrue(json.contains("\"dataId\":\"" + DATA_ID)); assertTrue(json.contains("\"group\":\"" + GROUP)); assertTrue(json.contains("\"tenant\":\"" + TENANT)); assertTrue(json.contains("\"requestId\":\"" + requestId)); } @Override @Test public void testDeserialize() throws JsonProcessingException { String json = "{\"headers\":{\"header1\":\"test_header1\"},\"dataId\":\"test_data\",\"group\":" + "\"group\",\"tenant\":\"test_tenant\",\"module\":\"config\"}"; ConfigChangeNotifyRequest actual = mapper.readValue(json, ConfigChangeNotifyRequest.class); assertEquals(DATA_ID, actual.getDataId()); assertEquals(GROUP, actual.getGroup()); assertEquals(TENANT, actual.getTenant()); assertEquals(Constants.Config.CONFIG_MODULE, actual.getModule()); assertEquals(HEADER_VALUE, actual.getHeader(HEADER_KEY)); } }
ConfigChangeNotifyRequestTest
java
elastic__elasticsearch
modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/AnalysisPredicateScript.java
{ "start": 1113, "end": 1235 }
class ____ { /** * Encapsulation of the state of the current token */ public static
AnalysisPredicateScript
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/admin/internals/ListConsumerGroupOffsetsHandlerTest.java
{ "start": 2597, "end": 28820 }
class ____ { private final LogContext logContext = new LogContext(); private final String group0 = "group0"; private final String group1 = "group1"; private final String group2 = "group2"; private final String group3 = "group3"; private final List<String> groups = List.of(group0, group1, group2); private final TopicPartition t0p0 = new TopicPartition("t0", 0); private final TopicPartition t0p1 = new TopicPartition("t0", 1); private final TopicPartition t1p0 = new TopicPartition("t1", 0); private final TopicPartition t1p1 = new TopicPartition("t1", 1); private final TopicPartition t2p0 = new TopicPartition("t2", 0); private final TopicPartition t2p1 = new TopicPartition("t2", 1); private final TopicPartition t2p2 = new TopicPartition("t2", 2); private final TopicPartition t3p0 = new TopicPartition("t3", 0); private final TopicPartition t3p1 = new TopicPartition("t3", 1); private final Map<String, ListConsumerGroupOffsetsSpec> singleGroupSpec = Map.of( group0, new ListConsumerGroupOffsetsSpec().topicPartitions(Arrays.asList(t0p0, t0p1, t1p0, t1p1)) ); private final Map<String, ListConsumerGroupOffsetsSpec> multiGroupSpecs = Map.of( group0, new ListConsumerGroupOffsetsSpec().topicPartitions(singletonList(t0p0)), group1, new ListConsumerGroupOffsetsSpec().topicPartitions(Arrays.asList(t0p0, t1p0, t1p1)), group2, new ListConsumerGroupOffsetsSpec().topicPartitions(Arrays.asList(t0p0, t1p0, t1p1, t2p0, t2p1, t2p2)) ); @Test public void testBuildRequest() { var handler = new ListConsumerGroupOffsetsHandler( singleGroupSpec, false, logContext ); assertEquals( new OffsetFetchRequestData() .setGroups(List.of( new OffsetFetchRequestData.OffsetFetchRequestGroup() .setGroupId(group0) .setTopics(List.of( new OffsetFetchRequestData.OffsetFetchRequestTopics() .setName(t0p0.topic()) .setPartitionIndexes(List.of(t0p0.partition(), t0p1.partition())), new OffsetFetchRequestData.OffsetFetchRequestTopics() .setName(t1p0.topic()) .setPartitionIndexes(List.of(t1p0.partition(), t1p1.partition())) )) )), handler.buildBatchedRequest(coordinatorKeys(group0)).build().data() ); } @Test public void testBuildRequestWithMultipleGroups() { var groupSpecs = new HashMap<>(multiGroupSpecs); groupSpecs.put( group3, new ListConsumerGroupOffsetsSpec().topicPartitions(List.of(t3p0, t3p1)) ); var handler = new ListConsumerGroupOffsetsHandler( groupSpecs, false, logContext ); var request1 = handler.buildBatchedRequest(coordinatorKeys(group0, group1, group2)).build(); assertEquals( Set.of( new OffsetFetchRequestData.OffsetFetchRequestGroup() .setGroupId(group0) .setTopics(List.of( new OffsetFetchRequestData.OffsetFetchRequestTopics() .setName(t0p0.topic()) .setPartitionIndexes(List.of(t0p0.partition())) )), new OffsetFetchRequestData.OffsetFetchRequestGroup() .setGroupId(group1) .setTopics(List.of( new OffsetFetchRequestData.OffsetFetchRequestTopics() .setName(t0p0.topic()) .setPartitionIndexes(List.of(t0p0.partition())), new OffsetFetchRequestData.OffsetFetchRequestTopics() .setName(t1p0.topic()) .setPartitionIndexes(List.of(t1p0.partition(), t1p1.partition())) )), new OffsetFetchRequestData.OffsetFetchRequestGroup() .setGroupId(group2) .setTopics(List.of( new OffsetFetchRequestData.OffsetFetchRequestTopics() .setName(t0p0.topic()) .setPartitionIndexes(List.of(t0p0.partition())), new OffsetFetchRequestData.OffsetFetchRequestTopics() .setName(t1p0.topic()) .setPartitionIndexes(List.of(t1p0.partition(), t1p1.partition())), new OffsetFetchRequestData.OffsetFetchRequestTopics() .setName(t2p0.topic()) .setPartitionIndexes(List.of(t2p0.partition(), t2p1.partition(), t2p2.partition())) )) ), Set.copyOf(request1.data().groups()) ); var request2 = handler.buildBatchedRequest(coordinatorKeys(group3)).build(); assertEquals( Set.of( new OffsetFetchRequestData.OffsetFetchRequestGroup() .setGroupId(group3) .setTopics(List.of( new OffsetFetchRequestData.OffsetFetchRequestTopics() .setName(t3p0.topic()) .setPartitionIndexes(List.of(t3p0.partition(), t3p1.partition())) )) ), Set.copyOf(request2.data().groups()) ); } @Test public void testBuildRequestBatchGroups() { ListConsumerGroupOffsetsHandler handler = new ListConsumerGroupOffsetsHandler(multiGroupSpecs, false, logContext); Collection<RequestAndKeys<CoordinatorKey>> requests = handler.buildRequest(1, coordinatorKeys(group0, group1, group2)); assertEquals(1, requests.size()); assertEquals(Set.of(group0, group1, group2), requestGroups((OffsetFetchRequest) requests.iterator().next().request.build())); } @Test public void testBuildRequestDoesNotBatchGroup() { ListConsumerGroupOffsetsHandler handler = new ListConsumerGroupOffsetsHandler(multiGroupSpecs, false, logContext); // Disable batching. ((CoordinatorStrategy) handler.lookupStrategy()).disableBatch(); Collection<RequestAndKeys<CoordinatorKey>> requests = handler.buildRequest(1, coordinatorKeys(group0, group1, group2)); assertEquals(3, requests.size()); assertEquals( Set.of(Set.of(group0), Set.of(group1), Set.of(group2)), requests.stream().map(requestAndKey -> requestGroups((OffsetFetchRequest) requestAndKey.request.build())).collect(Collectors.toSet()) ); } @Test public void testSuccessfulHandleResponse() { Map<TopicPartition, OffsetAndMetadata> expected = new HashMap<>(); assertCompleted(handleWithError(Errors.NONE), expected); } @Test public void testSuccessfulHandleResponseWithOnePartitionError() { Map<TopicPartition, OffsetAndMetadata> expectedResult = Collections.singletonMap(t0p0, new OffsetAndMetadata(10L)); // expected that there's only 1 partition result returned because the other partition is skipped with error assertCompleted(handleWithPartitionError(Errors.UNKNOWN_TOPIC_OR_PARTITION), expectedResult); assertCompleted(handleWithPartitionError(Errors.TOPIC_AUTHORIZATION_FAILED), expectedResult); assertCompleted(handleWithPartitionError(Errors.UNSTABLE_OFFSET_COMMIT), expectedResult); } @Test public void testSuccessfulHandleResponseWithOnePartitionErrorWithMultipleGroups() { var expectedResult = Map.of( group0, Map.of(t0p0, new OffsetAndMetadata(10L)), group1, Map.of(t1p1, new OffsetAndMetadata(10L)), group2, Map.of(t2p2, new OffsetAndMetadata(10L)) ); assertCompletedForMultipleGroups( handleWithPartitionErrorMultipleGroups(Errors.UNKNOWN_TOPIC_OR_PARTITION), expectedResult ); assertCompletedForMultipleGroups( handleWithPartitionErrorMultipleGroups(Errors.TOPIC_AUTHORIZATION_FAILED), expectedResult ); assertCompletedForMultipleGroups( handleWithPartitionErrorMultipleGroups(Errors.UNSTABLE_OFFSET_COMMIT), expectedResult ); } @Test public void testSuccessfulHandleResponseWithMultipleGroups() { Map<String, Map<TopicPartition, OffsetAndMetadata>> expected = new HashMap<>(); Map<String, Errors> errorMap = errorMap(groups, Errors.NONE); assertCompletedForMultipleGroups(handleWithErrorWithMultipleGroups(errorMap, multiGroupSpecs), expected); } @Test public void testUnmappedHandleResponse() { assertUnmapped(handleWithError(Errors.COORDINATOR_NOT_AVAILABLE)); assertUnmapped(handleWithError(Errors.NOT_COORDINATOR)); } @Test public void testUnmappedHandleResponseWithMultipleGroups() { var errorMap = Map.of( group0, Errors.NOT_COORDINATOR, group1, Errors.COORDINATOR_NOT_AVAILABLE, group2, Errors.NOT_COORDINATOR ); assertUnmappedWithMultipleGroups(handleWithErrorWithMultipleGroups(errorMap, multiGroupSpecs)); } @Test public void testRetriableHandleResponse() { assertRetriable(handleWithError(Errors.COORDINATOR_LOAD_IN_PROGRESS)); } @Test public void testRetriableHandleResponseWithMultipleGroups() { Map<String, Errors> errorMap = errorMap(groups, Errors.COORDINATOR_LOAD_IN_PROGRESS); assertRetriable(handleWithErrorWithMultipleGroups(errorMap, multiGroupSpecs)); } @Test public void testFailedHandleResponse() { assertFailed(GroupAuthorizationException.class, handleWithError(Errors.GROUP_AUTHORIZATION_FAILED)); assertFailed(GroupIdNotFoundException.class, handleWithError(Errors.GROUP_ID_NOT_FOUND)); assertFailed(InvalidGroupIdException.class, handleWithError(Errors.INVALID_GROUP_ID)); } @Test public void testFailedHandleResponseWithMultipleGroups() { var errorMap = Map.of( group0, Errors.GROUP_AUTHORIZATION_FAILED, group1, Errors.GROUP_ID_NOT_FOUND, group2, Errors.INVALID_GROUP_ID ); var groupToExceptionMap = Map.of( group0, (Class<? extends Throwable>) GroupAuthorizationException.class, group1, (Class<? extends Throwable>) GroupIdNotFoundException.class, group2, (Class<? extends Throwable>) InvalidGroupIdException.class ); assertFailedForMultipleGroups( groupToExceptionMap, handleWithErrorWithMultipleGroups(errorMap, multiGroupSpecs) ); } private OffsetFetchResponse buildResponse(Errors error) { return new OffsetFetchResponse( new OffsetFetchResponseData() .setGroups(List.of( new OffsetFetchResponseData.OffsetFetchResponseGroup() .setGroupId(group0) .setErrorCode(error.code()) )), ApiKeys.OFFSET_FETCH.latestVersion() ); } private AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> handleWithErrorWithMultipleGroups( Map<String, Errors> errorMap, Map<String, ListConsumerGroupOffsetsSpec> groupSpecs ) { var handler = new ListConsumerGroupOffsetsHandler( groupSpecs, false, logContext ); var response = new OffsetFetchResponse( new OffsetFetchResponseData() .setGroups(errorMap.entrySet().stream().map(entry -> new OffsetFetchResponseData.OffsetFetchResponseGroup() .setGroupId(entry.getKey()) .setErrorCode(entry.getValue().code()) ).collect(Collectors.toList())), ApiKeys.OFFSET_FETCH.latestVersion() ); return handler.handleResponse(new Node(1, "host", 1234), errorMap.keySet() .stream() .map(CoordinatorKey::byGroupId) .collect(Collectors.toSet()), response ); } private OffsetFetchResponse buildResponseWithPartitionError(Errors error) { return new OffsetFetchResponse( new OffsetFetchResponseData() .setGroups(List.of( new OffsetFetchResponseData.OffsetFetchResponseGroup() .setGroupId(group0) .setTopics(List.of( new OffsetFetchResponseData.OffsetFetchResponseTopics() .setName(t0p0.topic()) .setPartitions(List.of( new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t0p0.partition()) .setCommittedOffset(10), new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t0p1.partition()) .setCommittedOffset(10) .setErrorCode(error.code()) )) )) )), ApiKeys.OFFSET_FETCH.latestVersion() ); } private OffsetFetchResponse buildResponseWithPartitionErrorWithMultipleGroups(Errors error) { var data = new OffsetFetchResponseData() .setGroups(List.of( new OffsetFetchResponseData.OffsetFetchResponseGroup() .setGroupId(group0) .setTopics(List.of( new OffsetFetchResponseData.OffsetFetchResponseTopics() .setName(t0p0.topic()) .setPartitions(List.of( new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t0p0.partition()) .setCommittedOffset(10) .setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH) .setMetadata(OffsetFetchResponse.NO_METADATA) .setErrorCode(Errors.NONE.code()) )) )), new OffsetFetchResponseData.OffsetFetchResponseGroup() .setGroupId(group1) .setTopics(List.of( new OffsetFetchResponseData.OffsetFetchResponseTopics() .setName(t0p0.topic()) .setPartitions(List.of( new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t0p0.partition()) .setCommittedOffset(10) .setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH) .setMetadata(OffsetFetchResponse.NO_METADATA) .setErrorCode(error.code()) )), new OffsetFetchResponseData.OffsetFetchResponseTopics() .setName(t1p0.topic()) .setPartitions(List.of( new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t1p0.partition()) .setCommittedOffset(10) .setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH) .setMetadata(OffsetFetchResponse.NO_METADATA) .setErrorCode(error.code()), new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t1p1.partition()) .setCommittedOffset(10) .setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH) .setMetadata(OffsetFetchResponse.NO_METADATA) .setErrorCode(Errors.NONE.code()) )) )), new OffsetFetchResponseData.OffsetFetchResponseGroup() .setGroupId(group2) .setTopics(List.of( new OffsetFetchResponseData.OffsetFetchResponseTopics() .setName(t0p0.topic()) .setPartitions(List.of( new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t0p0.partition()) .setCommittedOffset(10) .setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH) .setMetadata(OffsetFetchResponse.NO_METADATA) .setErrorCode(error.code()) )), new OffsetFetchResponseData.OffsetFetchResponseTopics() .setName(t1p0.topic()) .setPartitions(List.of( new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t1p0.partition()) .setCommittedOffset(10) .setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH) .setMetadata(OffsetFetchResponse.NO_METADATA) .setErrorCode(error.code()), new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t1p1.partition()) .setCommittedOffset(10) .setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH) .setMetadata(OffsetFetchResponse.NO_METADATA) .setErrorCode(error.code()) )), new OffsetFetchResponseData.OffsetFetchResponseTopics() .setName(t2p0.topic()) .setPartitions(List.of( new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t2p0.partition()) .setCommittedOffset(10) .setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH) .setMetadata(OffsetFetchResponse.NO_METADATA) .setErrorCode(error.code()), new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t2p1.partition()) .setCommittedOffset(10) .setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH) .setMetadata(OffsetFetchResponse.NO_METADATA) .setErrorCode(error.code()), new OffsetFetchResponseData.OffsetFetchResponsePartitions() .setPartitionIndex(t2p2.partition()) .setCommittedOffset(10) .setCommittedLeaderEpoch(RecordBatch.NO_PARTITION_LEADER_EPOCH) .setMetadata(OffsetFetchResponse.NO_METADATA) .setErrorCode(Errors.NONE.code()) )) )) )); return new OffsetFetchResponse(data, ApiKeys.OFFSET_FETCH.latestVersion()); } private AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> handleWithPartitionError( Errors error ) { ListConsumerGroupOffsetsHandler handler = new ListConsumerGroupOffsetsHandler( singleGroupSpec, false, logContext ); OffsetFetchResponse response = buildResponseWithPartitionError(error); return handler.handleResponse(new Node(1, "host", 1234), singleton(CoordinatorKey.byGroupId(group0)), response); } private AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> handleWithPartitionErrorMultipleGroups( Errors error ) { ListConsumerGroupOffsetsHandler handler = new ListConsumerGroupOffsetsHandler( multiGroupSpecs, false, logContext ); OffsetFetchResponse response = buildResponseWithPartitionErrorWithMultipleGroups(error); return handler.handleResponse( new Node(1, "host", 1234), coordinatorKeys(group0, group1, group2), response ); } private AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> handleWithError( Errors error ) { ListConsumerGroupOffsetsHandler handler = new ListConsumerGroupOffsetsHandler( singleGroupSpec, false, logContext); OffsetFetchResponse response = buildResponse(error); return handler.handleResponse(new Node(1, "host", 1234), singleton(CoordinatorKey.byGroupId(group0)), response); } private void assertUnmapped( AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> result ) { assertEquals(emptySet(), result.completedKeys.keySet()); assertEquals(emptySet(), result.failedKeys.keySet()); assertEquals(singletonList(CoordinatorKey.byGroupId(group0)), result.unmappedKeys); } private void assertUnmappedWithMultipleGroups( AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> result ) { assertEquals(emptySet(), result.completedKeys.keySet()); assertEquals(emptySet(), result.failedKeys.keySet()); assertEquals(coordinatorKeys(group0, group1, group2), new HashSet<>(result.unmappedKeys)); } private void assertRetriable( AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> result ) { assertEquals(emptySet(), result.completedKeys.keySet()); assertEquals(emptySet(), result.failedKeys.keySet()); assertEquals(emptyList(), result.unmappedKeys); } private void assertCompleted( AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> result, Map<TopicPartition, OffsetAndMetadata> expected ) { CoordinatorKey key = CoordinatorKey.byGroupId(group0); assertEquals(emptySet(), result.failedKeys.keySet()); assertEquals(emptyList(), result.unmappedKeys); assertEquals(singleton(key), result.completedKeys.keySet()); assertEquals(expected, result.completedKeys.get(key)); } private void assertCompletedForMultipleGroups( AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> result, Map<String, Map<TopicPartition, OffsetAndMetadata>> expected ) { assertEquals(emptySet(), result.failedKeys.keySet()); assertEquals(emptyList(), result.unmappedKeys); for (String g : expected.keySet()) { CoordinatorKey key = CoordinatorKey.byGroupId(g); assertTrue(result.completedKeys.containsKey(key)); assertEquals(expected.get(g), result.completedKeys.get(key)); } } private void assertFailed( Class<? extends Throwable> expectedExceptionType, AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> result ) { CoordinatorKey key = CoordinatorKey.byGroupId(group0); assertEquals(emptySet(), result.completedKeys.keySet()); assertEquals(emptyList(), result.unmappedKeys); assertEquals(singleton(key), result.failedKeys.keySet()); assertInstanceOf(expectedExceptionType, result.failedKeys.get(key)); } private void assertFailedForMultipleGroups( Map<String, Class<? extends Throwable>> groupToExceptionMap, AdminApiHandler.ApiResult<CoordinatorKey, Map<TopicPartition, OffsetAndMetadata>> result ) { assertEquals(emptySet(), result.completedKeys.keySet()); assertEquals(emptyList(), result.unmappedKeys); for (String g : groupToExceptionMap.keySet()) { CoordinatorKey key = CoordinatorKey.byGroupId(g); assertTrue(result.failedKeys.containsKey(key)); assertInstanceOf(groupToExceptionMap.get(g), result.failedKeys.get(key)); } } private Set<CoordinatorKey> coordinatorKeys(String... groups) { return Stream.of(groups) .map(CoordinatorKey::byGroupId) .collect(Collectors.toSet()); } private Set<String> requestGroups(OffsetFetchRequest request) { return request.data().groups() .stream() .map(OffsetFetchRequestGroup::groupId) .collect(Collectors.toSet()); } private Map<String, Errors> errorMap(Collection<String> groups, Errors error) { return groups.stream().collect(Collectors.toMap(Function.identity(), unused -> error)); } }
ListConsumerGroupOffsetsHandlerTest
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/PersistentCollectionChangeWorkUnit.java
{ "start": 788, "end": 6913 }
class ____ extends AbstractAuditWorkUnit implements AuditWorkUnit { private final List<PersistentCollectionChangeData> collectionChanges; private final String referencingPropertyName; public PersistentCollectionChangeWorkUnit( SharedSessionContractImplementor sessionImplementor, String entityName, EnversService enversService, PersistentCollection collection, CollectionEntry collectionEntry, Serializable snapshot, Object id, String referencingPropertyName) { super( sessionImplementor, entityName, enversService, new PersistentCollectionChangeWorkUnitId( id, collectionEntry.getRole() ), RevisionType.MOD ); this.referencingPropertyName = referencingPropertyName; collectionChanges = enversService.getEntitiesConfigurations().get( getEntityName() ).getPropertyMapper() .mapCollectionChanges( sessionImplementor, referencingPropertyName, collection, snapshot, id ); } public PersistentCollectionChangeWorkUnit( SharedSessionContractImplementor sessionImplementor, String entityName, EnversService enversService, Object id, List<PersistentCollectionChangeData> collectionChanges, String referencingPropertyName) { super( sessionImplementor, entityName, enversService, id, RevisionType.MOD ); this.collectionChanges = collectionChanges; this.referencingPropertyName = referencingPropertyName; } @Override public boolean containsWork() { return collectionChanges != null && collectionChanges.size() != 0; } @Override public Map<String, Object> generateData(Object revisionData) { throw new UnsupportedOperationException( "Cannot generate data for a collection change work unit!" ); } @Override @SuppressWarnings("unchecked") public void perform(SharedSessionContractImplementor session, Object revisionData) { final Configuration configuration = enversService.getConfig(); for ( PersistentCollectionChangeData persistentCollectionChangeData : collectionChanges ) { // Setting the revision number ( (Map<String, Object>) persistentCollectionChangeData.getData().get( configuration.getOriginalIdPropertyName() ) ) .put( configuration.getRevisionFieldName(), revisionData ); auditStrategy.performCollectionChange( session, getEntityName(), referencingPropertyName, enversService.getConfig(), persistentCollectionChangeData, revisionData ); } } public String getReferencingPropertyName() { return referencingPropertyName; } public List<PersistentCollectionChangeData> getCollectionChanges() { return collectionChanges; } @Override public AuditWorkUnit merge(AddWorkUnit second) { return null; } @Override public AuditWorkUnit merge(ModWorkUnit second) { return null; } @Override public AuditWorkUnit merge(DelWorkUnit second) { return null; } @Override public AuditWorkUnit merge(CollectionChangeWorkUnit second) { return null; } @Override public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { return null; } @Override public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { if ( first instanceof PersistentCollectionChangeWorkUnit ) { final PersistentCollectionChangeWorkUnit original = (PersistentCollectionChangeWorkUnit) first; // Merging the collection changes in both work units. // First building a map from the ids of the collection-entry-entities from the "second" collection changes, // to the PCCD objects. That way, we will be later able to check if an "original" collection change // should be added, or if it is overshadowed by a new one. final Map<Object, PersistentCollectionChangeData> newChangesIdMap = new HashMap<>(); for ( PersistentCollectionChangeData persistentCollectionChangeData : getCollectionChanges() ) { newChangesIdMap.put( getOriginalId( persistentCollectionChangeData ), persistentCollectionChangeData ); } // This will be the list with the resulting (merged) changes. final List<PersistentCollectionChangeData> mergedChanges = new ArrayList<>(); // Including only those original changes, which are not overshadowed by new ones. for ( PersistentCollectionChangeData originalCollectionChangeData : original.getCollectionChanges() ) { final Object originalOriginalId = getOriginalId( originalCollectionChangeData ); if ( !newChangesIdMap.containsKey( originalOriginalId ) ) { mergedChanges.add( originalCollectionChangeData ); } else { // If the changes collide, checking if the first one isn't a DEL, and the second a subsequent ADD // If so, removing the change alltogether. final String revTypePropName = enversService.getConfig().getRevisionTypePropertyName(); if ( RevisionType.ADD.equals( newChangesIdMap.get( originalOriginalId ).getData().get( revTypePropName ) ) && RevisionType.DEL.equals( originalCollectionChangeData.getData().get( revTypePropName ) ) ) { newChangesIdMap.remove( originalOriginalId ); } } } // Finally adding all of the new changes to the end of the list (the map values may differ from // getCollectionChanges() because of the last operation above). mergedChanges.addAll( newChangesIdMap.values() ); return new PersistentCollectionChangeWorkUnit( sessionImplementor, entityName, enversService, id, mergedChanges, referencingPropertyName ); } else { throw new RuntimeException( "Trying to merge a " + first + " with a PersitentCollectionChangeWorkUnit. " + "This is not really possible." ); } } private Object getOriginalId(PersistentCollectionChangeData persistentCollectionChangeData) { return persistentCollectionChangeData.getData().get( enversService.getConfig().getOriginalIdPropertyName() ); } /** * A unique identifier for a collection work unit. Consists of an id of the owning entity and the name of * the entity plus the name of the field (the role). This is needed because such collections aren't entities * in the "normal" mapping, but they are entities for Envers. */ public static
PersistentCollectionChangeWorkUnit
java
spring-projects__spring-boot
module/spring-boot-health/src/main/java/org/springframework/boot/health/registry/AbstractRegistry.java
{ "start": 1157, "end": 1290 }
class ____ health registries. * * @param <C> the contributor type * @param <E> the entry type * @author Phillip Webb */ abstract
for
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/server/header/XXssProtectionServerHttpHeadersWriter.java
{ "start": 1034, "end": 2734 }
class ____ implements ServerHttpHeadersWriter { public static final String X_XSS_PROTECTION = "X-XSS-Protection"; private ServerHttpHeadersWriter delegate; private HeaderValue headerValue; /** * Creates a new instance */ public XXssProtectionServerHttpHeadersWriter() { this.headerValue = HeaderValue.DISABLED; updateDelegate(); } @Override public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) { return this.delegate.writeHttpHeaders(exchange); } /** * Sets the value of the X-XSS-PROTECTION header. Defaults to * {@link HeaderValue#DISABLED} * <p> * If {@link HeaderValue#DISABLED}, will specify that X-XSS-Protection is disabled. * For example: * * <pre> * X-XSS-Protection: 0 * </pre> * <p> * If {@link HeaderValue#ENABLED}, will contain a value of 1, but will not specify the * mode as blocked. In this instance, any content will be attempted to be fixed. For * example: * * <pre> * X-XSS-Protection: 1 * </pre> * <p> * If {@link HeaderValue#ENABLED_MODE_BLOCK}, will contain a value of 1 and will * specify mode as blocked. The content will be replaced with "#". For example: * * <pre> * X-XSS-Protection: 1; mode=block * </pre> * @param headerValue the new headerValue * @throws IllegalArgumentException if headerValue is null * @since 5.8 */ public void setHeaderValue(HeaderValue headerValue) { Assert.notNull(headerValue, "headerValue cannot be null"); this.headerValue = headerValue; updateDelegate(); } /** * The value of the x-xss-protection header. One of: "0", "1", "1; mode=block" * * @author Daniel Garnier-Moiroux * @since 5.8 */ public
XXssProtectionServerHttpHeadersWriter
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
{ "start": 8997, "end": 20765 }
class ____ and hash code. * @param interceptors one or more interceptors to register */ public void registerDeferredResultInterceptors(DeferredResultProcessingInterceptor... interceptors) { Assert.notNull(interceptors, "A DeferredResultProcessingInterceptor is required"); for (DeferredResultProcessingInterceptor interceptor : interceptors) { String key = interceptor.getClass().getName() + ":" + interceptor.hashCode(); this.deferredResultInterceptors.put(key, interceptor); } } /** * Mark the {@link WebAsyncManager} as wrapping a multipart async request. * @since 6.1.12 */ public void setMultipartRequestParsed(boolean isMultipart) { this.isMultipartRequestParsed = isMultipart; } /** * Return {@code true} if this {@link WebAsyncManager} was previously marked * as wrapping a multipart async request, {@code false} otherwise. * @since 6.1.12 */ public boolean isMultipartRequestParsed() { return this.isMultipartRequestParsed; } /** * Clear {@linkplain #getConcurrentResult() concurrentResult} and * {@linkplain #getConcurrentResultContext() concurrentResultContext}. */ public void clearConcurrentResult() { if (!this.state.compareAndSet(State.RESULT_SET, State.NOT_STARTED)) { if (logger.isDebugEnabled()) { logger.debug("Unexpected call to clear: [" + this.state.get() + "]"); } return; } synchronized (WebAsyncManager.this) { this.concurrentResult = RESULT_NONE; this.concurrentResultContext = null; } } /** * Start concurrent request processing and execute the given task with an * {@link #setTaskExecutor(AsyncTaskExecutor) AsyncTaskExecutor}. The result * from the task execution is saved and the request dispatched in order to * resume processing of that result. If the task raises an Exception then * the saved result will be the raised Exception. * @param callable a unit of work to be executed asynchronously * @param processingContext additional context to save that can be accessed * via {@link #getConcurrentResultContext()} * @throws Exception if concurrent processing failed to start * @see #getConcurrentResult() * @see #getConcurrentResultContext() */ @SuppressWarnings({"rawtypes", "unchecked"}) public void startCallableProcessing(Callable<?> callable, Object... processingContext) throws Exception { Assert.notNull(callable, "Callable must not be null"); startCallableProcessing(new WebAsyncTask(callable), processingContext); } /** * Use the given {@link WebAsyncTask} to configure the task executor as well as * the timeout value of the {@code AsyncWebRequest} before delegating to * {@link #startCallableProcessing(Callable, Object...)}. * @param webAsyncTask a WebAsyncTask containing the target {@code Callable} * @param processingContext additional context to save that can be accessed * via {@link #getConcurrentResultContext()} * @throws Exception if concurrent processing failed to start */ @SuppressWarnings("NullAway") // Lambda public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext) throws Exception { Assert.notNull(webAsyncTask, "WebAsyncTask must not be null"); Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null"); if (!this.state.compareAndSet(State.NOT_STARTED, State.ASYNC_PROCESSING)) { throw new IllegalStateException( "Unexpected call to startCallableProcessing: [" + this.state.get() + "]"); } Long timeout = webAsyncTask.getTimeout(); if (timeout != null) { this.asyncWebRequest.setTimeout(timeout); } AsyncTaskExecutor executor = webAsyncTask.getExecutor(); if (executor != null) { this.taskExecutor = executor; } List<CallableProcessingInterceptor> interceptors = new ArrayList<>(); interceptors.add(webAsyncTask.getInterceptor()); interceptors.addAll(this.callableInterceptors.values()); interceptors.add(timeoutCallableInterceptor); final Callable<?> callable = webAsyncTask.getCallable(); final CallableInterceptorChain interceptorChain = new CallableInterceptorChain(interceptors); this.asyncWebRequest.addTimeoutHandler(() -> { if (logger.isDebugEnabled()) { logger.debug("Servlet container timeout notification for " + formatUri(this.asyncWebRequest)); } Object result = interceptorChain.triggerAfterTimeout(this.asyncWebRequest, callable); if (result != CallableProcessingInterceptor.RESULT_NONE) { setConcurrentResultAndDispatch(result); } }); this.asyncWebRequest.addErrorHandler(ex -> { if (logger.isDebugEnabled()) { logger.debug("Servlet container error notification for " + formatUri(this.asyncWebRequest) + ": " + ex); } if (ex instanceof IOException) { ex = new AsyncRequestNotUsableException( "Servlet container error notification for disconnected client", ex); } Object result = interceptorChain.triggerAfterError(this.asyncWebRequest, callable, ex); result = (result != CallableProcessingInterceptor.RESULT_NONE ? result : ex); setConcurrentResultAndDispatch(result); }); this.asyncWebRequest.addCompletionHandler(() -> interceptorChain.triggerAfterCompletion(this.asyncWebRequest, callable)); interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, callable); startAsyncProcessing(processingContext); try { Future<?> future = this.taskExecutor.submit(() -> { Object result = null; try { interceptorChain.applyPreProcess(this.asyncWebRequest, callable); result = callable.call(); } catch (Throwable ex) { result = ex; } finally { result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, result); } setConcurrentResultAndDispatch(result); }); interceptorChain.setTaskFuture(future); } catch (Throwable ex) { Object result = interceptorChain.applyPostProcess(this.asyncWebRequest, callable, ex); setConcurrentResultAndDispatch(result); } } /** * Start concurrent request processing and initialize the given * {@link DeferredResult} with a {@link DeferredResultHandler} that saves * the result and dispatches the request to resume processing of that * result. The {@code AsyncWebRequest} is also updated with a completion * handler that expires the {@code DeferredResult} and a timeout handler * assuming the {@code DeferredResult} has a default timeout result. * @param deferredResult the DeferredResult instance to initialize * @param processingContext additional context to save that can be accessed * via {@link #getConcurrentResultContext()} * @throws Exception if concurrent processing failed to start * @see #getConcurrentResult() * @see #getConcurrentResultContext() */ @SuppressWarnings("NullAway") // Lambda public void startDeferredResultProcessing( final DeferredResult<?> deferredResult, Object... processingContext) throws Exception { Assert.notNull(deferredResult, "DeferredResult must not be null"); Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null"); if (!this.state.compareAndSet(State.NOT_STARTED, State.ASYNC_PROCESSING)) { throw new IllegalStateException( "Unexpected call to startDeferredResultProcessing: [" + this.state.get() + "]"); } Long timeout = deferredResult.getTimeoutValue(); if (timeout != null) { this.asyncWebRequest.setTimeout(timeout); } List<DeferredResultProcessingInterceptor> interceptors = new ArrayList<>(); interceptors.add(deferredResult.getLifecycleInterceptor()); interceptors.addAll(this.deferredResultInterceptors.values()); interceptors.add(timeoutDeferredResultInterceptor); final DeferredResultInterceptorChain interceptorChain = new DeferredResultInterceptorChain(interceptors); this.asyncWebRequest.addTimeoutHandler(() -> { if (logger.isDebugEnabled()) { logger.debug("Servlet container timeout notification for " + formatUri(this.asyncWebRequest)); } try { interceptorChain.triggerAfterTimeout(this.asyncWebRequest, deferredResult); synchronized (WebAsyncManager.this) { // If application thread set the DeferredResult first in a race, // we must still not return until setConcurrentResultAndDispatch is done return; } } catch (Throwable ex) { setConcurrentResultAndDispatch(ex); } }); this.asyncWebRequest.addErrorHandler(ex -> { if (logger.isDebugEnabled()) { logger.debug("Servlet container error notification for " + formatUri(this.asyncWebRequest)); } if (ex instanceof IOException) { ex = new AsyncRequestNotUsableException( "Servlet container error notification for disconnected client", ex); } try { interceptorChain.triggerAfterError(this.asyncWebRequest, deferredResult, ex); synchronized (WebAsyncManager.this) { // If application thread set the DeferredResult first in a race, // we must still not return until setConcurrentResultAndDispatch is done return; } } catch (Throwable interceptorEx) { setConcurrentResultAndDispatch(interceptorEx); } }); this.asyncWebRequest.addCompletionHandler(() -> interceptorChain.triggerAfterCompletion(this.asyncWebRequest, deferredResult)); interceptorChain.applyBeforeConcurrentHandling(this.asyncWebRequest, deferredResult); startAsyncProcessing(processingContext); try { interceptorChain.applyPreProcess(this.asyncWebRequest, deferredResult); deferredResult.setResultHandler(result -> { result = interceptorChain.applyPostProcess(this.asyncWebRequest, deferredResult, result); setConcurrentResultAndDispatch(result); }); } catch (Throwable ex) { setConcurrentResultAndDispatch(ex); } } private void startAsyncProcessing(Object[] processingContext) { synchronized (WebAsyncManager.this) { this.concurrentResult = RESULT_NONE; this.concurrentResultContext = processingContext; } Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null"); if (logger.isDebugEnabled()) { logger.debug("Started async request for " + formatUri(this.asyncWebRequest)); } this.asyncWebRequest.startAsync(); } private void setConcurrentResultAndDispatch(@Nullable Object result) { Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null"); synchronized (WebAsyncManager.this) { if (!this.state.compareAndSet(State.ASYNC_PROCESSING, State.RESULT_SET)) { if (logger.isDebugEnabled()) { logger.debug("Async result already set: [" + this.state.get() + "], " + "ignored result for " + formatUri(this.asyncWebRequest)); } return; } this.concurrentResult = result; if (logger.isDebugEnabled()) { logger.debug("Async result set for " + formatUri(this.asyncWebRequest)); } if (this.asyncWebRequest.isAsyncComplete()) { if (logger.isDebugEnabled()) { logger.debug("Async request already completed for " + formatUri(this.asyncWebRequest)); } return; } if (logger.isDebugEnabled()) { logger.debug("Performing async dispatch for " + formatUri(this.asyncWebRequest)); } this.asyncWebRequest.dispatch(); } } private static String formatUri(AsyncWebRequest asyncWebRequest) { HttpServletRequest request = asyncWebRequest.getNativeRequest(HttpServletRequest.class); return (request != null ? "\"" + request.getRequestURI() + "\"" : "servlet container"); } /** * Represents a state for {@link WebAsyncManager} to be in. * <p><pre> * +------> NOT_STARTED <------+ * | | | * | v | * | ASYNC_PROCESSING | * | | | * | v | * <-------+ RESULT_SET -------+ * </pre> * @since 5.3.33 */ private
name
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/JoinedInheritanceCollectionSameHierarchyTest.java
{ "start": 3904, "end": 4178 }
class ____ extends SuperEntity { // necessary intermediate entity so 'BaseUser' is the first child type and gets the lowest discriminator value public BaseUser() { } public BaseUser(Integer id) { super( id ); } } @Entity( name = "UserEntity" ) static
BaseUser
java
apache__camel
tooling/camel-tooling-model/src/main/java/org/apache/camel/tooling/model/SupportLevel.java
{ "start": 951, "end": 2175 }
enum ____ { /** * An experimental entity (not feature complete) that will change API, configuration, or functionality, or even be * removed in the future. * * Intended to be matured over time and become preview or stable. * * Using this entity is not recommended for production usage. */ Experimental, /** * A preview entity that may change API, configuration, or functionality. * * Intended to be matured over time and become stable. * * Can be used in production but use with care. */ Preview, /** * A stable entity. */ Stable; public static final SupportLevel baseStability = Stable; public static SupportLevel safeValueOf(String level) { if (level == null) { return baseStability; } if (level.compareToIgnoreCase(Experimental.name()) == 0) { return Experimental; } else if (level.compareToIgnoreCase(Preview.name()) == 0) { return Preview; } else if (level.compareToIgnoreCase(Stable.name()) == 0) { return Stable; } throw new IllegalArgumentException("Unknown supportLevel: " + level); } }
SupportLevel
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OAuth2RefreshTokenGrantTests.java
{ "start": 26114, "end": 27910 }
class ____ implements AuthenticationProvider { private final RegisteredClientRepository registeredClientRepository; private PublicClientRefreshTokenAuthenticationProvider(RegisteredClientRepository registeredClientRepository) { Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null"); this.registeredClientRepository = registeredClientRepository; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { PublicClientRefreshTokenAuthenticationToken publicClientAuthentication = (PublicClientRefreshTokenAuthenticationToken) authentication; if (!ClientAuthenticationMethod.NONE.equals(publicClientAuthentication.getClientAuthenticationMethod())) { return null; } String clientId = publicClientAuthentication.getPrincipal().toString(); RegisteredClient registeredClient = this.registeredClientRepository.findByClientId(clientId); if (registeredClient == null) { throwInvalidClient(OAuth2ParameterNames.CLIENT_ID); } if (!registeredClient.getClientAuthenticationMethods() .contains(publicClientAuthentication.getClientAuthenticationMethod())) { throwInvalidClient("authentication_method"); } return new PublicClientRefreshTokenAuthenticationToken(registeredClient); } @Override public boolean supports(Class<?> authentication) { return PublicClientRefreshTokenAuthenticationToken.class.isAssignableFrom(authentication); } private static void throwInvalidClient(String parameterName) { OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT, "Public client authentication failed: " + parameterName, null); throw new OAuth2AuthenticationException(error); } } }
PublicClientRefreshTokenAuthenticationProvider
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/arm-java/org/apache/hadoop/ipc/protobuf/TestProtosLegacy.java
{ "start": 112641, "end": 118577 }
class ____ extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_SleepRequestProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_SleepRequestProto_fieldAccessorTable .ensureFieldAccessorsInitialized( org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto.class, org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto.Builder.class); } // Construct using org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); milliSeconds_ = 0; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.internal_static_hadoop_common_SleepRequestProto_descriptor; } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto getDefaultInstanceForType() { return org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto.getDefaultInstance(); } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto build() { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto buildPartial() { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto result = new org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.milliSeconds_ = milliSeconds_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto) { return mergeFrom((org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto other) { if (other == org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto.getDefaultInstance()) return this; if (other.hasMilliSeconds()) { setMilliSeconds(other.getMilliSeconds()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { if (!hasMilliSeconds()) { return false; } return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.apache.hadoop.ipc.protobuf.TestProtosLegacy.SleepRequestProto) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; // required int32 milliSeconds = 1; private int milliSeconds_ ; /** * <code>required int32 milliSeconds = 1;</code> */ public boolean hasMilliSeconds() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>required int32 milliSeconds = 1;</code> */ public int getMilliSeconds() { return milliSeconds_; } /** * <code>required int32 milliSeconds = 1;</code> */ public Builder setMilliSeconds(int value) { bitField0_ |= 0x00000001; milliSeconds_ = value; onChanged(); return this; } /** * <code>required int32 milliSeconds = 1;</code> */ public Builder clearMilliSeconds() { bitField0_ = (bitField0_ & ~0x00000001); milliSeconds_ = 0; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:hadoop.common.SleepRequestProto) } static { defaultInstance = new SleepRequestProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:hadoop.common.SleepRequestProto) } public
Builder
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SmppsComponentBuilderFactory.java
{ "start": 1888, "end": 21939 }
interface ____ extends ComponentBuilder<SmppComponent> { /** * Defines the initial delay in milliseconds after the consumer/producer * tries to reconnect to the SMSC, after the connection was lost. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 5000 * Group: common * * @param initialReconnectDelay the value to set * @return the dsl builder */ default SmppsComponentBuilder initialReconnectDelay(long initialReconnectDelay) { doSetProperty("initialReconnectDelay", initialReconnectDelay); return this; } /** * Defines the maximum number of attempts to reconnect to the SMSC, if * SMSC returns a negative bind response. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 2147483647 * Group: common * * @param maxReconnect the value to set * @return the dsl builder */ default SmppsComponentBuilder maxReconnect(int maxReconnect) { doSetProperty("maxReconnect", maxReconnect); return this; } /** * Defines the interval in milliseconds between the reconnect attempts, * if the connection to the SMSC was lost and the previous was not * succeed. * * The option is a: &lt;code&gt;long&lt;/code&gt; type. * * Default: 5000 * Group: common * * @param reconnectDelay the value to set * @return the dsl builder */ default SmppsComponentBuilder reconnectDelay(long reconnectDelay) { doSetProperty("reconnectDelay", reconnectDelay); return this; } /** * You can specify a policy for handling long messages: ALLOW - the * default, long messages are split to 140 bytes per message TRUNCATE - * long messages are split and only the first fragment will be sent to * the SMSC. Some carriers drop subsequent fragments so this reduces * load on the SMPP connection sending parts of a message that will * never be delivered. REJECT - if a message would need to be split, it * is rejected with an SMPP NegativeResponseException and the reason * code signifying the message is too long. * * The option is a: * &lt;code&gt;org.apache.camel.component.smpp.SmppSplittingPolicy&lt;/code&gt; type. * * Default: ALLOW * Group: common * * @param splittingPolicy the value to set * @return the dsl builder */ default SmppsComponentBuilder splittingPolicy(org.apache.camel.component.smpp.SmppSplittingPolicy splittingPolicy) { doSetProperty("splittingPolicy", splittingPolicy); return this; } /** * This parameter is used to categorize the type of ESME (External Short * Message Entity) that is binding to the SMSC (max. 13 characters). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: common * * @param systemType the value to set * @return the dsl builder */ default SmppsComponentBuilder systemType(java.lang.String systemType) { doSetProperty("systemType", systemType); return this; } /** * You can specify the address range for the SmppConsumer as defined in * section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will * receive messages only from SMSC's which target an address (MSISDN or * IP address) within this range. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: consumer * * @param addressRange the value to set * @return the dsl builder */ default SmppsComponentBuilder addressRange(java.lang.String addressRange) { doSetProperty("addressRange", addressRange); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default SmppsComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Defines the destination SME address. For mobile terminated messages, * this is the directory number of the recipient MS. Only for SubmitSm, * SubmitMulti, CancelSm and DataSm. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: 1717 * Group: producer * * @param destAddr the value to set * @return the dsl builder */ default SmppsComponentBuilder destAddr(java.lang.String destAddr) { doSetProperty("destAddr", destAddr); return this; } /** * Defines the type of number (TON) to be used in the SME destination * address parameters. Only for SubmitSm, SubmitMulti, CancelSm and * DataSm. The following NPI values are defined: 0: Unknown 1: ISDN * (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: * National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to * be defined by WAP Forum). * * The option is a: &lt;code&gt;byte&lt;/code&gt; type. * * Group: producer * * @param destAddrNpi the value to set * @return the dsl builder */ default SmppsComponentBuilder destAddrNpi(byte destAddrNpi) { doSetProperty("destAddrNpi", destAddrNpi); return this; } /** * Defines the type of number (TON) to be used in the SME destination * address parameters. Only for SubmitSm, SubmitMulti, CancelSm and * DataSm. The following TON values are defined: 0: Unknown 1: * International 2: National 3: Network Specific 4: Subscriber Number 5: * Alphanumeric 6: Abbreviated. * * The option is a: &lt;code&gt;byte&lt;/code&gt; type. * * Group: producer * * @param destAddrTon the value to set * @return the dsl builder */ default SmppsComponentBuilder destAddrTon(byte destAddrTon) { doSetProperty("destAddrTon", destAddrTon); return this; } /** * Sessions can be lazily created to avoid exceptions, if the SMSC is * not available when the Camel producer is started. Camel will check * the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of * the first exchange. If they are present, Camel will use these data to * connect to the SMSC. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazySessionCreation the value to set * @return the dsl builder */ default SmppsComponentBuilder lazySessionCreation(boolean lazySessionCreation) { doSetProperty("lazySessionCreation", lazySessionCreation); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default SmppsComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Set this on producer in order to benefit from transceiver (TRX) * binding type. So once set, you don't need to define an 'SMTPP * consumer' endpoint anymore. You would set this to a 'Direct consumer' * endpoint instead. DISCALIMER: This feature is only tested with * 'Direct consumer' endpoint. The behavior with any other consumer type * is unknown and not tested. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param messageReceiverRouteId the value to set * @return the dsl builder */ default SmppsComponentBuilder messageReceiverRouteId(java.lang.String messageReceiverRouteId) { doSetProperty("messageReceiverRouteId", messageReceiverRouteId); return this; } /** * Defines the numeric plan indicator (NPI) to be used in the SME. The * following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: * Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: * Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined * by WAP Forum). * * The option is a: &lt;code&gt;byte&lt;/code&gt; type. * * Group: producer * * @param numberingPlanIndicator the value to set * @return the dsl builder */ default SmppsComponentBuilder numberingPlanIndicator(byte numberingPlanIndicator) { doSetProperty("numberingPlanIndicator", numberingPlanIndicator); return this; } /** * Allows the originating SME to assign a priority level to the short * message. Only for SubmitSm and SubmitMulti. Four Priority Levels are * supported: 0: Level 0 (lowest) priority 1: Level 1 priority 2: Level * 2 priority 3: Level 3 (highest) priority. * * The option is a: &lt;code&gt;byte&lt;/code&gt; type. * * Group: producer * * @param priorityFlag the value to set * @return the dsl builder */ default SmppsComponentBuilder priorityFlag(byte priorityFlag) { doSetProperty("priorityFlag", priorityFlag); return this; } /** * The protocol id. * * The option is a: &lt;code&gt;byte&lt;/code&gt; type. * * Group: producer * * @param protocolId the value to set * @return the dsl builder */ default SmppsComponentBuilder protocolId(byte protocolId) { doSetProperty("protocolId", protocolId); return this; } /** * Is used to request an SMSC delivery receipt and/or SME originated * acknowledgements. The following values are defined: 0: No SMSC * delivery receipt requested. 1: SMSC delivery receipt requested where * final delivery outcome is success or failure. 2: SMSC delivery * receipt requested where the final delivery outcome is delivery * failure. * * The option is a: &lt;code&gt;byte&lt;/code&gt; type. * * Group: producer * * @param registeredDelivery the value to set * @return the dsl builder */ default SmppsComponentBuilder registeredDelivery(byte registeredDelivery) { doSetProperty("registeredDelivery", registeredDelivery); return this; } /** * Used to request the SMSC to replace a previously submitted message, * that is still pending delivery. The SMSC will replace an existing * message provided that the source address, destination address and * service type match the same fields in the new message. The following * replace if present flag values are defined: 0: Don't replace 1: * Replace. * * The option is a: &lt;code&gt;byte&lt;/code&gt; type. * * Group: producer * * @param replaceIfPresentFlag the value to set * @return the dsl builder */ default SmppsComponentBuilder replaceIfPresentFlag(byte replaceIfPresentFlag) { doSetProperty("replaceIfPresentFlag", replaceIfPresentFlag); return this; } /** * The service type parameter can be used to indicate the SMS * Application service associated with the message. The following * generic service_types are defined: CMT: Cellular Messaging CPT: * Cellular Paging VMN: Voice Mail Notification VMA: Voice Mail Alerting * WAP: Wireless Application Protocol USSD: Unstructured Supplementary * Services Data. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param serviceType the value to set * @return the dsl builder */ default SmppsComponentBuilder serviceType(java.lang.String serviceType) { doSetProperty("serviceType", serviceType); return this; } /** * Defines the address of SME (Short Message Entity) which originated * this message. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: 1616 * Group: producer * * @param sourceAddr the value to set * @return the dsl builder */ default SmppsComponentBuilder sourceAddr(java.lang.String sourceAddr) { doSetProperty("sourceAddr", sourceAddr); return this; } /** * Defines the numeric plan indicator (NPI) to be used in the SME * originator address parameters. The following NPI values are defined: * 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: * Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet * (IP) 18: WAP Client Id (to be defined by WAP Forum). * * The option is a: &lt;code&gt;byte&lt;/code&gt; type. * * Group: producer * * @param sourceAddrNpi the value to set * @return the dsl builder */ default SmppsComponentBuilder sourceAddrNpi(byte sourceAddrNpi) { doSetProperty("sourceAddrNpi", sourceAddrNpi); return this; } /** * Defines the type of number (TON) to be used in the SME originator * address parameters. The following TON values are defined: 0: Unknown * 1: International 2: National 3: Network Specific 4: Subscriber Number * 5: Alphanumeric 6: Abbreviated. * * The option is a: &lt;code&gt;byte&lt;/code&gt; type. * * Group: producer * * @param sourceAddrTon the value to set * @return the dsl builder */ default SmppsComponentBuilder sourceAddrTon(byte sourceAddrTon) { doSetProperty("sourceAddrTon", sourceAddrTon); return this; } /** * Defines the type of number (TON) to be used in the SME. The following * TON values are defined: 0: Unknown 1: International 2: National 3: * Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated. * * The option is a: &lt;code&gt;byte&lt;/code&gt; type. * * Group: producer * * @param typeOfNumber the value to set * @return the dsl builder */ default SmppsComponentBuilder typeOfNumber(byte typeOfNumber) { doSetProperty("typeOfNumber", typeOfNumber); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default SmppsComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * To use the shared SmppConfiguration as configuration. * * The option is a: * &lt;code&gt;org.apache.camel.component.smpp.SmppConfiguration&lt;/code&gt; type. * * Group: advanced * * @param configuration the value to set * @return the dsl builder */ default SmppsComponentBuilder configuration(org.apache.camel.component.smpp.SmppConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * Defines the interval in milliseconds between the confidence checks. * The confidence check is used to test the communication path between * an ESME and an SMSC. * * The option is a: &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Default: 60000 * Group: advanced * * @param enquireLinkTimer the value to set * @return the dsl builder */ default SmppsComponentBuilder enquireLinkTimer(java.lang.Integer enquireLinkTimer) { doSetProperty("enquireLinkTimer", enquireLinkTimer); return this; } /** * Defines the
SmppsComponentBuilder
java
spring-projects__spring-security
oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/JWKS.java
{ "start": 1304, "end": 2698 }
class ____ { private JWKS() { } static OctetSequenceKey.Builder signing(SecretKey key) throws JOSEException { Date issued = new Date(); return new OctetSequenceKey.Builder(key).keyOperations(Set.of(KeyOperation.SIGN)) .keyUse(KeyUse.SIGNATURE) .algorithm(JWSAlgorithm.HS256) .keyIDFromThumbprint() .issueTime(issued) .notBeforeTime(issued); } static ECKey.Builder signingWithEc(ECPublicKey pub, ECPrivateKey key) throws JOSEException { Date issued = new Date(); Curve curve = Curve.forECParameterSpec(pub.getParams()); JWSAlgorithm algorithm = computeAlgorithm(curve); return new ECKey.Builder(curve, pub).privateKey(key) .keyOperations(Set.of(KeyOperation.SIGN)) .keyUse(KeyUse.SIGNATURE) .algorithm(algorithm) .keyIDFromThumbprint() .issueTime(issued) .notBeforeTime(issued); } private static JWSAlgorithm computeAlgorithm(Curve curve) { try { return ECDSA.resolveAlgorithm(curve); } catch (JOSEException ex) { throw new IllegalArgumentException(ex); } } static RSAKey.Builder signingWithRsa(RSAPublicKey pub, RSAPrivateKey key) throws JOSEException { Date issued = new Date(); return new RSAKey.Builder(pub).privateKey(key) .keyUse(KeyUse.SIGNATURE) .keyOperations(Set.of(KeyOperation.SIGN)) .algorithm(JWSAlgorithm.RS256) .keyIDFromThumbprint() .issueTime(issued) .notBeforeTime(issued); } }
JWKS
java
spring-projects__spring-boot
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/EndpointAccessResolver.java
{ "start": 815, "end": 1226 }
interface ____ { /** * Resolves the permitted level of access for the endpoint with the given * {@code endpointId} and {@code defaultAccess}. * @param endpointId the ID of the endpoint * @param defaultAccess the default access level of the endpoint * @return the permitted level of access, never {@code null} */ Access accessFor(EndpointId endpointId, Access defaultAccess); }
EndpointAccessResolver
java
google__error-prone
core/src/test/java/com/google/errorprone/ErrorProneCompilerIntegrationTest.java
{ "start": 12455, "end": 12684 }
class ____ { public Test() {} } """)))); } @Test public void flagEnablesCheck() { String[] testFile = { "package test;", // "public
Test
java
quarkusio__quarkus
extensions/azure-functions/deployment/src/main/java/io/quarkus/azure/functions/deployment/AzureFunctionsDeployCommand.java
{ "start": 3216, "end": 18749 }
class ____ { private static final Logger log = Logger.getLogger(AzureFunctionsDeployCommand.class); private static final String APP_NAME_PATTERN = "[a-zA-Z0-9\\-]{2,60}"; private static final String RESOURCE_GROUP_PATTERN = "[a-zA-Z0-9._\\-()]{1,90}"; private static final String APP_SERVICE_PLAN_NAME_PATTERN = "[a-zA-Z0-9\\-]{1,40}"; private static final String EMPTY_APP_NAME = "Please config the <appName> in pom.xml."; private static final String INVALID_APP_NAME = "The app name '%s' is not valid. The <appName> only allow alphanumeric characters, hyphens and cannot start or end in a hyphen."; private static final String EMPTY_RESOURCE_GROUP = "Please config the <resourceGroup> in pom.xml."; private static final String INVALID_RESOURCE_GROUP_NAME = "The <resourceGroup> only allow alphanumeric characters, periods, underscores, " + "hyphens and parenthesis and cannot end in a period."; private static final String INVALID_SERVICE_PLAN_NAME = "Invalid value for <appServicePlanName>, it need to match the pattern %s"; private static final String INVALID_SERVICE_PLAN_RESOURCE_GROUP_NAME = "Invalid value for <appServicePlanResourceGroup>, " + "it only allow alphanumeric characters, periods, underscores, hyphens and parenthesis and cannot end in a period."; private static final String EMPTY_IMAGE_NAME = "Please config the <image> of <runtime> in pom.xml."; private static final String INVALID_OS = "The value of <os> is not correct, supported values are: windows, linux and docker."; private static final String EXPANDABLE_PRICING_TIER_WARNING = "'%s' may not be a valid pricing tier, " + "please refer to https://aka.ms/maven_function_configuration#supported-pricing-tiers for valid values"; private static final String EXPANDABLE_REGION_WARNING = "'%s' may not be a valid region, " + "please refer to https://aka.ms/maven_function_configuration#supported-regions for valid values"; private static final Pattern JAVA_VERSION_PATTERN = Pattern.compile("(java )?[0-9]+", Pattern.CASE_INSENSITIVE); private static final String EXPANDABLE_JAVA_VERSION_WARNING = "'%s' may not be a valid java version, recommended values are `17` or `21`"; protected static final String USING_AZURE_ENVIRONMENT = "Using Azure environment: %s."; public static final String AZURE_FUNCTIONS = "azure-functions"; protected static final String SUBSCRIPTION_TEMPLATE = "Subscription: %s(%s)"; protected static final String SUBSCRIPTION_NOT_FOUND = "Subscription %s was not found in current account."; @BuildStep public void declare(BuildProducer<DeployCommandDeclarationBuildItem> producer) { producer.produce(new DeployCommandDeclarationBuildItem(AZURE_FUNCTIONS)); } @BuildStep public void deploy(DeployConfig deployConfig, AzureFunctionsConfig config, AzureFunctionsAppNameBuildItem appName, OutputTargetBuildItem output, BuildProducer<DeployCommandActionBuildItem> producer) throws Exception { if (!deployConfig.isEnabled(AZURE_FUNCTIONS)) { return; } validateParameters(config, appName.getAppName()); setCurrentOperation(); AzureMessager.setDefaultMessager(new QuarkusAzureMessager()); Azure.az().config().setLogLevel(HttpLogDetailLevel.NONE.name()); initAzureAppServiceClient(config); try { final FunctionAppBase<?, ?, ?> target = createOrUpdateResource( config.toFunctionAppConfig(subscriptionId, appName.getAppName())); Path outputDirectory = output.getOutputDirectory(); Path functionStagingDir = outputDirectory.resolve(AZURE_FUNCTIONS).resolve(appName.getAppName()); deployArtifact(functionStagingDir, target); } catch (AzureToolkitRuntimeException e) { throw new DeploymentException("Unable to deploy Azure function: " + e.getMessage().replace("\\r\\n", "\n"), e); } producer.produce(new DeployCommandActionBuildItem(AZURE_FUNCTIONS, true)); } private void setCurrentOperation() { // Note: // This gets rid of some these messages. Not sure why or how to remove the rest of them yet: // default to NULL OperationContext, because operation or its action operation is null:Quarkus try { Method push = OperationThreadContext.class.getDeclaredMethod("pushOperation", Operation.class); push.setAccessible(true); OperationBase dummy = new OperationBase() { @Override public Object getSource() { return null; } @Override public String getId() { return "Quarkus"; } @Override public Callable<?> getBody() { throw new RuntimeException("Not Implmented"); } @Override public String getType() { return "Quarkus"; } @Override public AzureString getDescription() { return AzureString.fromString("Quarkus"); } }; OperationThreadContext ctx = OperationThreadContext.current(); push.invoke(ctx, dummy); } catch (Exception e) { } } protected void validateParameters(AzureFunctionsConfig config, String appName) throws BuildException { // app name if (StringUtils.isBlank(appName)) { throw new BuildException(EMPTY_APP_NAME); } if (appName.startsWith("-") || !appName.matches(APP_NAME_PATTERN)) { throw new BuildException(format(INVALID_APP_NAME, appName)); } // resource group if (StringUtils.isBlank(config.resourceGroup())) { throw new BuildException(EMPTY_RESOURCE_GROUP); } if (config.resourceGroup().endsWith(".") || !config.resourceGroup().matches(RESOURCE_GROUP_PATTERN)) { throw new BuildException(INVALID_RESOURCE_GROUP_NAME); } // asp name & resource group if (StringUtils.isNotEmpty(config.appServicePlanName()) && !config.appServicePlanName().matches(APP_SERVICE_PLAN_NAME_PATTERN)) { throw new BuildException(format(INVALID_SERVICE_PLAN_NAME, APP_SERVICE_PLAN_NAME_PATTERN)); } if (config.appServicePlanResourceGroup().isPresent() && StringUtils.isNotEmpty(config.appServicePlanResourceGroup().orElse(null)) && (config.appServicePlanResourceGroup().orElse(null).endsWith(".") || !config.appServicePlanResourceGroup().orElse(null).matches(RESOURCE_GROUP_PATTERN))) { throw new BuildException(INVALID_SERVICE_PLAN_RESOURCE_GROUP_NAME); } // slot name /* * if (deploymentSlotSetting != null && StringUtils.isEmpty(deploymentSlotSetting.getName())) { * throw new BuildException(EMPTY_SLOT_NAME); * } * if (deploymentSlotSetting != null && !deploymentSlotSetting.getName().matches(SLOT_NAME_PATTERN)) { * throw new BuildException(String.format(INVALID_SLOT_NAME, SLOT_NAME_PATTERN)); * } * */ // region if (StringUtils.isNotEmpty(config.region()) && Region.fromName(config.region()).isExpandedValue()) { log.warn(format(EXPANDABLE_REGION_WARNING, config.region())); } // os if (StringUtils.isNotEmpty(config.runtime().os()) && OperatingSystem.fromString(config.runtime().os()) == null) { throw new BuildException(INVALID_OS); } // java version if (StringUtils.isNotEmpty(config.runtime().javaVersion()) && !JAVA_VERSION_PATTERN.matcher(config.runtime().javaVersion()).matches()) { log.warn(format(EXPANDABLE_JAVA_VERSION_WARNING, config.runtime().javaVersion())); } // pricing tier if (config.pricingTier().isPresent() && StringUtils.isNotEmpty(config.pricingTier().orElse(null)) && PricingTier.fromString(config.pricingTier().orElse(null)).isExpandedValue()) { log.warn(format(EXPANDABLE_PRICING_TIER_WARNING, config.pricingTier().orElse(null))); } // docker image if (OperatingSystem.fromString(config.runtime().os()) == OperatingSystem.DOCKER && StringUtils.isEmpty(config.runtime().image().orElse(null))) { throw new BuildException(EMPTY_IMAGE_NAME); } } protected static AzureAppService appServiceClient; protected static String subscriptionId; protected AzureAppService initAzureAppServiceClient(AzureFunctionsConfig config) throws BuildException { if (appServiceClient == null) { final Account account = loginAzure(config.auth()); final List<Subscription> subscriptions = account.getSubscriptions(); final String targetSubscriptionId = getTargetSubscriptionId(config.subscriptionId().orElse(null), subscriptions, account.getSelectedSubscriptions()); checkSubscription(subscriptions, targetSubscriptionId); com.microsoft.azure.toolkit.lib.Azure.az(AzureAccount.class).account() .setSelectedSubscriptions(Collections.singletonList(targetSubscriptionId)); appServiceClient = Azure.az(AzureAppService.class); printCurrentSubscription(appServiceClient); this.subscriptionId = targetSubscriptionId; } return appServiceClient; } protected static void checkSubscription(List<Subscription> subscriptions, String targetSubscriptionId) throws BuildException { if (StringUtils.isEmpty(targetSubscriptionId)) { return; } final Optional<Subscription> optionalSubscription = subscriptions.stream() .filter(subscription -> StringUtils.equals(subscription.getId(), targetSubscriptionId)) .findAny(); if (!optionalSubscription.isPresent()) { throw new BuildException(format(SUBSCRIPTION_NOT_FOUND, targetSubscriptionId)); } } protected Account loginAzure(AzureFunctionsConfig.AuthConfig auth) { if (Azure.az(AzureAccount.class).isLoggedIn()) { return Azure.az(AzureAccount.class).account(); } final AuthConfiguration authConfig = auth.toAuthConfiguration(); if (authConfig.getType() == AuthType.DEVICE_CODE) { authConfig.setDeviceCodeConsumer(info -> { final String message = StringUtils.replace(info.getMessage(), info.getUserCode(), TextUtils.cyan(info.getUserCode())); System.out.println(message); }); } final AzureEnvironment configEnv = AzureEnvironmentUtils.stringToAzureEnvironment(authConfig.getEnvironment()); promptAzureEnvironment(configEnv); Azure.az(AzureCloud.class).set(configEnv); final Account account = Azure.az(AzureAccount.class).login(authConfig, false); final AzureEnvironment env = account.getEnvironment(); final String environmentName = AzureEnvironmentUtils.azureEnvironmentToString(env); if (env != AzureEnvironment.AZURE && env != configEnv) { log.info(AzureString.format(USING_AZURE_ENVIRONMENT, environmentName)); } printCredentialDescription(account); return account; } protected static void printCredentialDescription(Account account) { final AuthType type = account.getType(); final String username = account.getUsername(); if (type != null) { log.info(AzureString.format("Auth type: %s", type.toString())); } if (account.isLoggedIn()) { final List<Subscription> selectedSubscriptions = account.getSelectedSubscriptions(); if (CollectionUtils.isNotEmpty(selectedSubscriptions) && selectedSubscriptions.size() == 1) { log.info(AzureString.format("Default subscription: %s(%s)", selectedSubscriptions.get(0).getName(), selectedSubscriptions.get(0).getId())); } } if (StringUtils.isNotEmpty(username)) { log.info(AzureString.format("Username: %s", username.trim())); } } private static void promptAzureEnvironment(AzureEnvironment env) { if (env != null && env != AzureEnvironment.AZURE) { log.info(AzureString.format("Auth environment: %s", AzureEnvironmentUtils.azureEnvironmentToString(env))); } } protected String getTargetSubscriptionId(String defaultSubscriptionId, List<Subscription> subscriptions, List<Subscription> selectedSubscriptions) throws BuildException { if (!StringUtils.isBlank(defaultSubscriptionId)) { return defaultSubscriptionId; } if (selectedSubscriptions.size() == 1) { return selectedSubscriptions.get(0).getId(); } if (selectedSubscriptions.isEmpty()) { throw new BuildException("You account does not have a subscription to deploy to"); } throw new BuildException("You must specify a subscription id to use for deployment as you have more than one"); } protected void printCurrentSubscription(AzureAppService appServiceClient) { if (appServiceClient == null) { return; } final List<Subscription> subscriptions = Azure.az(IAzureAccount.class).account().getSelectedSubscriptions(); final Subscription subscription = subscriptions.get(0); if (subscription != null) { log.info(format(SUBSCRIPTION_TEMPLATE, TextUtils.cyan(subscription.getName()), TextUtils.cyan(subscription.getId()))); } } protected FunctionAppBase<?, ?, ?> createOrUpdateResource(final FunctionAppConfig config) throws Exception { FunctionApp app = Azure.az(AzureFunctions.class).functionApps(config.subscriptionId()).updateOrCreate(config.appName(), config.resourceGroup()); final boolean newFunctionApp = !app.exists(); AppServiceConfig defaultConfig = !newFunctionApp ? fromAppService(app, app.getAppServicePlan()) : buildDefaultConfig(config.subscriptionId(), config.resourceGroup(), config.appName()); mergeAppServiceConfig(config, defaultConfig); if (!newFunctionApp && !config.disableAppInsights() && StringUtils.isEmpty(config.appInsightsKey())) { // fill ai key from existing app settings config.appInsightsKey(app.getAppSettings().get(CreateOrUpdateFunctionAppTask.APPINSIGHTS_INSTRUMENTATION_KEY)); } return new CreateOrUpdateFunctionAppTask(config).doExecute(); } private AppServiceConfig buildDefaultConfig(String subscriptionId, String resourceGroup, String appName) { return AppServiceConfig.buildDefaultFunctionConfig(resourceGroup, appName); } private void deployArtifact(Path functionStagingDir, final FunctionAppBase<?, ?, ?> target) { final File file = functionStagingDir.toFile(); new DeployFunctionAppTask(target, file, null).doExecute(); } public static
AzureFunctionsDeployCommand
java
google__gson
gson/src/test/java/com/google/gson/common/TestTypes.java
{ "start": 10566, "end": 10804 }
class ____ { public final BagOfPrimitives bag; public ClassWithObjects() { this(new BagOfPrimitives()); } public ClassWithObjects(BagOfPrimitives bag) { this.bag = bag; } } public static
ClassWithObjects
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/BasicTypeSerializerUpgradeTestSpecifications.java
{ "start": 1850, "end": 2211 }
class ____ { // ---------------------------------------------------------------------------------------------- // Specification for "big-dec-serializer" // ---------------------------------------------------------------------------------------------- /** BigDecSerializerSetup. */ public static final
BasicTypeSerializerUpgradeTestSpecifications
java
quarkusio__quarkus
extensions/vertx/deployment/src/test/java/io/quarkus/vertx/VertxInjectionTest.java
{ "start": 1578, "end": 1995 }
class ____ { @Inject EventBus vertx; @Inject io.vertx.mutiny.core.eventbus.EventBus mutiny; boolean ok; public boolean verify() { return ok; } public void init(@Observes StartupEvent ev) { Assertions.assertNotNull(vertx); Assertions.assertNotNull(mutiny); ok = true; } } }
MyBeanUsingEventBus
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamOperatorWrapper.java
{ "start": 9578, "end": 10550 }
class ____ implements Iterator<StreamOperatorWrapper<?, ?>>, Iterable<StreamOperatorWrapper<?, ?>> { private final boolean reverse; private StreamOperatorWrapper<?, ?> current; ReadIterator(StreamOperatorWrapper<?, ?> first, boolean reverse) { this.current = first; this.reverse = reverse; } @Override public boolean hasNext() { return this.current != null; } @Override public StreamOperatorWrapper<?, ?> next() { if (hasNext()) { StreamOperatorWrapper<?, ?> next = current; current = reverse ? current.previous : current.next; return next; } throw new NoSuchElementException(); } @Nonnull @Override public Iterator<StreamOperatorWrapper<?, ?>> iterator() { return this; } } }
ReadIterator
java
elastic__elasticsearch
x-pack/plugin/searchable-snapshots/src/internalClusterTest/java/org/elasticsearch/xpack/searchablesnapshots/SearchableSnapshotsUuidValidationIntegTests.java
{ "start": 1738, "end": 1860 }
class ____ extends BaseFrozenSearchableSnapshotsIntegTestCase { public static
SearchableSnapshotsUuidValidationIntegTests
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/TopBooleanAggregator.java
{ "start": 2895, "end": 3974 }
class ____ implements GroupingAggregatorState { private final BooleanBucketedSort sort; private GroupingState(BigArrays bigArrays, int limit, boolean ascending) { this.sort = new BooleanBucketedSort(bigArrays, ascending ? SortOrder.ASC : SortOrder.DESC, limit); } public void add(int groupId, boolean value) { sort.collect(value, groupId); } @Override public void toIntermediate(Block[] blocks, int offset, IntVector selected, DriverContext driverContext) { blocks[offset] = toBlock(driverContext.blockFactory(), selected); } Block toBlock(BlockFactory blockFactory, IntVector selected) { return sort.toBlock(blockFactory, selected); } @Override public void enableGroupIdTracking(SeenGroupIds seen) { // we figure out seen values from nulls on the values block } @Override public void close() { Releasables.closeExpectNoException(sort); } } public static
GroupingState
java
quarkusio__quarkus
extensions/agroal/deployment/src/test/java/io/quarkus/agroal/test/ConfigActiveFalseNamedDatasourceStaticInjectionTest.java
{ "start": 433, "end": 1959 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .overrideConfigKey("quarkus.datasource.users.active", "false") // We need at least one build-time property for the datasource, // otherwise it's considered unconfigured at build time... .overrideConfigKey("quarkus.datasource.users.db-kind", "h2") .assertException(e -> assertThat(e) // Can't use isInstanceOf due to weird classloading in tests .satisfies(t -> assertThat(t.getClass().getName()).isEqualTo(InactiveBeanException.class.getName())) .hasMessageContainingAll("Datasource 'users' was deactivated through configuration properties.", "To avoid this exception while keeping the bean inactive", // Message from Arc with generic hints "To activate the datasource, set configuration property 'quarkus.datasource.\"users\".active'" + " to 'true' and configure datasource 'users'", "Refer to https://quarkus.io/guides/datasource for guidance.", "This bean is injected into", MyBean.class.getName() + "#ds")); @Inject MyBean myBean; @Test public void test() { Assertions.fail("Startup should have failed"); } @ApplicationScoped public static
ConfigActiveFalseNamedDatasourceStaticInjectionTest
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/convert/ApplicationConversionServiceTests.java
{ "start": 17060, "end": 17226 }
class ____ implements Printer<Integer> { @Override public String print(Integer object, Locale locale) { return ""; } } @Configuration static
ExamplePrinter
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/converter/TimerDrivenTimePatternConverterTest.java
{ "start": 1241, "end": 2373 }
class ____ extends ContextTestSupport { private static final Logger LOG = LoggerFactory.getLogger(TimerDrivenTimePatternConverterTest.class); @Test public void testTimerInvocation() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(2); assertMockEndpointsSatisfied(); } @Test public void testTimerUsingStopWatch() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMinimumMessageCount(2); StopWatch watch = new StopWatch(); assertMockEndpointsSatisfied(); long interval = watch.taken(); LOG.trace("Should take approx 50 milliseconds, was: {}", interval); assertTrue(interval >= 40, "Should take approx 50 milliseconds, was: " + interval); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("timer://foo?fixedRate=true&delay=0&period=50").to("mock:result"); } }; } }
TimerDrivenTimePatternConverterTest
java
grpc__grpc-java
interop-testing/src/test/java/io/grpc/testing/integration/CompressionTest.java
{ "start": 10512, "end": 10960 }
class ____<ReqT, RespT> extends SimpleForwardingClientCall<ReqT, RespT> { protected ClientCompressor(ClientCall<ReqT, RespT> delegate) { super(delegate); } @Override public void start(io.grpc.ClientCall.Listener<RespT> responseListener, Metadata headers) { super.start(new ClientHeadersCapture<>(responseListener), headers); setMessageCompression(enableClientMessageCompression); } } private
ClientCompressor
java
hibernate__hibernate-orm
local-build-plugins/src/main/java/org/hibernate/build/xjc/XjcPlugin.java
{ "start": 297, "end": 548 }
class ____ implements Plugin<Project> { @Override public void apply(Project project) { // Create the Plugin extension object (for users to configure our execution). project.getExtensions().create( "xjc", XjcExtension.class, project ); } }
XjcPlugin
java
spring-projects__spring-boot
module/spring-boot-servlet/src/main/java/org/springframework/boot/servlet/autoconfigure/actuate/web/ServletManagementContextAutoConfiguration.java
{ "start": 1989, "end": 2221 }
class ____ { @Bean ManagementServletContext managementServletContext(WebEndpointProperties properties) { return properties::getBasePath; } // Put Servlets and Filters in their own nested
ServletManagementContextAutoConfiguration
java
google__gson
metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java
{ "start": 10083, "end": 11645 }
class ____ { @JsonProperty String name; @JsonProperty String profile_sidebar_border_color; @JsonProperty boolean profile_background_tile; @JsonProperty String profile_sidebar_fill_color; @JsonProperty Date created_at; @JsonProperty String location; @JsonProperty String profile_image_url; @JsonProperty boolean follow_request_sent; @JsonProperty String profile_link_color; @JsonProperty boolean is_translator; @JsonProperty String id_str; @JsonProperty int favourites_count; @JsonProperty boolean contributors_enabled; @JsonProperty String url; @JsonProperty boolean default_profile; @JsonProperty long utc_offset; @JsonProperty long id; @JsonProperty boolean profile_use_background_image; @JsonProperty int listed_count; @JsonProperty String lang; @JsonProperty("protected") @SerializedName("protected") boolean isProtected; @JsonProperty int followers_count; @JsonProperty String profile_text_color; @JsonProperty String profile_background_color; @JsonProperty String time_zone; @JsonProperty String description; @JsonProperty boolean notifications; @JsonProperty boolean geo_enabled; @JsonProperty boolean verified; @JsonProperty String profile_background_image_url; @JsonProperty boolean default_profile_image; @JsonProperty int friends_count; @JsonProperty int statuses_count; @JsonProperty String screen_name; @JsonProperty boolean following; @JsonProperty boolean show_all_inline_media; } static
User
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/columnar/vector/writable/WritableTimestampVector.java
{ "start": 1100, "end": 1417 }
interface ____ extends WritableColumnVector, TimestampColumnVector { /** Set {@link TimestampData} at rowId with the provided value. */ void setTimestamp(int rowId, TimestampData timestamp); /** Fill the column vector with the provided value. */ void fill(TimestampData value); }
WritableTimestampVector
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/reservedstate/service/ReservedStateErrorTask.java
{ "start": 1663, "end": 5556 }
class ____ implements ClusterStateTaskListener { private static final Logger logger = LogManager.getLogger(ReservedStateErrorTask.class); private final ErrorState errorState; private final ActionListener<ActionResponse.Empty> listener; public ReservedStateErrorTask(ErrorState errorState, ActionListener<ActionResponse.Empty> listener) { this.errorState = errorState; this.listener = listener; } @Override public void onFailure(Exception e) { listener.onFailure(e); } ActionListener<ActionResponse.Empty> listener() { return listener; } // package private for testing static boolean isNewError(ReservedStateMetadata existingMetadata, Long newStateVersion, ReservedStateVersionCheck versionCheck) { return (existingMetadata == null || existingMetadata.errorMetadata() == null || versionCheck.test(existingMetadata.errorMetadata().version(), newStateVersion) || newStateVersion.equals(RESTORED_VERSION) || newStateVersion.equals(EMPTY_VERSION) || newStateVersion.equals(NO_VERSION)); } static ReservedStateMetadata getMetadata(ClusterState state, ErrorState errorState) { return errorState.projectId() .map(ProjectStateRegistry.get(state)::reservedStateMetadata) .orElseGet(() -> state.metadata().reservedStateMetadata()) .get(errorState.namespace()); } static boolean checkErrorVersion(ClusterState currentState, ErrorState errorState) { ReservedStateMetadata existingMetadata = getMetadata(currentState, errorState); // check for noop here if (isNewError(existingMetadata, errorState.version(), errorState.versionCheck()) == false) { logger.info( () -> format( "Not updating error state because version [%s] is less or equal to the last state error version [%s]", errorState.version(), existingMetadata.errorMetadata().version() ) ); return false; } return true; } boolean shouldUpdate(ClusterState currentState) { return checkErrorVersion(currentState, errorState); } ClusterState execute(ClusterState currentState) { ClusterState.Builder stateBuilder = new ClusterState.Builder(currentState); var errorMetadata = new ReservedStateErrorMetadata(errorState.version(), errorState.errorKind(), errorState.errors()); if (errorState.projectId().isPresent()) { ProjectStateRegistry projectStateRegistry = ProjectStateRegistry.get(currentState); ProjectId projectId = errorState.projectId().get(); ReservedStateMetadata reservedMetadata = projectStateRegistry.reservedStateMetadata(projectId).get(errorState.namespace()); ReservedStateMetadata.Builder resBuilder = ReservedStateMetadata.builder(errorState.namespace(), reservedMetadata); resBuilder.errorMetadata(errorMetadata); stateBuilder.putCustom( ProjectStateRegistry.TYPE, ProjectStateRegistry.builder(projectStateRegistry).putReservedStateMetadata(projectId, resBuilder.build()).build() ); } else { Metadata.Builder metadataBuilder = Metadata.builder(currentState.metadata()); ReservedStateMetadata reservedMetadata = currentState.metadata().reservedStateMetadata().get(errorState.namespace()); ReservedStateMetadata.Builder resBuilder = ReservedStateMetadata.builder(errorState.namespace(), reservedMetadata); resBuilder.errorMetadata(errorMetadata); metadataBuilder.put(resBuilder.build()); stateBuilder.metadata(metadataBuilder); } return stateBuilder.build(); } }
ReservedStateErrorTask
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conversion/bignumbers/BigNumbersConversionTest.java
{ "start": 696, "end": 8404 }
class ____ { @RegisterExtension final GeneratedSource generatedSource = new GeneratedSource(); @ProcessorTest @IssueKey("21") @WithClasses({ BigIntegerSource.class, BigIntegerTarget.class, BigIntegerMapper.class }) public void shouldApplyBigIntegerConversions() { BigIntegerSource source = new BigIntegerSource(); source.setB( new BigInteger( "1" ) ); source.setBb( new BigInteger( "2" ) ); source.setS( new BigInteger( "3" ) ); source.setSs( new BigInteger( "4" ) ); source.setI( new BigInteger( "5" ) ); source.setIi( new BigInteger( "6" ) ); source.setL( new BigInteger( "7" ) ); source.setLl( new BigInteger( "8" ) ); source.setF( new BigInteger( "9" ) ); source.setFf( new BigInteger( "10" ) ); source.setD( new BigInteger( "11" ) ); source.setDd( new BigInteger( "12" ) ); source.setString( new BigInteger( "13" ) ); BigIntegerTarget target = BigIntegerMapper.INSTANCE.sourceToTarget( source ); assertThat( target ).isNotNull(); assertThat( target.getB() ).isEqualTo( (byte) 1 ); assertThat( target.getBb() ).isEqualTo( (byte) 2 ); assertThat( target.getS() ).isEqualTo( (short) 3 ); assertThat( target.getSs() ).isEqualTo( (short) 4 ); assertThat( target.getI() ).isEqualTo( 5 ); assertThat( target.getIi() ).isEqualTo( 6 ); assertThat( target.getL() ).isEqualTo( 7 ); assertThat( target.getLl() ).isEqualTo( 8 ); assertThat( target.getF() ).isEqualTo( 9.0f ); assertThat( target.getFf() ).isEqualTo( 10.0f ); assertThat( target.getD() ).isEqualTo( 11.0d ); assertThat( target.getDd() ).isEqualTo( 12.0d ); assertThat( target.getString() ).isEqualTo( "13" ); } @ProcessorTest @IssueKey("21") @WithClasses({ BigIntegerSource.class, BigIntegerTarget.class, BigIntegerMapper.class }) public void shouldApplyReverseBigIntegerConversions() { BigIntegerTarget target = new BigIntegerTarget(); target.setB( (byte) 1 ); target.setBb( (byte) 2 ); target.setS( (short) 3 ); target.setSs( (short) 4 ); target.setI( 5 ); target.setIi( 6 ); target.setL( 7 ); target.setLl( 8L ); target.setF( 9.0f ); target.setFf( 10.0f ); target.setD( 11.0d ); target.setDd( 12.0d ); target.setString( "13" ); BigIntegerSource source = BigIntegerMapper.INSTANCE.targetToSource( target ); assertThat( source ).isNotNull(); assertThat( source.getB() ).isEqualTo( new BigInteger( "1" ) ); assertThat( source.getBb() ).isEqualTo( new BigInteger( "2" ) ); assertThat( source.getS() ).isEqualTo( new BigInteger( "3" ) ); assertThat( source.getSs() ).isEqualTo( new BigInteger( "4" ) ); assertThat( source.getI() ).isEqualTo( new BigInteger( "5" ) ); assertThat( source.getIi() ).isEqualTo( new BigInteger( "6" ) ); assertThat( source.getL() ).isEqualTo( new BigInteger( "7" ) ); assertThat( source.getLl() ).isEqualTo( new BigInteger( "8" ) ); assertThat( source.getF() ).isEqualTo( new BigInteger( "9" ) ); assertThat( source.getFf() ).isEqualTo( new BigInteger( "10" ) ); assertThat( source.getD() ).isEqualTo( new BigInteger( "11" ) ); assertThat( source.getDd() ).isEqualTo( new BigInteger( "12" ) ); assertThat( source.getString() ).isEqualTo( new BigInteger( "13" ) ); } @ProcessorTest @IssueKey("21") @WithClasses({ BigDecimalSource.class, BigDecimalTarget.class, BigDecimalMapper.class }) public void shouldApplyBigDecimalConversions() { BigDecimalSource source = new BigDecimalSource(); source.setB( new BigDecimal( "1.45" ) ); source.setBb( new BigDecimal( "2.45" ) ); source.setS( new BigDecimal( "3.45" ) ); source.setSs( new BigDecimal( "4.45" ) ); source.setI( new BigDecimal( "5.45" ) ); source.setIi( new BigDecimal( "6.45" ) ); source.setL( new BigDecimal( "7.45" ) ); source.setLl( new BigDecimal( "8.45" ) ); source.setF( new BigDecimal( "9.45" ) ); source.setFf( new BigDecimal( "10.45" ) ); source.setD( new BigDecimal( "11.45" ) ); source.setDd( new BigDecimal( "12.45" ) ); source.setString( new BigDecimal( "13.45" ) ); source.setBigInteger( new BigDecimal( "14.45" ) ); BigDecimalTarget target = BigDecimalMapper.INSTANCE.sourceToTarget( source ); assertThat( target ).isNotNull(); assertThat( target.getB() ).isEqualTo( (byte) 1 ); assertThat( target.getBb() ).isEqualTo( (byte) 2 ); assertThat( target.getS() ).isEqualTo( (short) 3 ); assertThat( target.getSs() ).isEqualTo( (short) 4 ); assertThat( target.getI() ).isEqualTo( 5 ); assertThat( target.getIi() ).isEqualTo( 6 ); assertThat( target.getL() ).isEqualTo( 7 ); assertThat( target.getLl() ).isEqualTo( 8 ); assertThat( target.getF() ).isEqualTo( 9.45f ); assertThat( target.getFf() ).isEqualTo( 10.45f ); assertThat( target.getD() ).isEqualTo( 11.45d ); assertThat( target.getDd() ).isEqualTo( 12.45d ); assertThat( target.getString() ).isEqualTo( "13.45" ); assertThat( target.getBigInteger() ).isEqualTo( new BigInteger( "14" ) ); } @ProcessorTest @IssueKey("21") @WithClasses({ BigDecimalSource.class, BigDecimalTarget.class, BigDecimalMapper.class }) public void shouldApplyReverseBigDecimalConversions() { BigDecimalTarget target = new BigDecimalTarget(); target.setB( (byte) 1 ); target.setBb( (byte) 2 ); target.setS( (short) 3 ); target.setSs( (short) 4 ); target.setI( 5 ); target.setIi( 6 ); target.setL( 7 ); target.setLl( 8L ); target.setF( 9.0f ); target.setFf( 10.0f ); target.setD( 11.0d ); target.setDd( 12.0d ); target.setString( "13.45" ); target.setBigInteger( new BigInteger( "14" ) ); BigDecimalSource source = BigDecimalMapper.INSTANCE.targetToSource( target ); assertThat( source ).isNotNull(); assertThat( source.getB() ).isEqualTo( new BigDecimal( "1" ) ); assertThat( source.getBb() ).isEqualTo( new BigDecimal( "2" ) ); assertThat( source.getS() ).isEqualTo( new BigDecimal( "3" ) ); assertThat( source.getSs() ).isEqualTo( new BigDecimal( "4" ) ); assertThat( source.getI() ).isEqualTo( new BigDecimal( "5" ) ); assertThat( source.getIi() ).isEqualTo( new BigDecimal( "6" ) ); assertThat( source.getL() ).isEqualTo( new BigDecimal( "7" ) ); assertThat( source.getLl() ).isEqualTo( new BigDecimal( "8" ) ); assertThat( source.getF() ).isEqualTo( new BigDecimal( "9.0" ) ); assertThat( source.getFf() ).isEqualTo( new BigDecimal( "10.0" ) ); assertThat( source.getD() ).isEqualTo( new BigDecimal( "11.0" ) ); assertThat( source.getDd() ).isEqualTo( new BigDecimal( "12.0" ) ); assertThat( source.getString() ).isEqualTo( new BigDecimal( "13.45" ) ); assertThat( source.getBigInteger() ).isEqualTo( new BigDecimal( "14" ) ); } @ProcessorTest @IssueKey("1009") @WithClasses({ BigIntegerSource.class, BigIntegerTarget.class, BigIntegerMapper.class }) public void shouldNotGenerateCreateDecimalFormatMethod() { generatedSource.forMapper( BigIntegerMapper.class ).content().doesNotContain( "createDecimalFormat" ); } }
BigNumbersConversionTest
java
apache__camel
components/camel-dynamic-router/src/main/java/org/apache/camel/component/dynamicrouter/routing/DynamicRouterRecipientListHelper.java
{ "start": 1913, "end": 2038 }
class ____ creates a {@link RecipientList} {@link Processor} based on a {@link DynamicRouterConfiguration}. */ public final
that
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DfdlEndpointBuilderFactory.java
{ "start": 1504, "end": 1623 }
interface ____ { /** * Builder for endpoint for the DFDL component. */ public
DfdlEndpointBuilderFactory
java
elastic__elasticsearch
plugins/examples/stable-analysis/src/main/java/org/elasticsearch/example/analysis/CharacterSkippingTokenizerFactory.java
{ "start": 855, "end": 1275 }
class ____ implements TokenizerFactory { private final List<String> tokenizerListOfChars; @Inject public CharacterSkippingTokenizerFactory(ExampleAnalysisSettings settings) { this.tokenizerListOfChars = settings.singleCharsToSkipInTokenizer(); } @Override public Tokenizer create() { return new CharSkippingTokenizer(tokenizerListOfChars); } }
CharacterSkippingTokenizerFactory
java
quarkusio__quarkus
independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/runner/RunnerClassLoader.java
{ "start": 11804, "end": 12252 }
class ____ in the default package return null; } return className.substring(0, index); } private String getDirNameFromResourceName(String resourceName) { final int index = resourceName.lastIndexOf('/'); if (index == -1) { // we return null here since in this case no package is defined // this is same behavior as Package.getPackage(clazz) exhibits // when the
is
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/BigListStringFieldTest_private.java
{ "start": 1892, "end": 2232 }
class ____ { public List<String> values; } public String random(int count) { Random random = new Random(); char[] chars = new char[count]; for (int i = 0; i < count; ++i) { chars[i] = (char) random.nextInt(256); } return new String(chars); } }
Model
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/PluralAttributeSourceIdBagImpl.java
{ "start": 3680, "end": 4708 }
class ____ implements CollectionIdSource { private final ColumnSource columnSource; private final HibernateTypeSourceImpl typeSource; private final String generator; private final Map<String, String> parameters; public CollectionIdSourceImpl( ColumnSource columnSource, HibernateTypeSourceImpl typeSource, String generator, final Map<String, String> parameters) { this.columnSource = columnSource; this.typeSource = typeSource; this.generator = generator; if ( CollectionHelper.isEmpty( parameters ) ) { this.parameters = Collections.emptyMap(); } else { this.parameters = Collections.unmodifiableMap( parameters ); } } @Override public ColumnSource getColumnSource() { return columnSource; } @Override public HibernateTypeSourceImpl getTypeInformation() { return typeSource; } @Override public String getGeneratorName() { return generator; } public Map<String, String> getParameters() { return parameters; } } }
CollectionIdSourceImpl
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/jdk/ObjectArrayDeserializer.java
{ "start": 16576, "end": 17573 }
class ____ { private final boolean _untyped; private final Class<?> _elementType; private final List<Object> _accumulator = new ArrayList<>(); private Object[] _array; ObjectArrayReferringAccumulator(boolean untyped, Class<?> elementType) { _untyped = untyped; _elementType = elementType; } void add(Object value) { _accumulator.add(value); } Object[] buildArray() { if (_untyped) { _array = new Object[_accumulator.size()]; } else { _array = (Object[]) Array.newInstance(_elementType, _accumulator.size()); } for (int i = 0; i < _accumulator.size(); i++) { if (!(_accumulator.get(i) instanceof ArrayReferring)) { _array[i] = _accumulator.get(i); } } return _array; } } private static
ObjectArrayReferringAccumulator
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/datastream/WindowedStream.java
{ "start": 3921, "end": 41914 }
class ____<T, K, W extends Window> { /** The keyed data stream that is windowed by this stream. */ private final KeyedStream<T, K> input; private final WindowOperatorBuilder<T, K, W> builder; private boolean isEnableAsyncState; @PublicEvolving public WindowedStream(KeyedStream<T, K> input, WindowAssigner<? super T, W> windowAssigner) { this.input = input; this.isEnableAsyncState = input.isEnableAsyncState(); this.builder = new WindowOperatorBuilder<>( windowAssigner, windowAssigner.getDefaultTrigger(), input.getExecutionConfig(), input.getType(), input.getKeySelector(), input.getKeyType()); } /** Sets the {@code Trigger} that should be used to trigger window emission. */ @PublicEvolving public WindowedStream<T, K, W> trigger(Trigger<? super T, ? super W> trigger) { builder.trigger(trigger); return this; } /** * Sets the {@code AsyncTrigger} that should be used to trigger window emission. * * <p>Will automatically enable async state for {@code WindowedStream}. */ @Experimental public WindowedStream<T, K, W> trigger(AsyncTrigger<? super T, ? super W> trigger) { enableAsyncState(); builder.asyncTrigger(trigger); return this; } /** * Sets the time by which elements are allowed to be late. Elements that arrive behind the * watermark by more than the specified time will be dropped. By default, the allowed lateness * is {@code 0L}. * * <p>Setting an allowed lateness is only valid for event-time windows. */ @PublicEvolving public WindowedStream<T, K, W> allowedLateness(Duration lateness) { builder.allowedLateness(lateness); return this; } /** * Send late arriving data to the side output identified by the given {@link OutputTag}. Data is * considered late after the watermark has passed the end of the window plus the allowed * lateness set using {@link #allowedLateness(Duration)}. * * <p>You can get the stream of late data using {@link * SingleOutputStreamOperator#getSideOutput(OutputTag)} on the {@link * SingleOutputStreamOperator} resulting from the windowed operation with the same {@link * OutputTag}. */ @PublicEvolving public WindowedStream<T, K, W> sideOutputLateData(OutputTag<T> outputTag) { outputTag = input.getExecutionEnvironment().clean(outputTag); builder.sideOutputLateData(outputTag); return this; } /** * Sets the {@code Evictor} that should be used to evict elements from a window before emission. * * <p>Note: When using an evictor window performance will degrade significantly, since * incremental aggregation of window results cannot be used. */ @PublicEvolving public WindowedStream<T, K, W> evictor(Evictor<? super T, ? super W> evictor) { builder.evictor(evictor); return this; } // ------------------------------------------------------------------------ // Operations on the keyed windows // ------------------------------------------------------------------------ /** * Applies a reduce function to the window. The window function is called for each evaluation of * the window for each key individually. The output of the reduce function is interpreted as a * regular non-windowed stream. * * <p>This window will try and incrementally aggregate data as much as the window policies * permit. For example, tumbling time windows can aggregate the data, meaning that only one * element per key is stored. Sliding time windows will aggregate on the granularity of the * slide interval, so a few elements are stored per key (one per slide interval). Custom windows * may not be able to incrementally aggregate, or may need to store extra values in an * aggregation tree. * * @param function The reduce function. * @return The data stream that is the result of applying the reduce function to the window. */ @SuppressWarnings("unchecked") public SingleOutputStreamOperator<T> reduce(ReduceFunction<T> function) { if (function instanceof RichFunction) { throw new UnsupportedOperationException( "ReduceFunction of reduce can not be a RichFunction. " + "Please use reduce(ReduceFunction, WindowFunction) instead."); } // clean the closure function = input.getExecutionEnvironment().clean(function); return reduce(function, new PassThroughWindowFunction<>()); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Arriving data is incrementally aggregated using the given reducer. * * @param reduceFunction The reduce function that is used for incremental aggregation. * @param function The window function. * @return The data stream that is the result of applying the window function to the window. */ public <R> SingleOutputStreamOperator<R> reduce( ReduceFunction<T> reduceFunction, WindowFunction<T, R, K, W> function) { TypeInformation<T> inType = input.getType(); TypeInformation<R> resultType = getWindowFunctionReturnType(function, inType); return reduce(reduceFunction, function, resultType); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Arriving data is incrementally aggregated using the given reducer. * * @param reduceFunction The reduce function that is used for incremental aggregation. * @param function The window function. * @param resultType Type information for the result type of the window function. * @return The data stream that is the result of applying the window function to the window. */ public <R> SingleOutputStreamOperator<R> reduce( ReduceFunction<T> reduceFunction, WindowFunction<T, R, K, W> function, TypeInformation<R> resultType) { // clean the closures function = input.getExecutionEnvironment().clean(function); reduceFunction = input.getExecutionEnvironment().clean(reduceFunction); final String opName = builder.generateOperatorName(); final String opDescription = builder.generateOperatorDescription(reduceFunction, function); OneInputStreamOperator<T, R> operator = isEnableAsyncState ? builder.asyncReduce(reduceFunction, function) : builder.reduce(reduceFunction, function); return input.transform(opName, resultType, operator).setDescription(opDescription); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Arriving data is incrementally aggregated using the given reducer. * * @param reduceFunction The reduce function that is used for incremental aggregation. * @param function The window function. * @return The data stream that is the result of applying the window function to the window. */ @PublicEvolving public <R> SingleOutputStreamOperator<R> reduce( ReduceFunction<T> reduceFunction, ProcessWindowFunction<T, R, K, W> function) { TypeInformation<R> resultType = getProcessWindowFunctionReturnType(function, input.getType(), null); return reduce(reduceFunction, function, resultType); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Arriving data is incrementally aggregated using the given reducer. * * @param reduceFunction The reduce function that is used for incremental aggregation. * @param function The window function. * @param resultType Type information for the result type of the window function * @return The data stream that is the result of applying the window function to the window. */ @Internal public <R> SingleOutputStreamOperator<R> reduce( ReduceFunction<T> reduceFunction, ProcessWindowFunction<T, R, K, W> function, TypeInformation<R> resultType) { // clean the closures function = input.getExecutionEnvironment().clean(function); reduceFunction = input.getExecutionEnvironment().clean(reduceFunction); final String opName = builder.generateOperatorName(); final String opDescription = builder.generateOperatorDescription(reduceFunction, function); OneInputStreamOperator<T, R> operator = isEnableAsyncState ? builder.asyncReduce(reduceFunction, function) : builder.reduce(reduceFunction, function); return input.transform(opName, resultType, operator).setDescription(opDescription); } // ------------------------------------------------------------------------ // Aggregation Function // ------------------------------------------------------------------------ /** * Applies the given aggregation function to each window. The aggregation function is called for * each element, aggregating values incrementally and keeping the state to one accumulator per * key and window. * * @param function The aggregation function. * @return The data stream that is the result of applying the fold function to the window. * @param <ACC> The type of the AggregateFunction's accumulator * @param <R> The type of the elements in the resulting stream, equal to the AggregateFunction's * result type */ @PublicEvolving public <ACC, R> SingleOutputStreamOperator<R> aggregate(AggregateFunction<T, ACC, R> function) { checkNotNull(function, "function"); if (function instanceof RichFunction) { throw new UnsupportedOperationException( "This aggregation function cannot be a RichFunction."); } TypeInformation<ACC> accumulatorType = TypeExtractor.getAggregateFunctionAccumulatorType( function, input.getType(), null, false); TypeInformation<R> resultType = TypeExtractor.getAggregateFunctionReturnType( function, input.getType(), null, false); return aggregate(function, accumulatorType, resultType); } /** * Applies the given aggregation function to each window. The aggregation function is called for * each element, aggregating values incrementally and keeping the state to one accumulator per * key and window. * * @param function The aggregation function. * @return The data stream that is the result of applying the aggregation function to the * window. * @param <ACC> The type of the AggregateFunction's accumulator * @param <R> The type of the elements in the resulting stream, equal to the AggregateFunction's * result type */ @PublicEvolving public <ACC, R> SingleOutputStreamOperator<R> aggregate( AggregateFunction<T, ACC, R> function, TypeInformation<ACC> accumulatorType, TypeInformation<R> resultType) { checkNotNull(function, "function"); checkNotNull(accumulatorType, "accumulatorType"); checkNotNull(resultType, "resultType"); if (function instanceof RichFunction) { throw new UnsupportedOperationException( "This aggregation function cannot be a RichFunction."); } return aggregate(function, new PassThroughWindowFunction<>(), accumulatorType, resultType); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Arriving data is incrementally aggregated using the given aggregate function. This means * that the window function typically has only a single value to process when called. * * @param aggFunction The aggregate function that is used for incremental aggregation. * @param windowFunction The window function. * @return The data stream that is the result of applying the window function to the window. * @param <ACC> The type of the AggregateFunction's accumulator * @param <V> The type of AggregateFunction's result, and the WindowFunction's input * @param <R> The type of the elements in the resulting stream, equal to the WindowFunction's * result type */ @PublicEvolving public <ACC, V, R> SingleOutputStreamOperator<R> aggregate( AggregateFunction<T, ACC, V> aggFunction, WindowFunction<V, R, K, W> windowFunction) { checkNotNull(aggFunction, "aggFunction"); checkNotNull(windowFunction, "windowFunction"); TypeInformation<ACC> accumulatorType = TypeExtractor.getAggregateFunctionAccumulatorType( aggFunction, input.getType(), null, false); TypeInformation<V> aggResultType = TypeExtractor.getAggregateFunctionReturnType( aggFunction, input.getType(), null, false); TypeInformation<R> resultType = getWindowFunctionReturnType(windowFunction, aggResultType); return aggregate(aggFunction, windowFunction, accumulatorType, resultType); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Arriving data is incrementally aggregated using the given aggregate function. This means * that the window function typically has only a single value to process when called. * * @param aggregateFunction The aggregation function that is used for incremental aggregation. * @param windowFunction The window function. * @param accumulatorType Type information for the internal accumulator type of the aggregation * function * @param resultType Type information for the result type of the window function * @return The data stream that is the result of applying the window function to the window. * @param <ACC> The type of the AggregateFunction's accumulator * @param <V> The type of AggregateFunction's result, and the WindowFunction's input * @param <R> The type of the elements in the resulting stream, equal to the WindowFunction's * result type */ @PublicEvolving public <ACC, V, R> SingleOutputStreamOperator<R> aggregate( AggregateFunction<T, ACC, V> aggregateFunction, WindowFunction<V, R, K, W> windowFunction, TypeInformation<ACC> accumulatorType, TypeInformation<R> resultType) { checkNotNull(aggregateFunction, "aggregateFunction"); checkNotNull(windowFunction, "windowFunction"); checkNotNull(accumulatorType, "accumulatorType"); checkNotNull(resultType, "resultType"); if (aggregateFunction instanceof RichFunction) { throw new UnsupportedOperationException( "This aggregate function cannot be a RichFunction."); } // clean the closures windowFunction = input.getExecutionEnvironment().clean(windowFunction); aggregateFunction = input.getExecutionEnvironment().clean(aggregateFunction); final String opName = builder.generateOperatorName(); final String opDescription = builder.generateOperatorDescription(aggregateFunction, windowFunction); OneInputStreamOperator<T, R> operator = isEnableAsyncState ? builder.asyncAggregate(aggregateFunction, windowFunction, accumulatorType) : builder.aggregate(aggregateFunction, windowFunction, accumulatorType); return input.transform(opName, resultType, operator).setDescription(opDescription); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Arriving data is incrementally aggregated using the given aggregate function. This means * that the window function typically has only a single value to process when called. * * @param aggFunction The aggregate function that is used for incremental aggregation. * @param windowFunction The window function. * @return The data stream that is the result of applying the window function to the window. * @param <ACC> The type of the AggregateFunction's accumulator * @param <V> The type of AggregateFunction's result, and the WindowFunction's input * @param <R> The type of the elements in the resulting stream, equal to the WindowFunction's * result type */ @PublicEvolving public <ACC, V, R> SingleOutputStreamOperator<R> aggregate( AggregateFunction<T, ACC, V> aggFunction, ProcessWindowFunction<V, R, K, W> windowFunction) { checkNotNull(aggFunction, "aggFunction"); checkNotNull(windowFunction, "windowFunction"); TypeInformation<ACC> accumulatorType = TypeExtractor.getAggregateFunctionAccumulatorType( aggFunction, input.getType(), null, false); TypeInformation<V> aggResultType = TypeExtractor.getAggregateFunctionReturnType( aggFunction, input.getType(), null, false); TypeInformation<R> resultType = getProcessWindowFunctionReturnType(windowFunction, aggResultType, null); return aggregate(aggFunction, windowFunction, accumulatorType, aggResultType, resultType); } private static <IN, OUT, KEY> TypeInformation<OUT> getWindowFunctionReturnType( WindowFunction<IN, OUT, KEY, ?> function, TypeInformation<IN> inType) { return TypeExtractor.getUnaryOperatorReturnType( function, WindowFunction.class, 0, 1, new int[] {3, 0}, inType, null, true); } private static <IN, OUT, KEY> TypeInformation<OUT> getProcessWindowFunctionReturnType( ProcessWindowFunction<IN, OUT, KEY, ?> function, TypeInformation<IN> inType, String functionName) { return TypeExtractor.getUnaryOperatorReturnType( function, ProcessWindowFunction.class, 0, 1, TypeExtractor.NO_INDEX, inType, functionName, true); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Arriving data is incrementally aggregated using the given aggregate function. This means * that the window function typically has only a single value to process when called. * * @param aggregateFunction The aggregation function that is used for incremental aggregation. * @param windowFunction The window function. * @param accumulatorType Type information for the internal accumulator type of the aggregation * function * @param resultType Type information for the result type of the window function * @return The data stream that is the result of applying the window function to the window. * @param <ACC> The type of the AggregateFunction's accumulator * @param <V> The type of AggregateFunction's result, and the WindowFunction's input * @param <R> The type of the elements in the resulting stream, equal to the WindowFunction's * result type */ @PublicEvolving public <ACC, V, R> SingleOutputStreamOperator<R> aggregate( AggregateFunction<T, ACC, V> aggregateFunction, ProcessWindowFunction<V, R, K, W> windowFunction, TypeInformation<ACC> accumulatorType, TypeInformation<V> aggregateResultType, TypeInformation<R> resultType) { checkNotNull(aggregateFunction, "aggregateFunction"); checkNotNull(windowFunction, "windowFunction"); checkNotNull(accumulatorType, "accumulatorType"); checkNotNull(aggregateResultType, "aggregateResultType"); checkNotNull(resultType, "resultType"); if (aggregateFunction instanceof RichFunction) { throw new UnsupportedOperationException( "This aggregate function cannot be a RichFunction."); } // clean the closures windowFunction = input.getExecutionEnvironment().clean(windowFunction); aggregateFunction = input.getExecutionEnvironment().clean(aggregateFunction); final String opName = builder.generateOperatorName(); final String opDescription = builder.generateOperatorDescription(aggregateFunction, windowFunction); OneInputStreamOperator<T, R> operator = isEnableAsyncState ? builder.asyncAggregate(aggregateFunction, windowFunction, accumulatorType) : builder.aggregate(aggregateFunction, windowFunction, accumulatorType); return input.transform(opName, resultType, operator).setDescription(opDescription); } // ------------------------------------------------------------------------ // Window Function (apply) // ------------------------------------------------------------------------ /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Note that this function requires that all data in the windows is buffered until the window * is evaluated, as the function provides no means of incremental aggregation. * * @param function The window function. * @return The data stream that is the result of applying the window function to the window. */ public <R> SingleOutputStreamOperator<R> apply(WindowFunction<T, R, K, W> function) { TypeInformation<R> resultType = getWindowFunctionReturnType(function, getInputType()); return apply(function, resultType); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Note that this function requires that all data in the windows is buffered until the window * is evaluated, as the function provides no means of incremental aggregation. * * @param function The window function. * @param resultType Type information for the result type of the window function * @return The data stream that is the result of applying the window function to the window. */ public <R> SingleOutputStreamOperator<R> apply( WindowFunction<T, R, K, W> function, TypeInformation<R> resultType) { function = input.getExecutionEnvironment().clean(function); final String opName = builder.generateOperatorName(); final String opDescription = builder.generateOperatorDescription(function, null); OneInputStreamOperator<T, R> operator = isEnableAsyncState ? builder.asyncApply(function) : builder.apply(function); return input.transform(opName, resultType, operator).setDescription(opDescription); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Note that this function requires that all data in the windows is buffered until the window * is evaluated, as the function provides no means of incremental aggregation. * * @param function The window function. * @return The data stream that is the result of applying the window function to the window. */ @PublicEvolving public <R> SingleOutputStreamOperator<R> process(ProcessWindowFunction<T, R, K, W> function) { TypeInformation<R> resultType = getProcessWindowFunctionReturnType(function, getInputType(), null); return process(function, resultType); } /** * Applies the given window function to each window. The window function is called for each * evaluation of the window for each key individually. The output of the window function is * interpreted as a regular non-windowed stream. * * <p>Note that this function requires that all data in the windows is buffered until the window * is evaluated, as the function provides no means of incremental aggregation. * * @param function The window function. * @param resultType Type information for the result type of the window function * @return The data stream that is the result of applying the window function to the window. */ @Internal public <R> SingleOutputStreamOperator<R> process( ProcessWindowFunction<T, R, K, W> function, TypeInformation<R> resultType) { function = input.getExecutionEnvironment().clean(function); final String opName = builder.generateOperatorName(); final String opDesc = builder.generateOperatorDescription(function, null); OneInputStreamOperator<T, R> operator = isEnableAsyncState ? builder.asyncProcess(function) : builder.process(function); return input.transform(opName, resultType, operator).setDescription(opDesc); } // ------------------------------------------------------------------------ // Pre-defined aggregations on the keyed windows // ------------------------------------------------------------------------ /** * Applies an aggregation that sums every window of the data stream at the given position. * * @param positionToSum The position in the tuple/array to sum * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> sum(int positionToSum) { return aggregate( new SumAggregator<>(positionToSum, input.getType(), input.getExecutionConfig())); } /** * Applies an aggregation that sums every window of the pojo data stream at the given field for * every window. * * <p>A field expression is either the name of a public field or a getter method with * parentheses of the stream's underlying type. A dot can be used to drill down into objects, as * in {@code "field1.getInnerField2()" }. * * @param field The field to sum * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> sum(String field) { return aggregate(new SumAggregator<>(field, input.getType(), input.getExecutionConfig())); } /** * Applies an aggregation that gives the minimum value of every window of the data stream at the * given position. * * @param positionToMin The position to minimize * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> min(int positionToMin) { return aggregate( new ComparableAggregator<>( positionToMin, input.getType(), AggregationFunction.AggregationType.MIN, input.getExecutionConfig())); } /** * Applies an aggregation that gives the minimum value of the pojo data stream at the given * field expression for every window. * * <p>A field * expression is either the name of a public field or a getter method with * parentheses of the {@link DataStream}S underlying type. A dot can be used to drill down into * objects, as in {@code "field1.getInnerField2()" }. * * @param field The field expression based on which the aggregation will be applied. * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> min(String field) { return aggregate( new ComparableAggregator<>( field, input.getType(), AggregationFunction.AggregationType.MIN, false, input.getExecutionConfig())); } /** * Applies an aggregation that gives the minimum element of every window of the data stream by * the given position. If more elements have the same minimum value the operator returns the * first element by default. * * @param positionToMinBy The position to minimize by * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> minBy(int positionToMinBy) { return this.minBy(positionToMinBy, true); } /** * Applies an aggregation that gives the minimum element of every window of the data stream by * the given field. If more elements have the same minimum value the operator returns the first * element by default. * * @param field The field to minimize by * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> minBy(String field) { return this.minBy(field, true); } /** * Applies an aggregation that gives the minimum element of every window of the data stream by * the given position. If more elements have the same minimum value the operator returns either * the first or last one depending on the parameter setting. * * @param positionToMinBy The position to minimize * @param first If true, then the operator return the first element with the minimum value, * otherwise returns the last * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> minBy(int positionToMinBy, boolean first) { return aggregate( new ComparableAggregator<>( positionToMinBy, input.getType(), AggregationFunction.AggregationType.MINBY, first, input.getExecutionConfig())); } /** * Applies an aggregation that gives the minimum element of the pojo data stream by the given * field expression for every window. A field expression is either the name of a public field or * a getter method with parentheses of the {@link DataStream DataStreams} underlying type. A dot * can be used to drill down into objects, as in {@code "field1.getInnerField2()" }. * * @param field The field expression based on which the aggregation will be applied. * @param first If True then in case of field equality the first object will be returned * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> minBy(String field, boolean first) { return aggregate( new ComparableAggregator<>( field, input.getType(), AggregationFunction.AggregationType.MINBY, first, input.getExecutionConfig())); } /** * Applies an aggregation that gives the maximum value of every window of the data stream at the * given position. * * @param positionToMax The position to maximize * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> max(int positionToMax) { return aggregate( new ComparableAggregator<>( positionToMax, input.getType(), AggregationFunction.AggregationType.MAX, input.getExecutionConfig())); } /** * Applies an aggregation that gives the maximum value of the pojo data stream at the given * field expression for every window. A field expression is either the name of a public field or * a getter method with parentheses of the {@link DataStream DataStreams} underlying type. A dot * can be used to drill down into objects, as in {@code "field1.getInnerField2()" }. * * @param field The field expression based on which the aggregation will be applied. * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> max(String field) { return aggregate( new ComparableAggregator<>( field, input.getType(), AggregationFunction.AggregationType.MAX, false, input.getExecutionConfig())); } /** * Applies an aggregation that gives the maximum element of every window of the data stream by * the given position. If more elements have the same maximum value the operator returns the * first by default. * * @param positionToMaxBy The position to maximize by * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> maxBy(int positionToMaxBy) { return this.maxBy(positionToMaxBy, true); } /** * Applies an aggregation that gives the maximum element of every window of the data stream by * the given field. If more elements have the same maximum value the operator returns the first * by default. * * @param field The field to maximize by * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> maxBy(String field) { return this.maxBy(field, true); } /** * Applies an aggregation that gives the maximum element of every window of the data stream by * the given position. If more elements have the same maximum value the operator returns either * the first or last one depending on the parameter setting. * * @param positionToMaxBy The position to maximize by * @param first If true, then the operator return the first element with the maximum value, * otherwise returns the last * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> maxBy(int positionToMaxBy, boolean first) { return aggregate( new ComparableAggregator<>( positionToMaxBy, input.getType(), AggregationFunction.AggregationType.MAXBY, first, input.getExecutionConfig())); } /** * Applies an aggregation that gives the maximum element of the pojo data stream by the given * field expression for every window. A field expression is either the name of a public field or * a getter method with parentheses of the {@link DataStream}S underlying type. A dot can be * used to drill down into objects, as in {@code "field1.getInnerField2()" }. * * @param field The field expression based on which the aggregation will be applied. * @param first If True then in case of field equality the first object will be returned * @return The transformed DataStream. */ public SingleOutputStreamOperator<T> maxBy(String field, boolean first) { return aggregate( new ComparableAggregator<>( field, input.getType(), AggregationFunction.AggregationType.MAXBY, first, input.getExecutionConfig())); } private SingleOutputStreamOperator<T> aggregate(AggregationFunction<T> aggregator) { return reduce(aggregator); } /** * Enable the async state processing for following keyed processing function. This also requires * only State V2 APIs are used in the function. * * @return the configured WindowedStream itself. */ @Experimental public WindowedStream<T, K, W> enableAsyncState() { input.enableAsyncState(); this.isEnableAsyncState = true; return this; } public StreamExecutionEnvironment getExecutionEnvironment() { return input.getExecutionEnvironment(); } public TypeInformation<T> getInputType() { return input.getType(); } // -------------------- Testing Methods -------------------- @VisibleForTesting long getAllowedLateness() { return builder.getAllowedLateness(); } }
WindowedStream
java
apache__camel
components/camel-syslog/src/test/java/org/apache/camel/component/syslog/MinaManyUDPMessagesTest.java
{ "start": 1396, "end": 3516 }
class ____ extends CamelTestSupport { private static int serverPort; private final int messageCount = 100; private final String message = "<165>Aug 4 05:34:00 mymachine myproc[10]: %% It's\n time to make the do-nuts. %% Ingredients: Mix=OK, Jelly=OK #\n" + " Devices: Mixer=OK, Jelly_Injector=OK, Frier=OK # Transport:\n" + " Conveyer1=OK, Conveyer2=OK # %%"; @BeforeAll public static void initPort() { serverPort = AvailablePortFinder.getNextAvailable(); } @Test public void testSendingManyMessages() throws Exception { MockEndpoint stop1 = getMockEndpoint("mock:stop1"); MockEndpoint stop2 = getMockEndpoint("mock:stop2"); stop2.expectedMessageCount(messageCount); stop1.expectedMessageCount(messageCount); DatagramSocket socket = new DatagramSocket(); try { InetAddress address = InetAddress.getByName("127.0.0.1"); for (int i = 0; i < messageCount; i++) { byte[] data = message.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length, address, serverPort); socket.send(packet); Thread.sleep(100); } } finally { socket.close(); } MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { //context.setTracing(true); DataFormat syslogDataFormat = new SyslogDataFormat(); // we setup a Syslog listener on a random port. from("mina:udp://127.0.0.1:" + serverPort).unmarshal(syslogDataFormat).process(new Processor() { public void process(Exchange ex) { assertTrue(ex.getIn().getBody() instanceof SyslogMessage); } }).to("mock:stop1").marshal(syslogDataFormat).to("mock:stop2"); } }; } }
MinaManyUDPMessagesTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/query/SqlResultSetMappingDescriptor.java
{ "start": 2411, "end": 5224 }
class ____ implements NamedResultSetMappingDescriptor { // todo (6.0) : we can probably reuse the NamedResultSetMappingDefinition // implementation between HBM and annotation handling. We'd // just need different "builders" for each source and handle the // variances in those builders. But once we have a // NamedResultSetMappingDefinition and all of its sub-parts, // resolving to a memento is the same // - // additionally, consider having the sub-parts (the return // representations) be what is used and handed to the // NamedResultSetMappingMemento directly. They simply need // to be capable of resolving themselves into ResultBuilders // (`org.hibernate.query.results.ResultBuilder`) as part of the // memento for its resolution public static SqlResultSetMappingDescriptor from(SqlResultSetMapping mappingAnnotation, String name) { final EntityResult[] entityResults = mappingAnnotation.entities(); final ConstructorResult[] constructorResults = mappingAnnotation.classes(); final ColumnResult[] columnResults = mappingAnnotation.columns(); final List<ResultDescriptor> resultDescriptors = arrayList( entityResults.length + columnResults.length + columnResults.length ); for ( final EntityResult entityResult : entityResults ) { resultDescriptors.add( new EntityResultDescriptor( entityResult ) ); } for ( final ConstructorResult constructorResult : constructorResults ) { resultDescriptors.add( new ConstructorResultDescriptor( constructorResult, mappingAnnotation ) ); } for ( final ColumnResult columnResult : columnResults ) { resultDescriptors.add( new JpaColumnResultDescriptor( columnResult, mappingAnnotation ) ); } return new SqlResultSetMappingDescriptor( name, resultDescriptors ); } public static SqlResultSetMappingDescriptor from(SqlResultSetMapping mappingAnnotation) { return from( mappingAnnotation, mappingAnnotation.name() ); } private final String mappingName; private final List<ResultDescriptor> resultDescriptors; private SqlResultSetMappingDescriptor(String mappingName, List<ResultDescriptor> resultDescriptors) { this.mappingName = mappingName; this.resultDescriptors = resultDescriptors; } @Override public String getRegistrationName() { return mappingName; } @Override public NamedResultSetMappingMemento resolve(ResultSetMappingResolutionContext resolutionContext) { final List<ResultMemento> resultMementos = arrayList( resultDescriptors.size() ); resultDescriptors.forEach( resultDescriptor -> resultMementos.add( resultDescriptor.resolve( resolutionContext ) ) ); return new NamedResultSetMappingMementoImpl( mappingName, resultMementos ); } /** * @see jakarta.persistence.ColumnResult */ private static
SqlResultSetMappingDescriptor
java
google__dagger
javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java
{ "start": 37509, "end": 38260 }
class ____ {", " @Provides static Foo provideFoo(Set<String> strings) {", " return new Foo(strings);", " }", "", " @Provides @IntoSet static String string() {", " return \"provided1\";", " }", " }", "}"); Source provided2 = CompilerTests.javaSource( "test.Provided2", "package test;", "", "import dagger.Module;", "import dagger.Provides;", "import dagger.Subcomponent;", "import dagger.multibindings.IntoSet;", "", "@Subcomponent(modules = Provided2.Provided2Module.class)", "
Provided1Module
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/samples/client/standalone/FilterTests.java
{ "start": 2539, "end": 6122 }
class ____ { @Test public void whenFiltersCompleteMvcProcessesRequest() throws Exception { WebTestClient client = MockMvcWebTestClient.bindToController(new PersonController()) .filters(new ContinueFilter()) .build(); EntityExchangeResult<Void> exchangeResult = client.post().uri("/persons?name=Andy") .exchange() .expectStatus().isFound() .expectHeader().location("/person/1") .expectBody().isEmpty(); // Further assertions on the server response MockMvcWebTestClient.resultActionsFor(exchangeResult) .andExpect(model().size(1)) .andExpect(model().attributeExists("id")) .andExpect(flash().attributeCount(1)) .andExpect(flash().attribute("message", "success!")); } @Test public void filtersProcessRequest() { WebTestClient client = MockMvcWebTestClient.bindToController(new PersonController()) .filters(new ContinueFilter(), new RedirectFilter()) .build(); client.post().uri("/persons?name=Andy") .exchange() .expectStatus().isFound() .expectHeader().location("/login"); } @Test public void filterMappedBySuffix() { WebTestClient client = MockMvcWebTestClient.bindToController(new PersonController()) .filter(new RedirectFilter(), "*.html") .build(); client.post().uri("/persons.html?name=Andy") .exchange() .expectStatus().isFound() .expectHeader().location("/login"); } @Test public void filterWithExactMapping() { WebTestClient client = MockMvcWebTestClient.bindToController(new PersonController()) .filter(new RedirectFilter(), "/p", "/persons") .build(); client.post().uri("/persons?name=Andy") .exchange() .expectStatus().isFound() .expectHeader().location("/login"); } @Test public void filterSkipped() throws Exception { WebTestClient client = MockMvcWebTestClient.bindToController(new PersonController()) .filter(new RedirectFilter(), "/p", "/person") .build(); EntityExchangeResult<Void> exchangeResult = client.post().uri("/persons?name=Andy") .exchange() .expectStatus().isFound() .expectHeader().location("/person/1") .expectBody().isEmpty(); // Further assertions on the server response MockMvcWebTestClient.resultActionsFor(exchangeResult) .andExpect(model().size(1)) .andExpect(model().attributeExists("id")) .andExpect(flash().attributeCount(1)) .andExpect(flash().attribute("message", "success!")); } @Test public void filterWrapsRequestResponse() throws Exception { WebTestClient client = MockMvcWebTestClient.bindToController(new PersonController()) .filter(new WrappingRequestResponseFilter()) .build(); EntityExchangeResult<Void> exchangeResult = client.post().uri("/user").exchange().expectBody().isEmpty(); // Further assertions on the server response MockMvcWebTestClient.resultActionsFor(exchangeResult) .andExpect(model().attribute("principal", WrappingRequestResponseFilter.PRINCIPAL_NAME)); } @Test public void filterWrapsRequestResponseAndPerformsAsyncDispatch() { WebTestClient client = MockMvcWebTestClient.bindToController(new PersonController()) .filters(new WrappingRequestResponseFilter(), new ShallowEtagHeaderFilter()) .build(); client.get().uri("/persons/1") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectHeader().contentLength(53) .expectHeader().valueEquals("ETag", "\"08ff7f2f1f370ada7db137770dada33a0\"") .expectBody().json("{\"name\":\"Lukas\",\"someDouble\":0.0,\"someBoolean\":false}"); } @Controller private static
FilterTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/MaterializedInterfaceTest2.java
{ "start": 216, "end": 730 }
class ____ extends TestCase { public void test_parse() throws Exception { String text = "{\"id\":123, \"name\":\"chris\"}"; JSONObject object = JSON.parseObject(text); Bean bean = TypeUtils.cast(object, Bean.class, null); Assert.assertEquals(123, bean.getId()); Assert.assertEquals("chris", bean.getName()); String text2 = JSON.toJSONString(bean); System.out.println(text2); } public static
MaterializedInterfaceTest2
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/spi/ParameterDeclarationContext.java
{ "start": 419, "end": 643 }
interface ____ { /** * Are multi-valued parameter bindings allowed in this context? * * @return {@code true} if they are; {@code false} otherwise. */ boolean isMultiValuedBindingAllowed(); }
ParameterDeclarationContext
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/StateUtilTest.java
{ "start": 4553, "end": 5369 }
class ____ implements CompositeStateHandle { private static final long serialVersionUID = -8070326169926626355L; private final int size; private final int checkpointedSize; private TestStateObject(int size, int checkpointedSize) { this.size = size; this.checkpointedSize = checkpointedSize; } @Override public long getStateSize() { return size; } @Override public void discardState() {} @Override public long getCheckpointedSize() { return checkpointedSize; } @Override public void registerSharedStates(SharedStateRegistry stateRegistry, long checkpointID) { throw new UnsupportedOperationException(); } } }
TestStateObject
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/Location.java
{ "start": 630, "end": 3182 }
class ____ { private final String sourceName; private final int offset; /** * Create a new Location * @param sourceName script's name * @param offset character offset of script element */ public Location(String sourceName, int offset) { this.sourceName = Objects.requireNonNull(sourceName); this.offset = offset; } /** * Return the script's name */ public String getSourceName() { return sourceName; } /** * Return the character offset */ public int getOffset() { return offset; } /** * Augments an exception with this location's information. */ public RuntimeException createError(RuntimeException exception) { StackTraceElement element = new StackTraceElement(WriterConstants.CLASS_NAME, "compile", sourceName, offset + 1); StackTraceElement[] oldStack = exception.getStackTrace(); StackTraceElement[] newStack = new StackTraceElement[oldStack.length + 1]; System.arraycopy(oldStack, 0, newStack, 1, oldStack.length); newStack[0] = element; exception.setStackTrace(newStack); assert exception.getStackTrace().length == newStack.length : "non-writeable stacktrace for exception: " + exception.getClass(); return exception; } // This maximum length is theoretically 65535 bytes, but as it's CESU-8 encoded we don't know how large it is in bytes, so be safe private static final int MAX_NAME_LENGTH = 256; /** Computes the file name (mostly important for stacktraces) */ public static String computeSourceName(String scriptName) { StringBuilder fileName = new StringBuilder(); // its an anonymous script, include at least a portion of the source to help identify which one it is // but don't create stacktraces with filenames that contain newlines or huge names. // truncate to the first newline int limit = scriptName.indexOf('\n'); if (limit >= 0) { int limit2 = scriptName.indexOf('\r'); if (limit2 >= 0) { limit = Math.min(limit, limit2); } } else { limit = scriptName.length(); } // truncate to our limit limit = Math.min(limit, MAX_NAME_LENGTH); fileName.append(scriptName, 0, limit); // if we truncated, make it obvious if (limit != scriptName.length()) { fileName.append(" ..."); } return fileName.toString(); } }
Location
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/ProgrammaticExtensionRegistrationTests.java
{ "start": 17195, "end": 17279 }
interface ____ does not implement a supported {@link Extension} API. */
intentionally
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/model/ast/builder/TableInsertBuilder.java
{ "start": 428, "end": 876 }
interface ____ extends TableMutationBuilder<TableInsert>, ColumnValuesTableMutationBuilder<TableInsert>, SelectableConsumer { /** * Allows using the insert builder as selectable consumer. * @see org.hibernate.metamodel.mapping.ValuedModelPart#forEachInsertable(SelectableConsumer) */ @Override default void accept(int selectionIndex, SelectableMapping selectableMapping) { addValueColumn( selectableMapping ); } }
TableInsertBuilder
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/synapse/parser/SynapseLexer.java
{ "start": 220, "end": 412 }
class ____ extends SQLServerLexer { public SynapseLexer(String input, SQLParserFeature... features) { super(input, features); this.dbType = DbType.synapse; } }
SynapseLexer
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/UrlEncodeComponent.java
{ "start": 1694, "end": 3923 }
class ____ extends UnaryScalarFunction { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry( Expression.class, "UrlEncodeComponent", UrlEncodeComponent::new ); private UrlEncodeComponent(StreamInput in) throws IOException { super(in); } @FunctionInfo( returnType = "keyword", description = "URL-encodes the input. All characters are {wikipedia}/Percent-encoding[percent-encoded] except " + "for alphanumerics, `.`, `-`, `_`, and `~`. Spaces are encoded as `%20`.", examples = { @Example(file = "string", tag = "url_encode_component") }, appliesTo = { @FunctionAppliesTo(lifeCycle = FunctionAppliesToLifecycle.GA, version = "9.2.0") } ) public UrlEncodeComponent( Source source, @Param(name = "string", type = { "keyword", "text" }, description = "The URL to encode.") Expression str ) { super(source, str); } @Override public Expression replaceChildren(List<Expression> newChildren) { return new UrlEncodeComponent(source(), newChildren.get(0)); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, UrlEncodeComponent::new, field()); } @Override public String getWriteableName() { return ENTRY.name; } @Override protected TypeResolution resolveType() { if (childrenResolved() == false) { return new TypeResolution("Unresolved children"); } return isString(field, sourceText(), TypeResolutions.ParamOrdinal.DEFAULT); } @Override public EvalOperator.ExpressionEvaluator.Factory toEvaluator(ToEvaluator toEvaluator) { return new UrlEncodeComponentEvaluator.Factory( source(), toEvaluator.apply(field()), context -> new BreakingBytesRefBuilder(context.breaker(), "url_encode_component") ); } @ConvertEvaluator() static BytesRef process(final BytesRef val, @Fixed(includeInToString = false, scope = THREAD_LOCAL) BreakingBytesRefBuilder scratch) { return UrlCodecUtils.urlEncode(val, scratch, false); } }
UrlEncodeComponent
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/search/ccs/CrossClusterSearchLeakIT.java
{ "start": 1736, "end": 7906 }
class ____ extends AbstractMultiClustersTestCase { @Override protected List<String> remoteClusterAlias() { return List.of("cluster_a"); } @Override protected boolean reuseClusters() { return false; } private int indexDocs(Client client, String field, String index) { int numDocs = between(1, 200); for (int i = 0; i < numDocs; i++) { client.prepareIndex(index).setSource(field, "v" + i).get(); } client.admin().indices().prepareRefresh(index).get(); return numDocs; } /** * This test validates that we do not leak any memory when running CCS in various modes, actual validation is done by test framework * (leak detection) * <ul> * <li>proxy vs non-proxy</li> * <li>single-phase query-fetch or multi-phase</li> * <li>minimize roundtrip vs not</li> * <li>scroll vs no scroll</li> * </ul> */ public void testSearch() throws Exception { assertAcked( client(LOCAL_CLUSTER).admin() .indices() .prepareCreate("demo") .setMapping("f", "type=keyword") .setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, between(1, 3))) ); indexDocs(client(LOCAL_CLUSTER), "ignored", "demo"); final InternalTestCluster remoteCluster = cluster("cluster_a"); int minRemotes = between(2, 5); remoteCluster.ensureAtLeastNumDataNodes(minRemotes); List<String> remoteDataNodes = remoteCluster.clusterService() .state() .nodes() .stream() .filter(DiscoveryNode::canContainData) .map(DiscoveryNode::getName) .toList(); assertThat(remoteDataNodes.size(), Matchers.greaterThanOrEqualTo(minRemotes)); List<String> seedNodes = randomSubsetOf(between(1, remoteDataNodes.size() - 1), remoteDataNodes); disconnectFromRemoteClusters(); configureRemoteCluster("cluster_a", seedNodes); final Settings.Builder allocationFilter = Settings.builder(); if (rarely()) { allocationFilter.put("index.routing.allocation.include._name", String.join(",", seedNodes)); } else { // Provoke using proxy connections allocationFilter.put("index.routing.allocation.exclude._name", String.join(",", seedNodes)); } assertAcked( client("cluster_a").admin() .indices() .prepareCreate("prod") .setMapping("f", "type=keyword") .setSettings( Settings.builder() .put(allocationFilter.build()) .put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0) .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, between(1, 3)) ) ); assertFalse( client("cluster_a").admin() .cluster() .prepareHealth(TEST_REQUEST_TIMEOUT, "prod") .setWaitForYellowStatus() .setTimeout(TimeValue.timeValueSeconds(10)) .get() .isTimedOut() ); int docs = indexDocs(client("cluster_a"), "f", "prod"); List<ActionFuture<SearchResponse>> futures = new ArrayList<>(); for (int i = 0; i < 10; ++i) { String[] indices = randomBoolean() ? new String[] { "demo", "cluster_a:prod" } : new String[] { "cluster_a:prod" }; final SearchRequest searchRequest = new SearchRequest(indices); searchRequest.allowPartialSearchResults(false); boolean scroll = randomBoolean(); searchRequest.source( new SearchSourceBuilder().query(new MatchAllQueryBuilder()) .aggregation(terms("f").field("f").size(docs + between(0, 10))) .size(between(scroll ? 1 : 0, 1000)) ); if (scroll) { searchRequest.scroll(TimeValue.timeValueSeconds(30)); } searchRequest.setCcsMinimizeRoundtrips(rarely()); futures.add(client(LOCAL_CLUSTER).search(searchRequest)); } for (ActionFuture<SearchResponse> future : futures) { assertResponse(future, response -> { if (response.getScrollId() != null) { ClearScrollRequest clearScrollRequest = new ClearScrollRequest(); clearScrollRequest.scrollIds(List.of(response.getScrollId())); try { client(LOCAL_CLUSTER).clearScroll(clearScrollRequest).get(); } catch (Exception e) { throw new RuntimeException(e); } } Terms terms = response.getAggregations().get("f"); assertThat(terms.getBuckets().size(), equalTo(docs)); for (Terms.Bucket bucket : terms.getBuckets()) { assertThat(bucket.getDocCount(), equalTo(1L)); } }); } } @Override protected void configureRemoteCluster(String clusterAlias, Collection<String> seedNodes) throws Exception { if (rarely()) { super.configureRemoteCluster(clusterAlias, seedNodes); } else { final Settings.Builder settings = Settings.builder(); final String seedNode = randomFrom(seedNodes); final TransportService transportService = cluster(clusterAlias).getInstance(TransportService.class, seedNode); final String seedAddress = transportService.boundAddress().publishAddress().toString(); settings.put("cluster.remote." + clusterAlias + ".mode", "proxy"); settings.put("cluster.remote." + clusterAlias + ".proxy_address", seedAddress); client().admin() .cluster() .prepareUpdateSettings(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT) .setPersistentSettings(settings) .get(); } } }
CrossClusterSearchLeakIT
java
apache__spark
common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/ExecutorDiskUtils.java
{ "start": 1794, "end": 2018 }
class ____.io.FileSystem. // So we are creating a File just to get the normalized path back to intern it. // We return this interned normalized path. return new File(notNormalizedPath).getPath().intern(); } }
java
java
quarkusio__quarkus
extensions/oidc-client/runtime/src/main/java/io/quarkus/oidc/client/runtime/OidcClientImpl.java
{ "start": 1594, "end": 9061 }
enum ____ { GET("Get"), REFRESH("Refresh"), REVOKE("Revoke"); String op; Operation(String op) { this.op = op; } String operation() { return op; } } private static final Logger LOG = Logger.getLogger(OidcClientImpl.class); private static final String CLIENT_ID_ATTRIBUTE = "client-id"; private static final String DEFAULT_OIDC_CLIENT_ID = "Default"; private static final String AUTHORIZATION_HEADER = String.valueOf(HttpHeaders.AUTHORIZATION); private final WebClient client; private final String tokenRequestUri; private final String tokenRevokeUri; private final MultiMap tokenGrantParams; private final MultiMap commonRefreshGrantParams; private final String grantType; private final Key clientJwtKey; private final boolean jwtBearerAuthentication; private final OidcClientConfig oidcConfig; private final Map<OidcEndpoint.Type, List<OidcRequestFilter>> requestFilters; private final Map<OidcEndpoint.Type, List<OidcResponseFilter>> responseFilters; private final ClientAssertionProvider clientAssertionProvider; private volatile boolean closed; private volatile String clientSecret; private volatile String clientSecretBasicAuthScheme; private OidcClientImpl(WebClient client, String tokenRequestUri, String tokenRevokeUri, String grantType, MultiMap tokenGrantParams, MultiMap commonRefreshGrantParams, OidcClientConfig oidcClientConfig, Map<OidcEndpoint.Type, List<OidcRequestFilter>> requestFilters, Map<OidcEndpoint.Type, List<OidcResponseFilter>> responseFilters, Vertx vertx, ClientCredentials clientCredentials) { this.client = client; this.tokenRequestUri = tokenRequestUri; this.tokenRevokeUri = tokenRevokeUri; this.tokenGrantParams = tokenGrantParams; this.commonRefreshGrantParams = commonRefreshGrantParams; this.grantType = grantType; this.oidcConfig = oidcClientConfig; this.requestFilters = requestFilters; this.responseFilters = responseFilters; this.clientSecretBasicAuthScheme = clientCredentials.clientSecretBasicAuthScheme; this.jwtBearerAuthentication = oidcClientConfig.credentials().jwt().source() == Source.BEARER; this.clientJwtKey = jwtBearerAuthentication ? null : clientCredentials.clientJwtKey; this.clientSecret = clientCredentials.clientSecret; if (jwtBearerAuthentication && oidcClientConfig.credentials().jwt().tokenPath().isPresent()) { this.clientAssertionProvider = new ClientAssertionProvider(vertx, oidcClientConfig.credentials().jwt().tokenPath().get()); if (this.clientAssertionProvider.getClientAssertion() == null) { throw new OidcClientException("Cannot find a valid JWT bearer token at path: " + oidcClientConfig.credentials().jwt().tokenPath().get()); } } else { this.clientAssertionProvider = null; } } @Override public Uni<Tokens> getTokens(Map<String, String> additionalGrantParameters) { checkClosed(); if (tokenGrantParams == null) { throw new OidcClientException( "Only 'refresh_token' grant is supported, please call OidcClient#refreshTokens method instead"); } return getJsonResponse(OidcEndpoint.Type.TOKEN, tokenGrantParams, additionalGrantParameters, Operation.GET); } @Override public Uni<Tokens> refreshTokens(String refreshToken, Map<String, String> additionalGrantParameters) { checkClosed(); if (refreshToken == null) { throw new OidcClientException("Refresh token is null"); } MultiMap refreshGrantParams = copyMultiMap(commonRefreshGrantParams); refreshGrantParams.add(OidcConstants.REFRESH_TOKEN_VALUE, refreshToken); return getJsonResponse(OidcEndpoint.Type.TOKEN, refreshGrantParams, additionalGrantParameters, Operation.REFRESH); } @Override public Uni<Boolean> revokeAccessToken(String accessToken, Map<String, String> additionalParameters) { checkClosed(); if (accessToken == null) { throw new OidcClientException("Access token is null"); } OidcRequestContextProperties requestProps = getRequestProps(null); if (tokenRevokeUri != null) { MultiMap tokenRevokeParams = new MultiMap(io.vertx.core.MultiMap.caseInsensitiveMultiMap()); tokenRevokeParams.set(OidcConstants.REVOCATION_TOKEN, accessToken); return postRequest(requestProps, OidcEndpoint.Type.TOKEN_REVOCATION, client.postAbs(tokenRevokeUri), tokenRevokeParams, additionalParameters, Operation.REVOKE) .transform(resp -> toRevokeResponse(requestProps, resp)); } else { LOG.debugf("%s OidcClient can not revoke the access token because the revocation endpoint URL is not set"); return Uni.createFrom().item(false); } } private OidcRequestContextProperties getRequestProps(String grantType) { if (requestFilters.isEmpty() && responseFilters.isEmpty()) { return null; } Map<String, Object> props = new HashMap<>(); props.put(CLIENT_ID_ATTRIBUTE, oidcConfig.id().orElse(DEFAULT_OIDC_CLIENT_ID)); if (grantType != null) { props.put(OidcConstants.GRANT_TYPE, grantType); } return new OidcRequestContextProperties(props); } private Boolean toRevokeResponse(OidcRequestContextProperties requestProps, HttpResponse<Buffer> resp) { // Per RFC7009, 200 is returned if a token has been revoked successfully or if the client submitted an // invalid token, https://datatracker.ietf.org/doc/html/rfc7009#section-2.2. // 503 is at least theoretically possible if the OIDC server declines and suggests to Retry-After some period of time. // However this period of time can be set to unpredictable value. OidcCommonUtils.filterHttpResponse(requestProps, resp, responseFilters, OidcEndpoint.Type.TOKEN_REVOCATION); return resp.statusCode() == 503 ? false : true; } private Uni<Tokens> getJsonResponse( OidcEndpoint.Type endpointType, MultiMap formBody, Map<String, String> additionalGrantParameters, Operation op) { //Uni needs to be lazy by default, we don't send the request unless //something has subscribed to it. This is important for the CAS state //management in TokensHelper String currentGrantType = isRefresh(op) ? OidcConstants.REFRESH_TOKEN_GRANT : grantType; final OidcRequestContextProperties requestProps = getRequestProps(currentGrantType); return Uni.createFrom().deferred(new Supplier<Uni<? extends Tokens>>() { @Override public Uni<Tokens> get() { return postRequest(requestProps, endpointType, client.postAbs(tokenRequestUri), formBody, additionalGrantParameters, op) .transform(resp -> emitGrantTokens(requestProps, resp, op)); } }); } private record PreparedPostRequest(Uni<HttpResponse<Buffer>> postRequest, CredentialsToRetry credentialsToRetry) {
Operation
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamTask.java
{ "start": 81199, "end": 83163 }
class ____ implements Runnable { private final Suspension suspendedDefaultAction; @Nullable private final PeriodTimer timer; public ResumeWrapper(Suspension suspendedDefaultAction, @Nullable PeriodTimer timer) { this.suspendedDefaultAction = suspendedDefaultAction; if (timer != null) { timer.markStart(); } this.timer = timer; } @Override public void run() { if (timer != null) { timer.markEnd(); } suspendedDefaultAction.resume(); } } @Override public boolean isUsingNonBlockingInput() { return true; } /** * While we are outside the user code, we do not want to be interrupted further upon * cancellation. The shutdown logic below needs to make sure it does not issue calls that block * and stall shutdown. Additionally, the cancellation watch dog will issue a hard-cancel (kill * the TaskManager process) as a backup in case some shutdown procedure blocks outside our * control. */ private void disableInterruptOnCancel() { synchronized (shouldInterruptOnCancelLock) { shouldInterruptOnCancel = false; } } @Override public void maybeInterruptOnCancel( Thread toInterrupt, @Nullable String taskName, @Nullable Long timeout) { synchronized (shouldInterruptOnCancelLock) { if (shouldInterruptOnCancel) { if (taskName != null && timeout != null) { Task.logTaskThreadStackTrace(toInterrupt, taskName, timeout, "interrupting"); } toInterrupt.interrupt(); } } } @Override public final Environment getEnvironment() { return environment; } /** Check whether records can be emitted in batch. */ @FunctionalInterface public
ResumeWrapper
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/socket/WebSocketMessageBrokerSecurityConfigurationTests.java
{ "start": 31879, "end": 33012 }
class ____ implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { // @formatter:off registry.addEndpoint("/websocket") .setHandshakeHandler(testHandshakeHandler()) .addInterceptors(new HttpSessionHandshakeInterceptor()); // @formatter:on } @Bean AuthorizationManager<Message<?>> authorizationManager( MessageMatcherDelegatingAuthorizationManager.Builder messages) { // @formatter:off messages .simpDestMatchers("/permitAll/**").permitAll() .simpDestMatchers("/authenticated/**").authenticated() .simpDestMatchers("/fullyAuthenticated/**").fullyAuthenticated() .simpDestMatchers("/rememberMe/**").rememberMe() .simpDestMatchers("/anonymous/**").anonymous() .anyMessage().denyAll(); // @formatter:on return messages.build(); } @Bean TestHandshakeHandler testHandshakeHandler() { return new TestHandshakeHandler(); } } @Configuration(proxyBeanMethods = false) @EnableWebSocketSecurity @EnableWebSocketMessageBroker @Import(SyncExecutorConfig.class) static
WebSocketSecurityConfig
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/body/MessageBodyHandler.java
{ "start": 789, "end": 876 }
interface ____<T> extends MessageBodyReader<T>, MessageBodyWriter<T> { }
MessageBodyHandler
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-globalpolicygenerator/src/main/java/org/apache/hadoop/yarn/server/globalpolicygenerator/GlobalPolicyGenerator.java
{ "start": 3456, "end": 15296 }
class ____ extends CompositeService { public static final Logger LOG = LoggerFactory.getLogger(GlobalPolicyGenerator.class); // YARN Variables private static CompositeServiceShutdownHook gpgShutdownHook; public static final int SHUTDOWN_HOOK_PRIORITY = 30; private AtomicBoolean isStopping = new AtomicBoolean(false); private static final String METRICS_NAME = "Global Policy Generator"; private static long gpgStartupTime = System.currentTimeMillis(); // Federation Variables private GPGContext gpgContext; private RegistryOperations registry; // Scheduler service that runs tasks periodically private ScheduledThreadPoolExecutor scheduledExecutorService; private SubClusterCleaner subClusterCleaner; private ApplicationCleaner applicationCleaner; private PolicyGenerator policyGenerator; private String webAppAddress; private JvmPauseMonitor pauseMonitor; private WebApp webApp; public GlobalPolicyGenerator() { super(GlobalPolicyGenerator.class.getName()); this.gpgContext = new GPGContextImpl(); } protected void doSecureLogin() throws IOException { Configuration config = getConfig(); SecurityUtil.login(config, YarnConfiguration.GPG_KEYTAB, YarnConfiguration.GPG_PRINCIPAL, getHostName(config)); } protected void initAndStart(Configuration conf, boolean hasToReboot) { // Remove the old hook if we are rebooting. if (hasToReboot && null != gpgShutdownHook) { ShutdownHookManager.get().removeShutdownHook(gpgShutdownHook); } gpgShutdownHook = new CompositeServiceShutdownHook(this); ShutdownHookManager.get().addShutdownHook(gpgShutdownHook, SHUTDOWN_HOOK_PRIORITY); this.init(conf); this.start(); } @Override protected void serviceInit(Configuration conf) throws Exception { UserGroupInformation.setConfiguration(conf); // Set up the context this.gpgContext.setStateStoreFacade(FederationStateStoreFacade.getInstance(conf)); GPGPolicyFacade gpgPolicyFacade = new GPGPolicyFacade(this.gpgContext.getStateStoreFacade(), conf); this.gpgContext.setPolicyFacade(gpgPolicyFacade); this.registry = FederationStateStoreFacade.createInstance(conf, YarnConfiguration.YARN_REGISTRY_CLASS, YarnConfiguration.DEFAULT_YARN_REGISTRY_CLASS, RegistryOperations.class); this.registry.init(conf); UserGroupInformation user = UserGroupInformation.getCurrentUser(); FederationRegistryClient registryClient = new FederationRegistryClient(conf, this.registry, user); this.gpgContext.setRegistryClient(registryClient); this.scheduledExecutorService = new ScheduledThreadPoolExecutor( conf.getInt(YarnConfiguration.GPG_SCHEDULED_EXECUTOR_THREADS, YarnConfiguration.DEFAULT_GPG_SCHEDULED_EXECUTOR_THREADS)); this.subClusterCleaner = new SubClusterCleaner(conf, this.gpgContext); this.applicationCleaner = FederationStateStoreFacade.createInstance(conf, YarnConfiguration.GPG_APPCLEANER_CLASS, YarnConfiguration.DEFAULT_GPG_APPCLEANER_CLASS, ApplicationCleaner.class); this.applicationCleaner.init(conf, this.gpgContext); this.policyGenerator = new PolicyGenerator(conf, this.gpgContext); this.webAppAddress = WebAppUtils.getGPGWebAppURLWithoutScheme(conf); DefaultMetricsSystem.initialize(METRICS_NAME); JvmMetrics jm = JvmMetrics.initSingleton("GPG", null); pauseMonitor = new JvmPauseMonitor(); addService(pauseMonitor); jm.setPauseMonitor(pauseMonitor); // super.serviceInit after all services are added super.serviceInit(conf); WebServiceClient.initialize(conf); } @Override protected void serviceStart() throws Exception { try { doSecureLogin(); } catch (IOException e) { throw new YarnRuntimeException("Failed GPG login", e); } super.serviceStart(); this.registry.start(); // Schedule SubClusterCleaner service Configuration config = getConfig(); long scCleanerIntervalMs = config.getTimeDuration( YarnConfiguration.GPG_SUBCLUSTER_CLEANER_INTERVAL_MS, YarnConfiguration.DEFAULT_GPG_SUBCLUSTER_CLEANER_INTERVAL_MS, TimeUnit.MILLISECONDS); if (scCleanerIntervalMs > 0) { this.scheduledExecutorService.scheduleAtFixedRate(this.subClusterCleaner, 0, scCleanerIntervalMs, TimeUnit.MILLISECONDS); LOG.info("Scheduled sub-cluster cleaner with interval: {}", DurationFormatUtils.formatDurationISO(scCleanerIntervalMs)); } // Schedule ApplicationCleaner service long appCleanerIntervalMs = config.getTimeDuration( YarnConfiguration.GPG_APPCLEANER_INTERVAL_MS, YarnConfiguration.DEFAULT_GPG_APPCLEANER_INTERVAL_MS, TimeUnit.MILLISECONDS); if (appCleanerIntervalMs > 0) { this.scheduledExecutorService.scheduleAtFixedRate(this.applicationCleaner, 0, appCleanerIntervalMs, TimeUnit.MILLISECONDS); LOG.info("Scheduled application cleaner with interval: {}", DurationFormatUtils.formatDurationISO(appCleanerIntervalMs)); } // Schedule PolicyGenerator // We recommend using yarn.federation.gpg.policy.generator.interval // instead of yarn.federation.gpg.policy.generator.interval-ms // To ensure compatibility, // let's first obtain the value of "yarn.federation.gpg.policy.generator.interval-ms." long policyGeneratorIntervalMillis = 0L; String generatorIntervalMS = config.get(YarnConfiguration.GPG_POLICY_GENERATOR_INTERVAL_MS); if (generatorIntervalMS != null) { LOG.warn("yarn.federation.gpg.policy.generator.interval-ms is deprecated property, " + " we better set it yarn.federation.gpg.policy.generator.interval."); policyGeneratorIntervalMillis = Long.parseLong(generatorIntervalMS); } // If it is not available, let's retrieve // the value of "yarn.federation.gpg.policy.generator.interval" instead. if (policyGeneratorIntervalMillis == 0) { policyGeneratorIntervalMillis = config.getTimeDuration( YarnConfiguration.GPG_POLICY_GENERATOR_INTERVAL, YarnConfiguration.DEFAULT_GPG_POLICY_GENERATOR_INTERVAL, TimeUnit.MILLISECONDS); } if(policyGeneratorIntervalMillis > 0){ this.scheduledExecutorService.scheduleAtFixedRate(this.policyGenerator, 0, policyGeneratorIntervalMillis, TimeUnit.MILLISECONDS); LOG.info("Scheduled policy-generator with interval: {}", DurationFormatUtils.formatDurationISO(policyGeneratorIntervalMillis)); } startWepApp(); } @Override protected void serviceStop() throws Exception { if (this.registry != null) { this.registry.stop(); this.registry = null; } try { if (this.scheduledExecutorService != null && !this.scheduledExecutorService.isShutdown()) { this.scheduledExecutorService.shutdown(); LOG.info("Stopped ScheduledExecutorService"); } } catch (Exception e) { LOG.error("Failed to shutdown ScheduledExecutorService", e); throw e; } if (this.isStopping.getAndSet(true)) { return; } if (webApp != null) { webApp.stop(); } DefaultMetricsSystem.shutdown(); super.serviceStop(); WebServiceClient.destroy(); } public String getName() { return "FederationGlobalPolicyGenerator"; } public GPGContext getGPGContext() { return this.gpgContext; } @VisibleForTesting public void startWepApp() { Configuration configuration = getConfig(); boolean enableCors = configuration.getBoolean(YarnConfiguration.GPG_WEBAPP_ENABLE_CORS_FILTER, YarnConfiguration.DEFAULT_GPG_WEBAPP_ENABLE_CORS_FILTER); if (enableCors) { configuration.setBoolean(HttpCrossOriginFilterInitializer.PREFIX + HttpCrossOriginFilterInitializer.ENABLED_SUFFIX, true); } // Always load pseudo authentication filter to parse "user.name" in an URL // to identify a HTTP request's user. boolean hasHadoopAuthFilterInitializer = false; String filterInitializerConfKey = "hadoop.http.filter.initializers"; Class<?>[] initializersClasses = configuration.getClasses(filterInitializerConfKey); List<String> targets = new ArrayList<>(); if (initializersClasses != null) { for (Class<?> initializer : initializersClasses) { if (initializer.getName().equals(AuthenticationFilterInitializer.class.getName())) { hasHadoopAuthFilterInitializer = true; break; } targets.add(initializer.getName()); } } if (!hasHadoopAuthFilterInitializer) { targets.add(AuthenticationFilterInitializer.class.getName()); configuration.set(filterInitializerConfKey, StringUtils.join(",", targets)); } LOG.info("Instantiating GPGWebApp at {}.", webAppAddress); GPGWebApp gpgWebApp = new GPGWebApp(this); webApp = WebApps.$for("gpg", GPGContext.class, this.gpgContext, "gpg-ws").at(webAppAddress). withResourceConfig(gpgWebApp.resourceConfig()).start(gpgWebApp); } @SuppressWarnings("resource") public static void startGPG(String[] argv, Configuration conf) { boolean federationEnabled = conf.getBoolean(YarnConfiguration.FEDERATION_ENABLED, YarnConfiguration.DEFAULT_FEDERATION_ENABLED); if (federationEnabled) { Thread.setDefaultUncaughtExceptionHandler(new YarnUncaughtExceptionHandler()); StringUtils.startupShutdownMessage(GlobalPolicyGenerator.class, argv, LOG); GlobalPolicyGenerator globalPolicyGenerator = new GlobalPolicyGenerator(); globalPolicyGenerator.initAndStart(conf, false); } else { LOG.warn("Federation is not enabled. The gpg cannot start."); } } /** * Returns the hostname for this Router. If the hostname is not * explicitly configured in the given config, then it is determined. * * @param config configuration * @return the hostname (NB: may not be a FQDN) * @throws UnknownHostException if the hostname cannot be determined */ private String getHostName(Configuration config) throws UnknownHostException { String name = config.get(YarnConfiguration.GPG_KERBEROS_PRINCIPAL_HOSTNAME_KEY); if (name == null) { name = InetAddress.getLocalHost().getHostName(); } return name; } public static void main(String[] argv) { try { YarnConfiguration conf = new YarnConfiguration(); GenericOptionsParser hParser = new GenericOptionsParser(conf, argv); argv = hParser.getRemainingArgs(); if (argv.length > 1) { if (argv[0].equals("-format-policy-store")) { handFormatPolicyStateStore(conf); } else { printUsage(System.err); } } else { startGPG(argv, conf); } } catch (Throwable t) { LOG.error("Error starting global policy generator", t); System.exit(-1); } } public static long getGPGStartupTime() { return gpgStartupTime; } @VisibleForTesting public WebApp getWebApp() { return webApp; } private static void printUsage(PrintStream out) { out.println("Usage: yarn gpg [-format-policy-store]"); } private static void handFormatPolicyStateStore(Configuration conf) { try { System.out.println("Deleting Federation policy state store."); FederationStateStoreFacade facade = FederationStateStoreFacade.getInstance(conf); System.out.println("Federation policy state store has been cleaned."); facade.deleteAllPoliciesConfigurations(); } catch (Exception e) { LOG.error("Delete Federation policy state store error.", e); System.err.println("Delete Federation policy state store error, exception = " + e); } } @Override public void setConfig(Configuration conf) { super.setConfig(conf); } }
GlobalPolicyGenerator
java
google__guice
extensions/assistedinject/test/com/google/inject/assistedinject/FactoryProvider2Test.java
{ "start": 45678, "end": 45786 }
interface ____ { Equals equals(Equals.ComparisonMethod comparisonMethod); } public static
Factory
java
hibernate__hibernate-orm
hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/h2gis/H2GISGeometryType.java
{ "start": 984, "end": 2978 }
class ____ implements JdbcType { /** * An instance of this Descriptor */ public static final H2GISGeometryType INSTANCE = new H2GISGeometryType(); @Override public int getJdbcTypeCode() { return Types.ARRAY; } @Override public int getDefaultSqlTypeCode() { return SqlTypes.GEOMETRY; } @Override public <T> JdbcLiteralFormatter<T> getJdbcLiteralFormatter(JavaType<T> javaType) { return new GeometryLiteralFormatter<T>( javaType, Wkt.Dialect.SFA_1_1_0, "ST_GeomFromText" ); } @Override public <X> ValueBinder<X> getBinder(final JavaType<X> javaType) { return new BasicBinder<X>( javaType, this ) { @Override protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException { final Geometry geometry = getJavaType().unwrap( value, Geometry.class, options ); st.setBytes( index, H2GISWkb.to( geometry ) ); } @Override protected void doBind(CallableStatement st, X value, String name, WrapperOptions options) throws SQLException { final Geometry geometry = getJavaType().unwrap( value, Geometry.class, options ); st.setBytes( name, H2GISWkb.to( geometry ) ); } }; } @Override public <X> ValueExtractor<X> getExtractor(final JavaType<X> javaType) { return new BasicExtractor<X>( javaType, this ) { @Override protected X doExtract(ResultSet rs, int paramIndex, WrapperOptions options) throws SQLException { return getJavaType().wrap( H2GISWkb.from( rs.getObject( paramIndex ) ), options ); } @Override protected X doExtract(CallableStatement statement, int index, WrapperOptions options) throws SQLException { return getJavaType().wrap( H2GISWkb.from( statement.getObject( index ) ), options ); } @Override protected X doExtract(CallableStatement statement, String name, WrapperOptions options) throws SQLException { return getJavaType().wrap( H2GISWkb.from( statement.getObject( name ) ), options ); } }; } }
H2GISGeometryType
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ArgumentSelectionDefectCheckerTest.java
{ "start": 1462, "end": 1993 }
class ____ { private final CompilationTestHelper testHelper = CompilationTestHelper.newInstance( ArgumentSelectionDefectWithStringEquality.class, getClass()); /** * A {@link BugChecker} which runs the ArgumentSelectionDefectChecker checker using string * equality for edit distance */ @BugPattern( severity = SeverityLevel.ERROR, summary = "Run the ArgumentSelectionDefectChecker checker using string equality for edit distance") public static
ArgumentSelectionDefectCheckerTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conditional/basic/ConditionalMethodWithMappingTargetInUpdateMapper.java
{ "start": 513, "end": 1033 }
interface ____ { ConditionalMethodWithMappingTargetInUpdateMapper INSTANCE = Mappers.getMapper( ConditionalMethodWithMappingTargetInUpdateMapper.class ); void map(BasicEmployeeDto employee, @MappingTarget BasicEmployee targetEmployee); @Condition default boolean isNotBlankAndNotPresent(String value, @MappingTarget BasicEmployee targetEmployee) { return value != null && !value.trim().isEmpty() && targetEmployee.getName() == null; } }
ConditionalMethodWithMappingTargetInUpdateMapper
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_42283905.java
{ "start": 1408, "end": 2074 }
class ____ { private String name; private List<Command> battleCommandList = new ArrayList<Command>(); public Group(){ } public Group(String name){ this.name = name; } public List<Command> getBattleCommandList() { return battleCommandList; } public void setBattleCommandList(List<Command> battleCommandList) { this.battleCommandList = battleCommandList; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static
Group
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/isolation/SamplingTestPlugin.java
{ "start": 1050, "end": 3487 }
interface ____ { /** * @return the ClassLoader used to statically initialize this plugin class */ ClassLoader staticClassloader(); /** * @return the ClassLoader used to initialize this plugin instance */ ClassLoader classloader(); /** * @return All known instances of this class, including this instance. */ default List<SamplingTestPlugin> allInstances() { return List.of(this); } /** * @return a group of other SamplingTestPlugin instances known by this plugin * This should only return direct children, and not reference this instance directly */ default Map<String, SamplingTestPlugin> otherSamples() { return Map.of(); } /** * @return a flattened list of child samples including this entry keyed as "this" */ default Map<String, SamplingTestPlugin> flatten() { Map<String, SamplingTestPlugin> out = new HashMap<>(); Map<String, SamplingTestPlugin> otherSamples = otherSamples(); if (otherSamples != null) { for (Entry<String, SamplingTestPlugin> child : otherSamples.entrySet()) { for (Entry<String, SamplingTestPlugin> flattened : child.getValue().flatten().entrySet()) { String key = child.getKey(); if (!flattened.getKey().isEmpty()) { key += "." + flattened.getKey(); } out.put(key, flattened.getValue()); } } } out.put("", this); return out; } /** * Log the parent method call as a child sample. * Stores only the last invocation of each method if there are multiple invocations. * @param samples The collection of samples to which this method call should be added */ default void logMethodCall(Map<String, SamplingTestPlugin> samples) { StackTraceElement[] stackTraces = Thread.currentThread().getStackTrace(); if (stackTraces.length < 2) { return; } // 0 is inside getStackTrace // 1 is this method // 2 is our caller method StackTraceElement caller = stackTraces[2]; samples.put(caller.getMethodName(), new MethodCallSample( caller, Thread.currentThread().getContextClassLoader(), getClass().getClassLoader() )); }
SamplingTestPlugin
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/aot/JpaRepositoryContributor.java
{ "start": 3642, "end": 11373 }
class ____ extends RepositoryContributor { private final AotRepositoryContext context; private final EntityManagerFactory entityManagerFactory; private final Metamodel metamodel; private final PersistenceUnitUtil persistenceUnitUtil; private final PersistenceProvider persistenceProvider; private final QueriesFactory queriesFactory; private final EntityGraphLookup entityGraphLookup; public JpaRepositoryContributor(AotRepositoryContext repositoryContext) { this(repositoryContext, AotEntityManagerFactoryCreator.from(repositoryContext).getEntityManagerFactory()); } public JpaRepositoryContributor(AotRepositoryContext repositoryContext, EntityManagerFactory entityManagerFactory) { super(repositoryContext); this.entityManagerFactory = entityManagerFactory; this.metamodel = entityManagerFactory.getMetamodel(); this.persistenceUnitUtil = entityManagerFactory.getPersistenceUnitUtil(); this.persistenceProvider = PersistenceProvider.fromEntityManagerFactory(entityManagerFactory); this.queriesFactory = new QueriesFactory(repositoryContext.getConfigurationSource(), entityManagerFactory, repositoryContext.getRequiredClassLoader()); this.entityGraphLookup = new EntityGraphLookup(entityManagerFactory); this.context = repositoryContext; } public EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } @Override protected void customizeClass(AotRepositoryClassBuilder classBuilder) { classBuilder.customize(builder -> builder.superclass(TypeName.get(AotRepositoryFragmentSupport.class))); } @Override protected void customizeConstructor(AotRepositoryConstructorBuilder constructorBuilder) { String entityManagerFactoryRef = getEntityManagerFactoryRef(); constructorBuilder.addParameter("entityManager", EntityManager.class, customizer -> { customizer.bindToField().origin( StringUtils.hasText(entityManagerFactoryRef) ? new RuntimeBeanReference(entityManagerFactoryRef, EntityManager.class) : new RuntimeBeanReference(EntityManager.class)); }); constructorBuilder.addParameter("context", RepositoryFactoryBeanSupport.FragmentCreationContext.class); Optional<Class<QueryEnhancerSelector>> queryEnhancerSelector = getQueryEnhancerSelectorClass(); constructorBuilder.customize(builder -> { if (queryEnhancerSelector.isPresent()) { builder.addStatement("super(new T$(), context)", queryEnhancerSelector.get()); } else { builder.addStatement("super($T.DEFAULT_SELECTOR, context)", QueryEnhancerSelector.class); } }); } private @Nullable String getEntityManagerFactoryRef() { return context.getConfigurationSource().getAttribute("entityManagerFactoryRef") .filter(it -> !"entityManagerFactory".equals(it)).orElse(null); } @SuppressWarnings({ "rawtypes", "unchecked" }) private Optional<Class<QueryEnhancerSelector>> getQueryEnhancerSelectorClass() { return (Optional) context.getConfigurationSource().getAttribute("queryEnhancerSelector", Class.class) .filter(it -> !it.equals(QueryEnhancerSelector.DefaultQueryEnhancerSelector.class)); } @Override protected @Nullable MethodContributor<? extends QueryMethod> contributeQueryMethod(Method method) { JpaEntityMetadata<?> entityInformation = JpaEntityInformationSupport .getEntityInformation(getRepositoryInformation().getDomainType(), metamodel, persistenceUnitUtil); AotJpaQueryMethod queryMethod = new AotJpaQueryMethod(method, getRepositoryInformation(), entityInformation, getProjectionFactory(), persistenceProvider, JpaParameters::new); Optional<Class<QueryEnhancerSelector>> queryEnhancerSelectorClass = getQueryEnhancerSelectorClass(); QueryEnhancerSelector selector = queryEnhancerSelectorClass.map(BeanUtils::instantiateClass) .orElse(QueryEnhancerSelector.DEFAULT_SELECTOR); // no stored procedures for now. if (queryMethod.isProcedureQuery()) { Procedure procedure = AnnotatedElementUtils.findMergedAnnotation(method, Procedure.class); MethodContributor.QueryMethodMetadataContributorBuilder<JpaQueryMethod> builder = MethodContributor .forQueryMethod(queryMethod); if (procedure != null) { if (StringUtils.hasText(procedure.name())) { return builder.metadataOnly(new NamedStoredProcedureMetadata(procedure.name())); } if (StringUtils.hasText(procedure.procedureName())) { return builder.metadataOnly(new StoredProcedureMetadata(procedure.procedureName())); } if (StringUtils.hasText(procedure.value())) { return builder.metadataOnly(new StoredProcedureMetadata(procedure.value())); } } // TODO: Better fallback. return null; } ReturnedType returnedType = queryMethod.getResultProcessor().getReturnedType(); JpaParameters parameters = queryMethod.getParameters(); MergedAnnotation<Query> query = MergedAnnotations.from(method).get(Query.class); AotQueries aotQueries = queriesFactory.createQueries(getRepositoryInformation(), returnedType, selector, query, queryMethod); // no KeysetScrolling for now. if (parameters.hasScrollPositionParameter() || queryMethod.isScrollQuery()) { return MethodContributor.forQueryMethod(queryMethod) .metadataOnly(aotQueries.toMetadata(queryMethod.isPageQuery())); } // no dynamic projections. if (parameters.hasDynamicProjection()) { return MethodContributor.forQueryMethod(queryMethod) .metadataOnly(aotQueries.toMetadata(queryMethod.isPageQuery())); } if (queryMethod.isModifyingQuery() && !aotQueries.result().isDerived()) { TypeInformation<?> returnType = getRepositoryInformation().getReturnType(method); boolean returnsCount = JpaCodeBlocks.QueryExecutionBlockBuilder.returnsModifying(returnType.getType()); boolean isVoid = ClassUtils.isVoidType(returnType.getType()); if (!returnsCount && !isVoid) { return MethodContributor.forQueryMethod(queryMethod) .metadataOnly(aotQueries.toMetadata(queryMethod.isPageQuery())); } } return MethodContributor.forQueryMethod(queryMethod).withMetadata(aotQueries.toMetadata(queryMethod.isPageQuery())) .contribute(context -> { CodeBlock.Builder body = CodeBlock.builder(); MergedAnnotation<NativeQuery> nativeQuery = context.getAnnotation(NativeQuery.class); MergedAnnotation<QueryHints> queryHints = context.getAnnotation(QueryHints.class); MergedAnnotation<EntityGraph> entityGraph = context.getAnnotation(EntityGraph.class); MergedAnnotation<Modifying> modifying = context.getAnnotation(Modifying.class); AotEntityGraph aotEntityGraph = entityGraphLookup.findEntityGraph(entityGraph, getRepositoryInformation(), returnedType, queryMethod); body.add(JpaCodeBlocks.queryBuilder(context, queryMethod).filter(aotQueries) .queryReturnType(QueriesFactory.getQueryReturnType(aotQueries.result(), returnedType, context)) .nativeQuery(nativeQuery).queryHints(queryHints).entityGraph(aotEntityGraph) .queryRewriter(query.isPresent() ? query.getClass("queryRewriter") : null).build()); body.add(JpaCodeBlocks.executionBuilder(context, queryMethod).modifying(modifying).query(aotQueries.result()) .build()); return body.build(); }); } record StoredProcedureMetadata(String procedure) implements QueryMetadata { @Override public Map<String, Object> serialize() { return Map.of("procedure", procedure()); } } record NamedStoredProcedureMetadata(String procedureName) implements QueryMetadata { @Override public Map<String, Object> serialize() { return Map.of("procedure-name", procedureName()); } } /** * AOT extension to {@link JpaQueryMethod} providing a metamodel backed {@link JpaEntityMetadata} object. */ static
JpaRepositoryContributor
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ComparableTypeTest.java
{ "start": 5539, "end": 5678 }
class ____ extends A implements Comparable<A> { @Override public int compareTo(A o) { return 0; } } // ignore enums
B
java
apache__flink
flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/utils/CustomStateBackendFactory.java
{ "start": 1194, "end": 1587 }
class ____ implements StateBackendFactory<StateBackend> { @Override public StateBackend createFromConfig(ReadableConfig config, ClassLoader classLoader) throws IllegalConfigurationException, IOException { throw new ExpectedException(); } /** An expected exception. Used to verify this factory is used at runtime. */ public static
CustomStateBackendFactory
java
apache__hadoop
hadoop-tools/hadoop-gridmix/src/main/java/org/apache/hadoop/mapred/gridmix/JobSubmitter.java
{ "start": 3056, "end": 7975 }
class ____ implements Runnable { final GridmixJob job; public SubmitTask(GridmixJob job) { this.job = job; } public void run() { JobStats stats = Statistics.generateJobStats(job.getJob(), job.getJobDesc()); try { // pre-compute split information try { long start = System.currentTimeMillis(); job.buildSplits(inputDir); long end = System.currentTimeMillis(); LOG.info("[JobSubmitter] Time taken to build splits for job " + job.getJob().getJobID() + ": " + (end - start) + " ms."); } catch (IOException e) { LOG.warn("Failed to submit " + job.getJob().getJobName() + " as " + job.getUgi(), e); monitor.submissionFailed(stats); return; } catch (Exception e) { LOG.warn("Failed to submit " + job.getJob().getJobName() + " as " + job.getUgi(), e); monitor.submissionFailed(stats); return; } // Sleep until deadline long nsDelay = job.getDelay(TimeUnit.NANOSECONDS); while (nsDelay > 0) { TimeUnit.NANOSECONDS.sleep(nsDelay); nsDelay = job.getDelay(TimeUnit.NANOSECONDS); } try { // submit job long start = System.currentTimeMillis(); job.call(); long end = System.currentTimeMillis(); LOG.info("[JobSubmitter] Time taken to submit the job " + job.getJob().getJobID() + ": " + (end - start) + " ms."); // mark it as submitted job.setSubmitted(); // add to the monitor monitor.add(stats); // add to the statistics statistics.addJobStats(stats); if (LOG.isDebugEnabled()) { String jobID = job.getJob().getConfiguration().get(Gridmix.ORIGINAL_JOB_ID); LOG.debug("Original job '" + jobID + "' is being simulated as '" + job.getJob().getJobID() + "'"); LOG.debug("SUBMIT " + job + "@" + System.currentTimeMillis() + " (" + job.getJob().getJobID() + ")"); } } catch (IOException e) { LOG.warn("Failed to submit " + job.getJob().getJobName() + " as " + job.getUgi(), e); if (e.getCause() instanceof ClosedByInterruptException) { throw new InterruptedException("Failed to submit " + job.getJob().getJobName()); } monitor.submissionFailed(stats); } catch (ClassNotFoundException e) { LOG.warn("Failed to submit " + job.getJob().getJobName(), e); monitor.submissionFailed(stats); } } catch (InterruptedException e) { // abort execution, remove splits if nesc // TODO release ThdLoc GridmixJob.pullDescription(job.id()); Thread.currentThread().interrupt(); monitor.submissionFailed(stats); } catch(Exception e) { //Due to some exception job wasnt submitted. LOG.info(" Job " + job.getJob().getJobID() + " submission failed " , e); monitor.submissionFailed(stats); } finally { sem.release(); } } } /** * Enqueue the job to be submitted per the deadline associated with it. */ public void add(final GridmixJob job) throws InterruptedException { final boolean addToQueue = !shutdown; if (addToQueue) { final SubmitTask task = new SubmitTask(job); LOG.info("Total number of queued jobs: " + (queueDepth - sem.availablePermits())); sem.acquire(); try { sched.execute(task); } catch (RejectedExecutionException e) { sem.release(); } } } /** * (Re)scan the set of input files from which splits are derived. * @throws java.io.IOException */ public void refreshFilePool() throws IOException { inputDir.refresh(); } /** * Does nothing, as the threadpool is already initialized and waiting for * work from the upstream factory. */ public void start() { } /** * Continue running until all queued jobs have been submitted to the * cluster. */ public void join(long millis) throws InterruptedException { if (!shutdown) { throw new IllegalStateException("Cannot wait for active submit thread"); } sched.awaitTermination(millis, TimeUnit.MILLISECONDS); } /** * Finish all jobs pending submission, but do not accept new work. */ public void shutdown() { // complete pending tasks, but accept no new tasks shutdown = true; sched.shutdown(); } /** * Discard pending work, including precomputed work waiting to be * submitted. */ public void abort() { //pendingJobs.clear(); shutdown = true; sched.shutdownNow(); } }
SubmitTask
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/InfinispanEmbeddedEndpointBuilderFactory.java
{ "start": 19033, "end": 25359 }
interface ____ extends EndpointProducerBuilder { default AdvancedInfinispanEmbeddedEndpointProducerBuilder advanced() { return (AdvancedInfinispanEmbeddedEndpointProducerBuilder) this; } /** * Specifies the query builder. * * The option is a: * <code>org.apache.camel.component.infinispan.InfinispanQueryBuilder</code> type. * * Group: common * * @param queryBuilder the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder queryBuilder(org.apache.camel.component.infinispan.InfinispanQueryBuilder queryBuilder) { doSetProperty("queryBuilder", queryBuilder); return this; } /** * Specifies the query builder. * * The option will be converted to a * <code>org.apache.camel.component.infinispan.InfinispanQueryBuilder</code> type. * * Group: common * * @param queryBuilder the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder queryBuilder(String queryBuilder) { doSetProperty("queryBuilder", queryBuilder); return this; } /** * Set a specific default value for some producer operations. * * The option is a: <code>java.lang.Object</code> type. * * Group: producer * * @param defaultValue the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder defaultValue(Object defaultValue) { doSetProperty("defaultValue", defaultValue); return this; } /** * Set a specific default value for some producer operations. * * The option will be converted to a <code>java.lang.Object</code> type. * * Group: producer * * @param defaultValue the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder defaultValue(String defaultValue) { doSetProperty("defaultValue", defaultValue); return this; } /** * Set a specific key for producer operations. * * The option is a: <code>java.lang.Object</code> type. * * Group: producer * * @param key the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder key(Object key) { doSetProperty("key", key); return this; } /** * Set a specific key for producer operations. * * The option will be converted to a <code>java.lang.Object</code> type. * * Group: producer * * @param key the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder key(String key) { doSetProperty("key", key); return this; } /** * Set a specific old value for some producer operations. * * The option is a: <code>java.lang.Object</code> type. * * Group: producer * * @param oldValue the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder oldValue(Object oldValue) { doSetProperty("oldValue", oldValue); return this; } /** * Set a specific old value for some producer operations. * * The option will be converted to a <code>java.lang.Object</code> type. * * Group: producer * * @param oldValue the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder oldValue(String oldValue) { doSetProperty("oldValue", oldValue); return this; } /** * The operation to perform. * * The option is a: * <code>org.apache.camel.component.infinispan.InfinispanOperation</code> type. * * Default: PUT * Group: producer * * @param operation the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder operation(org.apache.camel.component.infinispan.InfinispanOperation operation) { doSetProperty("operation", operation); return this; } /** * The operation to perform. * * The option will be converted to a * <code>org.apache.camel.component.infinispan.InfinispanOperation</code> type. * * Default: PUT * Group: producer * * @param operation the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder operation(String operation) { doSetProperty("operation", operation); return this; } /** * Set a specific value for producer operations. * * The option is a: <code>java.lang.Object</code> type. * * Group: producer * * @param value the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder value(Object value) { doSetProperty("value", value); return this; } /** * Set a specific value for producer operations. * * The option will be converted to a <code>java.lang.Object</code> type. * * Group: producer * * @param value the value to set * @return the dsl builder */ default InfinispanEmbeddedEndpointProducerBuilder value(String value) { doSetProperty("value", value); return this; } } /** * Advanced builder for endpoint producers for the Infinispan Embedded component. */ public
InfinispanEmbeddedEndpointProducerBuilder
java
alibaba__nacos
plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/persistence/RoleInfo.java
{ "start": 772, "end": 1405 }
class ____ implements Serializable { private static final long serialVersionUID = 5946986388047856568L; private String role; private String username; public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "RoleInfo{" + "role='" + role + '\'' + ", username='" + username + '\'' + '}'; } }
RoleInfo
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/execution/DefaultBuildResumptionAnalyzer.java
{ "start": 1190, "end": 2517 }
class ____ implements BuildResumptionAnalyzer { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultBuildResumptionAnalyzer.class); @Override public Optional<BuildResumptionData> determineBuildResumptionData(final MavenExecutionResult result) { if (!result.hasExceptions()) { return Optional.empty(); } List<MavenProject> sortedProjects = result.getTopologicallySortedProjects(); boolean hasNoSuccess = sortedProjects.stream().noneMatch(project -> result.getBuildSummary(project) instanceof BuildSuccess); if (hasNoSuccess) { return Optional.empty(); } List<String> remainingProjects = sortedProjects.stream() .filter(project -> result.getBuildSummary(project) == null || result.getBuildSummary(project) instanceof BuildFailure) .map(project -> project.getGroupId() + ":" + project.getArtifactId()) .collect(Collectors.toList()); if (remainingProjects.isEmpty()) { LOGGER.info("No remaining projects found, resuming the build would not make sense."); return Optional.empty(); } return Optional.of(new BuildResumptionData(remainingProjects)); } }
DefaultBuildResumptionAnalyzer
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/config/ConfigDataLoadersTests.java
{ "start": 7290, "end": 7833 }
class ____ implements ConfigDataLoader<ConfigDataResource> { private final DeferredLogFactory logFactory; DeferredLogFactoryConfigDataLoader(DeferredLogFactory logFactory) { assertThat(logFactory).isNotNull(); this.logFactory = logFactory; } @Override public ConfigData load(ConfigDataLoaderContext context, ConfigDataResource resource) throws IOException { throw new AssertionError("Unexpected call"); } DeferredLogFactory getLogFactory() { return this.logFactory; } } static
DeferredLogFactoryConfigDataLoader
java
redisson__redisson
redisson-quarkus/redisson-quarkus-16/runtime/src/main/java/io/quarkus/redisson/client/runtime/RedissonClientProducer.java
{ "start": 1544, "end": 3526 }
class ____ { private RedissonClient redisson; @Inject public ShutdownConfig shutdownConfig; @Produces @Singleton @DefaultBean public RedissonClient create() throws IOException { String config = null; Optional<String> configFile = ConfigProvider.getConfig().getOptionalValue("quarkus.redisson.file", String.class); String configFileName = configFile.orElse("redisson.yaml"); try (InputStream configStream = Optional.ofNullable(getClass().getResourceAsStream(configFileName)) .orElse(Thread.currentThread().getContextClassLoader().getResourceAsStream(configFileName)) ) { if (configStream != null) { byte[] array = new byte[configStream.available()]; if (configStream.read(array) != -1) { config = new String(array, StandardCharsets.UTF_8); } } } if (config == null) { Stream<String> s = StreamSupport.stream(ConfigProvider.getConfig().getPropertyNames().spliterator(), false); config = PropertiesConvertor.toYaml("quarkus.redisson.", s.sorted().collect(Collectors.toList()), prop -> { return ConfigProvider.getConfig().getValue(prop, String.class); }, false); } ConfigSupport support = new ConfigSupport(true); Config c = support.fromYAML(config, Config.class); redisson = Redisson.create(c); return redisson; } public void setConfig(org.eclipse.microprofile.config.Config config) { } @PreDestroy public void close() { if (redisson != null) { if (shutdownConfig.isShutdownTimeoutSet()){ Duration grace = shutdownConfig.timeout.get(); redisson.shutdown(grace.toMillis(),grace.toMillis()*2, TimeUnit.MILLISECONDS); }else{ redisson.shutdown(); } } } }
RedissonClientProducer
java
quarkusio__quarkus
extensions/funqy/funqy-amazon-lambda/runtime/src/main/java/io/quarkus/funqy/lambda/event/dynamodb/DynamoDbEventHandler.java
{ "start": 515, "end": 2083 }
class ____ implements EventHandler<DynamodbEvent, DynamodbStreamRecord, StreamsEventResponse> { @Override public Stream<DynamodbStreamRecord> streamEvent(DynamodbEvent event, FunqyAmazonConfig amazonConfig) { if (event == null) { return Stream.empty(); } return event.getRecords().stream(); } @Override public String getIdentifier(DynamodbStreamRecord message, FunqyAmazonConfig amazonConfig) { return message.getDynamodb().getSequenceNumber(); } @Override public Supplier<InputStream> getBody(DynamodbStreamRecord message, FunqyAmazonConfig amazonConfig) { throw new IllegalStateException(""" DynamoDB records are too specific. It is not supported to extract a message from them. \ Use the DynamodbStreamRecord in your funq method, or use EventBridge Pipes with CloudEvents. """); } @Override public StreamsEventResponse createResponse(List<String> failures, FunqyAmazonConfig amazonConfig) { if (!amazonConfig.advancedEventHandling().dynamoDb().reportBatchItemFailures()) { return null; } return StreamsEventResponse.builder().withBatchItemFailures( failures.stream().map(id -> StreamsEventResponse.BatchItemFailure.builder() .withItemIdentifier(id).build()).toList()) .build(); } @Override public Class<DynamodbStreamRecord> getMessageClass() { return DynamodbStreamRecord.class; } }
DynamoDbEventHandler
java
apache__dubbo
dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/HttpOutputMessage.java
{ "start": 948, "end": 1380 }
interface ____ extends AutoCloseable { HttpOutputMessage EMPTY_MESSAGE = new HttpOutputMessage() { private final OutputStream INPUT_STREAM = new ByteArrayOutputStream(0); @Override public OutputStream getBody() { return INPUT_STREAM; } }; OutputStream getBody(); @Override default void close() throws IOException { getBody().close(); } }
HttpOutputMessage
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/engine/spi/ExtraStateTest.java
{ "start": 3210, "end": 3691 }
class ____ implements EntityEntryExtraState { private final long value; public TestExtraState(long value) { this.value = value; } public long getValue() { return value; } @Override public void addExtraState(EntityEntryExtraState extraState) { throw new UnsupportedOperationException(); } @Override public <T extends EntityEntryExtraState> T getExtraState(Class<T> extraStateType) { throw new UnsupportedOperationException(); } } }
TestExtraState
java
apache__logging-log4j2
log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/nogc/NoGcLayout.java
{ "start": 1585, "end": 2988 }
class ____ implements Layout<Serializable> { private static final byte[] EMPTY_BYTE_ARRAY = {}; private final StringBuilder cachedStringBuilder = new StringBuilder(2048); private final PatternSerializer2 serializer = new PatternSerializer2(); private final StringBuilderEncoder cachedHelper; public NoGcLayout(final Charset charset) { cachedHelper = new StringBuilderEncoder(charset); } @Override public void encode(final LogEvent event, final ByteBufferDestination destination) { final StringBuilder text = toText(event, getCachedStringBuilder()); final Encoder<StringBuilder> helper = getCachedHelper(); helper.encode(text, destination); } /** * Creates a text representation of the specified log event * and writes it into the specified StringBuilder. * <p> * Implementations are free to return a new StringBuilder if they can * detect in advance that the specified StringBuilder is too small. */ StringBuilder toText(final LogEvent e, final StringBuilder destination) { return serializer.toSerializable(e, destination); } public StringBuilder getCachedStringBuilder() { cachedStringBuilder.setLength(0); return cachedStringBuilder; } public Encoder<StringBuilder> getCachedHelper() { return cachedHelper; } private static
NoGcLayout
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/util/TimePeriodTest.java
{ "start": 2152, "end": 11345 }
class ____ { // This Long is too large to fit into an unsigned int. private static final long TOO_LARGE = Integer.MAX_VALUE * 3L; @Test void validateConstruction() { TimePeriod timePeriod = TimePeriod.of(12, 34, 56); assertSame(timePeriod, TimePeriod.from(timePeriod)); assertComponents(12, 34, 56, timePeriod); assertComponents(14, 3, 0, TimePeriod.from(IsoChronology.INSTANCE.period(1, 2, 3))); assertComponents(36_000, 0, 0, TimePeriod.from(TimeAmount.of(ChronoUnit.MILLENNIA, 3))); assertComponents(3_600, 0, 0, TimePeriod.from(TimeAmount.of(ChronoUnit.CENTURIES, 3))); assertComponents(360, 0, 0, TimePeriod.from(TimeAmount.of(ChronoUnit.DECADES, 3))); assertComponents(36, 0, 0, TimePeriod.from(TimeAmount.of(ChronoUnit.YEARS, 3))); assertComponents(3, 0, 0, TimePeriod.from(TimeAmount.of(MONTHS, 3))); assertComponents(0, 21, 0, TimePeriod.from(TimeAmount.of(ChronoUnit.WEEKS, 3))); assertComponents(0, 3, 0, TimePeriod.from(TimeAmount.of(DAYS, 3))); assertComponents(0, 2, 0, TimePeriod.from(TimeAmount.of(ChronoUnit.HALF_DAYS, 4))); assertComponents(0, 2, 43_200_000, TimePeriod.from(TimeAmount.of(ChronoUnit.HALF_DAYS, 5))); assertComponents(0, 0, 10_800_000, TimePeriod.from(TimeAmount.of(ChronoUnit.HOURS, 3))); assertComponents(0, 0, 180_000, TimePeriod.from(TimeAmount.of(ChronoUnit.MINUTES, 3))); assertComponents(0, 0, 3_000, TimePeriod.from(TimeAmount.of(ChronoUnit.SECONDS, 3))); assertComponents(0, 0, 3, TimePeriod.from(TimeAmount.of(MILLIS, 3))); assertComponents(0, 0, 3, TimePeriod.from(TimeAmount.of(MICROS, 3_000))); assertComponents(0, 0, 3, TimePeriod.from(TimeAmount.of(NANOS, 3_000_000))); // Micros and nanos must be a multiple of milliseconds assertThrows(DateTimeException.class, () -> TimePeriod.from(TimeAmount.of(ChronoUnit.MICROS, 3))); assertThrows(DateTimeException.class, () -> TimePeriod.from(TimeAmount.of(ChronoUnit.NANOS, 3))); // Unsupported cases (null, non-ISO chronology, unknown temporal unit, // non-ChronoUnit) assertThrows(NullPointerException.class, () -> TimePeriod.from(null)); assertThrows(DateTimeException.class, () -> TimePeriod.from(JapaneseChronology.INSTANCE.period(1, 2, 3))); assertThrows(UnsupportedTemporalTypeException.class, () -> TimePeriod.from(TimeAmount.of(ChronoUnit.ERAS, 1))); assertThrows(UnsupportedTemporalTypeException.class, () -> TimePeriod.from(TimeAmount.of(DummyUnit.INSTANCE, 3))); // Arguments are long, but must fit an unsigned long assertThrows(ArithmeticException.class, () -> TimePeriod.of(TOO_LARGE, 0, 0)); assertThrows(ArithmeticException.class, () -> TimePeriod.of(0, TOO_LARGE, 0)); assertThrows(ArithmeticException.class, () -> TimePeriod.of(0, 0, TOO_LARGE)); // Odd one out: querying an unsupported temporal unit // (assertComponents handles all valid cases) assertThrows(UnsupportedTemporalTypeException.class, () -> TimePeriod.of(1, 1, 1).get(ERAS)); } @Test void checkConversionsFromJavaTime() { assertEquals(TimePeriod.of(12, 0, 0), TimePeriod.from(Period.ofYears(1))); assertEquals(TimePeriod.of(2, 0, 0), TimePeriod.from(Period.ofMonths(2))); assertEquals(TimePeriod.of(0, 21, 0), TimePeriod.from(Period.ofWeeks(3))); assertEquals(TimePeriod.of(0, 4, 0), TimePeriod.from(Period.ofDays(4))); assertEquals(TimePeriod.of(0, 0, 1), TimePeriod.from(Duration.ofNanos(1_000_000))); assertEquals(TimePeriod.of(0, 0, 2), TimePeriod.from(Duration.ofMillis(2))); assertEquals(TimePeriod.of(0, 0, 3_000), TimePeriod.from(Duration.ofSeconds(3))); assertEquals(TimePeriod.of(0, 0, 240000), TimePeriod.from(Duration.ofMinutes(4))); assertEquals(TimePeriod.of(0, 0, 18000000), TimePeriod.from(Duration.ofHours(5))); // Duration never takes into account things like daylight saving assertEquals(TimePeriod.of(0, 0, 518400000), TimePeriod.from(Duration.ofDays(6))); } @Test void checkConversionsToJavaTime() { TimePeriod months = TimePeriod.of(1, 0, 0); TimePeriod days = TimePeriod.of(0, 2, 0); TimePeriod time = TimePeriod.of(0, 0, 3); TimePeriod all = TimePeriod.of(1, 2, 3); assertTrue(months.isDateBased()); assertTrue(days.isDateBased()); assertFalse(all.isDateBased()); assertFalse(time.isDateBased()); assertEquals(Period.of(0, 1, 0), months.toPeriod()); assertEquals(Period.of(0, 0, 2), days.toPeriod()); assertThrows(DateTimeException.class, all::toPeriod); assertThrows(DateTimeException.class, time::toPeriod); assertThrows(DateTimeException.class, () -> TimePeriod.of(0, Integer.MAX_VALUE * 2L, 0).toPeriod()); assertFalse(months.isTimeBased()); assertFalse(days.isTimeBased()); assertFalse(all.isTimeBased()); assertTrue(time.isTimeBased()); assertThrows(DateTimeException.class, months::toDuration); // Note: though Duration supports this, it uses a fixed 86400 seconds assertEquals(Duration.ofSeconds(172800), days.toDuration()); assertThrows(DateTimeException.class, all::toDuration); assertEquals(Duration.ofMillis(3), time.toDuration()); } @Test void checkAddingToTemporalItems() { TimePeriod monthAndTwoDays = TimePeriod.of(1, 2, 0); TimePeriod threeMillis = TimePeriod.of(0, 0, 3); TimePeriod complexTimePeriod = TimePeriod.of(1, 2, 3); LocalDateTime localDateTime = LocalDateTime.of(2001, 2, 3, 4, 5, 6, 7_000_000); LocalDate localDate = LocalDate.of(2001, 2, 3); LocalTime localTime = LocalTime.of(4, 5, 6, 7_000_000); assertEquals(localDateTime.plusMonths(1).plusDays(2), localDateTime.plus(monthAndTwoDays)); assertEquals(localDateTime.plus(3, MILLIS), localDateTime.plus(threeMillis)); assertEquals(localDateTime.plusMonths(1).plusDays(2).plus(3, MILLIS), localDateTime.plus(complexTimePeriod)); assertEquals(localDate.plusMonths(1).plusDays(2), localDate.plus(monthAndTwoDays)); assertEquals(localTime.plus(3, MILLIS), localTime.plus(threeMillis)); assertEquals(localDateTime.minusMonths(1).minusDays(2), localDateTime.minus(monthAndTwoDays)); assertEquals(localDateTime.minus(3, MILLIS), localDateTime.minus(threeMillis)); assertEquals(localDateTime.minusMonths(1).minusDays(2).minus(3, MILLIS), localDateTime.minus(complexTimePeriod)); assertEquals(localDate.minusMonths(1).minusDays(2), localDate.minus(monthAndTwoDays)); assertEquals(localTime.minus(3, MILLIS), localTime.minus(threeMillis)); } @Test void checkEqualityTests() { TimePeriod timePeriod1a = TimePeriod.of(1, 2, 3); TimePeriod timePeriod1b = TimePeriod.of(1, 2, 3); TimePeriod timePeriod2 = TimePeriod.of(9, 9, 9); TimePeriod timePeriod3 = TimePeriod.of(1, 9, 9); TimePeriod timePeriod4 = TimePeriod.of(1, 2, 9); // noinspection EqualsWithItself assertEquals(timePeriod1a, timePeriod1a); assertEquals(timePeriod1a, timePeriod1b); assertEquals(timePeriod1a.hashCode(), timePeriod1b.hashCode()); assertNotEquals(timePeriod1a, null); // noinspection AssertBetweenInconvertibleTypes assertNotEquals(timePeriod1a, "not equal"); assertNotEquals(timePeriod1a, timePeriod2); assertNotEquals(timePeriod1a.hashCode(), timePeriod2.hashCode()); assertNotEquals(timePeriod1a, timePeriod3); assertNotEquals(timePeriod1a.hashCode(), timePeriod3.hashCode()); assertNotEquals(timePeriod1a, timePeriod4); assertNotEquals(timePeriod1a.hashCode(), timePeriod4.hashCode()); } @Test void checkStringRepresentation() { assertEquals("P0", TimePeriod.of(0, 0, 0).toString()); assertEquals("P1Y", TimePeriod.of(12, 0, 0).toString()); assertEquals("P2M", TimePeriod.of(2, 0, 0).toString()); assertEquals("P3", TimePeriod.of(0, 3, 0).toString()); assertEquals("P1Y2M3", TimePeriod.of(14, 3, 0).toString()); assertEquals("PT04", TimePeriod.of(0, 0, 14400000).toString()); assertEquals("PT00:05", TimePeriod.of(0, 0, 300000).toString()); assertEquals("PT00:00:06", TimePeriod.of(0, 0, 6000).toString()); assertEquals("PT00:00:00.007", TimePeriod.of(0, 0, 7).toString()); assertEquals("P1Y2M3T04:05:06.007", TimePeriod.of(14, 3, 14706007).toString()); // Days and millis will never overflow to months/days, to respect differences // in months and days (daylight saving). assertEquals("P123T1193:02:47.295", TimePeriod.of(0, 123, 4294967295L).toString()); } private void assertComponents(long months, long days, long millis, TimePeriod timePeriod) { List<TemporalUnit> expectedUnits = new ArrayList<>(Arrays.asList(MONTHS, DAYS, MILLIS)); if (months == 0) { expectedUnits.remove(MONTHS); } if (days == 0) { expectedUnits.remove(DAYS); } if (millis == 0) { expectedUnits.remove(MILLIS); } assertEquals(expectedUnits, timePeriod.getUnits()); assertEquals(months, timePeriod.getMonths()); assertEquals(months, timePeriod.get(MONTHS)); assertEquals(days, timePeriod.getDays()); assertEquals(days, timePeriod.get(DAYS)); assertEquals(millis, timePeriod.getMillis()); assertEquals(millis, timePeriod.get(MILLIS)); } private static
TimePeriodTest
java
apache__flink
flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/input/WindowReaderTest.java
{ "start": 12831, "end": 13677 }
class ____ extends ProcessWindowFunction<Integer, Integer, Integer, TimeWindow> { @Override public void process( Integer integer, Context context, Iterable<Integer> elements, Collector<Integer> out) throws Exception { Integer element = elements.iterator().next(); context.globalState() .getReducingState( new ReducingStateDescriptor<>("per-key", new ReduceSum(), Types.INT)) .add(element); context.windowState() .getReducingState( new ReducingStateDescriptor<>("per-pane", new ReduceSum(), Types.INT)) .add(element); } } private static
MultiFireWindow
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/PromqlBaseParserVisitor.java
{ "start": 628, "end": 7366 }
interface ____<T> extends ParseTreeVisitor<T> { /** * Visit a parse tree produced by {@link PromqlBaseParser#singleStatement}. * @param ctx the parse tree * @return the visitor result */ T visitSingleStatement(PromqlBaseParser.SingleStatementContext ctx); /** * Visit a parse tree produced by the {@code valueExpression} * labeled alternative in {@link PromqlBaseParser#expression}. * @param ctx the parse tree * @return the visitor result */ T visitValueExpression(PromqlBaseParser.ValueExpressionContext ctx); /** * Visit a parse tree produced by the {@code subquery} * labeled alternative in {@link PromqlBaseParser#expression}. * @param ctx the parse tree * @return the visitor result */ T visitSubquery(PromqlBaseParser.SubqueryContext ctx); /** * Visit a parse tree produced by the {@code parenthesized} * labeled alternative in {@link PromqlBaseParser#expression}. * @param ctx the parse tree * @return the visitor result */ T visitParenthesized(PromqlBaseParser.ParenthesizedContext ctx); /** * Visit a parse tree produced by the {@code arithmeticBinary} * labeled alternative in {@link PromqlBaseParser#expression}. * @param ctx the parse tree * @return the visitor result */ T visitArithmeticBinary(PromqlBaseParser.ArithmeticBinaryContext ctx); /** * Visit a parse tree produced by the {@code arithmeticUnary} * labeled alternative in {@link PromqlBaseParser#expression}. * @param ctx the parse tree * @return the visitor result */ T visitArithmeticUnary(PromqlBaseParser.ArithmeticUnaryContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#subqueryResolution}. * @param ctx the parse tree * @return the visitor result */ T visitSubqueryResolution(PromqlBaseParser.SubqueryResolutionContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#value}. * @param ctx the parse tree * @return the visitor result */ T visitValue(PromqlBaseParser.ValueContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#function}. * @param ctx the parse tree * @return the visitor result */ T visitFunction(PromqlBaseParser.FunctionContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#functionParams}. * @param ctx the parse tree * @return the visitor result */ T visitFunctionParams(PromqlBaseParser.FunctionParamsContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#grouping}. * @param ctx the parse tree * @return the visitor result */ T visitGrouping(PromqlBaseParser.GroupingContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#selector}. * @param ctx the parse tree * @return the visitor result */ T visitSelector(PromqlBaseParser.SelectorContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#seriesMatcher}. * @param ctx the parse tree * @return the visitor result */ T visitSeriesMatcher(PromqlBaseParser.SeriesMatcherContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#modifier}. * @param ctx the parse tree * @return the visitor result */ T visitModifier(PromqlBaseParser.ModifierContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#labelList}. * @param ctx the parse tree * @return the visitor result */ T visitLabelList(PromqlBaseParser.LabelListContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#labels}. * @param ctx the parse tree * @return the visitor result */ T visitLabels(PromqlBaseParser.LabelsContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#label}. * @param ctx the parse tree * @return the visitor result */ T visitLabel(PromqlBaseParser.LabelContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#labelName}. * @param ctx the parse tree * @return the visitor result */ T visitLabelName(PromqlBaseParser.LabelNameContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#identifier}. * @param ctx the parse tree * @return the visitor result */ T visitIdentifier(PromqlBaseParser.IdentifierContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#evaluation}. * @param ctx the parse tree * @return the visitor result */ T visitEvaluation(PromqlBaseParser.EvaluationContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#offset}. * @param ctx the parse tree * @return the visitor result */ T visitOffset(PromqlBaseParser.OffsetContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#duration}. * @param ctx the parse tree * @return the visitor result */ T visitDuration(PromqlBaseParser.DurationContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#at}. * @param ctx the parse tree * @return the visitor result */ T visitAt(PromqlBaseParser.AtContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#constant}. * @param ctx the parse tree * @return the visitor result */ T visitConstant(PromqlBaseParser.ConstantContext ctx); /** * Visit a parse tree produced by the {@code decimalLiteral} * labeled alternative in {@link PromqlBaseParser#number}. * @param ctx the parse tree * @return the visitor result */ T visitDecimalLiteral(PromqlBaseParser.DecimalLiteralContext ctx); /** * Visit a parse tree produced by the {@code integerLiteral} * labeled alternative in {@link PromqlBaseParser#number}. * @param ctx the parse tree * @return the visitor result */ T visitIntegerLiteral(PromqlBaseParser.IntegerLiteralContext ctx); /** * Visit a parse tree produced by the {@code hexLiteral} * labeled alternative in {@link PromqlBaseParser#number}. * @param ctx the parse tree * @return the visitor result */ T visitHexLiteral(PromqlBaseParser.HexLiteralContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#string}. * @param ctx the parse tree * @return the visitor result */ T visitString(PromqlBaseParser.StringContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#timeValue}. * @param ctx the parse tree * @return the visitor result */ T visitTimeValue(PromqlBaseParser.TimeValueContext ctx); /** * Visit a parse tree produced by {@link PromqlBaseParser#nonReserved}. * @param ctx the parse tree * @return the visitor result */ T visitNonReserved(PromqlBaseParser.NonReservedContext ctx); }
PromqlBaseParserVisitor
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ClasComponentBuilderFactory.java
{ "start": 1233, "end": 1383 }
class ____. * * Generated by camel build tools - do NOT edit this file! */ @Generated("org.apache.camel.maven.packaging.ComponentDslMojo") public
name
java
quarkusio__quarkus
test-framework/junit5-component/src/test/java/io/quarkus/test/component/callbacks/QuarkusComponentTestCallbacksTest.java
{ "start": 859, "end": 1938 }
class ____ { @Inject MyComponent myComponent; @InjectMock Charlie charlie; @Order(1) @TestConfigProperty(key = "foo", value = "BAR") // overriden by listener @Test public void testPing() { // Note that we cannot test the build functionality of MyTestCallbacks directly (e.g. static fields) // because a different CL is used for build Mockito.when(charlie.ping()).thenReturn("foo"); assertEquals("foo and RAB", myComponent.ping()); // MyOtherComponent added by listener as component class // @Unremovable added to MyOtherComponent by listener assertEquals("foo", Arc.container().instance(MyOtherComponent.class).get().ping()); // This should be ok because afterStart is executed on an instance loaded by the QuarkusComponentTestClassLoader assertTrue(MyTestCallbacks.afterStart); assertFalse(MyTestCallbacks.afterStop); } @Order(2) @Test public void testPong() { assertTrue(MyTestCallbacks.afterStop); } }
QuarkusComponentTestCallbacksTest
java
grpc__grpc-java
xds/src/generated/thirdparty/grpc/com/github/xds/service/orca/v3/OpenRcaServiceGrpc.java
{ "start": 777, "end": 6251 }
class ____ { private OpenRcaServiceGrpc() {} public static final java.lang.String SERVICE_NAME = "xds.service.orca.v3.OpenRcaService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor<com.github.xds.service.orca.v3.OrcaLoadReportRequest, com.github.xds.data.orca.v3.OrcaLoadReport> getStreamCoreMetricsMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "StreamCoreMetrics", requestType = com.github.xds.service.orca.v3.OrcaLoadReportRequest.class, responseType = com.github.xds.data.orca.v3.OrcaLoadReport.class, methodType = io.grpc.MethodDescriptor.MethodType.SERVER_STREAMING) public static io.grpc.MethodDescriptor<com.github.xds.service.orca.v3.OrcaLoadReportRequest, com.github.xds.data.orca.v3.OrcaLoadReport> getStreamCoreMetricsMethod() { io.grpc.MethodDescriptor<com.github.xds.service.orca.v3.OrcaLoadReportRequest, com.github.xds.data.orca.v3.OrcaLoadReport> getStreamCoreMetricsMethod; if ((getStreamCoreMetricsMethod = OpenRcaServiceGrpc.getStreamCoreMetricsMethod) == null) { synchronized (OpenRcaServiceGrpc.class) { if ((getStreamCoreMetricsMethod = OpenRcaServiceGrpc.getStreamCoreMetricsMethod) == null) { OpenRcaServiceGrpc.getStreamCoreMetricsMethod = getStreamCoreMetricsMethod = io.grpc.MethodDescriptor.<com.github.xds.service.orca.v3.OrcaLoadReportRequest, com.github.xds.data.orca.v3.OrcaLoadReport>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.SERVER_STREAMING) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "StreamCoreMetrics")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.github.xds.service.orca.v3.OrcaLoadReportRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.github.xds.data.orca.v3.OrcaLoadReport.getDefaultInstance())) .setSchemaDescriptor(new OpenRcaServiceMethodDescriptorSupplier("StreamCoreMetrics")) .build(); } } } return getStreamCoreMetricsMethod; } /** * Creates a new async stub that supports all call types for the service */ public static OpenRcaServiceStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<OpenRcaServiceStub> factory = new io.grpc.stub.AbstractStub.StubFactory<OpenRcaServiceStub>() { @java.lang.Override public OpenRcaServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new OpenRcaServiceStub(channel, callOptions); } }; return OpenRcaServiceStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports all types of calls on the service */ public static OpenRcaServiceBlockingV2Stub newBlockingV2Stub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<OpenRcaServiceBlockingV2Stub> factory = new io.grpc.stub.AbstractStub.StubFactory<OpenRcaServiceBlockingV2Stub>() { @java.lang.Override public OpenRcaServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new OpenRcaServiceBlockingV2Stub(channel, callOptions); } }; return OpenRcaServiceBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static OpenRcaServiceBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<OpenRcaServiceBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<OpenRcaServiceBlockingStub>() { @java.lang.Override public OpenRcaServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new OpenRcaServiceBlockingStub(channel, callOptions); } }; return OpenRcaServiceBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static OpenRcaServiceFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<OpenRcaServiceFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<OpenRcaServiceFutureStub>() { @java.lang.Override public OpenRcaServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new OpenRcaServiceFutureStub(channel, callOptions); } }; return OpenRcaServiceFutureStub.newStub(factory, channel); } /** * <pre> * Out-of-band (OOB) load reporting service for the additional load reporting * agent that does not sit in the request path. Reports are periodically sampled * with sufficient frequency to provide temporal association with requests. * OOB reporting compensates the limitation of in-band reporting in revealing * costs for backends that do not provide a steady stream of telemetry such as * long running stream operations and zero QPS services. This is a server * streaming service, client needs to terminate current RPC and initiate * a new call to change backend reporting frequency. * </pre> */ public
OpenRcaServiceGrpc
java
apache__hadoop
hadoop-tools/hadoop-resourceestimator/src/main/java/org/apache/hadoop/resourceestimator/skylinestore/exceptions/SkylineStoreException.java
{ "start": 1042, "end": 1241 }
class ____ extends Exception { private static final long serialVersionUID = -684069387367879218L; public SkylineStoreException(final String message) { super(message); } }
SkylineStoreException
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/index/AdditionalIndexTest.java
{ "start": 1251, "end": 1417 }
class ____ { @Produces <T extends SuperClazz> List<T> produce() { return new ArrayList<>(); } } public static
SuperProducer
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/bom/bomr/ReleaseSchedule.java
{ "start": 2697, "end": 3178 }
class ____ { private final String libraryName; private final DependencyVersion version; private final LocalDate dueOn; Release(String libraryName, DependencyVersion version, LocalDate dueOn) { this.libraryName = libraryName; this.version = version; this.dueOn = dueOn; } String getLibraryName() { return this.libraryName; } DependencyVersion getVersion() { return this.version; } LocalDate getDueOn() { return this.dueOn; } } }
Release
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/validation/AssistedValidator.java
{ "start": 1908, "end": 5062 }
class ____ implements ClearableCache { private final InjectionAnnotations injectionAnnotations; private final Map<XExecutableParameterElement, ValidationReport> cache = new HashMap<>(); @Inject AssistedValidator(InjectionAnnotations injectionAnnotations) { this.injectionAnnotations = injectionAnnotations; } @Override public void clearCache() { cache.clear(); } public boolean containsCache(XExecutableParameterElement assisted) { return cache.containsKey(assisted); } public ValidationReport validate(XExecutableParameterElement assisted) { checkArgument(assisted.hasAnnotation(XTypeNames.ASSISTED)); return cache.computeIfAbsent(assisted, this::validateUncached); } private ValidationReport validateUncached(XExecutableParameterElement assisted) { ValidationReport.Builder report = ValidationReport.about(assisted); XExecutableElement enclosingElement = assisted.getEnclosingElement(); if (!isAssistedInjectConstructor(enclosingElement) && !isAssistedFactoryCreateMethod(enclosingElement) // The generated java stubs for kotlin data classes contain a "copy" method that has // the same parameters (and annotations) as the constructor, so just ignore it. && !isKotlinDataClassCopyMethod(enclosingElement)) { report.addError( "@Assisted parameters can only be used within an @AssistedInject-annotated " + "constructor.", assisted); } injectionAnnotations .getQualifiers(assisted) .forEach( qualifier -> report.addError( "Qualifiers cannot be used with @Assisted parameters.", assisted, qualifier)); return report.build(); } private boolean isAssistedInjectConstructor(XExecutableElement executableElement) { return isConstructor(executableElement) && executableElement.hasAnnotation(XTypeNames.ASSISTED_INJECT); } private boolean isAssistedFactoryCreateMethod(XExecutableElement executableElement) { if (isMethod(executableElement)) { XTypeElement enclosingElement = closestEnclosingTypeElement(executableElement); return isAssistedFactoryType(enclosingElement) // This assumes we've already validated AssistedFactory and that a valid method exists. && assistedFactoryMethod(enclosingElement).equals(executableElement); } return false; } private boolean isKotlinDataClassCopyMethod(XExecutableElement executableElement) { // Note: This is a best effort. Technically, we could check the return type and parameters of // the copy method to verify it's the one associated with the constructor, but I'd rather keep // this simple to avoid encoding too many details of kapt's stubs. At worst, we'll be allowing // an @Assisted annotation that has no affect, which is already true for many of Dagger's other // annotations. return isMethod(executableElement) && getSimpleName(asMethod(executableElement)).contentEquals("copy") && closestEnclosingTypeElement(executableElement.getEnclosingElement()).isDataClass(); } }
AssistedValidator
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/info/BuildParameterExtension.java
{ "start": 867, "end": 1913 }
interface ____ { String EXTENSION_NAME = "buildParams"; boolean getInFipsJvm(); Provider<File> getRuntimeJavaHome(); void withFipsEnabledOnly(Task task); Boolean getIsRuntimeJavaHomeSet(); RuntimeJava getRuntimeJava(); List<JavaHome> getJavaVersions(); JavaVersion getMinimumCompilerVersion(); JavaVersion getMinimumRuntimeVersion(); JavaVersion getGradleJavaVersion(); Provider<JavaVersion> getRuntimeJavaVersion(); Provider<? extends Action<JavaToolchainSpec>> getJavaToolChainSpec(); Provider<String> getRuntimeJavaDetails(); Provider<String> getGitRevision(); Provider<String> getGitOrigin(); ZonedDateTime getBuildDate(); String getTestSeed(); Provider<String> getTestSeedProvider(); Boolean getCi(); Integer getDefaultParallel(); Boolean getSnapshotBuild(); BwcVersions getBwcVersions(); Provider<BwcVersions> getBwcVersionsProvider(); Provider<Random> getRandom(); Boolean getGraalVmRuntime(); }
BuildParameterExtension
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/windowing/triggers/AsyncEventTimeTrigger.java
{ "start": 1422, "end": 4002 }
class ____ extends AsyncTrigger<Object, TimeWindow> { private static final long serialVersionUID = 1L; private AsyncEventTimeTrigger() {} @Override public StateFuture<TriggerResult> onElement( Object element, long timestamp, TimeWindow window, TriggerContext ctx) throws Exception { if (window.maxTimestamp() <= ctx.getCurrentWatermark()) { // if the watermark is already past the window fire immediately return StateFutureUtils.completedFuture(TriggerResult.FIRE); } else { ctx.registerEventTimeTimer(window.maxTimestamp()); return StateFutureUtils.completedFuture(TriggerResult.CONTINUE); } } @Override public StateFuture<TriggerResult> onEventTime( long time, TimeWindow window, TriggerContext ctx) { return StateFutureUtils.completedFuture( time == window.maxTimestamp() ? TriggerResult.FIRE : TriggerResult.CONTINUE); } @Override public StateFuture<TriggerResult> onProcessingTime( long time, TimeWindow window, TriggerContext ctx) throws Exception { return StateFutureUtils.completedFuture(TriggerResult.CONTINUE); } @Override public StateFuture<Void> clear(TimeWindow window, TriggerContext ctx) throws Exception { ctx.deleteEventTimeTimer(window.maxTimestamp()); return StateFutureUtils.completedVoidFuture(); } @Override public boolean canMerge() { return true; } @Override public void onMerge(TimeWindow window, OnMergeContext ctx) { // only register a timer if the watermark is not yet past the end of the merged window // this is in line with the logic in onElement(). If the watermark is past the end of // the window onElement() will fire and setting a timer here would fire the window twice. long windowMaxTimestamp = window.maxTimestamp(); if (windowMaxTimestamp > ctx.getCurrentWatermark()) { ctx.registerEventTimeTimer(windowMaxTimestamp); } } @Override public String toString() { return "AsyncEventTimeTrigger()"; } /** * Creates an event-time trigger that fires once the watermark passes the end of the window. * * <p>Once the trigger fires all elements are discarded. Elements that arrive late immediately * trigger window evaluation with just this one element. */ public static AsyncEventTimeTrigger create() { return new AsyncEventTimeTrigger(); } }
AsyncEventTimeTrigger