language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
alibaba__druid
core/src/test/java/com/alibaba/druid/demo/sql/PGVisitorDemo.java
{ "start": 468, "end": 1008 }
class ____ extends TestCase { public void test_for_demo() throws Exception { String sql = "select * from mytable a where a.id = 3"; List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, DbType.postgresql); ExportTableAliasVisitor visitor = new ExportTableAliasVisitor(); for (SQLStatement stmt : stmtList) { stmt.accept(visitor); } SQLTableSource tableSource = visitor.getAliasMap().get("a"); System.out.println(tableSource); } public static
PGVisitorDemo
java
quarkusio__quarkus
independent-projects/tools/registry-client/src/test/java/io/quarkus/registry/catalog/ExtensionTest.java
{ "start": 270, "end": 940 }
class ____ { static Path baseDir = Paths.get(System.getProperty("user.dir")).toAbsolutePath() .resolve("src/test/resources/extension"); @Test void deserializeYamlFile() throws Exception { final Path extYaml = baseDir.resolve("quarkus-extension.yaml"); assertThat(extYaml).exists(); final Extension e = Extension.fromFile(extYaml); assertThat(e.getArtifact()).isEqualTo(ArtifactCoords.jar("io.quarkus", "quarkus-resteasy-reactive", "999-PLACEHOLDER")); final Map<String, Object> metadata = e.getMetadata(); assertThat(metadata.get("short-name")).isEqualTo("resteasy-reactive"); } }
ExtensionTest
java
google__guice
extensions/dagger-adapter/test/com/google/inject/daggeradapter/BindsTest.java
{ "start": 2804, "end": 3784 }
interface ____ { @Binds @IntoSet @jakarta.inject.Singleton Object fromString(String string); @Binds CharSequence toCharSequence(String string); @Binds @IntoSet @jakarta.inject.Singleton Object fromCharSequence(CharSequence charSequence); } public void testJakartaScopedMultibindings() { Injector injector = Guice.createInjector( DaggerAdapter.from( new CountingMultibindingProviderModule(), JakartaScopedMultibindingBindsModule.class)); Binding<Set<Object>> binding = injector.getBinding(new Key<Set<Object>>() {}); assertThat(binding) .hasProvidedValueThat() .isEqualTo(ImmutableSet.of("multibound-1", "multibound-2")); assertThat(binding) .hasProvidedValueThat() .isEqualTo(ImmutableSet.of("multibound-1", "multibound-2")); } @Retention(RetentionPolicy.RUNTIME) @jakarta.inject.Qualifier @
JakartaScopedMultibindingBindsModule
java
elastic__elasticsearch
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpProcessor.java
{ "start": 1611, "end": 7282 }
class ____ extends AbstractProcessor { private static final DeprecationLogger deprecationLogger = DeprecationLogger.getLogger(GeoIpProcessor.class); static final String UNSUPPORTED_DATABASE_DEPRECATION_MESSAGE = "the geoip processor will no longer support database type [{}] " + "in a future version of Elasticsearch"; // TODO add a message about migration? public static final String GEOIP_TYPE = "geoip"; public static final String IP_LOCATION_TYPE = "ip_location"; private final String type; private final String field; private final Supplier<Boolean> isValid; private final String targetField; private final CheckedSupplier<IpDatabase, IOException> supplier; private final IpDataLookup ipDataLookup; private final boolean ignoreMissing; private final boolean firstOnly; private final String databaseFile; /** * Construct a geo-IP processor. * @param tag the processor tag * @param description the processor description * @param field the source field to geo-IP map * @param supplier a supplier of a geo-IP database reader; ideally this is lazily-loaded once on first use * @param isValid a supplier that determines if the available database files are up-to-date and license compliant * @param targetField the target field * @param ipDataLookup a lookup capable of retrieving a result from an available geo-IP database reader * @param ignoreMissing true if documents with a missing value for the field should be ignored * @param firstOnly true if only first result should be returned in case of array * @param databaseFile the name of the database file being queried; used only for tagging documents if the database is unavailable */ GeoIpProcessor( final String type, final String tag, final String description, final String field, final CheckedSupplier<IpDatabase, IOException> supplier, final Supplier<Boolean> isValid, final String targetField, final IpDataLookup ipDataLookup, final boolean ignoreMissing, final boolean firstOnly, final String databaseFile ) { super(tag, description); this.type = type; this.field = field; this.isValid = isValid; this.targetField = targetField; this.supplier = supplier; this.ipDataLookup = ipDataLookup; this.ignoreMissing = ignoreMissing; this.firstOnly = firstOnly; this.databaseFile = databaseFile; } boolean isIgnoreMissing() { return ignoreMissing; } @Override public IngestDocument execute(IngestDocument document) throws IOException { Object ip = document.getFieldValue(field, Object.class, ignoreMissing); if (isValid.get() == false) { document.appendFieldValue("tags", "_" + type + "_expired_database", false); return document; } else if (ip == null && ignoreMissing) { return document; } else if (ip == null) { throw new IllegalArgumentException("field [" + field + "] is null, cannot extract geoip information."); } try (IpDatabase ipDatabase = this.supplier.get()) { if (ipDatabase == null) { if (ignoreMissing == false) { tag(document, type, databaseFile); } return document; } if (ip instanceof String ipString) { Map<String, Object> data = ipDataLookup.getData(ipDatabase, ipString); if (data.isEmpty() == false) { document.setFieldValue(targetField, data); } } else if (ip instanceof List<?> ipList) { boolean match = false; List<Map<String, Object>> dataList = new ArrayList<>(ipList.size()); for (Object ipAddr : ipList) { if (ipAddr instanceof String == false) { throw new IllegalArgumentException("array in field [" + field + "] should only contain strings"); } Map<String, Object> data = ipDataLookup.getData(ipDatabase, (String) ipAddr); if (data.isEmpty()) { dataList.add(null); continue; } if (firstOnly) { document.setFieldValue(targetField, data); return document; } match = true; dataList.add(data); } if (match) { document.setFieldValue(targetField, dataList); } } else { throw new IllegalArgumentException("field [" + field + "] should contain only string or array of strings"); } } return document; } @Override public String getType() { return type; } String getField() { return field; } String getTargetField() { return targetField; } String getDatabaseType() throws IOException { return supplier.get().getDatabaseType(); } Set<Property> getProperties() { return ipDataLookup.getProperties(); } /** * Retrieves and verifies a {@link IpDatabase} instance for each execution of the {@link GeoIpProcessor}. Guards against missing * custom databases, and ensures that database instances are of the proper type before use. */ public static final
GeoIpProcessor
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/join/IncomparableKey.java
{ "start": 957, "end": 1193 }
class ____ implements WritableComparable { public void write(DataOutput out) { } public void readFields(DataInput in) { } public int compareTo(Object o) { throw new RuntimeException("Should never see this."); } }
IncomparableKey
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableDefaultIfEmptyTest.java
{ "start": 872, "end": 1912 }
class ____ extends RxJavaTest { @Test public void defaultIfEmpty() { Observable<Integer> source = Observable.just(1, 2, 3); Observable<Integer> observable = source.defaultIfEmpty(10); Observer<Integer> observer = TestHelper.mockObserver(); observable.subscribe(observer); verify(observer, never()).onNext(10); verify(observer).onNext(1); verify(observer).onNext(2); verify(observer).onNext(3); verify(observer).onComplete(); verify(observer, never()).onError(any(Throwable.class)); } @Test public void defaultIfEmptyWithEmpty() { Observable<Integer> source = Observable.empty(); Observable<Integer> observable = source.defaultIfEmpty(10); Observer<Integer> observer = TestHelper.mockObserver(); observable.subscribe(observer); verify(observer).onNext(10); verify(observer).onComplete(); verify(observer, never()).onError(any(Throwable.class)); } }
ObservableDefaultIfEmptyTest
java
apache__dubbo
dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/h2/NettyH2StreamChannel.java
{ "start": 1638, "end": 3867 }
class ____ implements H2StreamChannel { private final Http2StreamChannel http2StreamChannel; private final TripleConfig tripleConfig; public NettyH2StreamChannel(Http2StreamChannel http2StreamChannel, TripleConfig tripleConfig) { this.http2StreamChannel = http2StreamChannel; this.tripleConfig = tripleConfig; } @Override public CompletableFuture<Void> writeHeader(HttpMetadata httpMetadata) { // WriteQueue.enqueue header frame NettyHttpChannelFutureListener nettyHttpChannelFutureListener = new NettyHttpChannelFutureListener(); http2StreamChannel.write(httpMetadata).addListener(nettyHttpChannelFutureListener); return nettyHttpChannelFutureListener; } @Override public CompletableFuture<Void> writeMessage(HttpOutputMessage httpOutputMessage) { NettyHttpChannelFutureListener nettyHttpChannelFutureListener = new NettyHttpChannelFutureListener(); http2StreamChannel.write(httpOutputMessage).addListener(nettyHttpChannelFutureListener); return nettyHttpChannelFutureListener; } @Override public Http2OutputMessage newOutputMessage(boolean endStream) { ByteBuf buffer = http2StreamChannel.alloc().buffer(); ByteBufOutputStream outputStream = new LimitedByteBufOutputStream(buffer, tripleConfig.getMaxResponseBodySizeOrDefault()); return new Http2OutputMessageFrame(outputStream, endStream); } @Override public SocketAddress remoteAddress() { return this.http2StreamChannel.remoteAddress(); } @Override public SocketAddress localAddress() { return this.http2StreamChannel.localAddress(); } @Override public void flush() { this.http2StreamChannel.flush(); } @Override public CompletableFuture<Void> writeResetFrame(long errorCode) { DefaultHttp2ResetFrame resetFrame = new DefaultHttp2ResetFrame(errorCode); NettyHttpChannelFutureListener nettyHttpChannelFutureListener = new NettyHttpChannelFutureListener(); http2StreamChannel.write(resetFrame).addListener(nettyHttpChannelFutureListener); return nettyHttpChannelFutureListener; } }
NettyH2StreamChannel
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/web/OAuth2AuthorizationServerMetadataEndpointFilter.java
{ "start": 2663, "end": 8142 }
class ____ extends OncePerRequestFilter { /** * The default endpoint {@code URI} for OAuth 2.0 Authorization Server Metadata * requests. */ private static final String DEFAULT_OAUTH2_AUTHORIZATION_SERVER_METADATA_ENDPOINT_URI = "/.well-known/oauth-authorization-server"; private final RequestMatcher requestMatcher = createRequestMatcher(); private final OAuth2AuthorizationServerMetadataHttpMessageConverter authorizationServerMetadataHttpMessageConverter = new OAuth2AuthorizationServerMetadataHttpMessageConverter(); private Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer = ( authorizationServerMetadata) -> { }; /** * Sets the {@code Consumer} providing access to the * {@link OAuth2AuthorizationServerMetadata.Builder} allowing the ability to customize * the claims of the Authorization Server's configuration. * @param authorizationServerMetadataCustomizer the {@code Consumer} providing access * to the {@link OAuth2AuthorizationServerMetadata.Builder} */ public void setAuthorizationServerMetadataCustomizer( Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer) { Assert.notNull(authorizationServerMetadataCustomizer, "authorizationServerMetadataCustomizer cannot be null"); this.authorizationServerMetadataCustomizer = authorizationServerMetadataCustomizer; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!this.requestMatcher.matches(request)) { filterChain.doFilter(request, response); return; } AuthorizationServerContext authorizationServerContext = AuthorizationServerContextHolder.getContext(); String issuer = authorizationServerContext.getIssuer(); AuthorizationServerSettings authorizationServerSettings = authorizationServerContext .getAuthorizationServerSettings(); OAuth2AuthorizationServerMetadata.Builder authorizationServerMetadata = OAuth2AuthorizationServerMetadata .builder() .issuer(issuer) .authorizationEndpoint(asUrl(issuer, authorizationServerSettings.getAuthorizationEndpoint())) .tokenEndpoint(asUrl(issuer, authorizationServerSettings.getTokenEndpoint())) .tokenEndpointAuthenticationMethods(clientAuthenticationMethods()) .jwkSetUrl(asUrl(issuer, authorizationServerSettings.getJwkSetEndpoint())) .responseType(OAuth2AuthorizationResponseType.CODE.getValue()) .grantType(AuthorizationGrantType.AUTHORIZATION_CODE.getValue()) .grantType(AuthorizationGrantType.CLIENT_CREDENTIALS.getValue()) .grantType(AuthorizationGrantType.REFRESH_TOKEN.getValue()) .grantType(AuthorizationGrantType.TOKEN_EXCHANGE.getValue()) .tokenRevocationEndpoint(asUrl(issuer, authorizationServerSettings.getTokenRevocationEndpoint())) .tokenRevocationEndpointAuthenticationMethods(clientAuthenticationMethods()) .tokenIntrospectionEndpoint(asUrl(issuer, authorizationServerSettings.getTokenIntrospectionEndpoint())) .tokenIntrospectionEndpointAuthenticationMethods(clientAuthenticationMethods()) .codeChallengeMethod("S256") .tlsClientCertificateBoundAccessTokens(true) .dPoPSigningAlgorithms(dPoPSigningAlgorithms()); this.authorizationServerMetadataCustomizer.accept(authorizationServerMetadata); ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response); this.authorizationServerMetadataHttpMessageConverter.write(authorizationServerMetadata.build(), MediaType.APPLICATION_JSON, httpResponse); } private static RequestMatcher createRequestMatcher() { final RequestMatcher defaultRequestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.GET, DEFAULT_OAUTH2_AUTHORIZATION_SERVER_METADATA_ENDPOINT_URI); final RequestMatcher multipleIssuersRequestMatcher = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.GET, DEFAULT_OAUTH2_AUTHORIZATION_SERVER_METADATA_ENDPOINT_URI + "/**"); return (request) -> AuthorizationServerContextHolder.getContext() .getAuthorizationServerSettings() .isMultipleIssuersAllowed() ? multipleIssuersRequestMatcher.matches(request) : defaultRequestMatcher.matches(request); } private static Consumer<List<String>> clientAuthenticationMethods() { return (authenticationMethods) -> { authenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue()); authenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_POST.getValue()); authenticationMethods.add(ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue()); authenticationMethods.add(ClientAuthenticationMethod.PRIVATE_KEY_JWT.getValue()); authenticationMethods.add(ClientAuthenticationMethod.TLS_CLIENT_AUTH.getValue()); authenticationMethods.add(ClientAuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH.getValue()); }; } private static Consumer<List<String>> dPoPSigningAlgorithms() { return (algs) -> { algs.add(JwsAlgorithms.RS256); algs.add(JwsAlgorithms.RS384); algs.add(JwsAlgorithms.RS512); algs.add(JwsAlgorithms.PS256); algs.add(JwsAlgorithms.PS384); algs.add(JwsAlgorithms.PS512); algs.add(JwsAlgorithms.ES256); algs.add(JwsAlgorithms.ES384); algs.add(JwsAlgorithms.ES512); }; } private static String asUrl(String issuer, String endpoint) { return UriComponentsBuilder.fromUriString(issuer).path(endpoint).toUriString(); } }
OAuth2AuthorizationServerMetadataEndpointFilter
java
spring-projects__spring-boot
module/spring-boot-jdbc-test/src/dockerTest/java/org/springframework/boot/jdbc/test/autoconfigure/AutoConfigureTestDatabaseNonTestDatabaseIntegrationTests.java
{ "start": 2237, "end": 2643 }
class ____ { @Container static PostgreSQLContainer postgres = TestImage.container(PostgreSQLContainer.class); @Autowired private DataSource dataSource; @Test void dataSourceIsReplaced() { assertThat(this.dataSource).isInstanceOf(EmbeddedDatabase.class); } @Configuration @ImportAutoConfiguration(DataSourceAutoConfiguration.class) static
AutoConfigureTestDatabaseNonTestDatabaseIntegrationTests
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalAvailableTcpPortProviderPlugin.java
{ "start": 1180, "end": 1436 }
class ____ implements Plugin<Project> { AvailablePortAllocator allocator; @Override public void apply(Project project) { allocator = new AvailablePortAllocator(); } } }
InternalAvailableTcpPortProviderRootPlugin
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/vectors/es818/OffHeapBinarizedVectorValues.java
{ "start": 1706, "end": 6719 }
class ____ extends BinarizedByteVectorValues { final int dimension; final int size; final int numBytes; final VectorSimilarityFunction similarityFunction; final FlatVectorsScorer vectorsScorer; final IndexInput slice; final byte[] binaryValue; final ByteBuffer byteBuffer; final int byteSize; private int lastOrd = -1; final float[] correctiveValues; int quantizedComponentSum; final OptimizedScalarQuantizer binaryQuantizer; final float[] centroid; final float centroidDp; private final int discretizedDimensions; OffHeapBinarizedVectorValues( int dimension, int size, float[] centroid, float centroidDp, OptimizedScalarQuantizer quantizer, VectorSimilarityFunction similarityFunction, FlatVectorsScorer vectorsScorer, IndexInput slice ) { this.dimension = dimension; this.size = size; this.similarityFunction = similarityFunction; this.vectorsScorer = vectorsScorer; this.slice = slice; this.centroid = centroid; this.centroidDp = centroidDp; this.numBytes = BQVectorUtils.discretize(dimension, 64) / 8; this.correctiveValues = new float[3]; this.byteSize = numBytes + (Float.BYTES * 3) + Short.BYTES; this.byteBuffer = ByteBuffer.allocate(numBytes); this.binaryValue = byteBuffer.array(); this.binaryQuantizer = quantizer; this.discretizedDimensions = BQVectorUtils.discretize(dimension, 64); } @Override public int dimension() { return dimension; } @Override public int size() { return size; } @Override public byte[] vectorValue(int targetOrd) throws IOException { if (lastOrd == targetOrd) { return binaryValue; } slice.seek((long) targetOrd * byteSize); slice.readBytes(byteBuffer.array(), byteBuffer.arrayOffset(), numBytes); slice.readFloats(correctiveValues, 0, 3); quantizedComponentSum = Short.toUnsignedInt(slice.readShort()); lastOrd = targetOrd; return binaryValue; } @Override public int discretizedDimensions() { return discretizedDimensions; } @Override public float getCentroidDP() { return centroidDp; } @Override public OptimizedScalarQuantizer.QuantizationResult getCorrectiveTerms(int targetOrd) throws IOException { if (lastOrd == targetOrd) { return new OptimizedScalarQuantizer.QuantizationResult( correctiveValues[0], correctiveValues[1], correctiveValues[2], quantizedComponentSum ); } slice.seek(((long) targetOrd * byteSize) + numBytes); slice.readFloats(correctiveValues, 0, 3); quantizedComponentSum = Short.toUnsignedInt(slice.readShort()); return new OptimizedScalarQuantizer.QuantizationResult( correctiveValues[0], correctiveValues[1], correctiveValues[2], quantizedComponentSum ); } @Override public OptimizedScalarQuantizer getQuantizer() { return binaryQuantizer; } @Override public float[] getCentroid() { return centroid; } @Override public int getVectorByteLength() { return numBytes; } static OffHeapBinarizedVectorValues load( OrdToDocDISIReaderConfiguration configuration, int dimension, int size, OptimizedScalarQuantizer binaryQuantizer, VectorSimilarityFunction similarityFunction, FlatVectorsScorer vectorsScorer, float[] centroid, float centroidDp, long quantizedVectorDataOffset, long quantizedVectorDataLength, IndexInput vectorData ) throws IOException { if (configuration.isEmpty()) { return new EmptyOffHeapVectorValues(dimension, similarityFunction, vectorsScorer); } assert centroid != null; IndexInput bytesSlice = vectorData.slice("quantized-vector-data", quantizedVectorDataOffset, quantizedVectorDataLength); if (configuration.isDense()) { return new DenseOffHeapVectorValues( dimension, size, centroid, centroidDp, binaryQuantizer, similarityFunction, vectorsScorer, bytesSlice ); } else { return new SparseOffHeapVectorValues( configuration, dimension, size, centroid, centroidDp, binaryQuantizer, vectorData, similarityFunction, vectorsScorer, bytesSlice ); } } /** Dense off-heap binarized vector values */ static
OffHeapBinarizedVectorValues
java
processing__processing4
core/src/processing/core/PShapeSVG.java
{ "start": 67362, "end": 69570 }
class ____ extends PShapeSVG { // extends Path public String name; char unicode; int horizAdvX; public FontGlyph(PShapeSVG parent, XML properties, Font font) { super(parent, properties, true); super.parsePath(); // ?? name = properties.getString("glyph-name"); String u = properties.getString("unicode"); unicode = 0; if (u != null) { if (u.length() == 1) { unicode = u.charAt(0); //System.out.println("unicode for " + name + " is " + u); } else { System.err.println("unicode for " + name + " is more than one char: " + u); } } if (properties.hasAttribute("horiz-adv-x")) { horizAdvX = properties.getInt("horiz-adv-x"); } else { horizAdvX = font.horizAdvX; } } protected boolean isLegit() { // TODO need a better way to handle this... return vertexCount != 0; } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /** * Get a particular element based on its SVG ID. When editing SVG by hand, * this is the id="" tag on any SVG element. When editing from Illustrator, * these IDs can be edited by expanding the layers palette. The names used * in the layers palette, both for the layers or the shapes and groups * beneath them can be used here. * <PRE> * // This code grabs "Layer 3" and the shapes beneath it. * PShape layer3 = svg.getChild("Layer 3"); * </PRE> */ @Override public PShape getChild(String name) { PShape found = super.getChild(name); if (found == null) { // Otherwise try with underscores instead of spaces // (this is how Illustrator handles spaces in the layer names). found = super.getChild(name.replace(' ', '_')); } // Set bounding box based on the parent bounding box if (found != null) { // found.x = this.x; // found.y = this.y; found.width = this.width; found.height = this.height; } return found; } /** * Prints out the SVG document. Useful for parsing. */ public void print() { PApplet.println(element.toString()); } }
FontGlyph
java
apache__kafka
storage/src/test/java/org/apache/kafka/server/log/remote/storage/LocalTieredStorageHistory.java
{ "start": 1827, "end": 4096 }
class ____ { private static final int HARD_EVENT_COUNT_LIMIT = 1_000_000; private static final Logger LOGGER = getLogger(LocalTieredStorageHistory.class); private final Map<EventType, List<LocalTieredStorageEvent>> history; LocalTieredStorageHistory() { this.history = unmodifiableMap(stream(EventType.values()).collect(toMap(identity(), t -> new ArrayList<>()))); } /** * Returns the list of events accumulated by this instance of history from the {@link LocalTieredStorage} * it captures events from. * * @param type The type of the events to retrieve (e.g. offload or fetch a segment, fetch a time index, etc.) * @param topicPartition The topic-partition which the events relate to. * @return The list of events accumulated in this instance. */ public List<LocalTieredStorageEvent> getEvents(final EventType type, final TopicPartition topicPartition) { List<LocalTieredStorageEvent> matchingTypeEvents = history.get(type); synchronized (matchingTypeEvents) { matchingTypeEvents = new ArrayList<>(matchingTypeEvents); } return matchingTypeEvents.stream().filter(matches(topicPartition)).toList(); } /** * Returns the latest event captured so far of the given type and relating to the given topic-partition. * * @param type The type of the events to retrieve (e.g. offload or fetch a segment, fetch a time index, etc.) * @param topicPartition The topic-partition which the events relate to. * @return The latest event captured, if any. Otherwise, returns an empty value. */ public Optional<LocalTieredStorageEvent> latestEvent(final EventType type, final TopicPartition topicPartition) { return getEvents(type, topicPartition).stream().max(Comparator.naturalOrder()); } /** * Subscribes to the events generated by the given {@link LocalTieredStorage}. * Note there is no check performed against multiple subscriptions on the same storage. * * @param storage The {@link LocalTieredStorage} to subscribe to. */ void listenTo(final LocalTieredStorage storage) { storage.addListener(new InternalListener()); } private final
LocalTieredStorageHistory
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/globals/TemplateGlobalOverrideTest.java
{ "start": 1315, "end": 1669 }
class ____ { static native TemplateInstance hello(User user); } @Inject Template hello; @Test public void testOverride() { assertEquals("Hello Morna!", hello.data("user", new User("Morna")).render()); assertEquals("Hello Morna!", Templates.hello(new User("Morna")).render()); } public static
Templates
java
apache__dubbo
dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/route/MeshRuleManagerTest.java
{ "start": 1875, "end": 11225 }
class ____ { private static final String rule1 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + "metadata: { name: demo-route.Type1 }\n" + "spec:\n" + " host: demo\n" + "\n"; private static final String rule2 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route.Type1 }\n" + "spec:\n" + " hosts: [demo]\n"; private static final String rule3 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: DestinationRule\n" + "metadata: { name: demo-route.Type2 }\n" + "spec:\n" + " host: demo\n" + "\n"; private static final String rule4 = "apiVersion: service.dubbo.apache.org/v1alpha1\n" + "kind: VirtualService\n" + "metadata: { name: demo-route.Type2 }\n" + "spec:\n" + " hosts: [demo]\n"; private ModuleModel originModule; private ModuleModel moduleModel; private GovernanceRuleRepository ruleRepository; private Set<MeshEnvListenerFactory> envListenerFactories; @BeforeEach public void setup() { originModule = ApplicationModel.defaultModel().getDefaultModule(); moduleModel = Mockito.spy(originModule); ruleRepository = Mockito.mock(GovernanceRuleRepository.class); when(moduleModel.getDefaultExtension(GovernanceRuleRepository.class)).thenReturn(ruleRepository); ExtensionLoader<MeshEnvListenerFactory> envListenerFactoryLoader = Mockito.mock(ExtensionLoader.class); envListenerFactories = new HashSet<>(); when(envListenerFactoryLoader.getSupportedExtensionInstances()).thenReturn(envListenerFactories); when(moduleModel.getExtensionLoader(MeshEnvListenerFactory.class)).thenReturn(envListenerFactoryLoader); } @AfterEach public void teardown() { originModule.destroy(); } @Test void testRegister1() { MeshRuleManager meshRuleManager = new MeshRuleManager(moduleModel); MeshRuleListener meshRuleListener1 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { fail(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; meshRuleManager.register("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L); MeshAppRuleListener meshAppRuleListener = meshRuleManager.getAppRuleListeners().values().iterator().next(); verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); meshRuleManager.register("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); MeshRuleListener meshRuleListener2 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { fail(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type2"; } }; meshRuleManager.register("dubbo-demo", meshRuleListener2); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); assertEquals( 2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); assertEquals( 1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener2); assertEquals(0, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).removeListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); } @Test void testRegister2() { MeshRuleManager meshRuleManager = new MeshRuleManager(moduleModel); AtomicInteger invokeTimes = new AtomicInteger(0); MeshRuleListener meshRuleListener = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { assertEquals("dubbo-demo", appName); Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); assertTrue(rules.contains(yaml.load(rule1))); assertTrue(rules.contains(yaml.load(rule2))); invokeTimes.incrementAndGet(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; when(ruleRepository.getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L)).thenReturn(rule1 + "---\n" + rule2); meshRuleManager.register("dubbo-demo", meshRuleListener); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L); verify(ruleRepository, times(1)) .addListener( "dubbo-demo.MESHAPPRULE", "dubbo", meshRuleManager .getAppRuleListeners() .values() .iterator() .next()); assertEquals(1, invokeTimes.get()); meshRuleManager.register("dubbo-demo", meshRuleListener); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); } @Test void testRegister3() { MeshEnvListenerFactory meshEnvListenerFactory1 = Mockito.mock(MeshEnvListenerFactory.class); MeshEnvListenerFactory meshEnvListenerFactory2 = Mockito.mock(MeshEnvListenerFactory.class); MeshEnvListener meshEnvListener1 = Mockito.mock(MeshEnvListener.class); when(meshEnvListenerFactory1.getListener()).thenReturn(meshEnvListener1); MeshEnvListener meshEnvListener2 = Mockito.mock(MeshEnvListener.class); when(meshEnvListenerFactory2.getListener()).thenReturn(meshEnvListener2); envListenerFactories.add(meshEnvListenerFactory1); envListenerFactories.add(meshEnvListenerFactory2); MeshRuleManager meshRuleManager = new MeshRuleManager(moduleModel); MeshRuleListener meshRuleListener1 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { fail(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type1"; } }; when(meshEnvListener1.isEnable()).thenReturn(false); when(meshEnvListener2.isEnable()).thenReturn(true); meshRuleManager.register("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).getRule("dubbo-demo.MESHAPPRULE", "dubbo", 5000L); MeshAppRuleListener meshAppRuleListener = meshRuleManager.getAppRuleListeners().values().iterator().next(); verify(ruleRepository, times(1)).addListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); verify(meshEnvListener2, times(1)).onSubscribe("dubbo-demo", meshAppRuleListener); meshRuleManager.register("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); MeshRuleListener meshRuleListener2 = new MeshRuleListener() { @Override public void onRuleChange(String appName, List<Map<String, Object>> rules) { fail(); } @Override public void clearRule(String appName) {} @Override public String ruleSuffix() { return "Type2"; } }; meshRuleManager.register("dubbo-demo", meshRuleListener2); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); assertEquals( 2, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener1); assertEquals(1, meshRuleManager.getAppRuleListeners().size()); assertEquals( 1, meshAppRuleListener.getMeshRuleDispatcher().getListenerMap().size()); meshRuleManager.unregister("dubbo-demo", meshRuleListener2); assertEquals(0, meshRuleManager.getAppRuleListeners().size()); verify(ruleRepository, times(1)).removeListener("dubbo-demo.MESHAPPRULE", "dubbo", meshAppRuleListener); verify(meshEnvListener2, times(1)).onUnSubscribe("dubbo-demo"); } }
MeshRuleManagerTest
java
spring-projects__spring-boot
module/spring-boot-validation/src/test/java/org/springframework/boot/validation/autoconfigure/ValidationAutoConfigurationTests.java
{ "start": 15131, "end": 15502 }
class ____ { @Bean org.springframework.validation.Validator customValidator() { return mock(org.springframework.validation.Validator.class); } @Bean @Primary org.springframework.validation.Validator anotherCustomValidator() { return mock(org.springframework.validation.Validator.class); } } @Validated static
UserDefinedPrimarySpringValidatorConfig
java
mockito__mockito
mockito-integration-tests/inline-mocks-tests/src/test/java/org/mockitoinline/bugs/OngoingStubShiftTest.java
{ "start": 411, "end": 517 }
class ____ { static int getInt() { return 1; } } private static
StaticInt
java
apache__camel
components/camel-jpa/src/main/java/org/apache/camel/component/jpa/Callback.java
{ "start": 851, "end": 909 }
interface ____<R, P> { R callback(P parameter); }
Callback
java
spring-projects__spring-boot
configuration-metadata/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataRepositoryJsonBuilder.java
{ "start": 1051, "end": 6357 }
class ____ { private final Charset defaultCharset; private final JsonReader reader = new JsonReader(); private final List<SimpleConfigurationMetadataRepository> repositories = new ArrayList<>(); private ConfigurationMetadataRepositoryJsonBuilder(Charset defaultCharset) { this.defaultCharset = defaultCharset; } /** * Add the content of a {@link ConfigurationMetadataRepository} defined by the * specified {@link InputStream} JSON document using the default charset. If this * metadata repository holds items that were loaded previously, these are ignored. * <p> * Leaves the stream open when done. * @param inputStream the source input stream * @return this builder * @throws IOException in case of I/O errors */ public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(InputStream inputStream) throws IOException { return withJsonResource(inputStream, this.defaultCharset); } /** * Add the content of a {@link ConfigurationMetadataRepository} defined by the * specified {@link InputStream} JSON document using the specified {@link Charset}. If * this metadata repository holds items that were loaded previously, these are * ignored. * <p> * Leaves the stream open when done. * @param inputStream the source input stream * @param charset the charset of the input * @return this builder * @throws IOException in case of I/O errors */ public ConfigurationMetadataRepositoryJsonBuilder withJsonResource(InputStream inputStream, Charset charset) throws IOException { if (inputStream == null) { throw new IllegalArgumentException("InputStream must not be null."); } this.repositories.add(add(inputStream, charset)); return this; } /** * Build a {@link ConfigurationMetadataRepository} with the current state of this * builder. * @return this builder */ public ConfigurationMetadataRepository build() { SimpleConfigurationMetadataRepository result = new SimpleConfigurationMetadataRepository(); for (SimpleConfigurationMetadataRepository repository : this.repositories) { result.include(repository); } return result; } private SimpleConfigurationMetadataRepository add(InputStream in, Charset charset) throws IOException { try { RawConfigurationMetadata metadata = this.reader.read(in, charset); return create(metadata); } catch (IOException ex) { throw ex; } catch (Exception ex) { throw new IllegalStateException("Failed to read configuration metadata", ex); } } private SimpleConfigurationMetadataRepository create(RawConfigurationMetadata metadata) { SimpleConfigurationMetadataRepository repository = new SimpleConfigurationMetadataRepository(); repository.add(metadata.getSources()); for (ConfigurationMetadataItem item : metadata.getItems()) { ConfigurationMetadataSource source = metadata.getSource(item); repository.add(item, source); } Map<String, ConfigurationMetadataProperty> allProperties = repository.getAllProperties(); for (ConfigurationMetadataHint hint : metadata.getHints()) { ConfigurationMetadataProperty property = allProperties.get(hint.getId()); if (property != null) { addValueHints(property, hint); } else { String id = hint.resolveId(); property = allProperties.get(id); if (property != null) { if (hint.isMapKeyHints()) { addMapHints(property, hint); } else { addValueHints(property, hint); } } } } return repository; } private void addValueHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) { property.getHints().getValueHints().addAll(hint.getValueHints()); property.getHints().getValueProviders().addAll(hint.getValueProviders()); } private void addMapHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) { property.getHints().getKeyHints().addAll(hint.getValueHints()); property.getHints().getKeyProviders().addAll(hint.getValueProviders()); } /** * Create a new builder instance using {@link StandardCharsets#UTF_8} as the default * charset and the specified JSON resource. * @param inputStreams the source input streams * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. * @throws IOException on error */ public static ConfigurationMetadataRepositoryJsonBuilder create(InputStream... inputStreams) throws IOException { ConfigurationMetadataRepositoryJsonBuilder builder = create(); for (InputStream inputStream : inputStreams) { builder = builder.withJsonResource(inputStream); } return builder; } /** * Create a new builder instance using {@link StandardCharsets#UTF_8} as the default * charset. * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. */ public static ConfigurationMetadataRepositoryJsonBuilder create() { return create(StandardCharsets.UTF_8); } /** * Create a new builder instance using the specified default {@link Charset}. * @param defaultCharset the default charset to use * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. */ public static ConfigurationMetadataRepositoryJsonBuilder create(Charset defaultCharset) { return new ConfigurationMetadataRepositoryJsonBuilder(defaultCharset); } }
ConfigurationMetadataRepositoryJsonBuilder
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/Log4jThreadFactory.java
{ "start": 1007, "end": 3645 }
class ____ implements ThreadFactory { private static final String PREFIX = "TF-"; /** * Creates a new daemon thread factory. * * @param threadFactoryName * The thread factory name. * @return a new daemon thread factory. */ public static Log4jThreadFactory createDaemonThreadFactory(final String threadFactoryName) { return new Log4jThreadFactory(threadFactoryName, true, Thread.NORM_PRIORITY); } /** * Creates a new thread factory. * * This is mainly used for tests. Production code should be very careful with creating * non-daemon threads since those will block application shutdown * (see https://issues.apache.org/jira/browse/LOG4J2-1748). * * @param threadFactoryName * The thread factory name. * @return a new daemon thread factory. */ public static Log4jThreadFactory createThreadFactory(final String threadFactoryName) { return new Log4jThreadFactory(threadFactoryName, false, Thread.NORM_PRIORITY); } private static final AtomicInteger FACTORY_NUMBER = new AtomicInteger(1); private static final AtomicInteger THREAD_NUMBER = new AtomicInteger(1); private final boolean daemon; private final ThreadGroup group; private final int priority; private final String threadNamePrefix; /** * Constructs an initialized thread factory. * * @param threadFactoryName * The thread factory name. * @param daemon * Whether to create daemon threads. * @param priority * The thread priority. */ public Log4jThreadFactory(final String threadFactoryName, final boolean daemon, final int priority) { this.threadNamePrefix = PREFIX + FACTORY_NUMBER.getAndIncrement() + "-" + threadFactoryName + "-"; this.daemon = daemon; this.priority = priority; final SecurityManager securityManager = System.getSecurityManager(); this.group = securityManager != null ? securityManager.getThreadGroup() : Thread.currentThread().getThreadGroup(); } @Override public Thread newThread(final Runnable runnable) { // Log4jThread prefixes names with "Log4j2-". final Thread thread = new Log4jThread(group, runnable, threadNamePrefix + THREAD_NUMBER.getAndIncrement(), 0); if (thread.isDaemon() != daemon) { thread.setDaemon(daemon); } if (thread.getPriority() != priority) { thread.setPriority(priority); } return thread; } }
Log4jThreadFactory
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/audit/AuditSpanS3A.java
{ "start": 1005, "end": 1078 }
interface ____ extends AuditSpan, AWSAuditEventCallbacks { }
AuditSpanS3A
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/validation/beanvalidation/SpringValidatorAdapterTests.java
{ "start": 12685, "end": 12852 }
interface ____ { Same[] value(); } } @Documented @Inherited @Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @
List
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/dancing/DancingLinks.java
{ "start": 1464, "end": 1512 }
class ____ application's column names. */ public
of
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DelegatingDataSource.java
{ "start": 1438, "end": 4304 }
class ____ implements DataSource, InitializingBean { private @Nullable DataSource targetDataSource; /** * Create a new DelegatingDataSource. * @see #setTargetDataSource */ public DelegatingDataSource() { } /** * Create a new DelegatingDataSource. * @param targetDataSource the target DataSource */ public DelegatingDataSource(DataSource targetDataSource) { setTargetDataSource(targetDataSource); } /** * Set the target DataSource that this DataSource should delegate to. */ public void setTargetDataSource(@Nullable DataSource targetDataSource) { this.targetDataSource = targetDataSource; } /** * Return the target DataSource that this DataSource should delegate to. */ public @Nullable DataSource getTargetDataSource() { return this.targetDataSource; } /** * Obtain the target {@code DataSource} for actual use (never {@code null}). * @since 5.0 */ protected DataSource obtainTargetDataSource() { DataSource dataSource = getTargetDataSource(); Assert.state(dataSource != null, "No 'targetDataSource' set"); return dataSource; } @Override public void afterPropertiesSet() { if (getTargetDataSource() == null) { throw new IllegalArgumentException("Property 'targetDataSource' is required"); } } @Override public Connection getConnection() throws SQLException { return obtainTargetDataSource().getConnection(); } @Override public Connection getConnection(String username, String password) throws SQLException { return obtainTargetDataSource().getConnection(username, password); } @Override public ConnectionBuilder createConnectionBuilder() throws SQLException { return obtainTargetDataSource().createConnectionBuilder(); } @Override public ShardingKeyBuilder createShardingKeyBuilder() throws SQLException { return obtainTargetDataSource().createShardingKeyBuilder(); } @Override public int getLoginTimeout() throws SQLException { return obtainTargetDataSource().getLoginTimeout(); } @Override public void setLoginTimeout(int seconds) throws SQLException { obtainTargetDataSource().setLoginTimeout(seconds); } @Override public PrintWriter getLogWriter() throws SQLException { return obtainTargetDataSource().getLogWriter(); } @Override public void setLogWriter(PrintWriter out) throws SQLException { obtainTargetDataSource().setLogWriter(out); } @Override public Logger getParentLogger() { return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); } @Override @SuppressWarnings("unchecked") public <T> T unwrap(Class<T> iface) throws SQLException { if (iface.isInstance(this)) { return (T) this; } return obtainTargetDataSource().unwrap(iface); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return (iface.isInstance(this) || obtainTargetDataSource().isWrapperFor(iface)); } }
DelegatingDataSource
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/plugin/PluginLoaderTest.java
{ "start": 1223, "end": 2446 }
class ____ extends PluginTestBase { @Test public void testPluginLoading() throws Exception { final URL classpathA = createPluginJarURLFromString(PLUGIN_A); String[] parentPatterns = {TestSpi.class.getName(), OtherTestSpi.class.getName()}; PluginDescriptor pluginDescriptorA = new PluginDescriptor("A", new URL[] {classpathA}, parentPatterns); URLClassLoader pluginClassLoaderA = PluginLoader.createPluginClassLoader( pluginDescriptorA, PARENT_CLASS_LOADER, new String[0]); Assert.assertNotEquals(PARENT_CLASS_LOADER, pluginClassLoaderA); final PluginLoader pluginLoaderA = new PluginLoader("test-plugin", pluginClassLoaderA); Iterator<TestSpi> testSpiIteratorA = pluginLoaderA.load(TestSpi.class); Assert.assertTrue(testSpiIteratorA.hasNext()); TestSpi testSpiA = testSpiIteratorA.next(); Assert.assertFalse(testSpiIteratorA.hasNext()); Assert.assertNotNull(testSpiA.testMethod()); Assert.assertEquals( TestServiceA.class.getCanonicalName(), testSpiA.getClass().getCanonicalName()); // The plugin must return the same
PluginLoaderTest
java
google__guice
core/test/com/google/inject/errors/MissingImplementationErrorTest.java
{ "start": 2462, "end": 2551 }
class ____ { @Inject Server(Provider<RequestHandler> handler) {} } static
Server
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/Student.java
{ "start": 472, "end": 1015 }
class ____ implements Serializable { @Id @GeneratedValue private int id; private String name; @OneToMany(mappedBy = "student") private Set<CourseStudent> courses; public Student() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<CourseStudent> getCourses() { return courses; } public void setCourses(Set<CourseStudent> courses) { this.courses = courses; } }
Student
java
google__dagger
javatests/dagger/functional/nullables/JspecifyNullableTest.java
{ "start": 1771, "end": 1866 }
interface ____ { @Nullable Dependency dependency(); } @Module static
ComponentDependency
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/ConnectableLiftFuseable.java
{ "start": 949, "end": 2620 }
class ____<I, O> extends InternalConnectableFluxOperator<I, O> implements Scannable, Fuseable { final Operators.LiftFunction<I, O> liftFunction; ConnectableLiftFuseable(ConnectableFlux<I> p, Operators.LiftFunction<I, O> liftFunction) { super(Objects.requireNonNull(p, "source")); this.liftFunction = liftFunction; } @Override public int getPrefetch() { return source.getPrefetch(); } @Override public void connect(Consumer<? super Disposable> cancelSupport) { this.source.connect(cancelSupport); } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PREFETCH) return source.getPrefetch(); if (key == Attr.PARENT) return source; if (key == Attr.RUN_STYLE) return Scannable.from(source).scanUnsafe(key); if (key == Attr.LIFTER) return liftFunction.name; return super.scanUnsafe(key); } @Override public String stepName() { if (source instanceof Scannable) { return Scannable.from(source).stepName(); } return super.stepName(); } @Override public final CoreSubscriber<? super I> subscribeOrReturn(CoreSubscriber<? super O> actual) { // No need to wrap actual for CP, the Operators$LiftFunction handles it. CoreSubscriber<? super I> input = liftFunction.lifter.apply(source, actual); Objects.requireNonNull(input, "Lifted subscriber MUST NOT be null"); if (actual instanceof QueueSubscription && !(input instanceof QueueSubscription)) { //user didn't produce a QueueSubscription, original was one input = new FluxHide.SuppressFuseableSubscriber<>(input); } //otherwise QS is not required or user already made a compatible conversion return input; } }
ConnectableLiftFuseable
java
alibaba__nacos
core/src/test/java/com/alibaba/nacos/core/controller/compatibility/ApiCompatibilityConfigTest.java
{ "start": 1068, "end": 3243 }
class ____ { @BeforeEach void setUp() { EnvUtil.setEnvironment(new MockEnvironment()); } @AfterEach void tearDown() { EnvUtil.setEnvironment(null); ApiCompatibilityConfig config = ApiCompatibilityConfig.getInstance(); config.setConsoleApiCompatibility(false); config.setClientApiCompatibility(true); config.setAdminApiCompatibility(true); } @Test void testGetInstance() { ApiCompatibilityConfig instance1 = ApiCompatibilityConfig.getInstance(); ApiCompatibilityConfig instance2 = ApiCompatibilityConfig.getInstance(); assertEquals(instance1, instance2); } @Test void testGetConfigWithDefaultValues() { ApiCompatibilityConfig config = ApiCompatibilityConfig.getInstance(); config.getConfigFromEnv(); assertTrue(config.isClientApiCompatibility()); assertFalse(config.isConsoleApiCompatibility()); assertFalse(config.isAdminApiCompatibility()); assertEquals( "ApiCompatibilityConfig{clientApiCompatibility=true, consoleApiCompatibility=false, adminApiCompatibility=false}", config.printConfig()); } @Test void testGetConfigWithCustomValues() { MockEnvironment properties = new MockEnvironment(); properties.setProperty(ApiCompatibilityConfig.CLIENT_API_COMPATIBILITY_KEY, "false"); properties.setProperty(ApiCompatibilityConfig.CONSOLE_API_COMPATIBILITY_KEY, "true"); properties.setProperty(ApiCompatibilityConfig.ADMIN_API_COMPATIBILITY_KEY, "true"); EnvUtil.setEnvironment(properties); ApiCompatibilityConfig config = ApiCompatibilityConfig.getInstance(); config.getConfigFromEnv(); assertFalse(config.isClientApiCompatibility()); assertTrue(config.isConsoleApiCompatibility()); assertTrue(config.isAdminApiCompatibility()); assertEquals( "ApiCompatibilityConfig{clientApiCompatibility=false, consoleApiCompatibility=true, adminApiCompatibility=true}", config.printConfig()); } }
ApiCompatibilityConfigTest
java
processing__processing4
app/src/processing/app/contrib/ContributionTab.java
{ "start": 12796, "end": 18000 }
class ____ extends JTextField { List<String> filterWords = new ArrayList<>(); JLabel placeholderLabel; JButton resetButton; // Color textColor; // Color placeholderColor; // Color backgroundColor; FilterField() { // super(""); // necessary? // a label that appears above the component when empty and not focused placeholderLabel = new JLabel("Filter"); // filterLabel.setFont(ManagerFrame.NORMAL_PLAIN); placeholderLabel.setOpaque(false); // filterLabel.setOpaque(true); // setFont(ManagerFrame.NORMAL_PLAIN); // placeholderLabel.setIcon(Toolkit.getLibIconX("manager/search")); // JButton removeFilter = Toolkit.createIconButton("manager/remove"); resetButton = new JButton(); resetButton.setBorder(new EmptyBorder(0, 0, 0, 2)); resetButton.setBorderPainted(false); resetButton.setContentAreaFilled(false); resetButton.setCursor(Cursor.getDefaultCursor()); resetButton.addActionListener(e -> { setText(""); FilterField.this.requestFocusInWindow(); }); //setOpaque(false); setOpaque(true); setBorder(new EmptyBorder(3, 7, 3, 7)); GroupLayout fl = new GroupLayout(this); setLayout(fl); fl.setHorizontalGroup(fl .createSequentialGroup() .addComponent(placeholderLabel) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE) .addComponent(resetButton)); fl.setVerticalGroup(fl.createSequentialGroup() .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE) .addGroup(fl.createParallelGroup() .addComponent(placeholderLabel) .addComponent(resetButton)) .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE)); resetButton.setVisible(false); addFocusListener(new FocusListener() { public void focusLost(FocusEvent focusEvent) { if (getText().isEmpty()) { placeholderLabel.setVisible(true); } } public void focusGained(FocusEvent focusEvent) { placeholderLabel.setVisible(false); } }); getDocument().addDocumentListener(new DocumentListener() { public void removeUpdate(DocumentEvent e) { resetButton.setVisible(!getText().isEmpty()); applyFilter(); } public void insertUpdate(DocumentEvent e) { resetButton.setVisible(!getText().isEmpty()); applyFilter(); } public void changedUpdate(DocumentEvent e) { resetButton.setVisible(!getText().isEmpty()); applyFilter(); } }); updateTheme(); } private void applyFilter() { String filter = getText().toLowerCase(); // Replace anything but 0-9, a-z, or : with a space //filter = filter.replaceAll("[^\\x30-\\x39^\\x61-\\x7a\\x3a]", " "); filterWords = Arrays.asList(filter.split(" ")); //filterLibraries(category, filterWords); updateFilter(); } protected void updateTheme() { placeholderLabel.setForeground(Theme.getColor("manager.search.placeholder.color")); placeholderLabel.setIcon(Toolkit.renderIcon("manager/search", Theme.get("manager.search.icon.color"), 16)); resetButton.setIcon(Toolkit.renderIcon("manager/search-reset", Theme.get("manager.search.icon.color"), 16)); /* if (getUI() instanceof PdeTextFieldUI) { ((PdeTextFieldUI) getUI()).updateTheme(); } else { setUI(new PdeTextFieldUI("manager.search")); } */ // System.out.println(getBorder().getBorderInsets(FilterField.this)); //setBorder(new EmptyBorder(0, 5, 0, 5)); //setBorder(null); // setBorder(new EmptyBorder(3, 7, 3, 7)); setBackground(Theme.getColor("manager.search.background.color")); setForeground(Theme.getColor("manager.search.text.color")); // not yet in use, so leaving out for now //filterField.setDisabledTextColor(Theme.getColor("manager.search.disabled.text.color")); setSelectionColor(Theme.getColor("manager.search.selection.background.color")); setSelectedTextColor(Theme.getColor("manager.search.selection.text.color")); setCaretColor(Theme.getColor("manager.search.caret.color")); //SwingUtilities.updateComponentTreeUI(this); if (categoryChooser.getUI() instanceof PdeComboBoxUI) { ((PdeComboBoxUI) categoryChooser.getUI()).updateTheme(); } else { categoryChooser.setUI(new PdeComboBoxUI("manager.categories")); } /* textColor = Theme.getColor("manager.list.search.text.color"); placeholderColor = Theme.getColor("manager.list.search.placeholder.color"); backgroundColor = Theme.getColor("manager.list.search.background.color"); setBackground(backgroundColor); */ } } }
FilterField
java
google__guice
core/test/com/google/inject/CircularDependencyTest.java
{ "start": 18730, "end": 18897 }
class ____ implements J { @Inject JImpl(IImpl i) {} } @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RUNTIME) @ScopeAnnotation public @
JImpl
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/bytearray/ByteArrayAssert_containsOnly_Test.java
{ "start": 965, "end": 1324 }
class ____ extends ByteArrayAssertBaseTest { @Override protected ByteArrayAssert invoke_api_method() { return assertions.containsOnly((byte) 6, (byte) 8); } @Override protected void verify_internal_effects() { verify(arrays).assertContainsOnly(getInfo(assertions), getActual(assertions), arrayOf(6, 8)); } }
ByteArrayAssert_containsOnly_Test
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/FileConsumerPathWithAmpersandTest.java
{ "start": 1065, "end": 1804 }
class ____ extends ContextTestSupport { @Test public void testPathWithAmpersand() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); template.sendBodyAndHeader(fileUri("file&stuff"), "Hello World", Exchange.FILE_NAME, "hello.txt"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from(fileUri("file&stuff?delete=true&initialDelay=0&delay=10")).convertBodyTo(String.class) .to("mock:result"); } }; } }
FileConsumerPathWithAmpersandTest
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/erasurecode/coder/ErasureDecoder.java
{ "start": 1300, "end": 5118 }
class ____ extends Configured implements ErasureCoder { private final int numDataUnits; private final int numParityUnits; private final ErasureCoderOptions options; public ErasureDecoder(ErasureCoderOptions options) { this.options = options; this.numDataUnits = options.getNumDataUnits(); this.numParityUnits = options.getNumParityUnits(); } @Override public ErasureCodingStep calculateCoding(ECBlockGroup blockGroup) { // We may have more than this when considering complicate cases. HADOOP-11550 return prepareDecodingStep(blockGroup); } @Override public int getNumDataUnits() { return this.numDataUnits; } @Override public int getNumParityUnits() { return this.numParityUnits; } @Override public ErasureCoderOptions getOptions() { return options; } /** * We have all the data blocks and parity blocks as input blocks for * recovering by default. It's codec specific * @param blockGroup blockGroup. * @return input blocks */ protected ECBlock[] getInputBlocks(ECBlockGroup blockGroup) { ECBlock[] inputBlocks = new ECBlock[getNumDataUnits() + getNumParityUnits()]; System.arraycopy(blockGroup.getDataBlocks(), 0, inputBlocks, 0, getNumDataUnits()); System.arraycopy(blockGroup.getParityBlocks(), 0, inputBlocks, getNumDataUnits(), getNumParityUnits()); return inputBlocks; } /** * Which blocks were erased ? * @param blockGroup blockGroup. * @return output blocks to recover */ protected ECBlock[] getOutputBlocks(ECBlockGroup blockGroup) { ECBlock[] outputBlocks = new ECBlock[getNumErasedBlocks(blockGroup)]; int idx = 0; for (int i = 0; i < getNumDataUnits(); i++) { if (blockGroup.getDataBlocks()[i].isErased()) { outputBlocks[idx++] = blockGroup.getDataBlocks()[i]; } } for (int i = 0; i < getNumParityUnits(); i++) { if (blockGroup.getParityBlocks()[i].isErased()) { outputBlocks[idx++] = blockGroup.getParityBlocks()[i]; } } return outputBlocks; } @Override public boolean preferDirectBuffer() { return false; } @Override public void release() { // Nothing to do by default } /** * Perform decoding against a block blockGroup. * @param blockGroup blockGroup. * @return decoding step for caller to do the real work */ protected abstract ErasureCodingStep prepareDecodingStep( ECBlockGroup blockGroup); /** * Get the number of erased blocks in the block group. * @param blockGroup blockGroup. * @return number of erased blocks */ protected int getNumErasedBlocks(ECBlockGroup blockGroup) { int num = getNumErasedBlocks(blockGroup.getParityBlocks()); num += getNumErasedBlocks(blockGroup.getDataBlocks()); return num; } /** * Find out how many blocks are erased. * @param inputBlocks all the input blocks * @return number of erased blocks */ protected static int getNumErasedBlocks(ECBlock[] inputBlocks) { int numErased = 0; for (int i = 0; i < inputBlocks.length; i++) { if (inputBlocks[i].isErased()) { numErased ++; } } return numErased; } /** * Get indexes of erased blocks from inputBlocks * @param inputBlocks inputBlocks. * @return indexes of erased blocks from inputBlocks */ protected int[] getErasedIndexes(ECBlock[] inputBlocks) { int numErased = getNumErasedBlocks(inputBlocks); if (numErased == 0) { return new int[0]; } int[] erasedIndexes = new int[numErased]; int i = 0, j = 0; for (; i < inputBlocks.length && j < erasedIndexes.length; i++) { if (inputBlocks[i].isErased()) { erasedIndexes[j++] = i; } } return erasedIndexes; } }
ErasureDecoder
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/DelegateInjectionPointResolverImpl.java
{ "start": 459, "end": 4686 }
class ____ extends BeanResolverImpl { DelegateInjectionPointResolverImpl(BeanDeployment deployment) { super(deployment); } @Override public boolean matchTypeArguments(Type delegateType, Type beanParameter) { // this is the same as for bean types if (isActualType(delegateType) && isActualType(beanParameter)) { /* * the delegate type parameter and the bean type parameter are actual types with identical raw * type, and, if the type is parameterized, the bean type parameter is assignable to the delegate * type parameter according to these rules, or */ return matches(delegateType, beanParameter); } // this is the same as for bean types if (WILDCARD_TYPE.equals(delegateType.kind()) && isActualType(beanParameter)) { /* * the delegate type parameter is a wildcard, the bean type parameter is an actual type and the * actual type is assignable to the upper bound, if any, of the wildcard and assignable from the * lower bound, if any, of the wildcard, or */ return parametersMatch(delegateType.asWildcardType(), beanParameter); } // this is different from bean type rules if (WILDCARD_TYPE.equals(delegateType.kind()) && TYPE_VARIABLE.equals(beanParameter.kind())) { /* * the delegate type parameter is a wildcard, the bean type parameter is a type variable and the * upper bound of the type variable is assignable to the upper bound, if any, of the wildcard and * assignable from the lower bound, if any, of the wildcard, or */ return parametersMatch(delegateType.asWildcardType(), beanParameter.asTypeVariable()); } // this is different from bean type rules if (TYPE_VARIABLE.equals(delegateType.kind()) && TYPE_VARIABLE.equals(beanParameter.kind())) { /* * the required type parameter and the bean type parameter are both type variables and the upper bound of the * required type parameter is assignable * to the upper bound, if any, of the bean type parameter */ return parametersMatch(delegateType.asTypeVariable(), beanParameter.asTypeVariable()); } // this is different to bean type rules if (TYPE_VARIABLE.equals(delegateType.kind()) && isActualType(beanParameter)) { /* * the delegate type parameter is a type variable, the bean type parameter is an actual type, and * the actual type is assignable to the upper bound, if any, of the type variable */ return parametersMatch(delegateType.asTypeVariable(), beanParameter); } return false; } @Override boolean parametersMatch(WildcardType requiredParameter, TypeVariable beanParameter) { List<Type> beanParameterBounds = getUppermostTypeVariableBounds(beanParameter); if (!lowerBoundsOfWildcardMatch(beanParameterBounds, requiredParameter)) { return false; } List<Type> requiredUpperBounds = Collections.singletonList(requiredParameter.extendsBound()); // upper bound of the type variable is assignable to the upper bound of the wildcard return (boundsMatch(requiredUpperBounds, beanParameterBounds)); } @Override boolean parametersMatch(TypeVariable requiredParameter, TypeVariable beanParameter) { return boundsMatch(getUppermostTypeVariableBounds(requiredParameter), getUppermostTypeVariableBounds(beanParameter)); } protected boolean parametersMatch(TypeVariable delegateParameter, Type beanParameter) { for (Type type : getUppermostTypeVariableBounds(delegateParameter)) { if (!beanDeployment.getAssignabilityCheck().isAssignableFrom(type, beanParameter)) { return false; } } return true; } @Override protected BeanResolver getBeanResolver(BeanInfo bean) { return bean.getDeployment().delegateInjectionPointResolver; } }
DelegateInjectionPointResolverImpl
java
alibaba__druid
druid-admin/src/main/java/com/alibaba/druid/admin/model/dto/WallResult.java
{ "start": 540, "end": 1774 }
class ____ { @JSONField(name = "checkCount") private int checkCount; @JSONField(name = "hardCheckCount") private int hardCheckCount; @JSONField(name = "violationCount") private int violationCount; @JSONField(name = "violationEffectRowCount") private int violationEffectRowCount; @JSONField(name = "blackListHitCount") private int blackListHitCount; @JSONField(name = "blackListSize") private int blackListSize; @JSONField(name = "whiteListHitCount") private int whiteListHitCount; @JSONField(name = "whiteListSize") private int whiteListSize; @JSONField(name = "syntaxErrorCount") private int syntaxErrorCount; @JSONField(name = "tables") private List<TablesBean> tables = new ArrayList<>(); @JSONField(name = "functions") private List<FunctionsBean> functions = new ArrayList<>(); @JSONField(name = "blackList") private List<Object> blackList = new ArrayList<>(); @JSONField(name = "whiteList") private List<WhiteListBean> whiteList = new ArrayList<>(); @NoArgsConstructor @Data public static
ContentBean
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/DestroyMethodInferenceTests.java
{ "start": 6988, "end": 7138 }
class ____ implements AutoCloseable { boolean closed = false; @Override public void close() { closed = true; } } static
WithAutoCloseable
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/StreamingRuntimeContextTest.java
{ "start": 4376, "end": 5155 }
class ____ { @Test void testValueStateInstantiation() throws Exception { final ExecutionConfig config = new ExecutionConfig(); ((SerializerConfigImpl) config.getSerializerConfig()).registerKryoType(Path.class); final AtomicReference<Object> descriptorCapture = new AtomicReference<>(); StreamingRuntimeContext context = createRuntimeContext(descriptorCapture, config, false); ValueStateDescriptor<TaskInfo> descr = new ValueStateDescriptor<>("name", TaskInfo.class); context.getState(descr); StateDescriptor<?, ?> descrIntercepted = (StateDescriptor<?, ?>) descriptorCapture.get(); TypeSerializer<?> serializer = descrIntercepted.getSerializer(); // check that the Path
StreamingRuntimeContextTest
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/decorators/validation/NoDelegateInjectionPointTest.java
{ "start": 394, "end": 967 }
class ____ { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(Converter.class, DecoratorWithNoDelegateInjectionPoint.class).shouldFail().build(); @Test public void testFailure() { assertNotNull(container.getFailure()); assertTrue( container.getFailure().getMessage() .contains("DecoratorWithNoDelegateInjectionPoint has no @Delegate injection point"), container.getFailure().getMessage()); }
NoDelegateInjectionPointTest
java
spring-projects__spring-boot
module/spring-boot-restclient-test/src/main/java/org/springframework/boot/restclient/test/autoconfigure/RestClientTypeExcludeFilter.java
{ "start": 1128, "end": 2316 }
class ____ extends StandardAnnotationCustomizableTypeExcludeFilter<RestClientTest> { private static final Class<?>[] NO_COMPONENTS = {}; private static final String[] OPTIONAL_INCLUDES = { "tools.jackson.databind.JacksonModule", "org.springframework.boot.jackson.JacksonComponent", "com.fasterxml.jackson.databind.Module", "org.springframework.boot.jackson2.JsonComponent" }; private static final Set<Class<?>> KNOWN_INCLUDES; static { Set<Class<?>> includes = new LinkedHashSet<>(); for (String optionalInclude : OPTIONAL_INCLUDES) { try { includes.add(ClassUtils.forName(optionalInclude, null)); } catch (Exception ex) { // Ignore } } KNOWN_INCLUDES = Collections.unmodifiableSet(includes); } private final Class<?>[] components; RestClientTypeExcludeFilter(Class<?> testClass) { super(testClass); this.components = getAnnotation().getValue("components", Class[].class).orElse(NO_COMPONENTS); } @Override protected Set<Class<?>> getKnownIncludes() { return KNOWN_INCLUDES; } @Override protected Set<Class<?>> getComponentIncludes() { return new LinkedHashSet<>(Arrays.asList(this.components)); } }
RestClientTypeExcludeFilter
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/AbstractPropertyAccessorTests.java
{ "start": 65090, "end": 65552 }
class ____ { private String name; private Integer integer; private Simple(String name, Integer integer) { this.name = name; this.integer = integer; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getInteger() { return integer; } public void setInteger(Integer integer) { this.integer = integer; } } @SuppressWarnings("unused") private static
Simple
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/util/TestAnyModeMultipleInputStreamOperator.java
{ "start": 2278, "end": 2889 }
class ____ extends AbstractStreamOperatorFactory<String> { @Override public <T extends StreamOperator<String>> T createStreamOperator( StreamOperatorParameters<String> parameters) { return (T) new TestAnyModeMultipleInputStreamOperator(parameters); } @Override public Class<? extends StreamOperator> getStreamOperatorClass(ClassLoader classLoader) { return TestAnyModeMultipleInputStreamOperator.class; } } /** {@link AbstractInput} that converts argument to string pre-pending input id. */ public static
Factory
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/S3ClientFactory.java
{ "start": 2134, "end": 3398 }
interface ____ { /** * Creates a new {@link S3Client}. * The client returned supports synchronous operations. For * asynchronous operations, use * {@link #createS3AsyncClient(URI, S3ClientCreationParameters)}. * * @param uri S3A file system URI * @param parameters parameter object * @return S3 client * @throws IOException on any IO problem */ S3Client createS3Client(URI uri, S3ClientCreationParameters parameters) throws IOException; /** * Creates a new {@link S3AsyncClient}. * The client returned supports asynchronous operations. For * synchronous operations, use * {@link #createS3Client(URI, S3ClientCreationParameters)}. * * @param uri S3A file system URI * @param parameters parameter object * @return Async S3 client * @throws IOException on any IO problem */ S3AsyncClient createS3AsyncClient(URI uri, S3ClientCreationParameters parameters) throws IOException; /** * Creates a new {@link S3TransferManager}. * * @param s3AsyncClient the async client to be used by the TM. * @return S3 transfer manager */ S3TransferManager createS3TransferManager(S3AsyncClient s3AsyncClient); /** * Settings for the S3 Client. * Implemented as a
S3ClientFactory
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/TableReference.java
{ "start": 645, "end": 2074 }
interface ____ extends SqlAstNode, ColumnReferenceQualifier { String getIdentificationVariable(); /** * An identifier for the table reference. May be null if this is not a named table reference. */ String getTableId(); boolean isOptional(); @Override void accept(SqlAstWalker sqlTreeWalker); default void applyAffectedTableNames(Consumer<String> nameCollector) { visitAffectedTableNames( name -> { nameCollector.accept( name ); return null; } ); } default List<String> getAffectedTableNames() { final List<String> affectedTableNames = new ArrayList<>(); visitAffectedTableNames( name -> { affectedTableNames.add( name ); return null; } ); return affectedTableNames; } default boolean containsAffectedTableName(String requestedName) { return isEmpty( requestedName ) || Boolean.TRUE.equals( visitAffectedTableNames( requestedName::equals ) ); } Boolean visitAffectedTableNames(Function<String, Boolean> nameCollector); @Override TableReference resolveTableReference( NavigablePath navigablePath, String tableExpression); @Override TableReference getTableReference( NavigablePath navigablePath, String tableExpression, boolean resolve); default boolean isEmbeddableFunctionTableReference() { return false; } default @Nullable EmbeddableFunctionTableReference asEmbeddableFunctionTableReference() { return null; } }
TableReference
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/mapping/id/optimizer/EntityWithTableGenerator.java
{ "start": 224, "end": 410 }
class ____ { @Id @GeneratedValue(generator = "tab_gen") @TableGenerator(name = "tab_gen") Long id; public EntityWithTableGenerator() { } }
EntityWithTableGenerator
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/blocking/BlockingWithoutOutgoingOnIncomingErrorTest.java
{ "start": 455, "end": 978 }
class ____ { @Inject BeanWithBlocking referenceToForceArcToUseTheBean; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(BeanWithBlocking.class)) .setExpectedException(DeploymentException.class); @Test public void runTest() { fail("The expected DeploymentException was not thrown"); } @ApplicationScoped public static
BlockingWithoutOutgoingOnIncomingErrorTest
java
netty__netty
handler/src/test/java/io/netty/handler/ssl/DelegatingSslContextTest.java
{ "start": 893, "end": 2340 }
class ____ { private static final String[] EXPECTED_PROTOCOLS = { SslProtocols.TLS_v1_1 }; @Test public void testInitEngineOnNewEngine() throws Exception { SslContext delegating = newDelegatingSslContext(); SSLEngine engine = delegating.newEngine(UnpooledByteBufAllocator.DEFAULT); assertArrayEquals(EXPECTED_PROTOCOLS, engine.getEnabledProtocols()); engine = delegating.newEngine(UnpooledByteBufAllocator.DEFAULT, "localhost", 9090); assertArrayEquals(EXPECTED_PROTOCOLS, engine.getEnabledProtocols()); } @Test public void testInitEngineOnNewSslHandler() throws Exception { SslContext delegating = newDelegatingSslContext(); SslHandler handler = delegating.newHandler(UnpooledByteBufAllocator.DEFAULT); assertArrayEquals(EXPECTED_PROTOCOLS, handler.engine().getEnabledProtocols()); handler = delegating.newHandler(UnpooledByteBufAllocator.DEFAULT, "localhost", 9090); assertArrayEquals(EXPECTED_PROTOCOLS, handler.engine().getEnabledProtocols()); } private static SslContext newDelegatingSslContext() throws Exception { return new DelegatingSslContext(new JdkSslContext(SSLContext.getDefault(), false, ClientAuth.NONE)) { @Override protected void initEngine(SSLEngine engine) { engine.setEnabledProtocols(EXPECTED_PROTOCOLS); } }; } }
DelegatingSslContextTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/atomic/integerarray/AtomicIntegerArrayAssert_hasArray_Test.java
{ "start": 1087, "end": 1705 }
class ____ extends AtomicIntegerArrayAssertBaseTest { @Override protected AtomicIntegerArrayAssert invoke_api_method() { return assertions.hasArray(arrayOf(1, 2)); } @Override protected void verify_internal_effects() { verify(arrays).assertContainsExactly(info(), internalArray(), arrayOf(1, 2)); } @Test void should_honor_the_given_element_comparator() { AtomicIntegerArray actual = new AtomicIntegerArray(new int[] { 1, 2, 3 }); assertThat(actual).usingElementComparator(new AbsValueComparator<Integer>()).hasArray(new int[] { -1, 2, 3 }); } }
AtomicIntegerArrayAssert_hasArray_Test
java
elastic__elasticsearch
x-pack/plugin/slm/src/main/java/org/elasticsearch/xpack/slm/SnapshotRetentionTask.java
{ "start": 2370, "end": 15753 }
class ____ implements SchedulerEngine.Listener { private static final Logger logger = LogManager.getLogger(SnapshotRetentionTask.class); private static final Set<SnapshotState> RETAINABLE_STATES = EnumSet.of( SnapshotState.SUCCESS, SnapshotState.FAILED, SnapshotState.PARTIAL ); private final Client client; private final ClusterService clusterService; private final LongSupplier nowNanoSupplier; private final SnapshotHistoryStore historyStore; /** * Set of all currently deleting {@link SnapshotId} used to prevent starting multiple deletes for the same snapshot. */ private final Set<SnapshotId> runningDeletions = Collections.synchronizedSet(new HashSet<>()); public SnapshotRetentionTask( Client client, ClusterService clusterService, LongSupplier nowNanoSupplier, SnapshotHistoryStore historyStore ) { this.client = new OriginSettingClient(client, ClientHelper.INDEX_LIFECYCLE_ORIGIN); this.clusterService = clusterService; this.nowNanoSupplier = nowNanoSupplier; this.historyStore = historyStore; } @Override public void triggered(SchedulerEngine.Event event) { assert event.jobName().equals(SnapshotRetentionService.SLM_RETENTION_JOB_ID) || event.jobName().equals(SnapshotRetentionService.SLM_RETENTION_MANUAL_JOB_ID) : "expected id to be " + SnapshotRetentionService.SLM_RETENTION_JOB_ID + " or " + SnapshotRetentionService.SLM_RETENTION_MANUAL_JOB_ID + " but it was " + event.jobName(); final ClusterState state = clusterService.state(); // Skip running retention if SLM is disabled, however, even if it's // disabled we allow manual running. if (SnapshotLifecycleService.slmStoppedOrStopping(state) && event.jobName().equals(SnapshotRetentionService.SLM_RETENTION_MANUAL_JOB_ID) == false) { logger.debug("skipping SLM retention as SLM is currently stopped or stopping"); return; } AtomicReference<SnapshotLifecycleStats> slmStats = new AtomicReference<>(new SnapshotLifecycleStats()); // Defined here so it can be re-used without having to repeat it final Consumer<Exception> failureHandler = e -> { try { logger.error("error during snapshot retention task", e); slmStats.getAndUpdate(SnapshotLifecycleStats::withRetentionFailedIncremented); updateStateWithStats(slmStats.get()); } finally { logger.info("SLM retention snapshot cleanup task completed with error"); } }; try { logger.info("starting SLM retention snapshot cleanup task"); slmStats.getAndUpdate(SnapshotLifecycleStats::withRetentionRunIncremented); // Find all SLM policies that have retention enabled final Map<String, SnapshotLifecyclePolicy> policiesWithRetention = getAllPoliciesWithRetentionEnabled(state); logger.trace("policies with retention enabled: {}", policiesWithRetention.keySet()); // For those policies (there may be more than one for the same repo), // return the repos that we need to get the snapshots for final Set<String> repositioriesToFetch = policiesWithRetention.values() .stream() .map(SnapshotLifecyclePolicy::getRepository) .collect(Collectors.toSet()); logger.trace("fetching snapshots from repositories: {}", repositioriesToFetch); if (repositioriesToFetch.isEmpty()) { logger.info("there are no repositories to fetch, SLM retention snapshot cleanup task complete"); return; } // Finally, asynchronously retrieve all the snapshots, deleting them serially, // before updating the cluster state with the new metrics and setting 'running' // back to false getSnapshotsEligibleForDeletion(repositioriesToFetch, policiesWithRetention, new ActionListener<>() { @Override public void onResponse(Map<String, List<Tuple<SnapshotId, String>>> snapshotsToBeDeleted) { if (logger.isTraceEnabled()) { logger.trace("snapshots eligible for deletion: [{}]", snapshotsToBeDeleted); } // Finally, delete the snapshots that need to be deleted deleteSnapshots(snapshotsToBeDeleted, slmStats, ActionListener.running(() -> { updateStateWithStats(slmStats.get()); logger.info("SLM retention snapshot cleanup task complete"); })); } @Override public void onFailure(Exception e) { failureHandler.accept(e); } }); } catch (Exception e) { failureHandler.accept(e); } } static Map<String, SnapshotLifecyclePolicy> getAllPoliciesWithRetentionEnabled(final ClusterState state) { final SnapshotLifecycleMetadata snapMeta = state.metadata().getProject().custom(SnapshotLifecycleMetadata.TYPE); if (snapMeta == null) { return Collections.emptyMap(); } return snapMeta.getSnapshotConfigurations() .entrySet() .stream() .filter(e -> e.getValue().getPolicy().getRetentionPolicy() != null) .filter(e -> e.getValue().getPolicy().getRetentionPolicy().equals(SnapshotRetentionConfiguration.EMPTY) == false) .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getPolicy())); } void getSnapshotsEligibleForDeletion( Collection<String> repositories, Map<String, SnapshotLifecyclePolicy> policies, ActionListener<Map<String, List<Tuple<SnapshotId, String>>>> listener ) { client.execute( TransportSLMGetExpiredSnapshotsAction.INSTANCE, new TransportSLMGetExpiredSnapshotsAction.Request(repositories, policies), listener.delegateFailureAndWrap((l, m) -> l.onResponse(m.snapshotsToDelete())) ); } void deleteSnapshots( Map<String, List<Tuple<SnapshotId, String>>> snapshotsToDelete, AtomicReference<SnapshotLifecycleStats> slmStats, ActionListener<Void> listener ) { int count = snapshotsToDelete.values().stream().mapToInt(List::size).sum(); if (count == 0) { listener.onResponse(null); logger.debug("no snapshots are eligible for deletion"); return; } logger.info("starting snapshot retention deletion for [{}] snapshots", count); long startTime = nowNanoSupplier.getAsLong(); final AtomicInteger deleted = new AtomicInteger(0); final AtomicInteger failed = new AtomicInteger(0); final CountDownActionListener allDeletesListener = new CountDownActionListener( snapshotsToDelete.size(), ActionListener.runAfter(listener, () -> { TimeValue totalElapsedTime = TimeValue.timeValueNanos(nowNanoSupplier.getAsLong() - startTime); logger.debug("total elapsed time for deletion of [{}] snapshots: {}", deleted, totalElapsedTime); slmStats.getAndUpdate(s -> s.withDeletionTimeUpdated(totalElapsedTime)); }) ); for (Map.Entry<String, List<Tuple<SnapshotId, String>>> entry : snapshotsToDelete.entrySet()) { String repo = entry.getKey(); List<Tuple<SnapshotId, String>> snapshots = entry.getValue(); if (snapshots.isEmpty() == false) { deleteSnapshots(slmStats, deleted, failed, repo, snapshots, allDeletesListener); } } } private void deleteSnapshots( AtomicReference<SnapshotLifecycleStats> slmStats, AtomicInteger deleted, AtomicInteger failed, String repo, List<Tuple<SnapshotId, String>> snapshots, ActionListener<Void> listener ) { final ActionListener<Void> allDeletesListener = new CountDownActionListener(snapshots.size(), listener); for (Tuple<SnapshotId, String> info : snapshots) { final SnapshotId snapshotId = info.v1(); if (runningDeletions.add(snapshotId) == false) { // snapshot is already being deleted, no need to start another delete job for it allDeletesListener.onResponse(null); continue; } boolean success = false; try { final String policyId = info.v2(); final long deleteStartTime = nowNanoSupplier.getAsLong(); // TODO: Use snapshot multi-delete instead of this loop if all nodes in the cluster support it // i.e are newer or equal to SnapshotsService#MULTI_DELETE_VERSION deleteSnapshot(policyId, repo, snapshotId, slmStats, ActionListener.runAfter(ActionListener.wrap(acknowledgedResponse -> { deleted.incrementAndGet(); assert acknowledgedResponse.isAcknowledged(); historyStore.putAsync( SnapshotHistoryItem.deletionSuccessRecord(Instant.now().toEpochMilli(), snapshotId.getName(), policyId, repo) ); allDeletesListener.onResponse(null); }, e -> { failed.incrementAndGet(); try { final SnapshotHistoryItem result = SnapshotHistoryItem.deletionFailureRecord( Instant.now().toEpochMilli(), snapshotId.getName(), policyId, repo, e ); historyStore.putAsync(result); } catch (IOException ex) { // This shouldn't happen unless there's an issue with serializing the original exception logger.error( () -> format("failed to record snapshot deletion failure for snapshot lifecycle policy [%s]", policyId), ex ); } finally { allDeletesListener.onFailure(e); } }), () -> { runningDeletions.remove(snapshotId); long finishTime = nowNanoSupplier.getAsLong(); TimeValue deletionTime = TimeValue.timeValueNanos(finishTime - deleteStartTime); logger.debug("elapsed time for deletion of [{}] snapshot: {}", snapshotId, deletionTime); })); success = true; } catch (Exception e) { listener.onFailure(e); } finally { if (success == false) { runningDeletions.remove(snapshotId); } } } } /** * Delete the given snapshot from the repository in blocking manner * * @param repo The repository the snapshot is in * @param snapshot The snapshot metadata * @param listener {@link ActionListener#onResponse(Object)} is called if a {@link SnapshotHistoryItem} can be created representing a * successful or failed deletion call. {@link ActionListener#onFailure(Exception)} is called only if interrupted. */ void deleteSnapshot( String slmPolicy, String repo, SnapshotId snapshot, AtomicReference<SnapshotLifecycleStats> slmStats, ActionListener<AcknowledgedResponse> listener ) { logger.info("[{}] snapshot retention deleting snapshot [{}]", repo, snapshot); // don't time out on this request to not produce failed SLM runs in case of a temporarily slow master node client.admin() .cluster() .prepareDeleteSnapshot(TimeValue.MAX_VALUE, repo, snapshot.getName()) .execute(ActionListener.wrap(acknowledgedResponse -> { slmStats.getAndUpdate(s -> s.withDeletedIncremented(slmPolicy)); listener.onResponse(acknowledgedResponse); }, e -> { try { logger.warn(() -> format("[%s] failed to delete snapshot [%s] for retention", repo, snapshot), e); slmStats.getAndUpdate(s -> s.withDeleteFailureIncremented(slmPolicy)); } finally { listener.onFailure(e); } })); } void updateStateWithStats(SnapshotLifecycleStats newStats) { submitUnbatchedTask(UpdateSnapshotLifecycleStatsTask.TASK_SOURCE, new UpdateSnapshotLifecycleStatsTask(newStats)); } @SuppressForbidden(reason = "legacy usage of unbatched task") // TODO add support for batching here private void submitUnbatchedTask(@SuppressWarnings("SameParameterValue") String source, ClusterStateUpdateTask task) { clusterService.submitUnbatchedStateUpdateTask(source, task); } }
SnapshotRetentionTask
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/pagination/DataMetaPoint.java
{ "start": 180, "end": 1445 }
class ____ { private long id; private DataPoint dataPoint; private String meta; /** * @return Returns the id. */ public long getId() { return id; } /** * @param id * The id to set. */ public void setId(long id) { this.id = id; } public DataPoint getDataPoint() { return dataPoint; } public void setDataPoint(DataPoint dataPoint) { this.dataPoint = dataPoint; } public String getMeta() { return meta; } public void setMeta(String meta) { this.meta = meta; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dataPoint == null) ? 0 : dataPoint.hashCode()); result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + ((meta == null) ? 0 : meta.hashCode()); return result; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DataMetaPoint dataPoint = (DataMetaPoint) o; if (meta != null ? !meta.equals(dataPoint.meta) : dataPoint.meta != null) { return false; } if (dataPoint != null ? !dataPoint.equals(dataPoint.dataPoint) : dataPoint.dataPoint != null) { return false; } return true; } }
DataMetaPoint
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/NoCanIgnoreReturnValueOnClassesTest.java
{ "start": 7722, "end": 8152 }
class ____ { public int getValue() { return 42; } } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CheckReturnValue; public final
Nested
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/MediaTypesWithSuffixHandlingTest.java
{ "start": 3374, "end": 5745 }
class ____ implements ServerMessageBodyWriter<Object>, ServerMessageBodyReader<Object> { @Override public boolean isWriteable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo target, MediaType mediaType) { return true; } @Override public void writeResponse(Object o, Type genericType, ServerRequestContext context) throws WebApplicationException, IOException { String response = (String) o; response += " - no suffix writer"; context.getOrCreateOutputStream().write(response.getBytes(StandardCharsets.UTF_8)); } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { throw new IllegalStateException("should never have been called"); } @Override public void writeTo(Object o, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { throw new IllegalStateException("should never have been called"); } @Override public boolean isReadable(Class<?> type, Type genericType, ResteasyReactiveResourceInfo lazyMethod, MediaType mediaType) { return true; } @Override public Object readFrom(Class<Object> type, Type genericType, MediaType mediaType, ServerRequestContext context) throws WebApplicationException { return "from reader"; } @Override public boolean isReadable(Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType) { throw new IllegalStateException("should never have been called"); } @Override public Object readFrom(Class<Object> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> multivaluedMap, InputStream inputStream) throws WebApplicationException { throw new IllegalStateException("should never have been called"); } } @Provider @Consumes("text/test+suffix") @Produces("text/test+suffix") public static
NoSuffixMessageBodyWriter
java
apache__camel
components/camel-ai/camel-torchserve/src/main/java/org/apache/camel/component/torchserve/producer/MetricsProducer.java
{ "start": 1297, "end": 2435 }
class ____ extends TorchServeProducer { private final Metrics metrics; private final String operation; public MetricsProducer(TorchServeEndpoint endpoint) { super(endpoint); this.metrics = endpoint.getClient().metrics(); this.operation = endpoint.getOperation(); } @Override public void process(Exchange exchange) throws Exception { if ("metrics".equals(this.operation)) { metrics(exchange); } else { throw new IllegalArgumentException("Unsupported operation: " + this.operation); } } private void metrics(Exchange exchange) throws ApiException { Message message = exchange.getMessage(); TorchServeConfiguration configuration = getEndpoint().getConfiguration(); String metricsName = Optional .ofNullable(message.getHeader(TorchServeConstants.METRICS_NAME, String.class)) .orElse(configuration.getMetricsName()); String response = metricsName == null ? this.metrics.metrics() : this.metrics.metrics(metricsName); message.setBody(response); } }
MetricsProducer
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/QueryProducer.java
{ "start": 11203, "end": 12315 }
class ____ a registered * {@link org.hibernate.type.descriptor.java.JavaType}, then the * query must return a result set with a single column whose * {@code JdbcType} is compatible with that {@code JavaType}. * <li>Otherwise, the select items will be packaged into an instance of * the result type. The result type must have an appropriate * constructor with parameter types matching the select items, or it * must be one of the types {@code Object[]}, {@link java.util.List}, * {@link java.util.Map}, or {@link jakarta.persistence.Tuple}. * </ul> * * @param sqlString The native (SQL) query string * @param resultClass The Java type to map results to * * @return The {@link NativeQuery} instance for manipulation and execution * * @see jakarta.persistence.EntityManager#createNativeQuery(String,Class) */ <R> NativeQuery<R> createNativeQuery(String sqlString, Class<R> resultClass); /** * Create a {@link NativeQuery} instance for the given native SQL query * using an implicit mapping to the specified Java entity type. * <p> * The given
has
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/annotation/Property.java
{ "start": 1109, "end": 1549 }
interface ____ { /** * The name of the property in kebab case. Example: my-app.bar. * * @return The name of the property */ String name(); /** * @return The value of the property */ String value() default ""; /** * @return The default value if none is specified */ @AliasFor(annotation = Bindable.class, member = "defaultValue") String defaultValue() default ""; }
Property
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/bulk/BulkRequestParser.java
{ "start": 1950, "end": 8710 }
class ____ { @UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) // Remove deprecation logger when its usages in checkBulkActionIsProperlyClosed are removed private static final DeprecationLogger deprecationLogger = DeprecationLogger.getLogger(BulkRequestParser.class); private static final Set<String> SUPPORTED_ACTIONS = Set.of("create", "index", "update", "delete"); private static final String STRICT_ACTION_PARSING_WARNING_KEY = "bulk_request_strict_action_parsing"; private static final ParseField INDEX = new ParseField("_index"); private static final ParseField TYPE = new ParseField("_type"); private static final ParseField ID = new ParseField("_id"); private static final ParseField ROUTING = new ParseField("routing"); private static final ParseField OP_TYPE = new ParseField("op_type"); private static final ParseField VERSION = new ParseField("version"); private static final ParseField VERSION_TYPE = new ParseField("version_type"); private static final ParseField RETRY_ON_CONFLICT = new ParseField("retry_on_conflict"); private static final ParseField PIPELINE = new ParseField("pipeline"); private static final ParseField SOURCE = new ParseField("_source"); private static final ParseField IF_SEQ_NO = new ParseField("if_seq_no"); private static final ParseField IF_PRIMARY_TERM = new ParseField("if_primary_term"); private static final ParseField REQUIRE_ALIAS = new ParseField(DocWriteRequest.REQUIRE_ALIAS); private static final ParseField REQUIRE_DATA_STREAM = new ParseField(DocWriteRequest.REQUIRE_DATA_STREAM); private static final ParseField LIST_EXECUTED_PIPELINES = new ParseField(DocWriteRequest.LIST_EXECUTED_PIPELINES); private static final ParseField DYNAMIC_TEMPLATES = new ParseField("dynamic_templates"); private static final ParseField DYNAMIC_TEMPLATE_PARAMS = new ParseField("dynamic_template_params"); // TODO: Remove this parameter once the BulkMonitoring endpoint has been removed // for CompatibleApi V7 this means to deprecate on type, for V8+ it means to throw an error private final boolean deprecateOrErrorOnType; /** * Configuration for {@link XContentParser}. */ private final XContentParserConfiguration config; /** * Create a new parser. * * @param deprecateOrErrorOnType whether to allow _type information in the index line; used by BulkMonitoring * @param includeSourceOnError if to include the source in parser error messages * @param restApiVersion */ public BulkRequestParser(boolean deprecateOrErrorOnType, boolean includeSourceOnError, RestApiVersion restApiVersion) { this.deprecateOrErrorOnType = deprecateOrErrorOnType; this.config = XContentParserConfiguration.EMPTY.withDeprecationHandler(LoggingDeprecationHandler.INSTANCE) .withRestApiVersion(restApiVersion) .withIncludeSourceOnError(includeSourceOnError); } private static int findNextMarker(byte marker, int from, BytesReference data, boolean lastData) { final int res = data.indexOf(marker, from); if (res != -1) { assert res >= 0; return res; } if (from != data.length() && lastData) { throw new IllegalArgumentException("The bulk request must be terminated by a newline [\\n]"); } return res; } /** * Returns the sliced {@link BytesReference}. If the {@link XContentType} is JSON, the byte preceding the marker is checked to see * if it is a carriage return and if so, the BytesReference is sliced so that the carriage return is ignored */ private static BytesReference sliceTrimmingCarriageReturn( BytesReference bytesReference, int from, int nextMarker, XContentType xContentType ) { final int length; if (XContentType.JSON == xContentType && bytesReference.get(nextMarker - 1) == (byte) '\r') { length = nextMarker - from - 1; } else { length = nextMarker - from; } return bytesReference.slice(from, length); } /** * Parse the provided {@code data} assuming the provided default values. Index requests * will be passed to the {@code indexRequestConsumer}, update requests to the * {@code updateRequestConsumer} and delete requests to the {@code deleteRequestConsumer}. */ public void parse( BytesReference data, @Nullable String defaultIndex, @Nullable String defaultRouting, @Nullable FetchSourceContext defaultFetchSourceContext, @Nullable String defaultPipeline, @Nullable Boolean defaultRequireAlias, @Nullable Boolean defaultRequireDataStream, @Nullable Boolean defaultListExecutedPipelines, boolean allowExplicitIndex, XContentType xContentType, BiConsumer<IndexRequest, String> indexRequestConsumer, Consumer<UpdateRequest> updateRequestConsumer, Consumer<DeleteRequest> deleteRequestConsumer ) throws IOException { IncrementalParser incrementalParser = new IncrementalParser( defaultIndex, defaultRouting, defaultFetchSourceContext, defaultPipeline, defaultRequireAlias, defaultRequireDataStream, defaultListExecutedPipelines, allowExplicitIndex, xContentType, indexRequestConsumer, updateRequestConsumer, deleteRequestConsumer ); incrementalParser.parse(data, true); } public IncrementalParser incrementalParser( @Nullable String defaultIndex, @Nullable String defaultRouting, @Nullable FetchSourceContext defaultFetchSourceContext, @Nullable String defaultPipeline, @Nullable Boolean defaultRequireAlias, @Nullable Boolean defaultRequireDataStream, @Nullable Boolean defaultListExecutedPipelines, boolean allowExplicitIndex, XContentType xContentType, BiConsumer<IndexRequest, String> indexRequestConsumer, Consumer<UpdateRequest> updateRequestConsumer, Consumer<DeleteRequest> deleteRequestConsumer ) { return new IncrementalParser( defaultIndex, defaultRouting, defaultFetchSourceContext, defaultPipeline, defaultRequireAlias, defaultRequireDataStream, defaultListExecutedPipelines, allowExplicitIndex, xContentType, indexRequestConsumer, updateRequestConsumer, deleteRequestConsumer ); } public
BulkRequestParser
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToBooleanFromLongEvaluator.java
{ "start": 3835, "end": 4417 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final Source source; private final EvalOperator.ExpressionEvaluator.Factory l; public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory l) { this.source = source; this.l = l; } @Override public ToBooleanFromLongEvaluator get(DriverContext context) { return new ToBooleanFromLongEvaluator(source, l.get(context), context); } @Override public String toString() { return "ToBooleanFromLongEvaluator[" + "l=" + l + "]"; } } }
Factory
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/examples/ConnectToRedisSSL.java
{ "start": 157, "end": 684 }
class ____ { public static void main(String[] args) { // Syntax: rediss://[password@]host[:port][/databaseNumber] // Adopt the port to the stunnel port in front of your Redis instance RedisClient redisClient = RedisClient.create("rediss://password@localhost:6443/0"); StatefulRedisConnection<String, String> connection = redisClient.connect(); System.out.println("Connected to Redis using SSL"); connection.close(); redisClient.shutdown(); } }
ConnectToRedisSSL
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/generators/SimpleIdTests.java
{ "start": 2650, "end": 2882 }
class ____ { @Id @GeneratedValue private UUID id; private String name; public Entity4() { } public Entity4(String name) { this.name = name; } } @Entity(name="Entity5") @Table(name="Entity5") public static
Entity4
java
square__retrofit
retrofit-converters/scalars/src/main/java/retrofit2/converter/scalars/ScalarResponseBodyConverters.java
{ "start": 828, "end": 1135 }
class ____ implements Converter<ResponseBody, String> { static final StringResponseBodyConverter INSTANCE = new StringResponseBodyConverter(); @Override public String convert(ResponseBody value) throws IOException { return value.string(); } } static final
StringResponseBodyConverter
java
quarkusio__quarkus
extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/ExcludedTypeBuildItem.java
{ "start": 772, "end": 1004 }
class ____ extends MultiBuildItem { private final String match; public ExcludedTypeBuildItem(String match) { this.match = match; } public String getMatch() { return match; } }
ExcludedTypeBuildItem
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ejb3configuration/ConfigurationObjectSettingTest.java
{ "start": 1830, "end": 13165 }
class ____ { @Test public void testSharedCacheMode() { verifyCacheMode( AvailableSettings.JAKARTA_SHARED_CACHE_MODE ); verifyCacheMode( AvailableSettings.JPA_SHARED_CACHE_MODE ); } private void verifyCacheMode(String settingName) { // first, via the integration vars PersistenceUnitInfoAdapter empty = new PersistenceUnitInfoAdapter(); EntityManagerFactoryBuilderImpl builder = null; { // as object builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( empty, Collections.singletonMap( settingName, SharedCacheMode.DISABLE_SELECTIVE ) ); assertThat( builder.getConfigurationValues().get( settingName ) ).isEqualTo( SharedCacheMode.DISABLE_SELECTIVE ); } builder.cancel(); { // as string builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( empty, Collections.singletonMap( settingName, SharedCacheMode.DISABLE_SELECTIVE.name() ) ); assertThat( builder.getConfigurationValues().get( settingName ) ).isEqualTo( SharedCacheMode.DISABLE_SELECTIVE.name() ); } builder.cancel(); // next, via the PUI PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter() { @Override public SharedCacheMode getSharedCacheMode() { return SharedCacheMode.ENABLE_SELECTIVE; } }; { builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( adapter, null ); Object value = builder.getConfigurationValues().get( settingName ); // PUI should only set non-deprecated setting if (AvailableSettings.JPA_SHARED_CACHE_MODE.equals( settingName )) { assertNull( value ); } else { assertEquals( SharedCacheMode.ENABLE_SELECTIVE, value ); } } builder.cancel(); // via both, integration vars should take precedence { builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( adapter, Collections.singletonMap( settingName, SharedCacheMode.DISABLE_SELECTIVE ) ); assertEquals( SharedCacheMode.DISABLE_SELECTIVE, builder.getConfigurationValues().get( settingName ) ); } builder.cancel(); } @Test public void testValidationMode() { verifyValidationMode( AvailableSettings.JAKARTA_VALIDATION_MODE ); verifyValidationMode( AvailableSettings.JPA_VALIDATION_MODE ); } private void verifyValidationMode(String settingName) { // first, via the integration vars PersistenceUnitInfoAdapter empty = new PersistenceUnitInfoAdapter(); EntityManagerFactoryBuilderImpl builder = null; { // as object builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( empty, Collections.singletonMap( settingName, ValidationMode.CALLBACK ) ); assertThat( builder.getConfigurationValues().get( settingName ) ).isEqualTo( ValidationMode.CALLBACK ); } builder.cancel(); { // as string builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( empty, Collections.singletonMap( settingName, ValidationMode.CALLBACK.name() ) ); assertThat( builder.getConfigurationValues().get( settingName ) ).isEqualTo( ValidationMode.CALLBACK.name() ); } builder.cancel(); // next, via the PUI PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter() { @Override public ValidationMode getValidationMode() { return ValidationMode.CALLBACK; } }; { builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( adapter, null ); Object value = builder.getConfigurationValues().get( settingName ); // PUI should only set non-deprecated settings if (AvailableSettings.JPA_VALIDATION_MODE.equals( settingName )) { assertNull( value ); } else { assertThat( value ).isEqualTo( ValidationMode.CALLBACK ); } } builder.cancel(); // via both, integration vars should take precedence { builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( adapter, Collections.singletonMap( settingName, ValidationMode.NONE ) ); assertThat( builder.getConfigurationValues().get( settingName ) ).isEqualTo( ValidationMode.NONE ); } builder.cancel(); } @Test public void testValidationFactory() { verifyValidatorFactory( AvailableSettings.JAKARTA_VALIDATION_FACTORY ); verifyValidatorFactory( AvailableSettings.JPA_VALIDATION_FACTORY ); } private void verifyValidatorFactory(String settingName) { final Object token = new Object(); PersistenceUnitInfoAdapter adapter = new PersistenceUnitInfoAdapter(); try { Bootstrap.getEntityManagerFactoryBuilder( adapter, Collections.singletonMap( settingName, token ) ).cancel(); fail( "Was expecting error as token did not implement ValidatorFactory" ); } catch ( HibernateException e ) { // probably the condition we want but unfortunately the exception is not specific // and the pertinent info is in a cause } } @Test // @FailureExpected( // reason = "this is unfortunate to not be able to test. it fails because the values from `hibernate.properties` " + // "name the Hibernate-specific settings, which always take precedence. testing this needs to be able to erase " + // "those entries in the ConfigurationService Map" // ) public void testJdbcSettings() { verifyJdbcSettings( AvailableSettings.JAKARTA_JDBC_URL, AvailableSettings.JAKARTA_JDBC_DRIVER, AvailableSettings.JAKARTA_JDBC_USER, AvailableSettings.JAKARTA_JDBC_PASSWORD ); verifyJdbcSettings( AvailableSettings.JPA_JDBC_URL, AvailableSettings.JPA_JDBC_DRIVER, AvailableSettings.JPA_JDBC_USER, AvailableSettings.JPA_JDBC_PASSWORD ); } public static void applyToProperties(Properties properties, Object... pairs) { assert pairs.length % 2 == 0; for ( int i = 0; i < pairs.length; i+=2 ) { properties.put( pairs[i], pairs[i+1] ); } } private void verifyJdbcSettings(String jdbcUrl, String jdbcDriver, String jdbcUser, String jdbcPassword) { final String urlValue = "some:url"; final String driverValue = "some.jdbc.Driver"; final String userValue = "goofy"; final String passwordValue = "goober"; // first, via the integration vars PersistenceUnitInfoAdapter empty = new PersistenceUnitInfoAdapter(); EntityManagerFactoryBuilderImpl builder = null; { builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( empty, Map.of( jdbcUrl, urlValue, jdbcDriver, driverValue, jdbcUser, userValue, jdbcPassword, passwordValue ), mergedSettings -> mergedSettings.getConfigurationValues().clear() ); assertThat( builder.getConfigurationValues().get( jdbcUrl ) ).isEqualTo( urlValue ); assertThat( builder.getConfigurationValues().get( jdbcDriver ) ).isEqualTo( driverValue ); assertThat( builder.getConfigurationValues().get( jdbcUser ) ).isEqualTo( userValue ); assertThat( builder.getConfigurationValues().get( jdbcPassword ) ).isEqualTo( passwordValue ); builder.cancel(); } PersistenceUnitInfoAdapter pui = new PersistenceUnitInfoAdapter(); applyToProperties( pui.getProperties(), jdbcUrl, urlValue, jdbcDriver, driverValue, jdbcUser, userValue, jdbcPassword, passwordValue ); { builder = (EntityManagerFactoryBuilderImpl) Bootstrap.getEntityManagerFactoryBuilder( pui, null, mergedSettings -> mergedSettings.getConfigurationValues().clear() ); assertThat( builder.getConfigurationValues().get( jdbcUrl ) ).isEqualTo( urlValue ); assertThat( builder.getConfigurationValues().get( jdbcDriver ) ).isEqualTo( driverValue ); assertThat( builder.getConfigurationValues().get( jdbcUser ) ).isEqualTo( userValue ); assertThat( builder.getConfigurationValues().get( jdbcPassword ) ).isEqualTo( passwordValue ); builder.cancel(); } } @Test public void testSchemaGenSettings() { verifySchemaGenSettings( AvailableSettings.JAKARTA_HBM2DDL_DATABASE_ACTION, AvailableSettings.JAKARTA_HBM2DDL_SCRIPTS_ACTION, AvailableSettings.JAKARTA_HBM2DDL_CREATE_SCHEMAS, AvailableSettings.JAKARTA_HBM2DDL_DB_NAME ); verifySchemaGenSettings( AvailableSettings.HBM2DDL_DATABASE_ACTION, AvailableSettings.HBM2DDL_SCRIPTS_ACTION, AvailableSettings.HBM2DDL_CREATE_SCHEMAS, AvailableSettings.DIALECT_DB_NAME ); // verifySchemaGenSettingsPrecedence(); } public static Map<String,String> toMap(String... pairs) { assert pairs.length % 2 == 0; switch ( pairs.length ) { case 0: return emptyMap(); case 2: return singletonMap( pairs[0], pairs[1] ); default: final Map<String,String> result = new HashMap<>(); for ( int i = 0; i < pairs.length; i+=2 ) { result.put( pairs[i], pairs[i+1] ); } return result; } } private void verifySchemaGenSettings( String dbActionSettingName, String scriptActionSettingName, String createSchemasSettingName, String dbNameSettingName) { final Action dbAction = Action.CREATE_ONLY; final Action scriptAction = Action.CREATE_ONLY; final boolean createSchemas = true; final String dbName = "H2"; final Map<String, String> settings = toMap( dbActionSettingName, dbAction.getExternalJpaName(), scriptActionSettingName, scriptAction.getExternalJpaName(), createSchemasSettingName, Boolean.toString( createSchemas ), dbNameSettingName, dbName ); // first verify the individual interpretations final Action interpretedDbAction = ActionGrouping.determineJpaDbActionSetting( settings, null, null ); assertThat( interpretedDbAction ).isEqualTo( dbAction ); final Action interpretedScriptAction = ActionGrouping.determineJpaScriptActionSetting( settings, null, null ); assertThat( interpretedScriptAction ).isEqualTo( scriptAction ); // next verify the action-group determination final ActionGrouping actionGrouping = ActionGrouping.interpret( settings ); assertThat( actionGrouping.databaseAction() ).isEqualTo( dbAction ); assertThat( actionGrouping.scriptAction() ).isEqualTo( scriptAction ); // the check above uses a "for testing only" form of what happens for "real". // verify the "real" path as well try (StandardServiceRegistryImpl servicedRegistry = ServiceRegistryUtil.serviceRegistry()) { final Metadata metadata = new MetadataSources( servicedRegistry ) .addAnnotatedClass( Bell.class ) .buildMetadata(); final Set<ActionGrouping> actionGroupings = ActionGrouping.interpret( metadata, settings ); assertThat( actionGroupings ).hasSize( 1 ); final ActionGrouping grouping = actionGroupings.iterator().next(); assertThat( grouping.contributor() ).isEqualTo( "orm" ); assertThat( grouping.databaseAction() ).isEqualTo( dbAction ); assertThat( grouping.scriptAction() ).isEqualTo( scriptAction ); // verify also interpreting the db-name, etc... they are used by SF/EMF to resolve Dialect final DialectResolver dialectResolver = new DialectResolverInitiator() .initiateService( new HashMap<>( settings ), servicedRegistry ); final Dialect dialect = dialectResolver.resolveDialect( TestingDialectResolutionInfo.forDatabaseInfo( dbName ) ); assertThat( dialect ).isInstanceOf( H2Dialect.class ); } } }
ConfigurationObjectSettingTest
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/diagnostics/analyzer/MissingParameterNamesFailureAnalyzer.java
{ "start": 1353, "end": 4446 }
class ____ implements FailureAnalyzer { private static final String USE_PARAMETERS_MESSAGE = "Ensure that the compiler uses the '-parameters' flag"; static final String POSSIBILITY = "This may be due to missing parameter name information"; static final String ACTION = """ Ensure that your compiler is configured to use the '-parameters' flag. You may need to update both your build tool settings as well as your IDE. (See https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-6.1-Release-Notes#parameter-name-retention) """; @Override public @Nullable FailureAnalysis analyze(Throwable failure) { return analyzeForMissingParameters(failure); } /** * Analyze the given failure for missing parameter name exceptions. * @param failure the failure to analyze * @return a failure analysis or {@code null} */ static @Nullable FailureAnalysis analyzeForMissingParameters(Throwable failure) { return analyzeForMissingParameters(failure, failure, new HashSet<>()); } private static @Nullable FailureAnalysis analyzeForMissingParameters(Throwable rootFailure, @Nullable Throwable cause, Set<Throwable> seen) { if (cause != null && seen.add(cause)) { if (isSpringParametersException(cause)) { return getAnalysis(rootFailure, cause); } FailureAnalysis analysis = analyzeForMissingParameters(rootFailure, cause.getCause(), seen); if (analysis != null) { return analysis; } for (Throwable suppressed : cause.getSuppressed()) { analysis = analyzeForMissingParameters(rootFailure, suppressed, seen); if (analysis != null) { return analysis; } } } return null; } private static boolean isSpringParametersException(Throwable failure) { String message = failure.getMessage(); return message != null && message.contains(USE_PARAMETERS_MESSAGE) && isSpringException(failure); } private static boolean isSpringException(Throwable failure) { StackTraceElement[] elements = failure.getStackTrace(); return elements.length > 0 && isSpringClass(elements[0].getClassName()); } private static boolean isSpringClass(@Nullable String className) { return className != null && className.startsWith("org.springframework."); } private static FailureAnalysis getAnalysis(Throwable rootFailure, Throwable cause) { StringBuilder description = new StringBuilder(String.format("%s:%n", cause.getMessage())); if (rootFailure != cause) { description.append(String.format("%n Resulting Failure: %s", getExceptionTypeAndMessage(rootFailure))); } return new FailureAnalysis(description.toString(), ACTION, rootFailure); } private static String getExceptionTypeAndMessage(Throwable ex) { String message = ex.getMessage(); return ex.getClass().getName() + (StringUtils.hasText(message) ? ": " + message : ""); } static void appendPossibility(StringBuilder description) { if (!description.toString().endsWith(System.lineSeparator())) { description.append("%n".formatted()); } description.append("%n%s".formatted(POSSIBILITY)); } }
MissingParameterNamesFailureAnalyzer
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/hive/issues/Issue5430.java
{ "start": 958, "end": 9892 }
class ____ { private static final Log log = LogFactory.getLog(Issue5430.class); @Test public void test_createTable() throws Exception { DbType dbType = DbType.hive; int index = 0; for (String sql : new String[]{"Create table if not exists data01.test_20230830(a string ,b string) " + "PARTITIONED BY (load_date date, org string) ROW FORMAT DELIMITED NULL DEFINED AS '' STORED AS ORC", "Create table if not exists data01.test_20230830(a string ,b string) " + "PARTITIONED BY (load_date date, org string) ROW FORMAT DELIMITED NULL DEFINED AS \"\" STORED AS ORC", "Create table if not exists data01.test_20230830(a string ,b string) " + "PARTITIONED BY (load_date date, org string) ROW FORMAT DELIMITED NULL DEFINED AS 'aa' STORED AS ORC", "Create table if not exists data01.test_20230830(a string ,b string) " + "PARTITIONED BY (load_date date, org string) ROW FORMAT DELIMITED NULL DEFINED AS \"aa\" STORED AS ORC", "CREATE TABLE my_table(a string, b bigint)\n" + "ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe'\n" + "STORED AS TEXTFILE", "CREATE TABLE my_table(a string, b bigint)\n" + "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.JsonSerDe'\n" + "STORED AS TEXTFILE", "CREATE TABLE my_table(a string, b bigint) STORED AS JSONFILE", "create table table_name (\n" + " id int,\n" + " dtDontQuery string,\n" + " name string\n" + ")\n" + "partitioned by (date string)", "CREATE TABLE page_view(viewTime INT, userid BIGINT,\n" + " page_url STRING, referrer_url STRING,\n" + " ip STRING COMMENT 'IP Address of the User')\n" + " COMMENT 'This is the page view table'\n" + " PARTITIONED BY(dt STRING, country STRING)\n" + " STORED AS SEQUENCEFILE", "CREATE TABLE page_view(viewTime INT, userid BIGINT,\n" + " page_url STRING, referrer_url STRING,\n" + " ip STRING COMMENT 'IP Address of the User')\n" + " COMMENT 'This is the page view table'\n" + " PARTITIONED BY(dt STRING, country STRING)\n" + " ROW FORMAT DELIMITED\n" + " FIELDS TERMINATED BY '\\001'\n" + "STORED AS SEQUENCEFILE", "CREATE EXTERNAL TABLE page_view(viewTime INT, userid BIGINT,\n" + " page_url STRING, referrer_url STRING,\n" + " ip STRING COMMENT 'IP Address of the User',\n" + " country STRING COMMENT 'country of origination')\n" + " COMMENT 'This is the staging page view table'\n" + " ROW FORMAT DELIMITED FIELDS TERMINATED BY '\\054'\n" + " STORED AS TEXTFILE\n" + " LOCATION '<hdfs_location>'", "CREATE TABLE list_bucket_single (key STRING, value STRING)\n" + " SKEWED BY (key) ON (1,5,6) [STORED AS DIRECTORIES]", "CREATE TABLE list_bucket_multiple (col1 STRING, col2 int, col3 STRING)\n" + " SKEWED BY (col1, col2) ON (('s1',1), ('s3',3), ('s13',13), ('s78',78)) [STORED AS DIRECTORIES]", "CREATE TEMPORARY TABLE list_bucket_multiple (col1 STRING, col2 int, col3 STRING)", "CREATE TRANSACTIONAL TABLE transactional_table_test(key string, value string) PARTITIONED BY(ds string) STORED AS ORC", "create table pk(id1 integer, id2 integer,\n" + " primary key(id1, id2) disable novalidate)", "create table fk(id1 integer, id2 integer,\n" + " constraint c1 foreign key(id1, id2) references pk(id2, id1) disable novalidate)", "create table constraints1(id1 integer UNIQUE disable novalidate, id2 integer NOT NULL,\n" + " usr string DEFAULT current_user(), price double CHECK (price > 0 AND price <= 1000))", "create table constraints2(id1 integer, id2 integer,\n" + " constraint c1_unique UNIQUE(id1) disable novalidate)", "create table constraints3(id1 integer, id2 integer,\n" + " constraint c1_check CHECK(id1 + id2 > 0))", "CREATE TABLE apachelog (\n" + " host STRING,\n" + " identity STRING,\n" + " user STRING,\n" + " time STRING,\n" + " request STRING,\n" + " status STRING,\n" + " size STRING,\n" + " referer STRING,\n" + " agent STRING)\n" + "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'\n" + "WITH SERDEPROPERTIES (\n" + " \"input.regex\" = \"([^]*) ([^]*) ([^]*) (-|\\\\[^\\\\]*\\\\]) ([^ \\\"]*|\\\"[^\\\"]*\\\") (-|[0-9]*) (-|[0-9]*)(?: ([^ \\\"]*|\\\".*\\\") ([^ \\\"]*|\\\".*\\\"))?\"\n" + ")\n" + "STORED AS TEXTFILE;", "CREATE TABLE my_table(a string, b string)\n" + "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'\n" + "WITH SERDEPROPERTIES (\n" + " \"separatorChar\" = \"\\t\",\n" + " \"quoteChar\" = \"'\",\n" + " \"escapeChar\" = \"\\\\\"\n" + ") \n" + "STORED AS TEXTFILE", "CREATE TABLE new_key_value_store\n" + " ROW FORMAT SERDE \"org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe\"\n" + " STORED AS RCFile\n" + " AS\n" + "SELECT (key % 1024) new_key, concat(key, value) key_value_pair\n" + "FROM key_value_store\n" + "SORT BY new_key, key_value_pair", "CREATE TABLE page_view(viewTime INT, userid BIGINT,\n" + " page_url STRING, referrer_url STRING,\n" + " ip STRING COMMENT 'IP Address of the User')\n" + " COMMENT 'This is the page view table'\n" + " PARTITIONED BY(dt STRING, country STRING)\n" + " CLUSTERED BY(userid) SORTED BY(viewTime) INTO 32 BUCKETS\n" + " ROW FORMAT DELIMITED\n" + " FIELDS TERMINATED BY '\\001'\n" + " COLLECTION ITEMS TERMINATED BY '\\002'\n" + " MAP KEYS TERMINATED BY '\\003'\n" + " STORED AS SEQUENCEFILE", }) { index++; if (index >= 21) { continue; } String normalizeSql = normalizeSql(sql); System.out.println("第" + index + "条原始的sql格式归一化===" + normalizeSql); SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, dbType); SQLStatement statement = parser.parseStatement(); String newSql = statement.toString(); String normalizeNewSql = normalizeSql(newSql); System.out.println("第" + index + "条生成的sql格式归一化===" + normalizeNewSql); assertEquals(normalizeSql.toLowerCase(), normalizeNewSql.toLowerCase()); if (!normalizeSql.equalsIgnoreCase(normalizeNewSql)) { System.err.println("第" + index + "条是解析失败原始的sql===" + normalizeSql); } //assertTrue(newSql.equalsIgnoreCase(sql)); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(dbType); statement.accept(visitor); System.out.println("getTables==" + visitor.getTables()); Map<Name, TableStat> tableMap = visitor.getTables(); assertFalse(tableMap.isEmpty()); } } static String normalizeSql(String sql) { sql = StringUtils.replace(sql, " ( ", "("); sql = StringUtils.replace(sql, "( ", "("); sql = StringUtils.replace(sql, " )", ")"); sql = StringUtils.replace(sql, "\t", " "); sql = StringUtils.replace(sql, "\n", " "); sql = StringUtils.replace(sql, "\'", "\""); sql = StringUtils.replace(sql, " ( ", "("); sql = StringUtils.replace(sql, " (", "("); sql = StringUtils.replace(sql, "( ", "("); sql = StringUtils.replace(sql, " )", ")"); sql = StringUtils.replace(sql, "( ", "("); sql = StringUtils.replace(sql, " ", " "); sql = StringUtils.replace(sql, " ", " "); sql = StringUtils.replace(sql, " ", " "); sql = StringUtils.replace(sql, " ", " "); sql = StringUtils.replace(sql, "( ", "("); sql = StringUtils.replace(sql, ", ", ","); sql = StringUtils.replace(sql, " ,", ","); return sql; } }
Issue5430
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/persistent/PersistentTaskInitializationFailureIT.java
{ "start": 4479, "end": 5307 }
class ____ implements PersistentTaskParams { public FailingInitializationTaskParams() {} public FailingInitializationTaskParams(StreamInput in) throws IOException {} @Override public String getWriteableName() { return FailingInitializationPersistentTaskExecutor.TASK_NAME; } @Override public TransportVersion getMinimalSupportedVersion() { return TransportVersion.current(); } @Override public void writeTo(StreamOutput out) throws IOException {} @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.endObject(); return builder; } } static
FailingInitializationTaskParams
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/AWSUnsupportedFeatureException.java
{ "start": 1200, "end": 1586 }
class ____ extends AWSServiceIOException { /** * Instantiate. * @param operation operation which triggered this * @param cause the underlying cause */ public AWSUnsupportedFeatureException(String operation, AwsServiceException cause) { super(operation, cause); } @Override public boolean retryable() { return false; } }
AWSUnsupportedFeatureException
java
apache__camel
components/camel-undertow/src/test/java/org/apache/camel/component/undertow/spi/ProviderWithServletTest.java
{ "start": 1437, "end": 2373 }
class ____ extends AbstractProviderServletTest.MockSecurityProvider { @Override public boolean requireServletContext() { return true; } @Override void assertServletContext(ServletRequestContext servletRequestContext) { assertNotNull(servletRequestContext); } } @BeforeAll public static void initProvider() throws Exception { createSecurtyProviderConfigurationFile( org.apache.camel.component.undertow.spi.ProviderWithServletTest.MockSecurityProvider.class); } @Test public void test() throws Exception { getMockEndpoint("mock:input").expectedHeaderReceived(Exchange.HTTP_METHOD, "GET"); String out = template.requestBody("undertow:http://localhost:{{port}}/foo", null, String.class); assertEquals("user", out); MockEndpoint.assertIsSatisfied(context); } }
MockSecurityProvider
java
apache__dubbo
dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ServiceConfig.java
{ "start": 18709, "end": 19041 }
interface ____ mapping for service " + url.getServiceKey()); boolean succeeded = false; try { succeeded = serviceNameMapping.map(url); if (succeeded) { logger.info( "[INSTANCE_REGISTER][METADATA_REGISTER] Successfully registered
application
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/pkg/jar/ZipFileSystemArchiveCreator.java
{ "start": 599, "end": 6055 }
class ____ implements ArchiveCreator { private static final Path MANIFEST = Path.of("META-INF", "MANIFEST.MF"); // we probably don't need the Windows entry but let's be safe private static final Set<String> MANIFESTS = Set.of("META-INF/MANIFEST.MF", "META-INF\\MANIFEST.MF"); private final FileSystem zipFileSystem; private final Map<String, String> addedFiles = new HashMap<>(); public ZipFileSystemArchiveCreator(Path archivePath, boolean compressed, Instant entryTimestamp) { try { if (compressed) { zipFileSystem = ZipUtils.createNewReproducibleZipFileSystem(archivePath, entryTimestamp); } else { zipFileSystem = ZipUtils.createNewReproducibleZipFileSystem(archivePath, Map.of("compressionMethod", "STORED"), entryTimestamp); } } catch (IOException e) { throw new RuntimeException("Unable to initialize ZipFileSystem: " + archivePath, e); } } @Override public void addManifest(Manifest manifest) throws IOException { Path manifestInFsPath = zipFileSystem.getPath("META-INF", "MANIFEST.MF"); handleParentDirectories(manifestInFsPath, CURRENT_APPLICATION); try (final OutputStream os = Files.newOutputStream(manifestInFsPath)) { manifest.write(os); } } @Override public void addDirectory(String directory, String source) throws IOException { if (addedFiles.putIfAbsent(directory, source) != null) { return; } final Path targetInFsPath = zipFileSystem.getPath(directory); try { handleParentDirectories(targetInFsPath, source); Files.createDirectory(targetInFsPath); } catch (FileAlreadyExistsException e) { if (!Files.isDirectory(targetInFsPath)) { throw e; } } } @Override public void addFile(Path origin, String target, String source) throws IOException { if (MANIFESTS.contains(target)) { return; } if (addedFiles.putIfAbsent(target, source) != null) { return; } Path targetInFsPath = zipFileSystem.getPath(target); handleParentDirectories(targetInFsPath, source); Files.copy(origin, targetInFsPath, StandardCopyOption.REPLACE_EXISTING); } @Override public void addFile(byte[] bytes, String target, String source) throws IOException { if (MANIFESTS.contains(target)) { return; } Path targetInFsPath = zipFileSystem.getPath(target); handleParentDirectories(targetInFsPath, source); Files.write(targetInFsPath, bytes); addedFiles.put(target, source); } @Override public void addFileIfNotExists(Path origin, String target, String source) throws IOException { if (MANIFESTS.contains(target)) { return; } if (addedFiles.containsKey(target)) { return; } addFile(origin, target, source); } @Override public void addFileIfNotExists(byte[] bytes, String target, String source) throws IOException { if (MANIFESTS.contains(target)) { return; } if (addedFiles.containsKey(target)) { return; } addFile(bytes, target, source); } @Override public void addFile(List<byte[]> bytes, String target, String source) throws IOException { if (MANIFESTS.contains(target)) { return; } addFile(joinWithNewlines(bytes), target, source); } /** * Note: this method may only be used for Uberjars, for which we might need to amend the manifest at the end of the build. */ public boolean isMultiVersion() { return Files.isDirectory(zipFileSystem.getPath("META-INF", "versions")); } /** * Note: this method may only be used for Uberjars, for which we might need to amend the manifest at the end of the build. */ public void makeMultiVersion() throws IOException { final Path manifestPath = zipFileSystem.getPath("META-INF", "MANIFEST.MF"); final Manifest manifest = new Manifest(); // read the existing one try (final InputStream is = Files.newInputStream(manifestPath)) { manifest.read(is); } manifest.getMainAttributes().put(Attributes.Name.MULTI_RELEASE, "true"); try (final OutputStream os = Files.newOutputStream(manifestPath)) { manifest.write(os); } } private void handleParentDirectories(Path targetInFsPath, String source) throws IOException { if (targetInFsPath.getParent() != null) { Files.createDirectories(targetInFsPath.getParent()); } } private static byte[] joinWithNewlines(List<byte[]> lines) { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { for (byte[] line : lines) { out.write(line); out.write('\n'); } return out.toByteArray(); } catch (Exception e) { throw new RuntimeException("Error joining byte arrays", e); } } @Override public void close() { try { zipFileSystem.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } }
ZipFileSystemArchiveCreator
java
processing__processing4
java/libraries/io/src/processing/io/SoftwareServo.java
{ "start": 1486, "end": 4201 }
class ____ { public static final int DEFAULT_MIN_PULSE = 544; public static final int DEFAULT_MAX_PULSE = 2400; protected int pin = -1; // gpio number (-1 .. not attached) protected long handle = -1; // native thread id (<0 .. not started) protected int period = 20000; // 20 ms (50 Hz) protected int minPulse = 0; // minimum pulse width in microseconds protected int maxPulse = 0; // maximum pulse width in microseconds protected int pulse = 0; // current pulse in microseconds /** * Opens a servo motor * @param parent typically use "this" * @webref software_servo * @webBrief Opens a servo motor */ public SoftwareServo(PApplet parent) { NativeInterface.loadLibrary(); } /** * Closes a servo motor * */ public void close() { detach(); } protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } /** * Attaches a servo motor to a GPIO pin<br/> * <br/> * You must call this function before calling <b>write()</b>. Note that the servo motor * will only be instructed to move after the first time <b>write()</b> is called.<br/> * <br/> * The optional parameters <b>minPulse</b> and <b>maxPulse</b> control the minimum and maximum * pulse width durations. The default values, identical to those of Arduino's * Servo class, should be compatible with most servo motors. * * @param pin GPIO pin * @webref software_servo * @webBrief Attaches a servo motor to a GPIO pin */ public void attach(int pin) { detach(); this.pin = pin; this.minPulse = DEFAULT_MIN_PULSE; this.maxPulse = DEFAULT_MAX_PULSE; } /** * Attaches a servo motor to a GPIO pin<br/> * <br/> * You must call this function before calling <b>write()</b>. Note that the servo motor * will only be instructed to move after the first time <b>write()</b> is called.<br/> * <br/> * The optional parameters minPulse and maxPulse control the minimum and maximum * pulse width durations. The default values, identical to those of Arduino's * Servo class, should be compatible with most servo motors. * * @param minPulse minimum pulse width in microseconds (default: 544, same as on Arduino) * @param maxPulse maximum pulse width in microseconds (default: 2400, same as on Arduino) * @webref software_servo */ public void attach(int pin, int minPulse, int maxPulse) { detach(); this.pin = pin; this.minPulse = minPulse; this.maxPulse = maxPulse; } /** * Moves a servo motor to a given orientation<br/> * <br/> * If you are using this
SoftwareServo
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/factories/DefaultJobMasterServiceFactory.java
{ "start": 2274, "end": 6556 }
class ____ implements JobMasterServiceFactory { private final Executor executor; private final RpcService rpcService; private final JobMasterConfiguration jobMasterConfiguration; private ExecutionPlan executionPlan; private final HighAvailabilityServices haServices; private final SlotPoolServiceSchedulerFactory slotPoolServiceSchedulerFactory; private final JobManagerSharedServices jobManagerSharedServices; private final HeartbeatServices heartbeatServices; private final JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory; private final FatalErrorHandler fatalErrorHandler; private final ClassLoader userCodeClassloader; private final ShuffleMaster<?> shuffleMaster; private final Collection<FailureEnricher> failureEnrichers; private final long initializationTimestamp; public DefaultJobMasterServiceFactory( Executor executor, RpcService rpcService, JobMasterConfiguration jobMasterConfiguration, ExecutionPlan executionPlan, HighAvailabilityServices haServices, SlotPoolServiceSchedulerFactory slotPoolServiceSchedulerFactory, JobManagerSharedServices jobManagerSharedServices, HeartbeatServices heartbeatServices, JobManagerJobMetricGroupFactory jobManagerJobMetricGroupFactory, FatalErrorHandler fatalErrorHandler, ClassLoader userCodeClassloader, Collection<FailureEnricher> failureEnrichers, long initializationTimestamp) { this.executor = executor; this.rpcService = rpcService; this.jobMasterConfiguration = jobMasterConfiguration; this.executionPlan = executionPlan; this.haServices = haServices; this.slotPoolServiceSchedulerFactory = slotPoolServiceSchedulerFactory; this.jobManagerSharedServices = jobManagerSharedServices; this.heartbeatServices = heartbeatServices; this.jobManagerJobMetricGroupFactory = jobManagerJobMetricGroupFactory; this.fatalErrorHandler = fatalErrorHandler; this.userCodeClassloader = userCodeClassloader; this.shuffleMaster = jobManagerSharedServices.getShuffleMaster(); this.failureEnrichers = failureEnrichers; this.initializationTimestamp = initializationTimestamp; } @Override public CompletableFuture<JobMasterService> createJobMasterService( UUID leaderSessionId, OnCompletionActions onCompletionActions) { return CompletableFuture.supplyAsync( FunctionUtils.uncheckedSupplier( () -> internalCreateJobMasterService(leaderSessionId, onCompletionActions)), executor); } private JobMasterService internalCreateJobMasterService( UUID leaderSessionId, OnCompletionActions onCompletionActions) throws Exception { final JobMaster jobMaster = new JobMaster( rpcService, JobMasterId.fromUuidOrNull(leaderSessionId), jobMasterConfiguration, ResourceID.generate(), executionPlan, haServices, slotPoolServiceSchedulerFactory, jobManagerSharedServices, heartbeatServices, jobManagerJobMetricGroupFactory, onCompletionActions, fatalErrorHandler, userCodeClassloader, shuffleMaster, lookup -> new JobMasterPartitionTrackerImpl( executionPlan.getJobID(), shuffleMaster, lookup), new DefaultExecutionDeploymentTracker(), DefaultExecutionDeploymentReconciler::new, BlocklistUtils.loadBlocklistHandlerFactory( jobMasterConfiguration.getConfiguration()), failureEnrichers, initializationTimestamp); jobMaster.start(); return jobMaster; } }
DefaultJobMasterServiceFactory
java
apache__rocketmq
proxy/src/test/java/org/apache/rocketmq/proxy/service/cert/TlsCertificateManagerTest.java
{ "start": 2064, "end": 9583 }
class ____ { @Rule public TemporaryFolder tempDir = new TemporaryFolder(); private TlsCertificateManager manager; @Mock private TlsCertificateManager.TlsContextReloadListener listener1; @Mock private TlsCertificateManager.TlsContextReloadListener listener2; private File certFile; private File keyFile; private FileWatchService.Listener fileWatchListener; private Field configField; private ProxyConfig originalConfig; @Before public void setUp() throws Exception { ConfigurationManager.initEnv(); ConfigurationManager.intConfig(); // Create temporary certificate and key files certFile = tempDir.newFile("server.crt"); keyFile = tempDir.newFile("server.key"); try (FileWriter certWriter = new FileWriter(certFile); FileWriter keyWriter = new FileWriter(keyFile)) { certWriter.write("test certificate content"); keyWriter.write("test key content"); } // Set TlsSystemConfig paths TlsSystemConfig.tlsServerCertPath = certFile.getAbsolutePath(); TlsSystemConfig.tlsServerKeyPath = keyFile.getAbsolutePath(); // Create the TlsCertificateManager manager = new TlsCertificateManager(); // Extract the file watch listener using reflection fileWatchListener = extractFileWatchListener(manager); } @After public void tearDown() throws Exception { // Restore the original config if (configField != null && originalConfig != null) { configField.set(null, originalConfig); } } private FileWatchService.Listener extractFileWatchListener(TlsCertificateManager manager) throws Exception { Field fileWatchServiceField = TlsCertificateManager.class.getDeclaredField("fileWatchService"); fileWatchServiceField.setAccessible(true); FileWatchService fileWatchService = (FileWatchService) fileWatchServiceField.get(manager); Field listenerField = FileWatchService.class.getDeclaredField("listener"); listenerField.setAccessible(true); return (FileWatchService.Listener) listenerField.get(fileWatchService); } @Test public void testConstructor() { // The constructor should initialize the FileWatchService with the correct paths assertNotNull(manager); } @Test public void testStartAndShutdown() throws Exception { TlsCertificateManager managerSpy = spy(manager); Field watchServiceField = TlsCertificateManager.class.getDeclaredField("fileWatchService"); watchServiceField.setAccessible(true); FileWatchService watchService = (FileWatchService) watchServiceField.get(managerSpy); FileWatchService watchServiceSpy = spy(watchService); watchServiceField.set(managerSpy, watchServiceSpy); managerSpy.start(); verify(watchServiceSpy).start(); managerSpy.shutdown(); verify(watchServiceSpy).shutdown(); } @Test public void testRegisterAndUnregisterListener() { manager.registerReloadListener(listener1); List<TlsCertificateManager.TlsContextReloadListener> listeners = manager.getReloadListeners(); assertEquals(1, listeners.size()); assertTrue(listeners.contains(listener1)); manager.registerReloadListener(listener2); assertEquals(2, listeners.size()); assertTrue(listeners.contains(listener2)); manager.unregisterReloadListener(listener1); assertEquals(1, listeners.size()); assertFalse(listeners.contains(listener1)); assertTrue(listeners.contains(listener2)); manager.registerReloadListener(null); assertEquals(1, listeners.size()); // Should remain unchanged manager.unregisterReloadListener(null); assertEquals(1, listeners.size()); // Should remain unchanged } @Test public void testFileChangeNotification_CertOnly() throws Exception { manager.registerReloadListener(listener1); fileWatchListener.onChanged(certFile.getAbsolutePath()); verify(listener1, never()).onTlsContextReload(); } @Test public void testFileChangeNotification_KeyOnly() throws Exception { manager.registerReloadListener(listener1); fileWatchListener.onChanged(keyFile.getAbsolutePath()); verify(listener1, never()).onTlsContextReload(); } @Test public void testFileChangeNotification_BothFiles() throws Exception { manager.registerReloadListener(listener1); fileWatchListener.onChanged(certFile.getAbsolutePath()); fileWatchListener.onChanged(keyFile.getAbsolutePath()); verify(listener1, times(1)).onTlsContextReload(); } @Test public void testFileChangeNotification_MultipleListeners() throws Exception { manager.registerReloadListener(listener1); manager.registerReloadListener(listener2); fileWatchListener.onChanged(certFile.getAbsolutePath()); fileWatchListener.onChanged(keyFile.getAbsolutePath()); verify(listener1, times(1)).onTlsContextReload(); verify(listener2, times(1)).onTlsContextReload(); } @Test public void testFileChangeNotification_BothFilesReverseOrder() throws Exception { manager.registerReloadListener(listener1); fileWatchListener.onChanged(keyFile.getAbsolutePath()); fileWatchListener.onChanged(certFile.getAbsolutePath()); verify(listener1, times(1)).onTlsContextReload(); } @Test public void testFileChangeNotification_RepeatedChanges() throws Exception { manager.registerReloadListener(listener1); fileWatchListener.onChanged(certFile.getAbsolutePath()); fileWatchListener.onChanged(keyFile.getAbsolutePath()); verify(listener1, times(1)).onTlsContextReload(); fileWatchListener.onChanged(certFile.getAbsolutePath()); fileWatchListener.onChanged(keyFile.getAbsolutePath()); verify(listener1, times(2)).onTlsContextReload(); } @Test public void testFileChangeNotification_UnknownFile() throws Exception { manager.registerReloadListener(listener1); fileWatchListener.onChanged("/unknown/file/path"); verify(listener1, never()).onTlsContextReload(); } @Test public void testFileChangeNotification_ListenerThrowsException() throws Exception { TlsCertificateManager.TlsContextReloadListener exceptionListener = mock(TlsCertificateManager.TlsContextReloadListener.class); doThrow(new RuntimeException("Test exception")).when(exceptionListener).onTlsContextReload(); manager.registerReloadListener(exceptionListener); manager.registerReloadListener(listener1); fileWatchListener.onChanged(certFile.getAbsolutePath()); fileWatchListener.onChanged(keyFile.getAbsolutePath()); verify(exceptionListener, times(1)).onTlsContextReload(); verify(listener1, times(1)).onTlsContextReload(); } @Test public void testInnerCertKeyFileWatchListener() throws Exception { Class<?> innerClass = null; for (Class<?> clazz : TlsCertificateManager.class.getDeclaredClasses()) { if (clazz.getSimpleName().equals("CertKeyFileWatchListener")) { innerClass = clazz; break; } } assertNotNull(innerClass, "CertKeyFileWatchListener
TlsCertificateManagerTest
java
resilience4j__resilience4j
resilience4j-retry/src/main/java/io/github/resilience4j/retry/event/RetryEvent.java
{ "start": 1550, "end": 2056 }
enum ____ { /** * A RetryEvent which informs that a call has been tried, failed and will now be retried */ RETRY, /** * A RetryEvent which informs that a call has been retried, but still failed */ ERROR, /** * A RetryEvent which informs that a call has been successful */ SUCCESS, /** * A RetryEvent which informs that an error has been ignored */ IGNORED_ERROR } }
Type
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/TaskSegment.java
{ "start": 1200, "end": 2009 }
class ____ { // Can be both "LifeCycleTask" (clean/install) and "GoalTask" (org.mortbay.jetty:maven-jetty-plugin:6.1.19:run) private final List<Task> tasks; private final boolean aggregating; public TaskSegment(boolean aggregating) { this.aggregating = aggregating; tasks = new ArrayList<>(); } public TaskSegment(boolean aggregating, Task... tasks) { this.aggregating = aggregating; this.tasks = new ArrayList<>(Arrays.asList(tasks)); } @Override public String toString() { return getTasks().toString(); } public List<Task> getTasks() { return tasks; } public boolean isAggregating() { return aggregating; } // TODO Consider throwing UnsupportedSomething on hashCode/equals }
TaskSegment
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/windowing/functions/InternalIterableProcessAsyncWindowFunction.java
{ "start": 1703, "end": 3910 }
class ____<IN, OUT, KEY, W extends Window> extends WrappingFunction<ProcessWindowFunction<IN, OUT, KEY, W>> implements InternalAsyncWindowFunction<StateIterator<IN>, OUT, KEY, W> { private static final long serialVersionUID = 1L; public InternalIterableProcessAsyncWindowFunction( ProcessWindowFunction<IN, OUT, KEY, W> wrappedFunction) { super(wrappedFunction); } @Override public StateFuture<Void> process( KEY key, final W window, final InternalWindowContext context, StateIterator<IN> input, Collector<OUT> out) throws Exception { InternalProcessWindowContext<IN, OUT, KEY, W> ctx = new InternalProcessWindowContext<>(wrappedFunction); ctx.window = window; ctx.internalContext = context; List<IN> data = new ArrayList<>(); return input.onNext( (item) -> { data.add(item); }) .thenAccept( ignore -> { ProcessWindowFunction<IN, OUT, KEY, W> wrappedFunction = this.wrappedFunction; wrappedFunction.process(key, ctx, data, out); }); } @Override public StateFuture<Void> clear(final W window, final InternalWindowContext context) throws Exception { InternalProcessWindowContext<IN, OUT, KEY, W> ctx = new InternalProcessWindowContext<>(wrappedFunction); ctx.window = window; ctx.internalContext = context; ProcessWindowFunction<IN, OUT, KEY, W> wrappedFunction = this.wrappedFunction; wrappedFunction.clear(ctx); return StateFutureUtils.completedVoidFuture(); } @Override public RuntimeContext getRuntimeContext() { throw new RuntimeException("This should never be called."); } @Override public IterationRuntimeContext getIterationRuntimeContext() { throw new RuntimeException("This should never be called."); } }
InternalIterableProcessAsyncWindowFunction
java
spring-projects__spring-boot
module/spring-boot-web-server/src/testFixtures/java/org/springframework/boot/web/servlet/context/AbstractServletWebServerMvcIntegrationTests.java
{ "start": 2264, "end": 2455 }
class ____ integration testing of {@link ServletWebServerApplicationContext} and * {@link WebServer}s running Spring MVC. * * @author Phillip Webb * @author Ivan Sopov */ public abstract
for
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/MapOperationTests.java
{ "start": 1318, "end": 8093 }
class ____ { @BeforeEach public void createData(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityOfMaps entityContainingMaps = new EntityOfMaps( 1, "first-map-entity" ); entityContainingMaps.addBasicByBasic( "someKey", "someValue" ); entityContainingMaps.addBasicByBasic( "anotherKey", "anotherValue" ); entityContainingMaps.addSortedBasicByBasic( "key2", "value2" ); entityContainingMaps.addSortedBasicByBasic( "key1", "value1" ); entityContainingMaps.addSortedBasicByBasicWithComparator( "kEy1", "value1" ); entityContainingMaps.addSortedBasicByBasicWithComparator( "KeY2", "value2" ); entityContainingMaps.addSortedBasicByBasicWithSortNaturalByDefault( "key2", "value2" ); entityContainingMaps.addSortedBasicByBasicWithSortNaturalByDefault( "key1", "value1" ); entityContainingMaps.addBasicByEnum( EnumValue.ONE, "one" ); entityContainingMaps.addBasicByEnum( EnumValue.TWO, "two" ); entityContainingMaps.addBasicByConvertedEnum( EnumValue.THREE, "three" ); entityContainingMaps.addComponentByBasic( "the stuff", new SimpleComponent( "the stuff - 1", "the stuff - 2" ) ); entityContainingMaps.addComponentByBasic( "the other stuff", new SimpleComponent( "the other stuff - 1", "the other stuff - 2" ) ); session.persist( entityContainingMaps ); } ); } @AfterEach public void dropData(SessionFactoryScope scope, DomainModelScope domainModelScope) { // there is a problem with deleting entities which have basic collections. for some reason those // do not register as cascadable, so we do not delete the collection rows first scope.inTransaction( session -> { final EntityOfMaps entity = session.getReference( EntityOfMaps.class, 1 ); session.remove( entity ); } ); // uber hacky temp way: // TempDropDataHelper.cleanDatabaseSchema( scope, domainModelScope ); } @Test public void testSqmFetching(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityOfMaps entity = session.createQuery( "select e from EntityOfMaps e join fetch e.basicByEnum", EntityOfMaps.class ).getSingleResult(); assert Hibernate.isInitialized( entity.getBasicByEnum() ); assert entity.getBasicByEnum().size() == 2; } ); } @Test public void testDelete(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityOfMaps entity = session.createQuery( "select e from EntityOfMaps e join fetch e.basicByEnum", EntityOfMaps.class ).getSingleResult(); session.remove( entity ); } ); // re-create it so the drop-data can succeed createData( scope ); } @Test public void testSortedMapAccess(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityOfMaps entity = session.get( EntityOfMaps.class, 1 ); assertThat( entity.getSortedBasicByBasic(), InitializationCheckMatcher.isNotInitialized() ); // trigger the init Hibernate.initialize( entity.getSortedBasicByBasic() ); assertThat( entity.getSortedBasicByBasic(), InitializationCheckMatcher.isInitialized() ); assertThat( entity.getSortedBasicByBasic().size(), is( 2 ) ); assertThat( entity.getBasicByEnum(), InitializationCheckMatcher.isNotInitialized() ); final Iterator<Map.Entry<String, String>> iterator = entity.getSortedBasicByBasic().entrySet().iterator(); final Map.Entry<String, String> first = iterator.next(); final Map.Entry<String, String> second = iterator.next(); assertThat( first.getKey(), is( "key1" ) ); assertThat( first.getValue(), is( "value1" ) ); assertThat( second.getKey(), is( "key2" ) ); assertThat( second.getValue(), is( "value2" ) ); } ); } @Test public void testSortedMapWithComparatorAccess(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityOfMaps entity = session.get( EntityOfMaps.class, 1 ); assertThat( entity.getSortedBasicByBasicWithComparator(), InitializationCheckMatcher.isNotInitialized() ); // trigger the init Hibernate.initialize( entity.getSortedBasicByBasicWithComparator() ); assertThat( entity.getSortedBasicByBasicWithComparator(), InitializationCheckMatcher.isInitialized() ); assertThat( entity.getSortedBasicByBasicWithComparator().size(), is( 2 ) ); assertThat( entity.getBasicByEnum(), InitializationCheckMatcher.isNotInitialized() ); final Iterator<Map.Entry<String, String>> iterator = entity.getSortedBasicByBasicWithComparator().entrySet().iterator(); final Map.Entry<String, String> first = iterator.next(); final Map.Entry<String, String> second = iterator.next(); assertThat( first.getKey(), is( "kEy1" ) ); assertThat( first.getValue(), is( "value1" ) ); assertThat( second.getKey(), is( "KeY2" ) ); assertThat( second.getValue(), is( "value2" ) ); } ); } @Test public void testSortedMapWithSortNaturalByDefaultAccess(SessionFactoryScope scope) { scope.inTransaction( session -> { final EntityOfMaps entity = session.get( EntityOfMaps.class, 1 ); assertThat( entity.getSortedBasicByBasicWithSortNaturalByDefault(), InitializationCheckMatcher.isNotInitialized() ); // trigger the init Hibernate.initialize( entity.getSortedBasicByBasicWithSortNaturalByDefault() ); assertThat( entity.getSortedBasicByBasicWithSortNaturalByDefault(), InitializationCheckMatcher.isInitialized() ); assertThat( entity.getSortedBasicByBasicWithSortNaturalByDefault().size(), is( 2 ) ); assertThat( entity.getBasicByEnum(), InitializationCheckMatcher.isNotInitialized() ); final Iterator<Map.Entry<String, String>> iterator = entity.getSortedBasicByBasicWithSortNaturalByDefault().entrySet().iterator(); final Map.Entry<String, String> first = iterator.next(); final Map.Entry<String, String> second = iterator.next(); assertThat( first.getKey(), is( "key1" ) ); assertThat( first.getValue(), is( "value1" ) ); assertThat( second.getKey(), is( "key2" ) ); assertThat( second.getValue(), is( "value2" ) ); } ); } @Test public void testOrderedMap(SessionFactoryScope scope) { // atm we can only check the fragment translation final CollectionPersister collectionDescriptor = scope.getSessionFactory() .getRuntimeMetamodels() .getMappingMetamodel() .findCollectionDescriptor( EntityOfMaps.class.getName() + ".componentByBasicOrdered" ); assertThat( collectionDescriptor.getAttributeMapping().getOrderByFragment(), notNullValue() ); scope.inTransaction( session -> session.createQuery( "from EntityOfMaps e join fetch e.componentByBasicOrdered" ).list() ); } }
MapOperationTests
java
quarkusio__quarkus
extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/AdapterTest.java
{ "start": 2925, "end": 3082 }
class ____ { public String street; public String city; public String province; public String code; } public static
Home
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/delegation/Planner.java
{ "start": 1372, "end": 2546 }
interface ____ two purposes: * * <ul> * <li>SQL parser via {@link #getParser()} - transforms a SQL string into a Table API specific * objects e.g. tree of {@link Operation}s * <li>relational planner - provides a way to plan, optimize and transform tree of {@link * ModifyOperation} into a runnable form ({@link Transformation}) * </ul> * * <p>The Planner is execution agnostic. It is up to the {@link * org.apache.flink.table.api.TableEnvironment} to ensure that if any of the {@link QueryOperation} * pull any runtime configuration, all those configurations are equivalent. Example: If some of the * {@link QueryOperation}s scan DataStreams, all those DataStreams must come from the same * StreamExecutionEnvironment, because the result of {@link Planner#translate(List)} will strip any * execution configuration from the DataStream information. * * <p>All Tables referenced in either {@link Parser#parse(String)} or {@link * Planner#translate(List)} should be previously registered in a {@link * org.apache.flink.table.catalog.CatalogManager}, which will be provided during instantiation of * the {@link Planner}. */ @Internal public
serves
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/webmonitor/TestingExecutionGraphCache.java
{ "start": 2730, "end": 4236 }
class ____ { private IntSupplier sizeSupplier = () -> 0; private BiFunction<JobID, RestfulGateway, CompletableFuture<ExecutionGraphInfo>> getExecutionGraphFunction = (ignoredA, ignoredB) -> FutureUtils.completedExceptionally( new UnsupportedOperationException()); private Runnable cleanupRunnable = () -> {}; private Runnable closeRunnable = () -> {}; private Builder() {} public Builder setSizeSupplier(IntSupplier sizeSupplier) { this.sizeSupplier = sizeSupplier; return this; } public Builder setGetExecutionGraphFunction( BiFunction<JobID, RestfulGateway, CompletableFuture<ExecutionGraphInfo>> getExecutionGraphFunction) { this.getExecutionGraphFunction = getExecutionGraphFunction; return this; } public Builder setCleanupRunnable(Runnable cleanupRunnable) { this.cleanupRunnable = cleanupRunnable; return this; } public Builder setCloseRunnable(Runnable closeRunnable) { this.closeRunnable = closeRunnable; return this; } public TestingExecutionGraphCache build() { return new TestingExecutionGraphCache( sizeSupplier, getExecutionGraphFunction, cleanupRunnable, closeRunnable); } } }
Builder
java
google__gson
gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java
{ "start": 10348, "end": 10557 }
class ____ { final String firstName; final String lastName; User(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } } private static
User
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/launcher/ServiceLauncher.java
{ "start": 13029, "end": 13157 }
class ____ load but it isn't actually * a subclass of {@link Configuration}. * @throws ExitUtil.ExitException if a loaded
does
java
quarkusio__quarkus
integration-tests/smallrye-graphql/src/main/java/io/quarkus/it/smallrye/graphql/Salutation.java
{ "start": 57, "end": 117 }
class ____ { public abstract String getType(); }
Salutation
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/http/codec/multipart/FileStorageTests.java
{ "start": 1038, "end": 2244 }
class ____ { @Test void fromPath() throws IOException { Path path = Files.createTempFile("spring", "test"); FileStorage storage = FileStorage.fromPath(path); Mono<Path> directory = storage.directory(); StepVerifier.create(directory) .expectNext(path) .verifyComplete(); } @Test void tempDirectory() { FileStorage storage = FileStorage.tempDirectory(Schedulers::boundedElastic); Mono<Path> directory = storage.directory(); StepVerifier.create(directory) .consumeNextWith(path -> { assertThat(path).exists(); StepVerifier.create(directory) .expectNext(path) .verifyComplete(); }) .verifyComplete(); } @Test void tempDirectoryDeleted() { FileStorage storage = FileStorage.tempDirectory(Schedulers::boundedElastic); Mono<Path> directory = storage.directory(); StepVerifier.create(directory) .consumeNextWith(path1 -> { try { Files.delete(path1); StepVerifier.create(directory) .consumeNextWith(path2 -> assertThat(path2).isNotEqualTo(path1)) .verifyComplete(); } catch (IOException ex) { throw new UncheckedIOException(ex); } }) .verifyComplete(); } }
FileStorageTests
java
spring-projects__spring-boot
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/jar/JarFileUrlKey.java
{ "start": 855, "end": 2012 }
class ____ { private final String protocol; private final String host; private final int port; private final String file; private final boolean runtimeRef; JarFileUrlKey(URL url) { this.protocol = url.getProtocol(); this.host = url.getHost(); this.port = (url.getPort() != -1) ? url.getPort() : url.getDefaultPort(); this.file = url.getFile(); this.runtimeRef = "runtime".equals(url.getRef()); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } JarFileUrlKey other = (JarFileUrlKey) obj; // We check file first as case sensitive and the most likely item to be different return Objects.equals(this.file, other.file) && equalsIgnoringCase(this.protocol, other.protocol) && equalsIgnoringCase(this.host, other.host) && (this.port == other.port) && (this.runtimeRef == other.runtimeRef); } @Override public int hashCode() { return Objects.hashCode(this.file); } private boolean equalsIgnoringCase(String s1, String s2) { return (s1 == s2) || (s1 != null && s1.equalsIgnoreCase(s2)); } }
JarFileUrlKey
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/ApplicationPathTest.java
{ "start": 527, "end": 1127 }
class ____ { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(TestApplication.class, HelloResource.class); } }); @Test public void helloTest() { RestAssured.get("/app/hello") .then().body(Matchers.equalTo("hello")); } @ApplicationPath("app") public static
ApplicationPathTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/tasks/mailbox/MailboxExecutorImplTest.java
{ "start": 7721, "end": 8249 }
class ____ implements RunnableWithException { private Thread executedByThread = null; @Override public void run() { Preconditions.checkState( !isExecuted(), "Runnable was already executed before by " + executedByThread); executedByThread = Thread.currentThread(); } boolean isExecuted() { return executedByThread != null; } Thread wasExecutedBy() { return executedByThread; } } }
TestRunnable
java
quarkusio__quarkus
core/builder/src/main/java/io/quarkus/builder/json/JsonObject.java
{ "start": 171, "end": 865 }
class ____ implements JsonMultiValue { private final Map<JsonString, JsonValue> value; public JsonObject(Map<JsonString, JsonValue> value) { this.value = value; } @SuppressWarnings("unchecked") public <T extends JsonValue> T get(String attribute) { return (T) value.get(new JsonString(attribute)); } public List<JsonMember> members() { return value.entrySet().stream() .map(e -> new JsonMember(e.getKey(), e.getValue())) .collect(Collectors.toList()); } @Override public void forEach(JsonTransform transform) { members().forEach(member -> transform.accept(null, member)); } }
JsonObject
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/bean/priority/BeanHasPriorityTest.java
{ "start": 579, "end": 2252 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(NoPriority.class, ExplicitPriority0.class, ExplicitPriority1.class, Producers.class); @Test public void test() throws IOException { InjectableBean<?> bean = Arc.container().instance(NoPriority.class).getBean(); assertFalse(bean.hasPriority()); assertEquals(0, bean.getPriority()); bean = Arc.container().instance(ExplicitPriority0.class).getBean(); assertTrue(bean.hasPriority()); assertEquals(0, bean.getPriority()); bean = Arc.container().instance(ExplicitPriority1.class).getBean(); assertTrue(bean.hasPriority()); assertEquals(1, bean.getPriority()); bean = Arc.container().instance(Foo.class).getBean(); assertFalse(bean.hasPriority()); assertEquals(0, bean.getPriority()); bean = Arc.container().instance(Bar.class).getBean(); assertTrue(bean.hasPriority()); assertEquals(0, bean.getPriority()); bean = Arc.container().instance(Baz.class).getBean(); assertTrue(bean.hasPriority()); assertEquals(1, bean.getPriority()); bean = Arc.container().instance(Qux.class).getBean(); assertFalse(bean.hasPriority()); assertEquals(0, bean.getPriority()); bean = Arc.container().instance(Quux.class).getBean(); assertTrue(bean.hasPriority()); assertEquals(0, bean.getPriority()); bean = Arc.container().instance(Quuux.class).getBean(); assertTrue(bean.hasPriority()); assertEquals(1, bean.getPriority()); } static
BeanHasPriorityTest
java
playframework__playframework
web/play-java-forms/src/test/java/play/data/LegacyUser.java
{ "start": 484, "end": 614 }
class ____ implements Validatable<String> { @Override public String validate() { return "Some global error"; } }
LegacyUser
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/condition/DisabledForJreRange.java
{ "start": 1780, "end": 3800 }
class ____ being * instantiated, and it does not prevent the execution of class-level lifecycle * callbacks such as {@code @BeforeAll} methods, {@code @AfterAll} methods, and * corresponding extension APIs. * * <p>This annotation may be used as a meta-annotation in order to create a * custom <em>composed annotation</em> that inherits the semantics of this * annotation. * * <h2>Warning</h2> * * <p>This annotation can only be declared once on an * {@link java.lang.reflect.AnnotatedElement AnnotatedElement} (i.e., test * interface, test class, or test method). If this annotation is directly * present, indirectly present, or meta-present multiple times on a given * element, only the first such annotation discovered by JUnit will be used; * any additional declarations will be silently ignored. Note, however, that * this annotation may be used in conjunction with other {@code @Enabled*} or * {@code @Disabled*} annotations in this package. * * @since 5.6 * @see JRE * @see org.junit.jupiter.api.condition.EnabledIf * @see org.junit.jupiter.api.condition.DisabledIf * @see org.junit.jupiter.api.condition.EnabledOnOs * @see org.junit.jupiter.api.condition.DisabledOnOs * @see org.junit.jupiter.api.condition.EnabledOnJre * @see org.junit.jupiter.api.condition.DisabledOnJre * @see org.junit.jupiter.api.condition.EnabledForJreRange * @see org.junit.jupiter.api.condition.EnabledInNativeImage * @see org.junit.jupiter.api.condition.DisabledInNativeImage * @see org.junit.jupiter.api.condition.EnabledIfSystemProperty * @see org.junit.jupiter.api.condition.DisabledIfSystemProperty * @see org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable * @see org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable * @see org.junit.jupiter.api.Disabled */ @Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @ExtendWith(DisabledForJreRangeCondition.class) @API(status = STABLE, since = "5.6") @SuppressWarnings("exports") public @
from
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/configuration/ClassToBeMocked.java
{ "start": 173, "end": 233 }
class ____ mock that is created via Class.forClass */ public
to
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/net/DNS.java
{ "start": 7946, "end": 8338 }
interface ____ invalid */ public static String getDefaultIP(String strInterface) throws UnknownHostException { String[] ips = getIPs(strInterface); return ips[0]; } /** * Returns all the host names associated by the provided nameserver with the * address bound to the specified network interface * * @param strInterface * The name of the network
is
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/manytomany/mapkey/ManyToManyWithMaykeyAndSchemaDefinitionTest.java
{ "start": 2546, "end": 3240 }
class ____ { @Id private Long id; private String name; @ManyToMany @MapKey(name = "id") @JoinTable(name = "entitya_entityb", schema = "myschema", joinColumns = @JoinColumn(name = "entitya_pk"), inverseJoinColumns = @JoinColumn(name = "entityb_pk")) private Map<String, EntityB> entityBMap = new HashMap<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public void setEntityBs(String key, EntityB entityB) { this.entityBMap.put( key, entityB ); } public Map<String, EntityB> getEntityBMap() { return entityBMap; } } @Entity(name = "EntityB") @Table(name = "entityb", schema = "myschema") public static
EntityA
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/JsonTypeInfoIgnored2968Test.java
{ "start": 1435, "end": 1501 }
class ____ { public int size = 3; } static
SimpleBall
java
micronaut-projects__micronaut-core
core-reactive/src/main/java/io/micronaut/core/async/publisher/AsyncSingleResultPublisher.java
{ "start": 2115, "end": 4118 }
class ____<S> implements Subscription { private final Subscriber<? super S> subscriber; private final ExecutorService executor; private final Supplier<S> supplier; private Future<?> future; // to allow cancellation private boolean completed; /** * Constructor. * * @param subscriber subscriber * @param supplier supplier * @param executor executor */ ExecutorServiceSubscription(Subscriber<? super S> subscriber, Supplier<S> supplier, ExecutorService executor) { this.subscriber = subscriber; this.supplier = supplier; this.executor = executor; } /** * Request execution. * * @param n request number */ @Override public synchronized void request(long n) { if (n != 0 && !completed) { completed = true; if (n < 0) { IllegalArgumentException ex = new IllegalArgumentException(); executor.execute(() -> subscriber.onError(ex)); } else { future = executor.submit(() -> { try { S value = supplier.get(); if (value != null) { subscriber.onNext(value); } subscriber.onComplete(); } catch (Exception e) { subscriber.onError(e); } }); } } } /** * Cancel. */ @Override public synchronized void cancel() { completed = true; if (future != null) { future.cancel(false); } } } }
ExecutorServiceSubscription
java
google__dagger
javatests/dagger/android/processor/ContributesAndroidInjectorTest.java
{ "start": 4137, "end": 4484 }
class ____<T> extends Activity {}"); Source module = CompilerTests.javaSource( "test.TestModule", "package test;", "", "import dagger.Module;", "import dagger.android.ContributesAndroidInjector;", "", "@Module", "abstract
ParameterizedActivity
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ser/bean/BeanAsArraySerializer.java
{ "start": 1748, "end": 11653 }
class ____ extends BeanSerializerBase { /** * Serializer that would produce JSON Object version; used in * cases where array output cannot be used. */ protected final BeanSerializerBase _defaultSerializer; /* /********************************************************************** /* Life-cycle: constructors /********************************************************************** */ public BeanAsArraySerializer(BeanSerializerBase src) { super(src, (ObjectIdWriter) null); _defaultSerializer = src; } protected BeanAsArraySerializer(BeanSerializerBase src, Set<String> toIgnore, Set<String> toInclude) { super(src, toIgnore, toInclude); _defaultSerializer = src; } protected BeanAsArraySerializer(BeanSerializerBase src, ObjectIdWriter oiw, Object filterId) { super(src, oiw, filterId); _defaultSerializer = src; } /* /********************************************************************** /* Life-cycle: factory methods, fluent factories /********************************************************************** */ /** * @since 3.0 */ public static BeanSerializerBase construct(BeanSerializerBase src) { BeanSerializerBase ser = UnrolledBeanAsArraySerializer.tryConstruct(src); if (ser != null) { return ser; } return new BeanAsArraySerializer(src); } @Override public ValueSerializer<Object> unwrappingSerializer(NameTransformer transformer) { // If this gets called, we will just need delegate to the default // serializer, to "undo" as-array serialization return _defaultSerializer.unwrappingSerializer(transformer); } @Override public boolean isUnwrappingSerializer() { return false; } @Override public BeanSerializerBase withObjectIdWriter(ObjectIdWriter objectIdWriter) { // can't handle Object Ids, for now, so: return _defaultSerializer.withObjectIdWriter(objectIdWriter); } @Override public BeanSerializerBase withFilterId(Object filterId) { return new BeanAsArraySerializer(this, _objectIdWriter, filterId); } @Override protected BeanAsArraySerializer withByNameInclusion(Set<String> toIgnore, Set<String> toInclude) { return new BeanAsArraySerializer(this, toIgnore, toInclude); } @Override // @since 2.11.1 protected BeanSerializerBase withProperties(BeanPropertyWriter[] properties, BeanPropertyWriter[] filteredProperties) { // 16-Jun-2020, tatu: Added for [databind#2759] but with as-array we // probably do not want to reorder anything; so actually leave unchanged return this; } @Override protected BeanSerializerBase asArraySerializer() { // already is one, so: return this; } /* /********************************************************************** /* ValueSerializer implementation that differs between impls /********************************************************************** */ // Re-defined from base class, due to differing prefixes @Override public void serializeWithType(Object bean, JsonGenerator gen, SerializationContext ctxt, TypeSerializer typeSer) throws JacksonException { // 10-Dec-2014, tatu: Not sure if this can be made to work reliably; // but for sure delegating to default implementation will not work. So: if (_objectIdWriter != null) { _serializeWithObjectId(bean, gen, ctxt, typeSer); return; } gen.assignCurrentValue(bean); WritableTypeId typeIdDef = _typeIdDef(typeSer, bean, JsonToken.START_ARRAY); typeSer.writeTypePrefix(gen, ctxt, typeIdDef); final boolean filtered = (_filteredProps != null && ctxt.getActiveView() != null); if (filtered) { serializeFiltered(bean, gen, ctxt); } else { serializeNonFiltered(bean, gen, ctxt); } typeSer.writeTypeSuffix(gen, ctxt, typeIdDef); } /** * Main serialization method that will delegate actual output to * configured * {@link BeanPropertyWriter} instances. */ @Override public final void serialize(Object bean, JsonGenerator gen, SerializationContext provider) throws JacksonException { final boolean filtered = (_filteredProps != null && provider.getActiveView() != null); if (provider.isEnabled(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED) && hasSingleElement(provider)) { if (filtered) serializeFiltered(bean, gen, provider); else serializeNonFiltered(bean, gen, provider); return; } // note: it is assumed here that limitations (type id, object id, // any getter, filtering) have already been checked; so code here // is trivial. gen.writeStartArray(bean, _props.length); if (filtered) serializeFiltered(bean, gen, provider); else serializeNonFiltered(bean, gen, provider); gen.writeEndArray(); } /* /********************************************************************** /* Property serialization methods /********************************************************************** */ private boolean hasSingleElement(SerializationContext provider) { return _props.length == 1; } protected final void serializeNonFiltered(Object bean, JsonGenerator gen, SerializationContext provider) throws JacksonException { final BeanPropertyWriter[] props = _props; int i = 0; int left = props.length; BeanPropertyWriter prop = null; try { if (left > 3) { do { prop = props[i]; prop.serializeAsElement(bean, gen, provider); prop = props[i+1]; prop.serializeAsElement(bean, gen, provider); prop = props[i+2]; prop.serializeAsElement(bean, gen, provider); prop = props[i+3]; prop.serializeAsElement(bean, gen, provider); left -= 4; i += 4; } while (left > 3); } switch (left) { case 3: prop = props[i++]; prop.serializeAsElement(bean, gen, provider); case 2: prop = props[i++]; prop.serializeAsElement(bean, gen, provider); case 1: prop = props[i++]; prop.serializeAsElement(bean, gen, provider); } // NOTE: any getters cannot be supported either //if (_anyGetterWriter != null) { // _anyGetterWriter.getAndSerialize(bean, gen, provider); //} } catch (Exception e) { wrapAndThrow(provider, e, bean, prop.getName()); } catch (StackOverflowError e) { throw DatabindException.from(gen, "Infinite recursion (StackOverflowError)", e) .prependPath(bean, prop.getName()); } } protected final void serializeFiltered(Object bean, JsonGenerator gen, SerializationContext provider) throws JacksonException { final BeanPropertyWriter[] props = _filteredProps; int i = 0; int left = props.length; BeanPropertyWriter prop = null; try { if (left > 3) { do { prop = props[i]; if (prop == null) { // can have nulls in filtered list; but if so, MUST write placeholders gen.writeNull(); } else { prop.serializeAsElement(bean, gen, provider); } prop = props[i+1]; if (prop == null) { gen.writeNull(); } else { prop.serializeAsElement(bean, gen, provider); } prop = props[i+2]; if (prop == null) { gen.writeNull(); } else { prop.serializeAsElement(bean, gen, provider); } prop = props[i+3]; if (prop == null) { gen.writeNull(); } else { prop.serializeAsElement(bean, gen, provider); } left -= 4; i += 4; } while (left > 3); } switch (left) { case 3: prop = props[i++]; if (prop == null) { gen.writeNull(); } else { prop.serializeAsElement(bean, gen, provider); } case 2: prop = props[i++]; if (prop == null) { gen.writeNull(); } else { prop.serializeAsElement(bean, gen, provider); } case 1: prop = props[i++]; if (prop == null) { gen.writeNull(); } else { prop.serializeAsElement(bean, gen, provider); } } } catch (Exception e) { wrapAndThrow(provider, e, bean, prop.getName()); } catch (StackOverflowError e) { throw DatabindException.from(gen, "Infinite recursion (StackOverflowError)", e) .prependPath(bean, prop.getName()); } } }
BeanAsArraySerializer
java
quarkusio__quarkus
extensions/reactive-pg-client/deployment/src/test/java/io/quarkus/reactive/pg/client/ChangingCredentialsTestResource.java
{ "start": 465, "end": 1153 }
class ____ { @Inject Pool client; @Inject ChangingCredentialsProvider credentialsProvider; void addUser(@Observes StartupEvent ignored) { client.query("CREATE USER user2 WITH PASSWORD 'user2' SUPERUSER").executeAndAwait(); } @GET @Produces(MediaType.TEXT_PLAIN) public Uni<Response> connect() { return client.query("SELECT CURRENT_USER").execute() .map(pgRowSet -> { assertEquals(1, pgRowSet.size()); return Response.ok(pgRowSet.iterator().next().getString(0)).build(); }).eventually(credentialsProvider::changeProperties); } }
ChangingCredentialsTestResource