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
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/tofix/ExternalTypeCustomResolver1288Test.java
{ "start": 13517, "end": 14992 }
class ____ { private FormOfPayment formOfPayment; private PaymentDetails paymentDetails; public PaymentMean build() { return new PaymentMean (this.formOfPayment, this.paymentDetails); } // if you annotate with @JsonIgnore, it works, but the value // disappears in the constructor public Builder formOfPayment(final FormOfPayment val) { this.formOfPayment = val; return this; } @JsonTypeInfo (use = JsonTypeInfo.Id.CUSTOM, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "form_of_payment", visible = true) @JsonTypeIdResolver (PaymentDetailsTypeIdResolver.class) public Builder paymentDetails(final PaymentDetails val) { this.paymentDetails = val; return this; } } public static Builder create() { return new Builder(); } protected final FormOfPayment formOfPayment; protected final PaymentDetails paymentDetails; PaymentMean(final FormOfPayment formOfPayment, final PaymentDetails paymentDetails) { super (); this.formOfPayment = formOfPayment; this.paymentDetails = paymentDetails; } } public static
Builder
java
quarkusio__quarkus
extensions/container-image/container-image-docker-common/deployment/src/test/java/io/quarkus/container/image/docker/common/deployment/RedHatOpenJDKRuntimeBaseProviderTest.java
{ "start": 883, "end": 2437 }
class ____ { private final DockerFileBaseInformationProvider sut = new RedHatOpenJDKRuntimeBaseProvider(); @ParameterizedTest(name = DISPLAY_NAME_PLACEHOLDER + "[" + INDEX_PLACEHOLDER + "] (" + ARGUMENTS_WITH_NAMES_PLACEHOLDER + ")") @MethodSource("imageCombinations") void testImage(int javaVersion, int ubiVersion, String imageVersion) { var path = getPath("ubi%d-openjdk-%d-runtime".formatted(ubiVersion, javaVersion)); var result = sut.determine(path); assertThat(result) .isNotNull() .get() .extracting( DockerFileBaseInformation::baseImage, DockerFileBaseInformation::javaVersion) .containsExactly( "registry.access.redhat.com/ubi%d/openjdk-%d-runtime:%s".formatted(ubiVersion, javaVersion, imageVersion), javaVersion); } static Stream<Arguments> imageCombinations() { return Stream.of( Arguments.of(17, 8, ContainerImages.UBI8_JAVA_VERSION), Arguments.of(21, 8, ContainerImages.UBI8_JAVA_VERSION), Arguments.of(17, 9, ContainerImages.UBI8_JAVA_VERSION), Arguments.of(21, 9, ContainerImages.UBI8_JAVA_VERSION)); } @Test void testUnhandled() { Path path = getPath("ubi8-java17"); var result = sut.determine(path); assertThat(result).isEmpty(); } }
RedHatOpenJDKRuntimeBaseProviderTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LogEndpointBuilderFactory.java
{ "start": 1591, "end": 33779 }
interface ____ extends EndpointProducerBuilder { default AdvancedLogEndpointBuilder advanced() { return (AdvancedLogEndpointBuilder) this; } /** * If true, will hide stats when no new messages have been received for * a time interval, if false, show stats regardless of message traffic. * * The option is a: <code>boolean</code> type. * * Default: true * Group: producer * * @param groupActiveOnly the value to set * @return the dsl builder */ default LogEndpointBuilder groupActiveOnly(boolean groupActiveOnly) { doSetProperty("groupActiveOnly", groupActiveOnly); return this; } /** * If true, will hide stats when no new messages have been received for * a time interval, if false, show stats regardless of message traffic. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: producer * * @param groupActiveOnly the value to set * @return the dsl builder */ default LogEndpointBuilder groupActiveOnly(String groupActiveOnly) { doSetProperty("groupActiveOnly", groupActiveOnly); return this; } /** * Set the initial delay for stats (in millis). * * The option is a: <code>java.lang.Long</code> type. * * Group: producer * * @param groupDelay the value to set * @return the dsl builder */ default LogEndpointBuilder groupDelay(Long groupDelay) { doSetProperty("groupDelay", groupDelay); return this; } /** * Set the initial delay for stats (in millis). * * The option will be converted to a <code>java.lang.Long</code> type. * * Group: producer * * @param groupDelay the value to set * @return the dsl builder */ default LogEndpointBuilder groupDelay(String groupDelay) { doSetProperty("groupDelay", groupDelay); return this; } /** * If specified will group message stats by this time interval (in * millis). * * The option is a: <code>java.lang.Long</code> type. * * Group: producer * * @param groupInterval the value to set * @return the dsl builder */ default LogEndpointBuilder groupInterval(Long groupInterval) { doSetProperty("groupInterval", groupInterval); return this; } /** * If specified will group message stats by this time interval (in * millis). * * The option will be converted to a <code>java.lang.Long</code> type. * * Group: producer * * @param groupInterval the value to set * @return the dsl builder */ default LogEndpointBuilder groupInterval(String groupInterval) { doSetProperty("groupInterval", groupInterval); return this; } /** * An integer that specifies a group size for throughput logging. * * The option is a: <code>java.lang.Integer</code> type. * * Group: producer * * @param groupSize the value to set * @return the dsl builder */ default LogEndpointBuilder groupSize(Integer groupSize) { doSetProperty("groupSize", groupSize); return this; } /** * An integer that specifies a group size for throughput logging. * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Group: producer * * @param groupSize the value to set * @return the dsl builder */ default LogEndpointBuilder groupSize(String groupSize) { doSetProperty("groupSize", groupSize); return this; } /** * Logging level to use. The default value is INFO. * * The option is a: <code>java.lang.String</code> type. * * Default: INFO * Group: producer * * @param level the value to set * @return the dsl builder */ default LogEndpointBuilder level(String level) { doSetProperty("level", level); return this; } /** * If true, mask sensitive information like password or passphrase in * the log. * * The option is a: <code>java.lang.Boolean</code> type. * * Default: false * Group: producer * * @param logMask the value to set * @return the dsl builder */ default LogEndpointBuilder logMask(Boolean logMask) { doSetProperty("logMask", logMask); return this; } /** * If true, mask sensitive information like password or passphrase in * the log. * * The option will be converted to a <code>java.lang.Boolean</code> * type. * * Default: false * Group: producer * * @param logMask the value to set * @return the dsl builder */ default LogEndpointBuilder logMask(String logMask) { doSetProperty("logMask", logMask); return this; } /** * An optional Marker name to use. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param marker the value to set * @return the dsl builder */ default LogEndpointBuilder marker(String marker) { doSetProperty("marker", marker); return this; } /** * If enabled only the body will be printed out. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer * * @param plain the value to set * @return the dsl builder */ default LogEndpointBuilder plain(boolean plain) { doSetProperty("plain", plain); return this; } /** * If enabled only the body will be printed out. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer * * @param plain the value to set * @return the dsl builder */ default LogEndpointBuilder plain(String plain) { doSetProperty("plain", plain); return this; } /** * If enabled then the source location of where the log endpoint is used * in Camel routes, would be used as logger name, instead of the given * name. However, if the source location is disabled or not possible to * resolve then the existing logger name will be used. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer * * @param sourceLocationLoggerName the value to set * @return the dsl builder */ default LogEndpointBuilder sourceLocationLoggerName(boolean sourceLocationLoggerName) { doSetProperty("sourceLocationLoggerName", sourceLocationLoggerName); return this; } /** * If enabled then the source location of where the log endpoint is used * in Camel routes, would be used as logger name, instead of the given * name. However, if the source location is disabled or not possible to * resolve then the existing logger name will be used. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer * * @param sourceLocationLoggerName the value to set * @return the dsl builder */ default LogEndpointBuilder sourceLocationLoggerName(String sourceLocationLoggerName) { doSetProperty("sourceLocationLoggerName", sourceLocationLoggerName); return this; } /** * Limits the number of characters logged per line. * * The option is a: <code>int</code> type. * * Default: 10000 * Group: formatting * * @param maxChars the value to set * @return the dsl builder */ default LogEndpointBuilder maxChars(int maxChars) { doSetProperty("maxChars", maxChars); return this; } /** * Limits the number of characters logged per line. * * The option will be converted to a <code>int</code> type. * * Default: 10000 * Group: formatting * * @param maxChars the value to set * @return the dsl builder */ default LogEndpointBuilder maxChars(String maxChars) { doSetProperty("maxChars", maxChars); return this; } /** * If enabled then each information is outputted on a newline. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param multiline the value to set * @return the dsl builder */ default LogEndpointBuilder multiline(boolean multiline) { doSetProperty("multiline", multiline); return this; } /** * If enabled then each information is outputted on a newline. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param multiline the value to set * @return the dsl builder */ default LogEndpointBuilder multiline(String multiline) { doSetProperty("multiline", multiline); return this; } /** * Quick option for turning all options on. (multiline, maxChars has to * be manually set if to be used). * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showAll the value to set * @return the dsl builder */ default LogEndpointBuilder showAll(boolean showAll) { doSetProperty("showAll", showAll); return this; } /** * Quick option for turning all options on. (multiline, maxChars has to * be manually set if to be used). * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showAll the value to set * @return the dsl builder */ default LogEndpointBuilder showAll(String showAll) { doSetProperty("showAll", showAll); return this; } /** * Show all of the exchange properties (both internal and custom). * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showAllProperties the value to set * @return the dsl builder */ default LogEndpointBuilder showAllProperties(boolean showAllProperties) { doSetProperty("showAllProperties", showAllProperties); return this; } /** * Show all of the exchange properties (both internal and custom). * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showAllProperties the value to set * @return the dsl builder */ default LogEndpointBuilder showAllProperties(String showAllProperties) { doSetProperty("showAllProperties", showAllProperties); return this; } /** * Show the message body. * * The option is a: <code>boolean</code> type. * * Default: true * Group: formatting * * @param showBody the value to set * @return the dsl builder */ default LogEndpointBuilder showBody(boolean showBody) { doSetProperty("showBody", showBody); return this; } /** * Show the message body. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: formatting * * @param showBody the value to set * @return the dsl builder */ default LogEndpointBuilder showBody(String showBody) { doSetProperty("showBody", showBody); return this; } /** * Show the body Java type. * * The option is a: <code>boolean</code> type. * * Default: true * Group: formatting * * @param showBodyType the value to set * @return the dsl builder */ default LogEndpointBuilder showBodyType(boolean showBodyType) { doSetProperty("showBodyType", showBodyType); return this; } /** * Show the body Java type. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: formatting * * @param showBodyType the value to set * @return the dsl builder */ default LogEndpointBuilder showBodyType(String showBodyType) { doSetProperty("showBodyType", showBodyType); return this; } /** * Whether Camel should show cached stream bodies or not * (org.apache.camel.StreamCache). * * The option is a: <code>boolean</code> type. * * Default: true * Group: formatting * * @param showCachedStreams the value to set * @return the dsl builder */ default LogEndpointBuilder showCachedStreams(boolean showCachedStreams) { doSetProperty("showCachedStreams", showCachedStreams); return this; } /** * Whether Camel should show cached stream bodies or not * (org.apache.camel.StreamCache). * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: formatting * * @param showCachedStreams the value to set * @return the dsl builder */ default LogEndpointBuilder showCachedStreams(String showCachedStreams) { doSetProperty("showCachedStreams", showCachedStreams); return this; } /** * If the exchange has a caught exception, show the exception message * (no stack trace). A caught exception is stored as a property on the * exchange (using the key org.apache.camel.Exchange#EXCEPTION_CAUGHT) * and for instance a doCatch can catch exceptions. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showCaughtException the value to set * @return the dsl builder */ default LogEndpointBuilder showCaughtException(boolean showCaughtException) { doSetProperty("showCaughtException", showCaughtException); return this; } /** * If the exchange has a caught exception, show the exception message * (no stack trace). A caught exception is stored as a property on the * exchange (using the key org.apache.camel.Exchange#EXCEPTION_CAUGHT) * and for instance a doCatch can catch exceptions. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showCaughtException the value to set * @return the dsl builder */ default LogEndpointBuilder showCaughtException(String showCaughtException) { doSetProperty("showCaughtException", showCaughtException); return this; } /** * If the exchange has an exception, show the exception message (no * stacktrace). * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showException the value to set * @return the dsl builder */ default LogEndpointBuilder showException(boolean showException) { doSetProperty("showException", showException); return this; } /** * If the exchange has an exception, show the exception message (no * stacktrace). * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showException the value to set * @return the dsl builder */ default LogEndpointBuilder showException(String showException) { doSetProperty("showException", showException); return this; } /** * Show the unique exchange ID. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showExchangeId the value to set * @return the dsl builder */ default LogEndpointBuilder showExchangeId(boolean showExchangeId) { doSetProperty("showExchangeId", showExchangeId); return this; } /** * Show the unique exchange ID. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showExchangeId the value to set * @return the dsl builder */ default LogEndpointBuilder showExchangeId(String showExchangeId) { doSetProperty("showExchangeId", showExchangeId); return this; } /** * Shows the Message Exchange Pattern (or MEP for short). * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showExchangePattern the value to set * @return the dsl builder */ default LogEndpointBuilder showExchangePattern(boolean showExchangePattern) { doSetProperty("showExchangePattern", showExchangePattern); return this; } /** * Shows the Message Exchange Pattern (or MEP for short). * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showExchangePattern the value to set * @return the dsl builder */ default LogEndpointBuilder showExchangePattern(String showExchangePattern) { doSetProperty("showExchangePattern", showExchangePattern); return this; } /** * If enabled Camel will output files. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showFiles the value to set * @return the dsl builder */ default LogEndpointBuilder showFiles(boolean showFiles) { doSetProperty("showFiles", showFiles); return this; } /** * If enabled Camel will output files. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showFiles the value to set * @return the dsl builder */ default LogEndpointBuilder showFiles(String showFiles) { doSetProperty("showFiles", showFiles); return this; } /** * If enabled Camel will on Future objects wait for it to complete to * obtain the payload to be logged. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showFuture the value to set * @return the dsl builder */ default LogEndpointBuilder showFuture(boolean showFuture) { doSetProperty("showFuture", showFuture); return this; } /** * If enabled Camel will on Future objects wait for it to complete to * obtain the payload to be logged. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showFuture the value to set * @return the dsl builder */ default LogEndpointBuilder showFuture(String showFuture) { doSetProperty("showFuture", showFuture); return this; } /** * Show the message headers. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showHeaders the value to set * @return the dsl builder */ default LogEndpointBuilder showHeaders(boolean showHeaders) { doSetProperty("showHeaders", showHeaders); return this; } /** * Show the message headers. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showHeaders the value to set * @return the dsl builder */ default LogEndpointBuilder showHeaders(String showHeaders) { doSetProperty("showHeaders", showHeaders); return this; } /** * Show the exchange properties (only custom). Use showAllProperties to * show both internal and custom properties. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showProperties the value to set * @return the dsl builder */ default LogEndpointBuilder showProperties(boolean showProperties) { doSetProperty("showProperties", showProperties); return this; } /** * Show the exchange properties (only custom). Use showAllProperties to * show both internal and custom properties. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showProperties the value to set * @return the dsl builder */ default LogEndpointBuilder showProperties(String showProperties) { doSetProperty("showProperties", showProperties); return this; } /** * Show route Group. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showRouteGroup the value to set * @return the dsl builder */ default LogEndpointBuilder showRouteGroup(boolean showRouteGroup) { doSetProperty("showRouteGroup", showRouteGroup); return this; } /** * Show route Group. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showRouteGroup the value to set * @return the dsl builder */ default LogEndpointBuilder showRouteGroup(String showRouteGroup) { doSetProperty("showRouteGroup", showRouteGroup); return this; } /** * Show route ID. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showRouteId the value to set * @return the dsl builder */ default LogEndpointBuilder showRouteId(boolean showRouteId) { doSetProperty("showRouteId", showRouteId); return this; } /** * Show route ID. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showRouteId the value to set * @return the dsl builder */ default LogEndpointBuilder showRouteId(String showRouteId) { doSetProperty("showRouteId", showRouteId); return this; } /** * Show the stack trace, if an exchange has an exception. Only effective * if one of showAll, showException or showCaughtException are enabled. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showStackTrace the value to set * @return the dsl builder */ default LogEndpointBuilder showStackTrace(boolean showStackTrace) { doSetProperty("showStackTrace", showStackTrace); return this; } /** * Show the stack trace, if an exchange has an exception. Only effective * if one of showAll, showException or showCaughtException are enabled. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showStackTrace the value to set * @return the dsl builder */ default LogEndpointBuilder showStackTrace(String showStackTrace) { doSetProperty("showStackTrace", showStackTrace); return this; } /** * Whether Camel should show stream bodies or not (eg such as * java.io.InputStream). Beware if you enable this option then you may * not be able later to access the message body as the stream have * already been read by this logger. To remedy this you will have to use * Stream Caching. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showStreams the value to set * @return the dsl builder */ default LogEndpointBuilder showStreams(boolean showStreams) { doSetProperty("showStreams", showStreams); return this; } /** * Whether Camel should show stream bodies or not (eg such as * java.io.InputStream). Beware if you enable this option then you may * not be able later to access the message body as the stream have * already been read by this logger. To remedy this you will have to use * Stream Caching. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showStreams the value to set * @return the dsl builder */ default LogEndpointBuilder showStreams(String showStreams) { doSetProperty("showStreams", showStreams); return this; } /** * Show the variables. * * The option is a: <code>boolean</code> type. * * Default: false * Group: formatting * * @param showVariables the value to set * @return the dsl builder */ default LogEndpointBuilder showVariables(boolean showVariables) { doSetProperty("showVariables", showVariables); return this; } /** * Show the variables. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: formatting * * @param showVariables the value to set * @return the dsl builder */ default LogEndpointBuilder showVariables(String showVariables) { doSetProperty("showVariables", showVariables); return this; } /** * Whether to skip line separators when logging the message body. This * allows to log the message body in one line, setting this option to * false will preserve any line separators from the body, which then * will log the body as is. * * The option is a: <code>boolean</code> type. * * Default: true * Group: formatting * * @param skipBodyLineSeparator the value to set * @return the dsl builder */ default LogEndpointBuilder skipBodyLineSeparator(boolean skipBodyLineSeparator) { doSetProperty("skipBodyLineSeparator", skipBodyLineSeparator); return this; } /** * Whether to skip line separators when logging the message body. This * allows to log the message body in one line, setting this option to * false will preserve any line separators from the body, which then * will log the body as is. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: formatting * * @param skipBodyLineSeparator the value to set * @return the dsl builder */ default LogEndpointBuilder skipBodyLineSeparator(String skipBodyLineSeparator) { doSetProperty("skipBodyLineSeparator", skipBodyLineSeparator); return this; } /** * Sets the outputs style to use. * * The option is a: * <code>org.apache.camel.support.processor.DefaultExchangeFormatter.OutputStyle</code> type. * * Default: Default * Group: formatting * * @param style the value to set * @return the dsl builder */ default LogEndpointBuilder style(org.apache.camel.support.processor.DefaultExchangeFormatter.OutputStyle style) { doSetProperty("style", style); return this; } /** * Sets the outputs style to use. * * The option will be converted to a * <code>org.apache.camel.support.processor.DefaultExchangeFormatter.OutputStyle</code> type. * * Default: Default * Group: formatting * * @param style the value to set * @return the dsl builder */ default LogEndpointBuilder style(String style) { doSetProperty("style", style); return this; } } /** * Advanced builder for endpoint for the Log Data component. */ public
LogEndpointBuilder
java
google__dagger
javatests/artifacts/dagger/build-tests/src/test/java/buildtests/TransitiveMapKeyTest.java
{ "start": 1146, "end": 3558 }
class ____ { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void testTransitiveMapKey_WithImplementation() throws IOException { BuildResult result = setupRunnerWith("implementation").buildAndFail(); assertThat(result.getOutput()).contains("Task :app:compileJava FAILED"); assertThat(result.getOutput()) .contains( "Missing map key annotation for method: library1.MyModule#provideString(). " + "That method was annotated with: [" + "@dagger.Provides, " + "@dagger.multibindings.IntoMap, " + "@library2.MyMapKey(\"some-key\")" + "]"); } @Test public void testTransitiveMapKey_WithApi() throws IOException { // Test that if we use an "api" dependency for the custom map key things work properly. BuildResult result = setupRunnerWith("api").build(); assertThat(result.task(":app:assemble").getOutcome()).isEqualTo(SUCCESS); } private GradleRunner setupRunnerWith(String dependencyType) throws IOException { File projectDir = folder.getRoot(); GradleModule.create(projectDir) .addSettingsFile( "include 'app'", "include 'library1'", "include 'library2'") .addBuildFile( "buildscript {", " ext {", String.format("dagger_version = \"%s\"", System.getProperty("dagger_version")), " }", "}", "", "allprojects {", " repositories {", " mavenCentral()", " mavenLocal()", " }", "}"); GradleModule.create(projectDir, "app") .addBuildFile( "plugins {", " id 'java'", " id 'application'", "}", "dependencies {", " implementation project(':library1')", " implementation \"com.google.dagger:dagger:$dagger_version\"", " annotationProcessor \"com.google.dagger:dagger-compiler:$dagger_version\"", "}") .addSrcFile( "MyComponent.java", "package app;", "", "import dagger.Component;", "import library1.MyModule;", "import java.util.Map;", "", "@Component(modules = MyModule.class)", "public
TransitiveMapKeyTest
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/HasChangedUnversionedProperties.java
{ "start": 1157, "end": 3057 }
class ____ extends AbstractModifiedFlagsEntityTest { private Integer id1; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { em.getTransaction().begin(); BasicTestEntity2 bte2 = new BasicTestEntity2( "x", "a" ); em.persist( bte2 ); em.getTransaction().commit(); id1 = bte2.getId(); } ); scope.inEntityManager( em -> { em.getTransaction().begin(); BasicTestEntity2 bte2 = em.find( BasicTestEntity2.class, id1 ); bte2.setStr1( "x" ); bte2.setStr2( "a" ); em.getTransaction().commit(); } ); scope.inEntityManager( em -> { em.getTransaction().begin(); BasicTestEntity2 bte2 = em.find( BasicTestEntity2.class, id1 ); bte2.setStr1( "y" ); bte2.setStr2( "b" ); em.getTransaction().commit(); } ); scope.inEntityManager( em -> { em.getTransaction().begin(); BasicTestEntity2 bte2 = em.find( BasicTestEntity2.class, id1 ); bte2.setStr1( "y" ); bte2.setStr2( "c" ); em.getTransaction().commit(); } ); } @Test public void testHasChangedQuery(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); List list = AbstractModifiedFlagsEntityTest.queryForPropertyHasChanged( auditReader, BasicTestEntity2.class, id1, "str1" ); assertEquals( 2, list.size() ); assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); } ); } @Test public void testExceptionOnHasChangedQuery(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); assertThrows( IllegalArgumentException.class, () -> AbstractModifiedFlagsEntityTest.queryForPropertyHasChangedWithDeleted( auditReader, BasicTestEntity2.class, id1, "str2" ) ); } ); } }
HasChangedUnversionedProperties
java
apache__flink
flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/LogicalTypesTest.java
{ "start": 41719, "end": 41822 }
class ____ extends Human { public int setting; public LocalDateTime timestamp; } }
User
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/cache/internal/SimpleCacheKeysFactory.java
{ "start": 549, "end": 1629 }
class ____ implements CacheKeysFactory { public static final String SHORT_NAME = "simple"; public static CacheKeysFactory INSTANCE = new SimpleCacheKeysFactory(); @Override public Object createCollectionKey(Object id, CollectionPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) { return id; } @Override public Object createEntityKey(Object id, EntityPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) { return id; } @Override public Object createNaturalIdKey( Object naturalIdValues, EntityPersister persister, SharedSessionContractImplementor session) { // natural ids always need to be wrapped return NaturalIdCacheKey.from( naturalIdValues, persister, null, session ); } @Override public Object getEntityId(Object cacheKey) { return cacheKey; } @Override public Object getCollectionId(Object cacheKey) { return cacheKey; } @Override public Object getNaturalIdValues(Object cacheKey) { return ((NaturalIdCacheKey) cacheKey).getNaturalIdValues(); } }
SimpleCacheKeysFactory
java
google__dagger
hilt-compiler/main/java/dagger/hilt/processor/internal/generatesrootinput/KspGeneratesRootInputProcessor.java
{ "start": 1669, "end": 1915 }
class ____ implements SymbolProcessorProvider { @Override public SymbolProcessor create(SymbolProcessorEnvironment symbolProcessorEnvironment) { return new KspGeneratesRootInputProcessor(symbolProcessorEnvironment); } } }
Provider
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/TreatDisjunctionTest.java
{ "start": 3003, "end": 3301 }
class ____ { @Id @GeneratedValue private Long id; public BaseEntity() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } } @Entity(name = "PAccountDirectory") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public static
BaseEntity
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/exceptions/ServiceLaunchException.java
{ "start": 1093, "end": 2228 }
class ____ extends YarnException implements ExitCodeProvider, LauncherExitCodes { private final int exitCode; /** * Create an exception with the specific exit code * @param exitCode exit code * @param cause cause of the exception */ public ServiceLaunchException(int exitCode, Throwable cause) { super(cause); this.exitCode = exitCode; } /** * Create an exception with the specific exit code and text * @param exitCode exit code * @param message message to use in exception */ public ServiceLaunchException(int exitCode, String message) { super(message); this.exitCode = exitCode; } /** * Create an exception with the specific exit code, text and cause * @param exitCode exit code * @param message message to use in exception * @param cause cause of the exception */ public ServiceLaunchException(int exitCode, String message, Throwable cause) { super(message, cause); this.exitCode = exitCode; } /** * Get the exit code * @return the exit code */ @Override public int getExitCode() { return exitCode; } }
ServiceLaunchException
java
spring-projects__spring-security
messaging/src/test/java/org/springframework/security/messaging/handler/invocation/ResolvableMethod.java
{ "start": 5024, "end": 10565 }
class ____ { private static final Log logger = LogFactory.getLog(ResolvableMethod.class); private static final SpringObjenesis objenesis = new SpringObjenesis(); private static final ParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer(); // Matches ValueConstants.DEFAULT_NONE (spring-web and spring-messaging) private static final String DEFAULT_VALUE_NONE = "\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n"; private final Method method; private ResolvableMethod(Method method) { Assert.notNull(method, "'method' is required"); this.method = method; } /** * Return the resolved method. */ public Method method() { return this.method; } /** * Return the declared return type of the resolved method. */ public MethodParameter returnType() { return new SynthesizingMethodParameter(this.method, -1); } /** * Find a unique argument matching the given type. * @param type the expected type * @param generics optional array of generic types */ public MethodParameter arg(Class<?> type, Class<?>... generics) { return new ArgResolver().arg(type, generics); } /** * Find a unique argument matching the given type. * @param type the expected type * @param generic at least one generic type * @param generics optional array of generic types */ public MethodParameter arg(Class<?> type, ResolvableType generic, ResolvableType... generics) { return new ArgResolver().arg(type, generic, generics); } /** * Find a unique argument matching the given type. * @param type the expected type */ public MethodParameter arg(ResolvableType type) { return new ArgResolver().arg(type); } /** * Filter on method arguments with annotation. See * {@link org.springframework.web.method.MvcAnnotationPredicates}. */ @SafeVarargs public final ArgResolver annot(Predicate<MethodParameter>... filter) { return new ArgResolver(filter); } @SafeVarargs public final ArgResolver annotPresent(Class<? extends Annotation>... annotationTypes) { return new ArgResolver().annotPresent(annotationTypes); } /** * Filter on method arguments that don't have the given annotation type(s). * @param annotationTypes the annotation types */ @SafeVarargs public final ArgResolver annotNotPresent(Class<? extends Annotation>... annotationTypes) { return new ArgResolver().annotNotPresent(annotationTypes); } @Override public String toString() { return "ResolvableMethod=" + formatMethod(); } private String formatMethod() { return (method().getName() + Arrays.stream(this.method.getParameters()) .map(this::formatParameter) .collect(Collectors.joining(",\n\t", "(\n\t", "\n)"))); } private String formatParameter(Parameter param) { Annotation[] anns = param.getAnnotations(); return (anns.length > 0) ? Arrays.stream(anns).map(this::formatAnnotation).collect(Collectors.joining(",", "[", "]")) + " " + param : param.toString(); } private String formatAnnotation(Annotation annotation) { Map<String, Object> map = AnnotationUtils.getAnnotationAttributes(annotation); map.forEach((key, value) -> { if (value.equals(DEFAULT_VALUE_NONE)) { map.put(key, "NONE"); } }); return annotation.annotationType().getName() + map; } private static ResolvableType toResolvableType(Class<?> type, Class<?>... generics) { return (ObjectUtils.isEmpty(generics) ? ResolvableType.forClass(type) : ResolvableType.forClassWithGenerics(type, generics)); } private static ResolvableType toResolvableType(Class<?> type, ResolvableType generic, ResolvableType... generics) { ResolvableType[] genericTypes = new ResolvableType[generics.length + 1]; genericTypes[0] = generic; System.arraycopy(generics, 0, genericTypes, 1, generics.length); return ResolvableType.forClassWithGenerics(type, genericTypes); } /** * Create a {@code ResolvableMethod} builder for the given handler class. */ public static <T> Builder<T> on(Class<T> objectClass) { return new Builder<>(objectClass); } @SuppressWarnings("unchecked") private static <T> T initProxy(Class<?> type, MethodInvocationInterceptor interceptor) { Assert.notNull(type, "'type' must not be null"); if (type.isInterface()) { ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE); factory.addInterface(type); factory.addInterface(Supplier.class); factory.addAdvice(interceptor); return (T) factory.getProxy(); } else { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(type); enhancer.setInterfaces(new Class<?>[] { Supplier.class }); enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE); enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class); Class<?> proxyClass = enhancer.createClass(); Object proxy = null; if (objenesis.isWorthTrying()) { try { proxy = objenesis.newInstance(proxyClass, enhancer.getUseCache()); } catch (ObjenesisException ex) { logger.debug("Objenesis failed, falling back to default constructor", ex); } } if (proxy == null) { try { proxy = ReflectionUtils.accessibleConstructor(proxyClass).newInstance(); } catch (Throwable ex) { throw new IllegalStateException( "Unable to instantiate proxy " + "via both Objenesis and default constructor fails as well", ex); } } ((Factory) proxy).setCallbacks(new Callback[] { interceptor }); return (T) proxy; } } /** * Builder for {@code ResolvableMethod}. */ public static final
ResolvableMethod
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/core/annotation/UniqueSecurityAnnotationScannerTests.java
{ "start": 17067, "end": 17155 }
class ____ { String method() { return "ok"; } } private static
AnnotationOnClass
java
apache__spark
sql/core/src/main/java/org/apache/spark/sql/execution/UnsafeKVExternalSorter.java
{ "start": 1866, "end": 1982 }
class ____ performing external sorting on key-value records. Both key and value are UnsafeRows. * * Note that this
for
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/StGeotileErrorTests.java
{ "start": 800, "end": 1638 }
class ____ extends ErrorsForCasesWithoutExamplesTestCase { @Override protected List<TestCaseSupplier> cases() { return paramsToSuppliers(StGeotileTests.parameters()); } @Override protected Expression build(Source source, List<Expression> args) { return new StGeotile(source, args.get(0), args.get(1), args.size() > 2 ? args.get(2) : null); } @Override protected Matcher<String> expectedTypeErrorMatcher(List<Set<DataType>> validPerPosition, List<DataType> signature) { return equalTo(typeErrorMessage(true, validPerPosition, signature, (v, p) -> switch (p) { case 0 -> "geo_point"; case 1 -> "integer"; case 2 -> "geo_shape"; default -> throw new IllegalStateException("Unexpected value: " + p); })); } }
StGeotileErrorTests
java
quarkusio__quarkus
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/validatorfactory/MultipleValidatorFactoryCustomizersTest.java
{ "start": 521, "end": 1157 }
class ____ { @Inject ValidatorFactory validatorFactory; @RegisterExtension static final QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(() -> ShrinkWrap .create(JavaArchive.class) .addClasses(MyEmailValidatorFactoryCustomizer.class, MyNumberValidatorFactoryCustomizer.class, MyEmailValidator.class, MyNumValidator.class)); @Test public void testOverrideConstraintValidatorConstraint() { assertThat(validatorFactory.getValidator().validate(new TestBean())).hasSize(2); } static
MultipleValidatorFactoryCustomizersTest
java
google__jimfs
jimfs/src/test/java/com/google/common/jimfs/ByteBufferChannel.java
{ "start": 866, "end": 2550 }
class ____ implements SeekableByteChannel { private final ByteBuffer buffer; public ByteBufferChannel(byte[] bytes) { this.buffer = ByteBuffer.wrap(bytes); } public ByteBufferChannel(byte[] bytes, int offset, int length) { this.buffer = ByteBuffer.wrap(bytes, offset, length); } public ByteBufferChannel(int capacity) { this.buffer = ByteBuffer.allocate(capacity); } public ByteBufferChannel(ByteBuffer buffer) { this.buffer = buffer; } public ByteBuffer buffer() { return buffer; } @Override public int read(ByteBuffer dst) throws IOException { if (buffer.remaining() == 0) { return -1; } int length = min(dst.remaining(), buffer.remaining()); for (int i = 0; i < length; i++) { dst.put(buffer.get()); } return length; } @Override public int write(ByteBuffer src) throws IOException { int length = min(src.remaining(), buffer.remaining()); for (int i = 0; i < length; i++) { buffer.put(src.get()); } return length; } @Override public long position() throws IOException { return buffer.position(); } @Override @CanIgnoreReturnValue public SeekableByteChannel position(long newPosition) throws IOException { buffer.position((int) newPosition); return this; } @Override public long size() throws IOException { return buffer.limit(); } @Override @CanIgnoreReturnValue public SeekableByteChannel truncate(long size) throws IOException { buffer.limit((int) size); return this; } @Override public boolean isOpen() { return true; } @Override public void close() throws IOException {} }
ByteBufferChannel
java
google__dagger
javatests/dagger/functional/producers/subcomponent/pruning/ParentDoesntUseProductionSubcomponent.java
{ "start": 2407, "end": 2732 }
class ____ { @Produces @IntoSet static Class<?> produceComponentType() { return ChildB.class; } @Produces @FromChildA Set<Class<?>> fromChildA(ChildA.Builder childABuilder) throws Exception { return childABuilder.build().componentHierarchy().get(); } } @Qualifier @
ChildBModule
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoBeanSuperAndSubtypeIntegrationTests.java
{ "start": 1124, "end": 1554 }
class ____ designed to reproduce scenarios that previously failed * along the lines of the following. * * <p>BeanNotOfRequiredTypeException: Bean named 'Subtype#0' is expected to be * of type 'Subtype' but was actually of type 'Supertype$MockitoMock$XHb7Aspo' * * @author Sam Brannen * @since 6.2.1 * @see <a href="https://github.com/spring-projects/spring-framework/issues/34025">gh-34025</a> */ @SpringJUnitConfig public
is
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 111804, "end": 111984 }
class ____ {", " StringBuilder toBuilder() {", " return null;", " }", " }", "", " public static
Buh
java
apache__rocketmq
remoting/src/test/java/org/apache/rocketmq/remoting/protocol/RocketMQSerializableTest.java
{ "start": 7792, "end": 9475 }
class ____ implements CommandCustomHeader { private String str; private int num; @Override public void checkFields() throws RemotingCommandException { } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public int getNum() { return num; } public void setNum(int num) { this.num = num; } } @Test public void testFastEncode() throws Exception { ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(16); MyHeader1 header1 = new MyHeader1(); header1.setStr("s1"); header1.setNum(100); RemotingCommand cmd = RemotingCommand.createRequestCommand(1, header1); cmd.setRemark("remark"); cmd.setOpaque(1001); cmd.setVersion(99); cmd.setLanguage(LanguageCode.JAVA); cmd.setFlag(3); cmd.makeCustomHeaderToNet(); RocketMQSerializable.rocketMQProtocolEncode(cmd, buf); RemotingCommand cmd2 = RocketMQSerializable.rocketMQProtocolDecode(buf, buf.readableBytes()); assertThat(cmd2.getRemark()).isEqualTo("remark"); assertThat(cmd2.getCode()).isEqualTo(1); assertThat(cmd2.getOpaque()).isEqualTo(1001); assertThat(cmd2.getVersion()).isEqualTo(99); assertThat(cmd2.getLanguage()).isEqualTo(LanguageCode.JAVA); assertThat(cmd2.getFlag()).isEqualTo(3); MyHeader1 h2 = (MyHeader1) cmd2.decodeCommandCustomHeader(MyHeader1.class); assertThat(h2.getStr()).isEqualTo("s1"); assertThat(h2.getNum()).isEqualTo(100); } }
MyHeader1
java
apache__kafka
server-common/src/main/java/org/apache/kafka/server/share/persister/PersisterStateManager.java
{ "start": 31804, "end": 41314 }
class ____ extends PersisterStateManagerHandler { private final int stateEpoch; private final int leaderEpoch; private final long startOffset; private final int deliveryCompleteCount; private final List<PersisterStateBatch> batches; private final CompletableFuture<WriteShareGroupStateResponse> result; private final BackoffManager writeStateBackoff; public WriteStateHandler( String groupId, Uuid topicId, int partition, int stateEpoch, int leaderEpoch, long startOffset, int deliveryCompleteCount, List<PersisterStateBatch> batches, CompletableFuture<WriteShareGroupStateResponse> result, long backoffMs, long backoffMaxMs, int maxRPCRetryAttempts ) { super(groupId, topicId, partition, backoffMs, backoffMaxMs, maxRPCRetryAttempts); this.stateEpoch = stateEpoch; this.leaderEpoch = leaderEpoch; this.startOffset = startOffset; this.deliveryCompleteCount = deliveryCompleteCount; this.batches = batches; this.result = result; this.writeStateBackoff = new BackoffManager(maxRPCRetryAttempts, backoffMs, backoffMaxMs); } public WriteStateHandler( String groupId, Uuid topicId, int partition, int stateEpoch, int leaderEpoch, long startOffset, int deliveryCompleteCount, List<PersisterStateBatch> batches, CompletableFuture<WriteShareGroupStateResponse> result, Consumer<ClientResponse> onCompleteCallback ) { this( groupId, topicId, partition, stateEpoch, leaderEpoch, startOffset, deliveryCompleteCount, batches, result, REQUEST_BACKOFF_MS, REQUEST_BACKOFF_MAX_MS, MAX_FIND_COORD_ATTEMPTS ); } @Override protected String name() { return "WriteStateHandler"; } @Override protected AbstractRequest.Builder<? extends AbstractRequest> requestBuilder() { throw new RuntimeException("Write requests are batchable, hence individual requests not needed."); } @Override protected boolean isResponseForRequest(ClientResponse response) { return response.requestHeader().apiKey() == ApiKeys.WRITE_SHARE_GROUP_STATE; } @Override protected void handleRequestResponse(ClientResponse response) { log.debug("Write state response received - {}", response); writeStateBackoff.incrementAttempt(); Errors clientResponseError = checkResponseError(response).orElse(Errors.NONE); String clientResponseErrorMessage = clientResponseError.message(); switch (clientResponseError) { case NONE: // response can be a combined one for large number of requests // we need to deconstruct it WriteShareGroupStateResponse combinedResponse = (WriteShareGroupStateResponse) response.responseBody(); for (WriteShareGroupStateResponseData.WriteStateResult writeStateResult : combinedResponse.data().results()) { if (writeStateResult.topicId().equals(partitionKey().topicId())) { Optional<WriteShareGroupStateResponseData.PartitionResult> partitionStateData = writeStateResult.partitions().stream().filter(partitionResult -> partitionResult.partition() == partitionKey().partition()) .findFirst(); if (partitionStateData.isPresent()) { Errors error = Errors.forCode(partitionStateData.get().errorCode()); String errorMessage = partitionStateData.get().errorMessage(); if (errorMessage == null || errorMessage.isEmpty()) { errorMessage = error.message(); } switch (error) { case NONE: writeStateBackoff.resetAttempts(); WriteShareGroupStateResponseData.WriteStateResult result = WriteShareGroupStateResponse.toResponseWriteStateResult( partitionKey().topicId(), List.of(partitionStateData.get()) ); this.result.complete(new WriteShareGroupStateResponse( new WriteShareGroupStateResponseData().setResults(List.of(result)))); return; // check retriable errors case COORDINATOR_NOT_AVAILABLE: case COORDINATOR_LOAD_IN_PROGRESS: case NOT_COORDINATOR: case UNKNOWN_TOPIC_OR_PARTITION: log.debug("Received retriable error in write state RPC for key {}: {}", partitionKey(), errorMessage); if (!writeStateBackoff.canAttempt()) { log.error("Exhausted max retries for write state RPC for key {} without success.", partitionKey()); requestErrorResponse(error, new Exception("Exhausted max retries to complete write state RPC without success.")); return; } super.resetCoordinatorNode(); timer.add(new PersisterTimerTask(writeStateBackoff.backOff(), this)); return; default: log.error("Unable to perform write state RPC for key {}: {}", partitionKey(), errorMessage); requestErrorResponse(error, new Exception(errorMessage)); return; } } } } // no response found specific topic partition IllegalStateException exception = new IllegalStateException( "Failed to write state for share partition: " + partitionKey() ); requestErrorResponse(Errors.forException(exception), exception); return; case NETWORK_EXCEPTION: // Retriable client response error codes. case REQUEST_TIMED_OUT: log.debug("Received retriable error in write state RPC client response for key {}: {}", partitionKey(), clientResponseErrorMessage); if (!writeStateBackoff.canAttempt()) { log.error("Exhausted max retries for write state RPC due to error in client response for key {}.", partitionKey()); requestErrorResponse(clientResponseError, new Exception("Exhausted max retries to complete write state RPC without success.")); return; } super.resetCoordinatorNode(); timer.add(new PersisterTimerTask(writeStateBackoff.backOff(), this)); return; default: log.error("Unable to perform write state RPC due to error in client response for key {}: {}", partitionKey(), clientResponseError.code()); requestErrorResponse(clientResponseError, new Exception(clientResponseErrorMessage)); } } @Override public void requestErrorResponse(Errors error, Exception exception) { this.result.complete(new WriteShareGroupStateResponse( WriteShareGroupStateResponse.toErrorResponseData(partitionKey().topicId(), partitionKey().partition(), error, "Error in write state RPC. " + (exception == null ? error.message() : exception.getMessage())))); } @Override protected void findCoordinatorErrorResponse(Errors error, Exception exception) { this.result.complete(new WriteShareGroupStateResponse( WriteShareGroupStateResponse.toErrorResponseData(partitionKey().topicId(), partitionKey().partition(), error, "Error in find coordinator. " + (exception == null ? error.message() : exception.getMessage())))); } protected CompletableFuture<WriteShareGroupStateResponse> result() { return result; } @Override protected boolean isBatchable() { return true; } @Override protected RPCType rpcType() { return RPCType.WRITE; } } public
WriteStateHandler
java
apache__camel
components/camel-opentelemetry/src/test/java/org/apache/camel/opentelemetry/AsyncCxfTest.java
{ "start": 1079, "end": 2699 }
class ____ extends CamelOpenTelemetryTestSupport { private static int port1 = CXFTestSupport.getPort1(); private static SpanTestData[] testdata = {}; // not used yet, fix context leak first AsyncCxfTest() { super(testdata); } @Test void testRoute() throws InterruptedException { MockEndpoint mock = getMockEndpoint("mock:end"); mock.expectedMessageCount(4); int num = 4; for (int i = 0; i < num; i++) { template.requestBody("direct:start", "foo"); } mock.assertIsSatisfied(5000); verifyTraceSpanNumbers(num, 7); } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").routeId("myRoute") .to("direct:send") .end(); from("direct:send") .log("message") .to("cxfrs:http://localhost:" + port1 + "/rest/helloservice/sayHello?synchronous=false"); // setting to 'true' resolves the issue restConfiguration() .port(port1); rest("/rest/helloservice") .post("/sayHello").routeId("rest-GET-say-hi") .to("direct:sayHi"); from("direct:sayHi") .routeId("mock-GET-say-hi") .log("example") .to("mock:end"); } }; } }
AsyncCxfTest
java
quarkusio__quarkus
tcks/microprofile-lra/src/main/java/io/quarkus/tck/lra/ArquillianExtension.java
{ "start": 629, "end": 707 }
class ____.observer(LRACoordinatorManager.class); } }
extensionBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/MapElement.java
{ "start": 200, "end": 243 }
class ____ { private String name; }
MapElement
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/accept/AbstractMappingContentNegotiationStrategy.java
{ "start": 2027, "end": 5451 }
class ____ extends MappingMediaTypeFileExtensionResolver implements ContentNegotiationStrategy { protected final Log logger = LogFactory.getLog(getClass()); private boolean useRegisteredExtensionsOnly = false; private boolean ignoreUnknownExtensions = false; /** * Create an instance with the given map of file extensions and media types. */ public AbstractMappingContentNegotiationStrategy(@Nullable Map<String, MediaType> mediaTypes) { super(mediaTypes); } /** * Whether to only use the registered mappings to look up file extensions, * or also to use dynamic resolution (for example, via {@link MediaTypeFactory}). * <p>By default this is set to {@code false}. */ public void setUseRegisteredExtensionsOnly(boolean useRegisteredExtensionsOnly) { this.useRegisteredExtensionsOnly = useRegisteredExtensionsOnly; } public boolean isUseRegisteredExtensionsOnly() { return this.useRegisteredExtensionsOnly; } /** * Whether to ignore requests with unknown file extension. Setting this to * {@code false} results in {@code HttpMediaTypeNotAcceptableException}. * <p>By default, this is set to {@literal false}. */ public void setIgnoreUnknownExtensions(boolean ignoreUnknownExtensions) { this.ignoreUnknownExtensions = ignoreUnknownExtensions; } public boolean isIgnoreUnknownExtensions() { return this.ignoreUnknownExtensions; } @Override public List<MediaType> resolveMediaTypes(NativeWebRequest webRequest) throws HttpMediaTypeNotAcceptableException { return resolveMediaTypeKey(webRequest, getMediaTypeKey(webRequest)); } /** * An alternative to {@link #resolveMediaTypes(NativeWebRequest)} that accepts * an already extracted key. * @since 3.2.16 */ public List<MediaType> resolveMediaTypeKey(NativeWebRequest webRequest, @Nullable String key) throws HttpMediaTypeNotAcceptableException { if (StringUtils.hasText(key)) { MediaType mediaType = lookupMediaType(key); if (mediaType != null) { handleMatch(key, mediaType); return Collections.singletonList(mediaType); } mediaType = handleNoMatch(webRequest, key); if (mediaType != null) { addMapping(key, mediaType); return Collections.singletonList(mediaType); } } return MEDIA_TYPE_ALL_LIST; } /** * Extract a key from the request to use to look up media types. * @return the lookup key, or {@code null} if none */ protected abstract @Nullable String getMediaTypeKey(NativeWebRequest request); /** * Override to provide handling when a key is successfully resolved via * {@link #lookupMediaType}. */ protected void handleMatch(String key, MediaType mediaType) { } /** * Override to provide handling when a key is not resolved via. * {@link #lookupMediaType}. Subclasses can take further steps to * determine the media type(s). If a MediaType is returned from * this method it will be added to the cache in the base class. */ protected @Nullable MediaType handleNoMatch(NativeWebRequest request, String key) throws HttpMediaTypeNotAcceptableException { if (!isUseRegisteredExtensionsOnly()) { Optional<MediaType> mediaType = MediaTypeFactory.getMediaType("file." + key); if (mediaType.isPresent()) { return mediaType.get(); } } if (isIgnoreUnknownExtensions()) { return null; } throw new HttpMediaTypeNotAcceptableException(getAllMediaTypes()); } }
AbstractMappingContentNegotiationStrategy
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oceanbase/OceanbaseAlterTableRepairPartitionTest.java
{ "start": 967, "end": 2468 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "ALTER TABLE tnrange REPAIR PARTITION p1;"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); SQLStatement stmt = stmtList.get(0); { String result = SQLUtils.toMySqlString(stmt); assertEquals("ALTER TABLE tnrange" + "\n\tREPAIR PARTITION p1;", result); } { String result = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION); assertEquals("alter table tnrange" + "\n\trepair partition p1;", result); } assertEquals(1, stmtList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(0, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("t_basic_store"))); } }
OceanbaseAlterTableRepairPartitionTest
java
quarkusio__quarkus
extensions/panache/hibernate-orm-rest-data-panache/deployment/src/test/java/io/quarkus/hibernate/orm/rest/data/panache/deployment/entity/PanacheEntityResourceHalDisabledTest.java
{ "start": 354, "end": 1693 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(Project.class, ProjectResource.class) .addAsResource("application.properties")); @Test void shouldHalNotBeSupported() { given().accept("application/hal+json") .when().get("/group/projects/1") .then().statusCode(406); } @Test void shouldNotContainLocationAndLinks() { Response response = given().accept("application/json") .and().contentType("application/json") .and().body("{\"name\": \"projectname\"}") .when().post("/group/projects") .thenReturn(); assertThat(response.statusCode()).isEqualTo(201); assertThat(response.header("Location")).isBlank(); assertThat(response.getHeaders().getList("Link")).isEmpty(); response = given().accept("application/json") .when().get("/group/projects/projectname") .thenReturn(); assertThat(response.statusCode()).isEqualTo(200); assertThat(response.header("Location")).isBlank(); assertThat(response.getHeaders().getList("Link")).isEmpty(); } }
PanacheEntityResourceHalDisabledTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/ProtoDurationGetSecondsGetNanoTest.java
{ "start": 3077, "end": 3712 }
class ____ { public static void foo(Duration duration) { long seconds = duration.getSeconds(); if (true) { // BUG: Diagnostic contains: ProtoDurationGetSecondsGetNano int nanos = duration.getNanos(); } } } """) .doTest(); } @Test public void getSecondsWithGetNanosInDifferentMethods() { compilationHelper .addSourceLines( "test/TestCase.java", """ package test; import com.google.protobuf.Duration; public
TestCase
java
apache__dubbo
dubbo-plugin/dubbo-mutiny/src/main/java/org/apache/dubbo/mutiny/handler/ManyToManyMethodHandler.java
{ "start": 1269, "end": 1888 }
class ____<T, R> implements StubMethodHandler<T, R> { private final Function<Multi<T>, Multi<R>> func; public ManyToManyMethodHandler(Function<Multi<T>, Multi<R>> func) { this.func = func; } @SuppressWarnings("unchecked") @Override public CompletableFuture<StreamObserver<T>> invoke(Object[] arguments) { CallStreamObserver<R> responseObserver = (CallStreamObserver<R>) arguments[0]; StreamObserver<T> requestObserver = MutinyServerCalls.manyToMany(responseObserver, func); return CompletableFuture.completedFuture(requestObserver); } }
ManyToManyMethodHandler
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/ResourceOptionInfo.java
{ "start": 1272, "end": 2168 }
class ____ { @XmlElement(name = "resource") private ResourceInfo resource = new ResourceInfo(); @XmlElement(name = "overCommitTimeout") private int overCommitTimeout; /** Internal resource option for caching. */ private ResourceOption resourceOption; public ResourceOptionInfo() { } // JAXB needs this public ResourceOptionInfo(ResourceOption resourceOption) { if (resourceOption != null) { this.resource = new ResourceInfo(resourceOption.getResource()); this.overCommitTimeout = resourceOption.getOverCommitTimeout(); } } public ResourceOption getResourceOption() { if (resourceOption == null) { resourceOption = ResourceOption.newInstance( resource.getResource(), overCommitTimeout); } return resourceOption; } @Override public String toString() { return getResourceOption().toString(); } }
ResourceOptionInfo
java
playframework__playframework
core/play/src/main/java/play/core/cookie/encoding/ServerCookieDecoder.java
{ "start": 1158, "end": 4678 }
class ____ extends CookieDecoder { private static final String RFC2965_VERSION = "$Version"; private static final String RFC2965_PATH = "$" + CookieHeaderNames.PATH; private static final String RFC2965_DOMAIN = "$" + CookieHeaderNames.DOMAIN; private static final String RFC2965_PORT = "$Port"; /** * Strict encoder that validates that name and value chars are in the valid scope defined in * RFC6265 */ public static final ServerCookieDecoder STRICT = new ServerCookieDecoder(true); /** Lax instance that doesn't validate name and value */ public static final ServerCookieDecoder LAX = new ServerCookieDecoder(false); private ServerCookieDecoder(boolean strict) { super(strict); } /** * Decodes the specified Set-Cookie HTTP header value into a {@link Cookie}. * * @param header the Set-Cookie header. * @return the decoded {@link Cookie} */ public Set<Cookie> decode(String header) { if (header == null) { throw new NullPointerException("header"); } final int headerLen = header.length(); if (headerLen == 0) { return Collections.emptySet(); } Set<Cookie> cookies = new TreeSet<>(); int i = 0; boolean rfc2965Style = false; if (header.regionMatches(true, 0, RFC2965_VERSION, 0, RFC2965_VERSION.length())) { // RFC 2965 style cookie, move to after version value i = header.indexOf(';') + 1; rfc2965Style = true; } loop: for (; ; ) { // Skip spaces and separators. for (; ; ) { if (i == headerLen) { break loop; } char c = header.charAt(i); if (c == '\t' || c == '\n' || c == 0x0b || c == '\f' || c == '\r' || c == ' ' || c == ',' || c == ';') { i++; continue; } break; } int nameBegin = i; int nameEnd = i; int valueBegin = -1; int valueEnd = -1; if (i != headerLen) { keyValLoop: for (; ; ) { char curChar = header.charAt(i); if (curChar == ';') { // NAME; (no value till ';') nameEnd = i; valueBegin = valueEnd = -1; break keyValLoop; } else if (curChar == '=') { // NAME=VALUE nameEnd = i; i++; if (i == headerLen) { // NAME= (empty value, i.e. nothing after '=') valueBegin = valueEnd = 0; break keyValLoop; } valueBegin = i; // NAME=VALUE; int semiPos = header.indexOf(';', i); valueEnd = i = semiPos > 0 ? semiPos : headerLen; break keyValLoop; } else { i++; } if (i == headerLen) { // NAME (no value till the end of string) nameEnd = headerLen; valueBegin = valueEnd = -1; break; } } } if (rfc2965Style && (header.regionMatches(nameBegin, RFC2965_PATH, 0, RFC2965_PATH.length()) || header.regionMatches(nameBegin, RFC2965_DOMAIN, 0, RFC2965_DOMAIN.length()) || header.regionMatches(nameBegin, RFC2965_PORT, 0, RFC2965_PORT.length()))) { // skip obsolete RFC2965 fields continue; } DefaultCookie cookie = initCookie(header, nameBegin, nameEnd, valueBegin, valueEnd); if (cookie != null) { cookies.add(cookie); } } return cookies; } }
ServerCookieDecoder
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/longpolling/PopRequest.java
{ "start": 1248, "end": 3456 }
class ____ { private static final AtomicLong COUNTER = new AtomicLong(Long.MIN_VALUE); private final RemotingCommand remotingCommand; private final ChannelHandlerContext ctx; private final AtomicBoolean complete = new AtomicBoolean(false); private final long op = COUNTER.getAndIncrement(); private final long expired; private final SubscriptionData subscriptionData; private final MessageFilter messageFilter; public PopRequest(RemotingCommand remotingCommand, ChannelHandlerContext ctx, long expired, SubscriptionData subscriptionData, MessageFilter messageFilter) { this.ctx = ctx; this.remotingCommand = remotingCommand; this.expired = expired; this.subscriptionData = subscriptionData; this.messageFilter = messageFilter; } public Channel getChannel() { return ctx.channel(); } public ChannelHandlerContext getCtx() { return ctx; } public RemotingCommand getRemotingCommand() { return remotingCommand; } public boolean isTimeout() { return System.currentTimeMillis() > (expired - 50); } public boolean complete() { return complete.compareAndSet(false, true); } public long getExpired() { return expired; } public SubscriptionData getSubscriptionData() { return subscriptionData; } public MessageFilter getMessageFilter() { return messageFilter; } @Override public String toString() { final StringBuilder sb = new StringBuilder("PopRequest{"); sb.append("cmd=").append(remotingCommand); sb.append(", ctx=").append(ctx); sb.append(", expired=").append(expired); sb.append(", complete=").append(complete); sb.append(", op=").append(op); sb.append('}'); return sb.toString(); } public static final Comparator<PopRequest> COMPARATOR = (o1, o2) -> { int ret = (int) (o1.getExpired() - o2.getExpired()); if (ret != 0) { return ret; } ret = (int) (o1.op - o2.op); if (ret != 0) { return ret; } return -1; }; }
PopRequest
java
square__retrofit
retrofit/java-test/src/test/java/retrofit2/AnnotationArraySubject.java
{ "start": 356, "end": 1206 }
class ____ extends Subject { public static Factory<AnnotationArraySubject, Annotation[]> annotationArrays() { return AnnotationArraySubject::new; } public static AnnotationArraySubject assertThat(Annotation[] actual) { return assertAbout(annotationArrays()).that(actual); } private final List<Annotation> actual; private AnnotationArraySubject(FailureMetadata metadata, Annotation[] actual) { super(metadata, actual); this.actual = new ArrayList<>(actual.length); Collections.addAll(this.actual, actual); } public void hasAtLeastOneElementOfType(Class<? extends Annotation> cls) { for (Annotation annotation : actual) { if (cls.isAssignableFrom(annotation.annotationType())) { return; } } failWithActual(simpleFact("No annotations of instance " + cls)); } }
AnnotationArraySubject
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/io/support/ConstructorArgsDummyFactory.java
{ "start": 756, "end": 1090 }
class ____ implements DummyFactory { private final String string; public ConstructorArgsDummyFactory(String string) { this(string, 0); } private ConstructorArgsDummyFactory(String string, int reasonCode) { this.string = string; } @Override public String getString() { return this.string; } }
ConstructorArgsDummyFactory
java
apache__dubbo
dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/Invocation.java
{ "start": 3292, "end": 5909 }
class ____ implements Invocation { private org.apache.dubbo.rpc.Invocation delegate; public CompatibleInvocation(org.apache.dubbo.rpc.Invocation invocation) { this.delegate = invocation; } @Override public String getTargetServiceUniqueName() { return delegate.getTargetServiceUniqueName(); } @Override public String getProtocolServiceKey() { return delegate.getProtocolServiceKey(); } @Override public String getMethodName() { return delegate.getMethodName(); } @Override public String getServiceName() { return null; } @Override public Class<?>[] getParameterTypes() { return delegate.getParameterTypes(); } @Override public Object[] getArguments() { return delegate.getArguments(); } @Override public Map<String, String> getAttachments() { return delegate.getAttachments(); } @Override public String getAttachment(String key) { return delegate.getAttachment(key); } @Override public String getAttachment(String key, String defaultValue) { return delegate.getAttachment(key, defaultValue); } @Override @Transient public Invoker<?> getInvoker() { return new Invoker.CompatibleInvoker(delegate.getInvoker()); } @Override public void setServiceModel(ServiceModel serviceModel) { delegate.setServiceModel(serviceModel); } @Override public ServiceModel getServiceModel() { return delegate.getServiceModel(); } @Override public Object put(Object key, Object value) { return delegate.put(key, value); } @Override public Object get(Object key) { return delegate.get(key); } @Override public Map<Object, Object> getAttributes() { return delegate.getAttributes(); } @Override public org.apache.dubbo.rpc.Invocation getOriginal() { return delegate; } @Override public void addInvokedInvoker(org.apache.dubbo.rpc.Invoker<?> invoker) { delegate.addInvokedInvoker(invoker); } @Override public List<org.apache.dubbo.rpc.Invoker<?>> getInvokedInvokers() { return delegate.getInvokedInvokers(); } } }
CompatibleInvocation
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/enum_/EnumUsingToString.java
{ "start": 694, "end": 932 }
enum ____ { M("男"), W("女"); private String msg; Gender(String msg) { this.msg = msg; } @Override public String toString() { return msg; } } }
Gender
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/mutability/converted/ImmutabilityConverterTests.java
{ "start": 1785, "end": 2256 }
class ____ { @Id private Integer id; @Basic private String name; @Convert( converter = ImmutabilityDateConverter.class ) private Date theDate; private TestEntity() { // for use by Hibernate } public TestEntity(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
TestEntity
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/record/CompressionType.java
{ "start": 1094, "end": 6927 }
enum ____ { NONE((byte) 0, "none", 1.0f), // Shipped with the JDK GZIP((byte) 1, "gzip", 1.0f) { public static final int MIN_LEVEL = Deflater.BEST_SPEED; public static final int MAX_LEVEL = Deflater.BEST_COMPRESSION; public static final int DEFAULT_LEVEL = Deflater.DEFAULT_COMPRESSION; @Override public int defaultLevel() { return DEFAULT_LEVEL; } @Override public int maxLevel() { return MAX_LEVEL; } @Override public int minLevel() { return MIN_LEVEL; } @Override public ConfigDef.Validator levelValidator() { return ConfigDef.LambdaValidator.with((name, value) -> { if (value == null) throw new ConfigException(name, null, "Value must be non-null"); int level = ((Number) value).intValue(); if (level > MAX_LEVEL || (level < MIN_LEVEL && level != DEFAULT_LEVEL)) { throw new ConfigException(name, value, "Value must be between " + MIN_LEVEL + " and " + MAX_LEVEL + " or equal to " + DEFAULT_LEVEL); } }, () -> "[" + MIN_LEVEL + ",...," + MAX_LEVEL + "] or " + DEFAULT_LEVEL); } }, // We should only load classes from a given compression library when we actually use said compression library. This // is because compression libraries include native code for a set of platforms and we want to avoid errors // in case the platform is not supported and the compression library is not actually used. // To ensure this, we only reference compression library code from classes that are only invoked when actual usage // happens. SNAPPY((byte) 2, "snappy", 1.0f), LZ4((byte) 3, "lz4", 1.0f) { // These values come from net.jpountz.lz4.LZ4Constants // We may need to update them if the lz4 library changes these values. private static final int MIN_LEVEL = 1; private static final int MAX_LEVEL = 17; private static final int DEFAULT_LEVEL = 9; @Override public int defaultLevel() { return DEFAULT_LEVEL; } @Override public int maxLevel() { return MAX_LEVEL; } @Override public int minLevel() { return MIN_LEVEL; } @Override public ConfigDef.Validator levelValidator() { return between(MIN_LEVEL, MAX_LEVEL); } }, ZSTD((byte) 4, "zstd", 1.0f) { // These values come from the zstd library. We don't use the Zstd.minCompressionLevel(), // Zstd.maxCompressionLevel() and Zstd.defaultCompressionLevel() methods to not load the Zstd library // while parsing configuration. // See ZSTD_minCLevel in https://github.com/facebook/zstd/blob/dev/lib/compress/zstd_compress.c#L6987 // and ZSTD_TARGETLENGTH_MAX https://github.com/facebook/zstd/blob/dev/lib/zstd.h#L1249 private static final int MIN_LEVEL = -131072; // See ZSTD_MAX_CLEVEL in https://github.com/facebook/zstd/blob/dev/lib/compress/clevels.h#L19 private static final int MAX_LEVEL = 22; // See ZSTD_CLEVEL_DEFAULT in https://github.com/facebook/zstd/blob/dev/lib/zstd.h#L129 private static final int DEFAULT_LEVEL = 3; @Override public int defaultLevel() { return DEFAULT_LEVEL; } @Override public int maxLevel() { return MAX_LEVEL; } @Override public int minLevel() { return MIN_LEVEL; } @Override public ConfigDef.Validator levelValidator() { return between(MIN_LEVEL, MAX_LEVEL); } }; // compression type is represented by two bits in the attributes field of the record batch header, so `byte` is // large enough public final byte id; public final String name; public final float rate; CompressionType(byte id, String name, float rate) { this.id = id; this.name = name; this.rate = rate; } public static CompressionType forId(int id) { switch (id) { case 0: return NONE; case 1: return GZIP; case 2: return SNAPPY; case 3: return LZ4; case 4: return ZSTD; default: throw new IllegalArgumentException("Unknown compression type id: " + id); } } public static CompressionType forName(String name) { if (NONE.name.equals(name)) return NONE; else if (GZIP.name.equals(name)) return GZIP; else if (SNAPPY.name.equals(name)) return SNAPPY; else if (LZ4.name.equals(name)) return LZ4; else if (ZSTD.name.equals(name)) return ZSTD; else throw new IllegalArgumentException("Unknown compression name: " + name); } public int defaultLevel() { throw new UnsupportedOperationException("Compression levels are not defined for this compression type: " + name); } public int maxLevel() { throw new UnsupportedOperationException("Compression levels are not defined for this compression type: " + name); } public int minLevel() { throw new UnsupportedOperationException("Compression levels are not defined for this compression type: " + name); } public ConfigDef.Validator levelValidator() { throw new UnsupportedOperationException("Compression levels are not defined for this compression type: " + name); } @Override public String toString() { return name; } }
CompressionType
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/info/ProcessInfo.java
{ "start": 4899, "end": 5564 }
class ____ { private final int mounted; private final long queued; private final int parallelism; private final int poolSize; VirtualThreadsInfo(int mounted, long queued, int parallelism, int poolSize) { this.mounted = mounted; this.queued = queued; this.parallelism = parallelism; this.poolSize = poolSize; } public int getMounted() { return this.mounted; } public long getQueued() { return this.queued; } public int getParallelism() { return this.parallelism; } public int getPoolSize() { return this.poolSize; } } /** * Memory information. * * @since 3.4.0 */ public static
VirtualThreadsInfo
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/ConfigurationInfoTest.java
{ "start": 1078, "end": 1606 }
class ____ extends RestResponseMarshallingTestBase<ConfigurationInfo> { @Override protected Class<ConfigurationInfo> getTestResponseClass() { return ConfigurationInfo.class; } @Override protected ConfigurationInfo getTestResponseInstance() { final ConfigurationInfo expected = new ConfigurationInfo(2); expected.add(new ConfigurationInfoEntry("key1", "value1")); expected.add(new ConfigurationInfoEntry("key2", "value2")); return expected; } }
ConfigurationInfoTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/shard/ShardSplittingQuery.java
{ "start": 2524, "end": 12880 }
class ____ extends Query { private final IndexMetadata indexMetadata; private final IndexRouting indexRouting; private final int shardId; private final BitSetProducer nestedParentBitSetProducer; public ShardSplittingQuery(IndexMetadata indexMetadata, int shardId, boolean hasNested) { this.indexMetadata = indexMetadata; this.indexRouting = IndexRouting.fromIndexMetadata(indexMetadata); this.shardId = shardId; this.nestedParentBitSetProducer = hasNested ? newParentDocBitSetProducer(indexMetadata.getCreationVersion()) : null; } @Override public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) { return new ConstantScoreWeight(this, boost) { @Override public String toString() { return "weight(delete docs query)"; } @Override public ScorerSupplier scorerSupplier(LeafReaderContext context) throws IOException { LeafReader leafReader = context.reader(); FixedBitSet bitSet = new FixedBitSet(leafReader.maxDoc()); Terms terms = leafReader.terms(RoutingFieldMapper.NAME); Predicate<BytesRef> includeInShard = ref -> { // TODO IndexRouting should build the query somehow int targetShardId = indexRouting.getShard(Uid.decodeId(ref.bytes, ref.offset, ref.length), null); return shardId == targetShardId; }; return new ScorerSupplier() { @Override public Scorer get(long leadCost) throws IOException { if (terms == null) { // this is the common case - no partitioning and no _routing values // in this case we also don't do anything special with regards to nested docs since we basically delete // by ID and parent and nested all have the same id. assert indexMetadata.isRoutingPartitionedIndex() == false; findSplitDocs(IdFieldMapper.NAME, includeInShard, leafReader, bitSet::set); } else { final BitSet parentBitSet; if (nestedParentBitSetProducer == null) { parentBitSet = null; } else { parentBitSet = nestedParentBitSetProducer.getBitSet(context); if (parentBitSet == null) { return null; // no matches } } if (indexMetadata.isRoutingPartitionedIndex()) { // this is the heaviest invariant. Here we have to visit all docs stored fields do extract _id and _routing // this index is routing partitioned. Visitor visitor = new Visitor(leafReader); TwoPhaseIterator twoPhaseIterator = parentBitSet == null ? new RoutingPartitionedDocIdSetIterator(visitor) : new NestedRoutingPartitionedDocIdSetIterator(visitor, parentBitSet); return new ConstantScoreScorer(score(), scoreMode, twoPhaseIterator); } else { // here we potentially guard the docID consumers with our parent bitset if we have one. // this ensures that we are only marking root documents in the nested case and if necessary // we do a second pass to mark the corresponding children in markChildDocs Function<IntConsumer, IntConsumer> maybeWrapConsumer = consumer -> { if (parentBitSet != null) { return docId -> { if (parentBitSet.get(docId)) { consumer.accept(docId); } }; } return consumer; }; // in the _routing case we first go and find all docs that have a routing value and mark the ones we have to // delete findSplitDocs(RoutingFieldMapper.NAME, ref -> { int targetShardId = indexRouting.getShard(null, ref.utf8ToString()); return shardId == targetShardId; }, leafReader, maybeWrapConsumer.apply(bitSet::set)); // TODO have the IndexRouting build the query and pass routingRequired in boolean routingRequired = indexMetadata.mapping() == null ? false : indexMetadata.mapping().routingRequired(); // now if we have a mixed index where some docs have a _routing value and some don't we have to exclude the // ones // with a routing value from the next iteration and delete / select based on the ID. if (routingRequired == false && terms.getDocCount() != leafReader.maxDoc()) { /* * This is a special case where some docs don't have routing values. * It's annoying, but it's allowed to build an index where some documents * hve routing and others don't. * * Luckily, if the routing field is required in the mapping then we can * safely assume that all documents which are don't have a routing are * nested documents. And we pick those up later based on the assignment * of the document that contains them. */ FixedBitSet hasRoutingValue = new FixedBitSet(leafReader.maxDoc()); findSplitDocs( RoutingFieldMapper.NAME, Predicates.never(), leafReader, maybeWrapConsumer.apply(hasRoutingValue::set) ); IntConsumer bitSetConsumer = maybeWrapConsumer.apply(bitSet::set); findSplitDocs(IdFieldMapper.NAME, includeInShard, leafReader, docId -> { if (hasRoutingValue.get(docId) == false) { bitSetConsumer.accept(docId); } }); } } if (parentBitSet != null) { // if nested docs are involved we also need to mark all child docs that belong to a matching parent doc. markChildDocs(parentBitSet, bitSet); } } return new ConstantScoreScorer(score(), scoreMode, new BitSetIterator(bitSet, bitSet.length())); } @Override public long cost() { return leafReader.maxDoc(); } }; } @Override public boolean isCacheable(LeafReaderContext ctx) { // This is not a regular query, let's not cache it. It wouldn't help // anyway. return false; } }; } private static void markChildDocs(BitSet parentDocs, BitSet matchingDocs) { int currentDeleted = 0; while (currentDeleted < matchingDocs.length() && (currentDeleted = matchingDocs.nextSetBit(currentDeleted)) != DocIdSetIterator.NO_MORE_DOCS) { int previousParent = parentDocs.prevSetBit(Math.max(0, currentDeleted - 1)); for (int i = previousParent + 1; i < currentDeleted; i++) { matchingDocs.set(i); } currentDeleted++; } } @Override public String toString(String field) { return "shard_splitting_query"; } @Override public boolean equals(Object o) { if (this == o) return true; if (sameClassAs(o) == false) return false; ShardSplittingQuery that = (ShardSplittingQuery) o; if (shardId != that.shardId) return false; return indexMetadata.equals(that.indexMetadata); } @Override public int hashCode() { int result = indexMetadata.hashCode(); result = 31 * result + shardId; return classHash() ^ result; } @Override public void visit(QueryVisitor visitor) { visitor.visitLeaf(this); } private static void findSplitDocs(String idField, Predicate<BytesRef> includeInShard, LeafReader leafReader, IntConsumer consumer) throws IOException { Terms terms = leafReader.terms(idField); TermsEnum iterator = terms.iterator(); BytesRef idTerm; PostingsEnum postingsEnum = null; while ((idTerm = iterator.next()) != null) { if (includeInShard.test(idTerm) == false) { postingsEnum = iterator.postings(postingsEnum); int doc; while ((doc = postingsEnum.nextDoc()) != DocIdSetIterator.NO_MORE_DOCS) { consumer.accept(doc); } } } } /* this
ShardSplittingQuery
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TestTaskManagerActions.java
{ "start": 1649, "end": 3669 }
class ____ implements TaskManagerActions { private final JobMasterGateway jobMasterGateway; private final TaskSlotTable<Task> taskSlotTable; private final TaskManagerActionListeners taskManagerActionListeners = new TaskManagerActionListeners(); public TestTaskManagerActions( TaskSlotTable<Task> taskSlotTable, JobMasterGateway jobMasterGateway) { this.taskSlotTable = taskSlotTable; this.jobMasterGateway = jobMasterGateway; } public void addListener( ExecutionAttemptID eid, ExecutionState executionState, CompletableFuture<Void> future) { taskManagerActionListeners.addListener(eid, executionState, future); } @Override public void notifyFatalError(String message, Throwable cause) {} @Override public void failTask(ExecutionAttemptID executionAttemptID, Throwable cause) { if (taskSlotTable != null) { taskSlotTable.getTask(executionAttemptID).failExternally(cause); } } @Override public void updateTaskExecutionState(TaskExecutionState taskExecutionState) { Optional<CompletableFuture<Void>> listenerFuture = taskManagerActionListeners.getListenerFuture( taskExecutionState.getID(), taskExecutionState.getExecutionState()); if (listenerFuture.isPresent()) { listenerFuture.get().complete(null); } if (jobMasterGateway != null) { CompletableFuture<Acknowledge> futureAcknowledge = jobMasterGateway.updateTaskExecutionState(taskExecutionState); futureAcknowledge.whenComplete( (ack, throwable) -> { if (throwable != null) { failTask(taskExecutionState.getID(), throwable); } }); } } @Override public void notifyEndOfData(ExecutionAttemptID executionAttemptID) {} private static
TestTaskManagerActions
java
google__guice
extensions/assistedinject/src/com/google/inject/assistedinject/BindingCollector.java
{ "start": 947, "end": 1086 }
class ____ collecting factory bindings. Used for configuring {@link FactoryProvider2}. * * @author schmitt@google.com (Peter Schmitt) */
for
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/elementcollection/EmbeddedElementCollectionWithIdenticallyNamedAssociationTest.java
{ "start": 3827, "end": 4337 }
class ____ { @Id private Integer id; private String name; @OneToOne(mappedBy = "identicallyNamedAssociation", fetch = FetchType.EAGER) private EntityB b; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public EntityB getB() { return b; } public void setB(EntityB b) { this.b = b; } @Override public String toString() { return "EntityA{" + "id=" + id + '}'; } } @Entity(name = "entityB") public static
EntityA
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-test/src/test/java/smoketest/test/SampleTestApplicationWebIntegrationTests.java
{ "start": 1808, "end": 2403 }
class ____ { private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("01234567890123456"); @Autowired private TestRestTemplate restTemplate; @MockitoBean private VehicleDetailsService vehicleDetailsService; @BeforeEach void setup() { given(this.vehicleDetailsService.getVehicleDetails(VIN)).willReturn(new VehicleDetails("Honda", "Civic")); } @Test void test() { assertThat(this.restTemplate.getForEntity("/{username}/vehicle", String.class, "sframework").getStatusCode()) .isEqualTo(HttpStatus.OK); } }
SampleTestApplicationWebIntegrationTests
java
quarkusio__quarkus
extensions/elasticsearch-rest-client-common/deployment/src/main/java/io/quarkus/elasticsearch/restclient/common/deployment/ElasticsearchRestClientProcessor.java
{ "start": 286, "end": 660 }
class ____ { @BuildStep public void build(BuildProducer<ExtensionSslNativeSupportBuildItem> extensionSslNativeSupport) { // Indicates that this extension would like the SSL support to be enabled extensionSslNativeSupport.produce(new ExtensionSslNativeSupportBuildItem(Feature.ELASTICSEARCH_REST_CLIENT_COMMON)); } }
ElasticsearchRestClientProcessor
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/LifeCycle.java
{ "start": 1105, "end": 1760 }
class ____ been loaded. From here, calling the {@link #start()} method will change this * state to {@link State#STARTING}. After successfully being started, this state is changed to {@link State#STARTED}. * When the {@link #stop()} is called, this goes into the {@link State#STOPPING} state. After successfully being * stopped, this goes into the {@link State#STOPPED} state. In most circumstances, implementation classes should * store their {@link State} in a {@code volatile} field or inside an * {@link java.util.concurrent.atomic.AtomicReference} dependent on synchronization and concurrency requirements. * * @see AbstractLifeCycle */ public
has
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/aot/hint/support/SpringPropertiesRuntimeHintsTests.java
{ "start": 1183, "end": 1700 }
class ____ { private RuntimeHints hints; @BeforeEach void setup() { this.hints = new RuntimeHints(); SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories") .load(RuntimeHintsRegistrar.class).forEach(registrar -> registrar .registerHints(this.hints, ClassUtils.getDefaultClassLoader())); } @Test void springPropertiesResourceHasHints() { assertThat(RuntimeHintsPredicates.resource().forResource("spring.properties")).accepts(this.hints); } }
SpringPropertiesRuntimeHintsTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/InterruptedExceptionSwallowedTest.java
{ "start": 4442, "end": 4924 }
class ____ implements AutoCloseable { public int close = 1; public void close() {} } void test() { try (Mischief m = new Mischief()) {} } } """) .doTest(); } @Test public void negative_rethrown() { compilationHelper .addSourceLines( "Test.java", """ import java.util.concurrent.Future;
Mischief
java
apache__camel
tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/SchemaGeneratorMojo.java
{ "start": 57269, "end": 59719 }
class ____ it will override the // setExpression method where we can provide the javadoc for the // given EIP String docComment = findJavaDoc(fieldElement, fieldName, name, originalClassType, true); // indicate that this element is one of when Set<String> oneOfTypes = new HashSet<>(); oneOfTypes.add("when"); // when is predicate boolean asPredicate = true; boolean important = false; String displayName = null; Metadata metadata = fieldElement.getAnnotation(Metadata.class); if (metadata != null) { displayName = metadata.displayName(); important = metadata.important(); } boolean deprecated = fieldElement.getAnnotation(Deprecated.class) != null; String deprecationNote = null; if (metadata != null) { deprecationNote = metadata.deprecationNote(); } String label = null; if (metadata != null) { label = metadata.label(); } final String kind = "element"; EipOptionModel ep = createOption(name, displayName, kind, fieldTypeName, false, "", label, docComment, deprecated, deprecationNote, false, null, oneOfTypes, asPredicate, false, important); eipOptions.add(ep); } } private String fetchName(String elementRef, String fieldName, String prefix) { String name = elementRef; if (Strings.isNullOrEmpty(name) || "##default".equals(name)) { name = fieldName; } name = prefix + name; return name; } private String fetchElementName(XmlElement element, Field fieldElement, String prefix) { String fieldName = fieldElement.getName(); String name = element.name(); if (Strings.isNullOrEmpty(name) || "##default".equals(name)) { name = fieldName; } // special for value definition which can be wrapped if ("value".equals(name)) { XmlElementWrapper wrapper = fieldElement.getAnnotation(XmlElementWrapper.class); String n = wrapper.name(); if (!"##default".equals(n)) { name = n; } } name = prefix + name; return name; } /** * Whether the
as
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/PhysicalSlotRequest.java
{ "start": 3175, "end": 3684 }
class ____ { private final SlotRequestId slotRequestId; private final PhysicalSlot physicalSlot; public Result(final SlotRequestId slotRequestId, final PhysicalSlot physicalSlot) { this.slotRequestId = slotRequestId; this.physicalSlot = physicalSlot; } public SlotRequestId getSlotRequestId() { return slotRequestId; } public PhysicalSlot getPhysicalSlot() { return physicalSlot; } } }
Result
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/FluxSampleTest.java
{ "start": 1183, "end": 7961 }
class ____ { @Test public void sourceNull() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> { new FluxSample<>(null, Flux.never()); }); } @Test public void otherNull() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> { Flux.never().sample((Publisher<Object>) null); }); } void sample(boolean complete, boolean which) { Sinks.Many<Integer> main = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<String> other = Sinks.unsafe().many().multicast().directBestEffort(); AssertSubscriber<Integer> ts = AssertSubscriber.create(); main.asFlux().sample(other.asFlux()).subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertNoError(); main.emitNext(1, FAIL_FAST); ts.assertNoValues() .assertNotComplete() .assertNoError(); other.emitNext("first", FAIL_FAST); ts.assertValues(1) .assertNoError() .assertNotComplete(); other.emitNext("second", FAIL_FAST); ts.assertValues(1) .assertNoError() .assertNotComplete(); main.emitNext(2, FAIL_FAST); ts.assertValues(1) .assertNoError() .assertNotComplete(); other.emitNext("third", FAIL_FAST); ts.assertValues(1, 2) .assertNoError() .assertNotComplete(); Sinks.Many<?> p = which ? main : other; if (complete) { p.emitComplete(FAIL_FAST); ts.assertValues(1, 2) .assertComplete() .assertNoError(); } else { p.emitError(new RuntimeException("forced failure"), FAIL_FAST); ts.assertValues(1, 2) .assertNotComplete() .assertError(RuntimeException.class) .assertErrorMessage("forced failure"); } assertThat(main.currentSubscriberCount()).as("main has subscriber").isZero(); assertThat(other.currentSubscriberCount()).as("other has subscriber").isZero(); } @Test public void normal1() { sample(true, false); } @Test public void normal2() { sample(true, true); } @Test public void error1() { sample(false, false); } @Test public void error2() { sample(false, true); } @Test public void subscriberCancels() { Sinks.Many<Integer> main = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<String> other = Sinks.unsafe().many().multicast().directBestEffort(); AssertSubscriber<Integer> ts = AssertSubscriber.create(); main.asFlux().sample(other.asFlux()).subscribe(ts); assertThat(main.currentSubscriberCount()).as("main has subscriber").isPositive(); assertThat(other.currentSubscriberCount()).as("other has subscriber").isPositive(); ts.cancel(); assertThat(main.currentSubscriberCount()).as("main has subscriber").isZero(); assertThat(other.currentSubscriberCount()).as("other has subscriber").isZero(); ts.assertNoValues() .assertNoError() .assertNotComplete(); } public void completeImmediately(boolean which) { Sinks.Many<Integer> main = Sinks.unsafe().many().multicast().directBestEffort(); Sinks.Many<String> other = Sinks.unsafe().many().multicast().directBestEffort(); if (which) { main.emitComplete(FAIL_FAST); } else { other.emitComplete(FAIL_FAST); } AssertSubscriber<Integer> ts = AssertSubscriber.create(); main.asFlux().sample(other.asFlux()).subscribe(ts); assertThat(main.currentSubscriberCount()).as("main has subscriber").isZero(); assertThat(other.currentSubscriberCount()).as("other has subscriber").isZero(); ts.assertNoValues() .assertNoError() .assertComplete(); } @Test public void mainCompletesImmediately() { completeImmediately(true); } @Test public void otherCompletesImmediately() { completeImmediately(false); } @Test public void sampleIncludesLastItem() { Flux<Integer> source = Flux.concat( Flux.range(1, 5), Mono.delay(Duration.ofMillis(300)).ignoreElement().map(Long::intValue), Flux.just(80, 90, 100) ).hide(); Duration duration = StepVerifier.create(source.sample(Duration.ofMillis(250))) .expectNext(5) .expectNext(100) .verifyComplete(); //sanity check on the sequence duration assertThat(duration.toMillis()).isLessThan(500); } @Test public void sourceTerminatesBeforeSamplingEmits() { Flux<Integer> source = Flux.just(1, 2).hide(); Duration duration = StepVerifier.create(source.sample(Duration.ofMillis(250))) .expectNext(2) .verifyComplete(); //sanity check on the sequence duration assertThat(duration.toMillis()).isLessThan(250); } @Test public void sourceErrorsBeforeSamplingNoEmission() { Flux<Integer> source = Flux.just(1, 2).concatWith(Mono.error(new IllegalStateException("boom"))); Duration duration = StepVerifier.create(source.sample(Duration.ofMillis(250))) .verifyErrorMessage("boom"); //sanity check on the sequence duration assertThat(duration.toMillis()).isLessThan(250); } @Test public void scanMainSubscriber() { CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null); FluxSample.SampleMainSubscriber<Integer> test = new FluxSample.SampleMainSubscriber<>(actual); Subscription parent = Operators.emptySubscription(); test.onSubscribe(parent); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent); assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); test.requested = 35; assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(35L); test.value = 5; assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(1); assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse(); test.cancel(); assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue(); } @Test public void scanOtherSubscriber() { CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null); FluxSample.SampleMainSubscriber<Integer> main = new FluxSample.SampleMainSubscriber<>(actual); FluxSample.SampleOther<Integer, Integer> test = new FluxSample.SampleOther<>(main); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(main.other); assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(main); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(Integer.MAX_VALUE); assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse(); main.cancelOther(); assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue(); } }
FluxSampleTest
java
spring-projects__spring-security
saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/Saml2RedirectAuthenticationRequestTests.java
{ "start": 954, "end": 2544 }
class ____ { private static final String IDP_SSO_URL = "https://sso-url.example.com/IDP/SSO"; @Test void serializeWhenDeserializeThenSameFields() { Saml2RedirectAuthenticationRequest authenticationRequest = getAuthenticationRequestBuilder().build(); byte[] bytes = SerializationUtils.serialize(authenticationRequest); Saml2RedirectAuthenticationRequest deserializedAuthenticationRequest = (Saml2RedirectAuthenticationRequest) SerializationUtils .deserialize(bytes); assertThat(deserializedAuthenticationRequest).usingRecursiveComparison().isEqualTo(authenticationRequest); } @Test void serializeWhenDeserializeAndCompareToOtherThenNotSame() { Saml2RedirectAuthenticationRequest authenticationRequest = getAuthenticationRequestBuilder().build(); Saml2RedirectAuthenticationRequest otherAuthenticationRequest = getAuthenticationRequestBuilder() .relayState("relay") .build(); byte[] bytes = SerializationUtils.serialize(otherAuthenticationRequest); Saml2RedirectAuthenticationRequest deserializedAuthenticationRequest = (Saml2RedirectAuthenticationRequest) SerializationUtils .deserialize(bytes); assertThat(deserializedAuthenticationRequest).usingRecursiveComparison().isNotEqualTo(authenticationRequest); } private Saml2RedirectAuthenticationRequest.Builder getAuthenticationRequestBuilder() { return Saml2RedirectAuthenticationRequest .withRelyingPartyRegistration(TestRelyingPartyRegistrations.relyingPartyRegistration().build()) .samlRequest("request") .authenticationRequestUri(IDP_SSO_URL); } }
Saml2RedirectAuthenticationRequestTests
java
redisson__redisson
redisson/src/main/java/org/redisson/api/Message.java
{ "start": 808, "end": 1919 }
class ____<V> { String id; V payload; Map<String, Object> headers; public Message(String id, V payload, Map<String, Object> headers) { this.id = id; this.payload = payload; this.headers = Collections.unmodifiableMap(headers); } public <T> Map<String, T> getHeaders() { return (Map<String, T>) headers; } public String getId() { return id; } public V getPayload() { return payload; } @Override public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) return false; Message<?> message = (Message<?>) o; return Objects.equals(id, message.id) && Objects.equals(payload, message.payload) && Objects.equals(headers, message.headers); } @Override public int hashCode() { return Objects.hash(id, payload, headers); } @Override public String toString() { return "Message{" + "id='" + id + '\'' + ", payload=" + payload + ", headers=" + headers + '}'; } }
Message
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/Uuid.java
{ "start": 1417, "end": 6829 }
class ____ implements Comparable<Uuid> { /** * A reserved UUID. Will never be returned by the randomUuid method. */ public static final Uuid ONE_UUID = new Uuid(0L, 1L); /** * A UUID for the metadata topic in KRaft mode. Will never be returned by the randomUuid method. */ public static final Uuid METADATA_TOPIC_ID = ONE_UUID; /** * A UUID that represents a null or empty UUID. Will never be returned by the randomUuid method. */ public static final Uuid ZERO_UUID = new Uuid(0L, 0L); /** * The set of reserved UUIDs that will never be returned by the randomUuid method. */ public static final Set<Uuid> RESERVED = Set.of(ZERO_UUID, ONE_UUID); private final long mostSignificantBits; private final long leastSignificantBits; /** * Constructs a 128-bit type 4 UUID where the first long represents the most significant 64 bits * and the second long represents the least significant 64 bits. */ public Uuid(long mostSigBits, long leastSigBits) { this.mostSignificantBits = mostSigBits; this.leastSignificantBits = leastSigBits; } private static Uuid unsafeRandomUuid() { java.util.UUID jUuid = java.util.UUID.randomUUID(); return new Uuid(jUuid.getMostSignificantBits(), jUuid.getLeastSignificantBits()); } /** * Static factory to retrieve a type 4 (pseudo randomly generated) UUID. * * This will not generate a UUID equal to 0, 1, or one whose string representation starts with a dash ("-") */ public static Uuid randomUuid() { Uuid uuid = unsafeRandomUuid(); while (RESERVED.contains(uuid) || uuid.toString().startsWith("-")) { uuid = unsafeRandomUuid(); } return uuid; } /** * Returns the most significant bits of the UUID's 128 value. */ public long getMostSignificantBits() { return this.mostSignificantBits; } /** * Returns the least significant bits of the UUID's 128 value. */ public long getLeastSignificantBits() { return this.leastSignificantBits; } /** * Returns true iff obj is another Uuid represented by the same two long values. */ @Override public boolean equals(Object obj) { if ((null == obj) || (obj.getClass() != this.getClass())) return false; Uuid id = (Uuid) obj; return this.mostSignificantBits == id.mostSignificantBits && this.leastSignificantBits == id.leastSignificantBits; } /** * Returns a hash code for this UUID */ @Override public int hashCode() { long xor = mostSignificantBits ^ leastSignificantBits; return (int) (xor >> 32) ^ (int) xor; } /** * Returns a base64 string encoding of the UUID. */ @Override public String toString() { return Base64.getUrlEncoder().withoutPadding().encodeToString(getBytesFromUuid()); } /** * Creates a UUID based on a base64 string encoding used in the toString() method. */ public static Uuid fromString(String str) { if (str.length() > 24) { throw new IllegalArgumentException("Input string with prefix `" + str.substring(0, 24) + "` is too long to be decoded as a base64 UUID"); } ByteBuffer uuidBytes = ByteBuffer.wrap(Base64.getUrlDecoder().decode(str)); if (uuidBytes.remaining() != 16) { throw new IllegalArgumentException("Input string `" + str + "` decoded as " + uuidBytes.remaining() + " bytes, which is not equal to the expected 16 bytes " + "of a base64-encoded UUID"); } return new Uuid(uuidBytes.getLong(), uuidBytes.getLong()); } private byte[] getBytesFromUuid() { // Extract bytes for uuid which is 128 bits (or 16 bytes) long. ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]); uuidBytes.putLong(this.mostSignificantBits); uuidBytes.putLong(this.leastSignificantBits); return uuidBytes.array(); } @Override public int compareTo(Uuid other) { if (mostSignificantBits > other.mostSignificantBits) { return 1; } else if (mostSignificantBits < other.mostSignificantBits) { return -1; } else if (leastSignificantBits > other.leastSignificantBits) { return 1; } else if (leastSignificantBits < other.leastSignificantBits) { return -1; } else { return 0; } } /** * Convert a list of Uuid to an array of Uuid. * * @param list The input list * @return The output array */ public static Uuid[] toArray(List<Uuid> list) { if (list == null) return null; Uuid[] array = new Uuid[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = list.get(i); } return array; } /** * Convert an array of Uuids to a list of Uuid. * * @param array The input array * @return The output list */ public static List<Uuid> toList(Uuid[] array) { if (array == null) return null; List<Uuid> list = new ArrayList<>(array.length); list.addAll(Arrays.asList(array)); return list; } }
Uuid
java
elastic__elasticsearch
modules/reindex/src/main/java/org/elasticsearch/reindex/Reindexer.java
{ "start": 20861, "end": 23207 }
class ____ extends ScriptApplier<ReindexMetadata> { private ReindexScript.Factory reindex; ReindexScriptApplier( WorkerBulkByScrollTaskState taskWorker, ScriptService scriptService, Script script, Map<String, Object> params, LongSupplier nowInMillisSupplier ) { super(taskWorker, scriptService, script, params, nowInMillisSupplier); } @Override protected CtxMap<ReindexMetadata> execute(ScrollableHitSource.Hit doc, Map<String, Object> source) { if (reindex == null) { reindex = scriptService.compile(script, ReindexScript.CONTEXT); } CtxMap<ReindexMetadata> ctxMap = new CtxMap<>( source, new ReindexMetadata( doc.getIndex(), doc.getId(), doc.getVersion(), doc.getRouting(), INDEX, nowInMillisSupplier.getAsLong() ) ); reindex.newInstance(params, ctxMap).execute(); return ctxMap; } @Override protected void updateRequest(RequestWrapper<?> request, ReindexMetadata metadata) { if (metadata.indexChanged()) { request.setIndex(metadata.getIndex()); } if (metadata.idChanged()) { request.setId(metadata.getId()); } if (metadata.versionChanged()) { if (metadata.isVersionInternal()) { request.setVersion(Versions.MATCH_ANY); request.setVersionType(INTERNAL); } else { request.setVersion(metadata.getVersion()); } } /* * Its important that routing comes after parent in case you want to * change them both. */ if (metadata.routingChanged()) { request.setRouting(metadata.getRouting()); } } } } }
ReindexScriptApplier
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/jackson/SimpleGrantedAuthorityMixinTests.java
{ "start": 1200, "end": 3030 }
class ____ extends AbstractMixinTests { // @formatter:off public static final String AUTHORITY_JSON = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"authority\": \"ROLE_USER\"}"; public static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", [" + AUTHORITY_JSON + "]]"; public static final String AUTHORITIES_SET_JSON = "[\"java.util.Collections$UnmodifiableSet\", [" + AUTHORITY_JSON + "]]"; public static final String NO_AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", []]"; public static final String EMPTY_AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$EmptyList\", []]"; public static final String NO_AUTHORITIES_SET_JSON = "[\"java.util.Collections$UnmodifiableSet\", []]"; // @formatter:on @Test public void serializeSimpleGrantedAuthorityTest() throws JsonProcessingException, JSONException { SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_USER"); String serializeJson = this.mapper.writeValueAsString(authority); JSONAssert.assertEquals(AUTHORITY_JSON, serializeJson, true); } @Test public void deserializeGrantedAuthorityTest() throws IOException { SimpleGrantedAuthority authority = this.mapper.readValue(AUTHORITY_JSON, SimpleGrantedAuthority.class); assertThat(authority).isNotNull(); assertThat(authority.getAuthority()).isNotNull().isEqualTo("ROLE_USER"); } @Test public void deserializeGrantedAuthorityWithoutRoleTest() throws IOException { String json = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"}"; assertThatExceptionOfType(ValueInstantiationException.class) .isThrownBy(() -> this.mapper.readValue(json, SimpleGrantedAuthority.class)); } }
SimpleGrantedAuthorityMixinTests
java
spring-projects__spring-framework
spring-aop/src/test/java/org/springframework/aop/framework/AbstractProxyExceptionHandlingTests.java
{ "start": 6072, "end": 6129 }
class ____ extends Exception { } }
DeclaredCheckedException
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/test/store/MockFSDirectoryFactory.java
{ "start": 7317, "end": 7792 }
class ____ extends MockDirectoryWrapper { private final boolean crash; public ElasticsearchMockDirectoryWrapper(Random random, Directory delegate, boolean crash) { super(random, delegate); this.crash = crash; } @Override public synchronized void crash() throws IOException { if (crash) { super.crash(); } } } static final
ElasticsearchMockDirectoryWrapper
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/DefaultAssertionErrorCollector.java
{ "start": 885, "end": 5940 }
class ____ implements AssertionErrorCollector { // Marking this field as volatile doesn't ensure complete thread safety // (mutual exclusion, race-free behavior), but guarantees eventual visibility private volatile boolean wasSuccess = true; private final List<AssertionError> collectedAssertionErrors = synchronizedList(new ArrayList<>()); private final List<AfterAssertionErrorCollected> callbacks = synchronizedList(new ArrayList<>()); private AssertionErrorCollector delegate = null; public DefaultAssertionErrorCollector() { super(); callbacks.add(this); } // I think ideally, this would be set in the constructor and made final; // however, that would require a new constructor that would not make it // backward compatible with existing SoftAssertionProvider implementations. @Override public void setDelegate(AssertionErrorCollector delegate) { this.delegate = delegate; } @Override public Optional<AssertionErrorCollector> getDelegate() { return Optional.ofNullable(delegate); } @Override public void collectAssertionError(AssertionError error) { if (delegate == null) { collectedAssertionErrors.add(error); wasSuccess = false; } else { delegate.collectAssertionError(error); } callbacks.forEach(callback -> callback.onAssertionErrorCollected(error)); } /** * Returns a list of soft assertions collected errors. If a delegate * has been set (see {@link #setDelegate(AssertionErrorCollector) setDelegate()}, * then this method will return the result of the delegate's {@code assertErrorsCollected()}. * * @return A list of soft assertions collected errors. */ @Override public List<AssertionError> assertionErrorsCollected() { List<AssertionError> errors = delegate != null ? delegate.assertionErrorsCollected() : unmodifiableList(collectedAssertionErrors); return decorateErrorsCollected(errors); } /** * Same as {@link DefaultAssertionErrorCollector#addAfterAssertionErrorCollected(AfterAssertionErrorCollected)}, but * also removes all previously added callbacks. * * @param afterAssertionErrorCollected the callback. * * @since 3.17.0 */ public void setAfterAssertionErrorCollected(AfterAssertionErrorCollected afterAssertionErrorCollected) { callbacks.clear(); addAfterAssertionErrorCollected(afterAssertionErrorCollected); } /** * Register a callback allowing to react after an {@link AssertionError} is collected by the current soft assertions. * <p> * The callback is an instance of {@link AfterAssertionErrorCollected} which can be expressed as a lambda. * <p> * Example: * <pre><code class='java'> SoftAssertions softly = new SoftAssertions(); * StringBuilder reportBuilder = new StringBuilder(String.format("Assertion errors report:%n")); * * // register a single callback with: * softly.setAfterAssertionErrorCollected(error -&gt; reportBuilder.append(String.format("------------------%n%s%n", error.getMessage()))); * // or as many as needed with: * // softly.addAfterAssertionErrorCollected(error -&gt; reportBuilder.append(String.format("------------------%n%s%n", error.getMessage()))); * * // the AssertionErrors corresponding to the failing assertions are registered in the report * softly.assertThat("The Beatles").isEqualTo("The Rolling Stones"); * softly.assertThat(123).isEqualTo(123) * .isEqualTo(456);</code></pre> * <p> * Resulting {@code reportBuilder}: * <pre><code class='java'> Assertion errors report: * ------------------ * Expecting: * &lt;"The Beatles"&gt; * to be equal to: * &lt;"The Rolling Stones"&gt; * but was not. * ------------------ * Expecting: * &lt;123&gt; * to be equal to: * &lt;456&gt; * but was not.</code></pre> * <p> * Alternatively, if you have defined your own SoftAssertions subclass and inherited from {@link AbstractSoftAssertions}, * the only thing you have to do is to override {@link AfterAssertionErrorCollected#onAssertionErrorCollected(AssertionError)}. * * @param afterAssertionErrorCollected the callback. * * @since 3.26.0 */ public void addAfterAssertionErrorCollected(AfterAssertionErrorCollected afterAssertionErrorCollected) { callbacks.add(afterAssertionErrorCollected); } @Override public void succeeded() { if (delegate == null) { wasSuccess = true; } else { delegate.succeeded(); } } @Override public boolean wasSuccess() { return delegate == null ? wasSuccess : delegate.wasSuccess(); } /** * Modifies collected errors. Override to customize modification. * @param <T> the supertype to use in the list return value * @param errors list of errors to decorate * @return decorated list */ protected <T extends Throwable> List<T> decorateErrorsCollected(List<? extends T> errors) { return Throwables.addLineNumberToErrorMessages(errors); } }
DefaultAssertionErrorCollector
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/console/command/CommandLineOptionsParsingTests.java
{ "start": 34042, "end": 35017 }
enum ____ { args { @Override Result parseArgLine(String argLine) { return parse(split(argLine)); } }, atFile { @Override Result parseArgLine(String argLine) throws IOException { var atFile = Files.createTempFile("junit-launcher-args", ".txt"); try { Files.write(atFile, List.of(split(argLine))); return parse("@" + atFile); } finally { Files.deleteIfExists(atFile); } } }; abstract Result parseArgLine(String argLine) throws IOException; private static String[] split(String argLine) { return argLine.isEmpty() ? new String[0] : argLine.split("\\s+"); } } private static Result parse(String... args) { ExecuteTestsCommand command = new ExecuteTestsCommand((__, ___) -> mock()); command.parseArgs(args); return new Result(command.toTestDiscoveryOptions(), command.toTestConsoleOutputOptions()); } record Result(TestDiscoveryOptions discovery, TestConsoleOutputOptions output) { } }
ArgsType
java
apache__camel
components/camel-aws/camel-aws2-sqs/src/test/java/org/apache/camel/component/aws2/sqs/SqsComponentTest.java
{ "start": 1401, "end": 4829 }
class ____ extends CamelTestSupport { @EndpointInject("direct:start") private ProducerTemplate template; @EndpointInject("mock:result") private MockEndpoint result; @BindToRegistry("amazonSQSClient") private AmazonSQSClientMock client = new AmazonSQSClientMock(); @Test public void sendInOnly() throws Exception { result.expectedMessageCount(1); Exchange exchange = template.send("direct:start", ExchangePattern.InOnly, new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody("This is my message text."); } }); MockEndpoint.assertIsSatisfied(context); Exchange resultExchange = result.getExchanges().get(0); assertEquals("This is my message text.", resultExchange.getIn().getBody()); assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.MESSAGE_ID)); assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.RECEIPT_HANDLE)); assertEquals("6a1559560f67c5e7a7d5d838bf0272ee", resultExchange.getIn().getHeader(Sqs2Constants.MD5_OF_BODY)); assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.ATTRIBUTES)); assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.MESSAGE_ATTRIBUTES)); assertEquals("This is my message text.", exchange.getIn().getBody()); assertNotNull(exchange.getIn().getHeader(Sqs2Constants.MESSAGE_ID)); assertEquals("6a1559560f67c5e7a7d5d838bf0272ee", exchange.getIn().getHeader(Sqs2Constants.MD5_OF_BODY)); } @Test public void sendInOut() throws Exception { result.expectedMessageCount(1); Exchange exchange = template.send("direct:start", ExchangePattern.InOut, new Processor() { public void process(Exchange exchange) { exchange.getIn().setBody("This is my message text."); } }); MockEndpoint.assertIsSatisfied(context); Exchange resultExchange = result.getExchanges().get(0); assertEquals("This is my message text.", resultExchange.getIn().getBody()); assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.RECEIPT_HANDLE)); assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.MESSAGE_ID)); assertEquals("6a1559560f67c5e7a7d5d838bf0272ee", resultExchange.getIn().getHeader(Sqs2Constants.MD5_OF_BODY)); assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.ATTRIBUTES)); assertNotNull(resultExchange.getIn().getHeader(Sqs2Constants.MESSAGE_ATTRIBUTES)); assertEquals("This is my message text.", exchange.getMessage().getBody()); assertNotNull(exchange.getMessage().getHeader(Sqs2Constants.MESSAGE_ID)); assertEquals("6a1559560f67c5e7a7d5d838bf0272ee", exchange.getMessage().getHeader(Sqs2Constants.MD5_OF_BODY)); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { final String sqsURI = String.format( "aws2-sqs://MyQueue?amazonSQSClient=#amazonSQSClient&messageRetentionPeriod=%s&maximumMessageSize=%s&policy=%s", "1209600", "65536", ""); @Override public void configure() { from("direct:start").to(sqsURI); from(sqsURI).to("mock:result"); } }; } }
SqsComponentTest
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/authorization/ExpressionAuthorizationDecision.java
{ "start": 896, "end": 1420 }
class ____ extends AuthorizationDecision { private final Expression expression; public ExpressionAuthorizationDecision(boolean granted, Expression expressionAttribute) { super(granted); this.expression = expressionAttribute; } public Expression getExpression() { return this.expression; } @Override public String toString() { return getClass().getSimpleName() + " [" + "granted=" + isGranted() + ", expressionAttribute=" + this.expression.getExpressionString() + ']'; } }
ExpressionAuthorizationDecision
java
bumptech__glide
mocks/src/main/java/com/bumptech/glide/load/engine/executor/MockGlideExecutor.java
{ "start": 1261, "end": 3180 }
class ____ extends ForwardingExecutorService { private static final StrictMode.ThreadPolicy THREAD_POLICY = new StrictMode.ThreadPolicy.Builder().detectNetwork().penaltyDeath().build(); private final ExecutorService delegate; DirectExecutorService() { delegate = MoreExecutors.newDirectExecutorService(); } @Override protected ExecutorService delegate() { return delegate; } @NonNull @Override public <T> Future<T> submit(@NonNull Runnable task, @NonNull T result) { return getUninterruptibly(super.submit(task, result)); } @NonNull @Override public <T> Future<T> submit(@NonNull Callable<T> task) { return getUninterruptibly(super.submit(task)); } @NonNull @Override public Future<?> submit(@NonNull Runnable task) { return getUninterruptibly(super.submit(task)); } @Override public void execute(@NonNull final Runnable command) { delegate.execute( new Runnable() { @Override public void run() { StrictMode.ThreadPolicy oldPolicy = StrictMode.getThreadPolicy(); StrictMode.setThreadPolicy(THREAD_POLICY); try { command.run(); } finally { StrictMode.setThreadPolicy(oldPolicy); } } }); } private <T> Future<T> getUninterruptibly(Future<T> future) { boolean interrupted = false; try { while (!future.isDone()) { try { future.get(); } catch (ExecutionException e) { throw new RuntimeException(e); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } return future; } } }
DirectExecutorService
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/filter/MapInclusionTest.java
{ "start": 1727, "end": 3374 }
class ____ { @JsonInclude(JsonInclude.Include.NON_EMPTY) public Wrapper2909 nested = new Wrapper2909(); } /* /********************************************************** /* Test methods /********************************************************** */ final private ObjectMapper MAPPER = newJsonMapper(); // [databind#588] @Test public void testNonEmptyValueMapViaProp() throws IOException { String json = MAPPER.writeValueAsString(new NoEmptiesMapContainer() .add("a", null) .add("b", "")); assertEquals(a2q("{}"), json); } @Test public void testNoNullsMap() throws IOException { NoNullsMapContainer input = new NoNullsMapContainer() .add("a", null) .add("b", ""); String json = MAPPER.writeValueAsString(input); assertEquals(a2q("{'stuff':{'b':''}}"), json); } @Test public void testNonEmptyNoNullsMap() throws IOException { NoNullsNotEmptyMapContainer input = new NoNullsNotEmptyMapContainer() .add("a", null) .add("b", ""); String json = MAPPER.writeValueAsString(input); assertEquals(a2q("{'stuff':{'b':''}}"), json); json = MAPPER.writeValueAsString(new NoNullsNotEmptyMapContainer() .add("a", null) .add("b", null)); assertEquals(a2q("{}"), json); } // [databind#2909] @Test public void testMapViaJsonValue() throws Exception { assertEquals(a2q("{}"), MAPPER.writeValueAsString(new TopLevel2099())); } }
TopLevel2099
java
apache__camel
tooling/maven/camel-api-component-maven-plugin/src/main/java/org/apache/camel/maven/AbstractSourceGeneratorMojo.java
{ "start": 989, "end": 1305 }
class ____ extends AbstractGeneratorMojo { @Parameter(defaultValue = "${project.basedir}/src/generated/java") protected File generatedSrcDir; @Parameter(defaultValue = "${project.build.directory}/generated-test-sources/camel-component") protected File generatedTestDir;
AbstractSourceGeneratorMojo
java
quarkusio__quarkus
integration-tests/hibernate-orm-panache/src/main/java/io/quarkus/it/panache/defaultpu/BeerRepository.java
{ "start": 263, "end": 412 }
class ____ implements PanacheRepository<Beer> { public List<Beer> findOrdered() { return find("ORDER BY name").list(); } }
BeerRepository
java
dropwizard__dropwizard
dropwizard-jersey/src/main/java/io/dropwizard/jersey/jsr310/LocalTimeParam.java
{ "start": 313, "end": 596 }
class ____ extends AbstractParam<LocalTime> { public LocalTimeParam(@Nullable final String input) { super(input); } @Override protected LocalTime parse(@Nullable final String input) throws Exception { return LocalTime.parse(input); } }
LocalTimeParam
java
elastic__elasticsearch
x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/TrainedModelCRUDIT.java
{ "start": 1480, "end": 6432 }
class ____ extends MlSingleNodeTestCase { static final String BASE_64_ENCODED_MODEL = "UEsDBAAACAgAAAAAAAAAAAAAAAAAAAAAAAAUAA4Ac2ltcGxlbW9kZWwvZGF0YS5wa2xGQgoAWlpaWlpaWlpaWoACY19fdG9yY2hfXwp" + "TdXBlclNpbXBsZQpxACmBfShYCAAAAHRyYWluaW5ncQGIdWJxAi5QSwcIXOpBBDQAAAA0AAAAUEsDBBQACAgIAAAAAAAAAAAAAAAAAA" + "AAAAAdAEEAc2ltcGxlbW9kZWwvY29kZS9fX3RvcmNoX18ucHlGQj0AWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaW" + "lpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWnWOMWvDMBCF9/yKI5MMrnHTQsHgjt2aJdlCEIp9SgWSTpykFvfXV1htaYds0nfv473Jqhjh" + "kAPywbhgUbzSnC02wwZAyqBYOUzIUUoY4XRe6SVr/Q8lVsYbf4UBLkS2kBk1aOIPxbOIaPVQtEQ8vUnZ/WlrSxTA+JCTNHMc4Ig+Ele" + "s+Jod+iR3N/jDDf74wxu4e/5+DmtE9mUyhdgFNq7bZ3ekehbruC6aTxS/c1rom6Z698WrEfIYxcn4JGTftLA7tzCnJeD41IJVC+U07k" + "umUHw3E47Vqh+xnULeFisYLx064mV8UTZibWFMmX0p23wBUEsHCE0EGH3yAAAAlwEAAFBLAwQUAAgICAAAAAAAAAAAAAAAAAAAAAAAJ" + "wA5AHNpbXBsZW1vZGVsL2NvZGUvX190b3JjaF9fLnB5LmRlYnVnX3BrbEZCNQBaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpa" + "WlpaWlpaWlpaWlpaWlpaWlpaWlpaWrWST0+DMBiHW6bOod/BGS94kKpo2Mwyox5x3pbgiXSAFtdR/nQu3IwHiZ9oX88CaeGu9tL0efq" + "+v8P7fmiGA1wgTgoIcECZQqe6vmYD6G4hAJOcB1E8NazTm+ELyzY4C3Q0z8MsRwF+j4JlQUPEEo5wjH0WB9hCNFqgpOCExZY5QnnEw7" + "ME+0v8GuaIs8wnKI7RigVrKkBzm0lh2OdjkeHllG28f066vK6SfEypF60S+vuYt4gjj2fYr/uPrSvRv356TepfJ9iWJRN0OaELQSZN3" + "FRPNbcP1PTSntMr0x0HzLZQjPYIEo3UaFeiISRKH0Mil+BE/dyT1m7tCBLwVO1MX4DK3bbuTlXuy8r71j5Aoho66udAoseOnrdVzx28" + "UFW6ROuO/lT6QKKyo79VU54emj9QSwcInsUTEDMBAAAFAwAAUEsDBAAACAgAAAAAAAAAAAAAAAAAAAAAAAAZAAYAc2ltcGxlbW9kZWw" + "vY29uc3RhbnRzLnBrbEZCAgBaWoACKS5QSwcIbS8JVwQAAAAEAAAAUEsDBAAACAgAAAAAAAAAAAAAAAAAAAAAAAATADsAc2ltcGxlbW" + "9kZWwvdmVyc2lvbkZCNwBaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaMwpQSwcI0" + "Z5nVQIAAAACAAAAUEsBAgAAAAAICAAAAAAAAFzqQQQ0AAAANAAAABQAAAAAAAAAAAAAAAAAAAAAAHNpbXBsZW1vZGVsL2RhdGEucGts" + "UEsBAgAAFAAICAgAAAAAAE0EGH3yAAAAlwEAAB0AAAAAAAAAAAAAAAAAhAAAAHNpbXBsZW1vZGVsL2NvZGUvX190b3JjaF9fLnB5UEs" + "BAgAAFAAICAgAAAAAAJ7FExAzAQAABQMAACcAAAAAAAAAAAAAAAAAAgIAAHNpbXBsZW1vZGVsL2NvZGUvX190b3JjaF9fLnB5LmRlYn" + "VnX3BrbFBLAQIAAAAACAgAAAAAAABtLwlXBAAAAAQAAAAZAAAAAAAAAAAAAAAAAMMDAABzaW1wbGVtb2RlbC9jb25zdGFudHMucGtsU" + "EsBAgAAAAAICAAAAAAAANGeZ1UCAAAAAgAAABMAAAAAAAAAAAAAAAAAFAQAAHNpbXBsZW1vZGVsL3ZlcnNpb25QSwYGLAAAAAAAAAAe" + "Ay0AAAAAAAAAAAAFAAAAAAAAAAUAAAAAAAAAagEAAAAAAACSBAAAAAAAAFBLBgcAAAAA/AUAAAAAAAABAAAAUEsFBgAAAAAFAAUAagE" + "AAJIEAAAAAA=="; static final long RAW_MODEL_SIZE; // size of the model before base64 encoding static { RAW_MODEL_SIZE = Base64.getDecoder().decode(BASE_64_ENCODED_MODEL).length; } @Before public void createComponents() throws Exception { waitForMlTemplates(); } public void testPutTrainedModelAndDefinition() { String modelId = "pytorch-model-put"; TrainedModelConfig config = client().execute( PutTrainedModelAction.INSTANCE, new PutTrainedModelAction.Request( TrainedModelConfig.builder() .setModelType(TrainedModelType.PYTORCH) .setInferenceConfig( new PassThroughConfig( new VocabularyConfig(InferenceIndexConstants.nativeDefinitionStore()), new BertTokenization(null, false, null, Tokenization.Truncate.NONE, -1), null ) ) .setModelId(modelId) .build(), false ) ).actionGet().getResponse(); assertThat(config.getLocation(), isA(IndexLocation.class)); assertThat(((IndexLocation) config.getLocation()).getIndexName(), equalTo(InferenceIndexConstants.nativeDefinitionStore())); client().execute( PutTrainedModelDefinitionPartAction.INSTANCE, new PutTrainedModelDefinitionPartAction.Request( modelId, new BytesArray(Base64.getDecoder().decode(BASE_64_ENCODED_MODEL)), 0, RAW_MODEL_SIZE, 1, false ) ).actionGet(); assertThat( client().admin() .indices() .prepareGetIndex(TEST_REQUEST_TIMEOUT) .addIndices(InferenceIndexConstants.nativeDefinitionStore()) .get() .indices().length, equalTo(1) ); client().execute(DeleteTrainedModelAction.INSTANCE, new DeleteTrainedModelAction.Request(modelId)).actionGet(); assertHitCount(client().prepareSearch(InferenceIndexConstants.nativeDefinitionStore()).setTrackTotalHitsUpTo(1).setSize(0), 0); } }
TrainedModelCRUDIT
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/Counters.java
{ "start": 12867, "end": 13329 }
class ____<T extends Enum<T>> extends FrameworkCounterGroup<T, Counter> { FrameworkGroupImpl(Class<T> cls) { super(cls); } @Override protected Counter newCounter(T key) { return new Counter(new FrameworkCounter<T>(key, getName())); } @Override public CounterGroupBase<Counter> getUnderlyingGroup() { return this; } } // Mix the file system counter group implementation into the Group
FrameworkGroupImpl
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/resources/TestTrafficController.java
{ "start": 3763, "end": 3989 }
class ____ dev eth0"; private static final int MIN_CONTAINER_CLASS_ID = 4; private static final String FORMAT_CONTAINER_CLASS_STR = "0x0042%04d"; private static final String FORMAT_ADD_CONTAINER_CLASS_TO_DEVICE = "
show
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_allMatch_Test.java
{ "start": 1028, "end": 1542 }
class ____ extends AtomicReferenceArrayAssertBaseTest { private Predicate<Object> predicate; @BeforeEach void beforeOnce() { predicate = o -> o != null; } @Override protected AtomicReferenceArrayAssert<Object> invoke_api_method() { return assertions.allMatch(predicate); } @Override protected void verify_internal_effects() { verify(iterables).assertAllMatch(info(), newArrayList(internalArray()), predicate, PredicateDescription.GIVEN); } }
AtomicReferenceArrayAssert_allMatch_Test
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsTests.java
{ "start": 114132, "end": 114311 }
interface ____ { String pattern(); } @ComponentScan(excludeFilters = { @Filter(pattern = "*Test"), @Filter(pattern = "*Tests") }) @Retention(RetentionPolicy.RUNTIME) @
Filter
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UngroupedOverloadsTest.java
{ "start": 12256, "end": 13431 }
class ____ { private void bar() {} // Something about `bar`. /** Does something. */ public void bar(int x) {} // Something about this `bar`. public void bar(int x, int y) {} // More stuff about `bar`. public void bar(int x, int y, int z) { // Some internal comments too. } public void bar(String s) {} public static final String FOO = "foo"; // This is super-important comment for `foo`. // Something about `baz`. public static final String BAZ = "baz"; // Stuff about `baz` continues. public void quux() {} }\ """) .doTest(); } @Test public void ungroupedOverloadsRefactoringMultiple() { refactoringHelper .addInputLines( "UngroupedOverloadsRefactoringMultiple.java", """ package com.google.errorprone.bugpatterns.testdata; /** * @author hanuszczak@google.com (Łukasz Hanuszczak) */
UngroupedOverloadsRefactoringComments
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/WebSocketFrameEncoder.java
{ "start": 956, "end": 1023 }
interface ____ extends ChannelOutboundHandler { }
WebSocketFrameEncoder
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/test/java/org/hibernate/processor/test/namedquery/TitleAndIsbn.java
{ "start": 157, "end": 421 }
class ____ { private final String title; private final String isbn; public TitleAndIsbn(String title, String isbn) { this.title = title; this.isbn = isbn; } public String title() { return title; } public String isbn() { return isbn; } }
TitleAndIsbn
java
resilience4j__resilience4j
resilience4j-framework-common/src/main/java/io/github/resilience4j/common/retry/configuration/CommonRetryConfigurationProperties.java
{ "start": 1344, "end": 11197 }
class ____ extends CommonProperties { private static final String DEFAULT = "default"; private final Map<String, InstanceProperties> instances = new HashMap<>(); private Map<String, InstanceProperties> configs = new HashMap<>(); /** * @param backend backend name * @return the retry configuration */ public RetryConfig createRetryConfig(String backend, CompositeCustomizer<RetryConfigCustomizer> compositeRetryCustomizer) { return createRetryConfig(instances.get(backend), compositeRetryCustomizer, backend); } /** * @param backend retry backend name * @return the configured spring backend properties */ @Nullable public InstanceProperties getBackendProperties(String backend) { InstanceProperties instanceProperties = instances.get(backend); if (instanceProperties == null) { instanceProperties = configs.get(DEFAULT); } else if (configs.get(DEFAULT) != null) { ConfigUtils.mergePropertiesIfAny(configs.get(DEFAULT), instanceProperties); } return instanceProperties; } /** * @return the configured retry backend properties */ public Map<String, InstanceProperties> getInstances() { return instances; } /** * For backwards compatibility when setting backends in configuration properties. */ public Map<String, InstanceProperties> getBackends() { return instances; } /** * @return common configuration for retry backend */ public Map<String, InstanceProperties> getConfigs() { return configs; } /** * @param instanceProperties the retry backend spring properties * @return the retry configuration */ public RetryConfig createRetryConfig(@Nullable InstanceProperties instanceProperties, CompositeCustomizer<RetryConfigCustomizer> compositeRetryCustomizer, String instanceName) { RetryConfig baseConfig = null; if (instanceProperties != null && StringUtils.isNotEmpty(instanceProperties.getBaseConfig())) { InstanceProperties baseProperties = configs.get(instanceProperties.getBaseConfig()); if (baseProperties == null) { throw new ConfigurationNotFoundException(instanceProperties.getBaseConfig()); } ConfigUtils.mergePropertiesIfAny(baseProperties, instanceProperties); baseConfig = createRetryConfig(baseProperties, compositeRetryCustomizer, instanceProperties.getBaseConfig()); } else if (!instanceName.equals(DEFAULT) && configs.get(DEFAULT) != null) { if (instanceProperties != null) { ConfigUtils.mergePropertiesIfAny(configs.get(DEFAULT), instanceProperties); } baseConfig = createRetryConfig(configs.get(DEFAULT), compositeRetryCustomizer, DEFAULT); } return buildConfig(baseConfig != null ? from(baseConfig) : custom(), instanceProperties, compositeRetryCustomizer, instanceName); } /** * @param properties the configured spring backend properties * @return retry config builder instance */ @SuppressWarnings("unchecked") private RetryConfig buildConfig(RetryConfig.Builder builder, @Nullable InstanceProperties properties, CompositeCustomizer<RetryConfigCustomizer> compositeRetryCustomizer, String backend) { if (properties != null) { configureRetryIntervalFunction(properties, builder); if (properties.getMaxAttempts() != null && properties.getMaxAttempts() != 0) { builder.maxAttempts(properties.getMaxAttempts()); } if (properties.getRetryExceptionPredicate() != null) { Predicate<Throwable> predicate = ClassUtils .instantiatePredicateClass(properties.getRetryExceptionPredicate()); builder.retryOnException(predicate); } if (properties.getIgnoreExceptions() != null) { builder.ignoreExceptions(properties.getIgnoreExceptions()); } if (properties.getRetryExceptions() != null) { builder.retryExceptions(properties.getRetryExceptions()); } if (properties.getResultPredicate() != null) { Predicate<Object> predicate = ClassUtils .instantiatePredicateClass(properties.getResultPredicate()); builder.retryOnResult(predicate); } if(properties.getConsumeResultBeforeRetryAttempt() != null){ BiConsumer<Integer, Object> biConsumer = ClassUtils.instantiateBiConsumer(properties.getConsumeResultBeforeRetryAttempt()); builder.consumeResultBeforeRetryAttempt(biConsumer); } if (properties.getIntervalBiFunction() != null) { IntervalBiFunction<Object> intervalBiFunction = ClassUtils .instantiateIntervalBiFunctionClass(properties.getIntervalBiFunction()); builder.intervalBiFunction(intervalBiFunction); } if(properties.getFailAfterMaxAttempts() != null) { builder.failAfterMaxAttempts(properties.getFailAfterMaxAttempts()); } } compositeRetryCustomizer.getCustomizer(backend) .ifPresent(customizer -> customizer.customize(builder)); return builder.build(); } /** * decide which retry delay policy will be configured based into the configured properties * * @param properties the backend retry properties * @param builder the retry config builder */ private void configureRetryIntervalFunction(InstanceProperties properties, RetryConfig.Builder<Object> builder) { // these take precedence over deprecated properties. Setting one or the other will still work. Duration waitDuration = properties.getWaitDuration(); if (waitDuration != null && waitDuration.toMillis() >= 0) { if (Boolean.TRUE.equals(properties.getEnableExponentialBackoff()) && Boolean.TRUE.equals(properties.getEnableRandomizedWait())) { configureExponentialBackoffAndRandomizedWait(properties, builder); } else if (Boolean.TRUE.equals(properties.getEnableExponentialBackoff())) { configureExponentialBackoff(properties, builder); } else if (Boolean.TRUE.equals(properties.getEnableRandomizedWait())) { configureRandomizedWait(properties, builder); } else { builder.waitDuration(waitDuration); } } } private void configureExponentialBackoffAndRandomizedWait(InstanceProperties properties, RetryConfig.Builder<Object> builder) { Duration waitDuration = properties.getWaitDuration(); Double backoffMultiplier = properties.getExponentialBackoffMultiplier(); Double randomizedWaitFactor = properties.getRandomizedWaitFactor(); Duration maxWaitDuration = properties.getExponentialMaxWaitDuration(); if (maxWaitDuration != null && randomizedWaitFactor != null && backoffMultiplier != null) { withIntervalBiFunction(builder, IntervalFunction.ofExponentialRandomBackoff(waitDuration, backoffMultiplier, randomizedWaitFactor, maxWaitDuration)); } else if (randomizedWaitFactor != null && backoffMultiplier != null) { withIntervalBiFunction(builder, IntervalFunction.ofExponentialRandomBackoff(waitDuration, backoffMultiplier, randomizedWaitFactor)); } else if (backoffMultiplier != null) { withIntervalBiFunction(builder, IntervalFunction.ofExponentialRandomBackoff(waitDuration, backoffMultiplier)); } else { withIntervalBiFunction(builder, IntervalFunction.ofExponentialRandomBackoff(waitDuration)); } } private void configureExponentialBackoff(InstanceProperties properties, RetryConfig.Builder<Object> builder) { Duration waitDuration = properties.getWaitDuration(); Double backoffMultiplier = properties.getExponentialBackoffMultiplier(); Duration maxWaitDuration = properties.getExponentialMaxWaitDuration(); if (maxWaitDuration != null && backoffMultiplier != null) { withIntervalBiFunction(builder, IntervalFunction.ofExponentialBackoff(waitDuration, backoffMultiplier, maxWaitDuration)); } else if (backoffMultiplier != null) { withIntervalBiFunction(builder, IntervalFunction.ofExponentialBackoff(waitDuration, backoffMultiplier)); } else { withIntervalBiFunction(builder, IntervalFunction.ofExponentialBackoff(waitDuration)); } } private void configureRandomizedWait(InstanceProperties properties, RetryConfig.Builder<Object> builder) { Duration waitDuration = properties.getWaitDuration(); Double randomizedWaitFactor = properties.getRandomizedWaitFactor(); if (randomizedWaitFactor != null) { withIntervalBiFunction(builder, IntervalFunction.ofRandomized(waitDuration, randomizedWaitFactor)); } else { withIntervalBiFunction(builder, IntervalFunction.ofRandomized(waitDuration)); } } private void withIntervalBiFunction(RetryConfig.Builder<Object> builder, IntervalFunction intervalFunction) { builder.intervalBiFunction(IntervalBiFunction.ofIntervalFunction(intervalFunction)); } /** * Class storing property values for configuring {@link io.github.resilience4j.retry.Retry} * instances. */ public static
CommonRetryConfigurationProperties
java
google__dagger
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
{ "start": 58098, "end": 58805 }
interface ____ {", " @Multibinds Set<Integer> multibindIntegerSet();", "", " @Provides", " static Object provideObject(Set<Integer> intSet) {", " return new Object();", " }", "}"); Source repeatedSubModule = CompilerTests.javaSource( "test.RepeatedSubModule", "package test;", "", "import dagger.Module;", "import dagger.Provides;", "import dagger.multibindings.IntoSet;", "import java.util.Set;", "import dagger.multibindings.Multibinds;", "", "@Module", "public
Child2Module
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_19.java
{ "start": 931, "end": 2025 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "SELECT * FROM mj_list WHERE ( uid = 1 ) AND ( status = 1 ) ORDER BY view DESC LIMIT 10"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); // print(statementList); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); statemen.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(4, visitor.getColumns().size()); assertEquals(2, visitor.getConditions().size()); assertEquals(1, visitor.getOrderByColumns().size()); } }
MySqlSelectTest_19
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/engine/support/descriptor/DefaultUriSourceTests.java
{ "start": 840, "end": 1815 }
class ____ extends AbstractTestSourceTests { @Override Stream<UriSource> createSerializableInstances() { return Stream.of(new DefaultUriSource(URI.create("sample://instance"))); } @SuppressWarnings("DataFlowIssue") @Test void nullSourceUriYieldsException() { assertPreconditionViolationFor(() -> new DefaultUriSource(null)); } @Test void getterReturnsSameUriInstanceAsSuppliedToTheConstructor() throws Exception { var expected = new URI("foo.txt"); var actual = new DefaultUriSource(expected).getUri(); assertSame(expected, actual); } @Test void equalsAndHashCode() throws Exception { var uri1 = new URI("foo.txt"); var uri2 = new URI("bar.txt"); assertEqualsAndHashCode(new DefaultUriSource(uri1), new DefaultUriSource(uri1), new DefaultUriSource(uri2)); } @Test void testToString() { var actual = new DefaultUriSource(URI.create("foo.txt")).toString(); assertEquals("DefaultUriSource [uri = foo.txt]", actual); } }
DefaultUriSourceTests
java
google__guava
android/guava-testlib/src/com/google/common/testing/NullPointerTester.java
{ "start": 20909, "end": 22640 }
class ____ and * thus are invisible at runtime. Thus, we conclude that the parameter types are * *non*-nullable, even when they are declared as `Foo?`. */ || hasAutomaticNullChecksFromKotlin(member); } private static boolean hasAutomaticNullChecksFromKotlin(Member member) { for (Annotation annotation : member.getDeclaringClass().getAnnotations()) { if (annotation.annotationType().getName().equals("kotlin.Metadata")) { return true; } } return false; } /** * Returns true if the given member is a method that overrides {@link Object#equals(Object)}. * * <p>The documentation for {@link Object#equals} says it should accept null, so don't require an * explicit {@code @NullableDecl} annotation (see <a * href="https://github.com/google/guava/issues/1819">#1819</a>). * * <p>It is not necessary to consider visibility, return type, or type parameter declarations. The * declaration of a method with the same name and formal parameters as {@link Object#equals} that * is not public and boolean-returning, or that declares any type parameters, would be rejected at * compile-time. */ private static boolean isEquals(Member member) { if (!(member instanceof Method)) { return false; } Method method = (Method) member; if (!method.getName().contentEquals("equals")) { return false; } Class<?>[] parameters = method.getParameterTypes(); if (parameters.length != 1) { return false; } if (!parameters[0].equals(Object.class)) { return false; } return true; } /** Strategy for exception type matching used by {@link NullPointerTester}. */ private
retention
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/naturalid/JoinColumnNaturalIdTest.java
{ "start": 728, "end": 2909 }
class ____ { private Integer customerId; private Integer deviceId; private Integer accountId; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { // Revision 1 scope.inTransaction( em -> { Customer customer = new Customer(); customer.setCustomerNumber( "1234567" ); customer.setName( "ACME" ); em.persist( customer ); customerId = customer.getId(); } ); // Revision 2 scope.inTransaction( em -> { Customer customer = em.find( Customer.class, customerId ); Device device = new Device(); device.setCustomer( customer ); Account account = new Account(); account.setCustomer( customer ); em.persist( account ); em.persist( device ); accountId = account.getId(); deviceId = device.getId(); } ); // Revision 3 scope.inTransaction( em -> { Account account = em.find( Account.class, accountId ); em.remove( account ); } ); } @Test public void testRevisionCounts(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); assertEquals( 3, auditReader.getRevisions( Customer.class, customerId ).size() ); assertEquals( 2, auditReader.getRevisions( Account.class, accountId ).size() ); assertEquals( 1, auditReader.getRevisions( Device.class, deviceId ).size() ); } ); } @Test public void testRevisionHistoryOfCustomer(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); final Customer customer = new Customer( customerId, "1234567", "ACME" ); Customer rev1 = auditReader.find( Customer.class, customerId, 1 ); assertEquals( customer, rev1 ); final Account account = new Account( accountId, customer ); final Device device = new Device( deviceId, customer ); customer.getAccounts().add( account ); customer.getDevices().add( device ); Customer rev2 = auditReader.find( Customer.class, customerId, 2 ); assertEquals( customer, rev2 ); customer.getAccounts().clear(); Customer rev3 = auditReader.find( Customer.class, customerId, 3 ); assertEquals( customer, rev3 ); } ); } }
JoinColumnNaturalIdTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java
{ "start": 46595, "end": 47077 }
class ____ { public record SimpleRecord(Integer foo, Long bar) { void f() { // BUG: Diagnostic contains: is never read int x = foo; } } } """) .doTest(); } @Test public void manyUnusedAssignments_terminalAssignmentBecomesVariable() { refactoringHelper .addInputLines( "Test.java", """ public
SimpleClass
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/schedulers/AbstractDirectTaskTest.java
{ "start": 919, "end": 7367 }
class ____ extends RxJavaTest { @Test public void cancelSetFuture() { AbstractDirectTask task = new AbstractDirectTask(Functions.EMPTY_RUNNABLE, true) { private static final long serialVersionUID = 208585707945686116L; }; final Boolean[] interrupted = { null }; assertFalse(task.isDisposed()); task.dispose(); assertTrue(task.isDisposed()); task.dispose(); assertTrue(task.isDisposed()); FutureTask<Void> ft = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null) { @Override public boolean cancel(boolean mayInterruptIfRunning) { interrupted[0] = mayInterruptIfRunning; return super.cancel(mayInterruptIfRunning); } }; task.setFuture(ft); assertTrue(interrupted[0]); assertTrue(task.isDisposed()); } @Test public void cancelSetFutureCurrentThread() { AbstractDirectTask task = new AbstractDirectTask(Functions.EMPTY_RUNNABLE, true) { private static final long serialVersionUID = 208585707945686116L; }; final Boolean[] interrupted = { null }; assertFalse(task.isDisposed()); task.runner = Thread.currentThread(); task.dispose(); assertTrue(task.isDisposed()); task.dispose(); assertTrue(task.isDisposed()); FutureTask<Void> ft = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null) { @Override public boolean cancel(boolean mayInterruptIfRunning) { interrupted[0] = mayInterruptIfRunning; return super.cancel(mayInterruptIfRunning); } }; task.setFuture(ft); assertFalse(interrupted[0]); assertTrue(task.isDisposed()); } @Test public void setFutureCancel() { AbstractDirectTask task = new AbstractDirectTask(Functions.EMPTY_RUNNABLE, true) { private static final long serialVersionUID = 208585707945686116L; }; final Boolean[] interrupted = { null }; FutureTask<Void> ft = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null) { @Override public boolean cancel(boolean mayInterruptIfRunning) { interrupted[0] = mayInterruptIfRunning; return super.cancel(mayInterruptIfRunning); } }; assertFalse(task.isDisposed()); task.setFuture(ft); assertFalse(task.isDisposed()); task.dispose(); assertTrue(task.isDisposed()); assertTrue(interrupted[0]); } @Test public void setFutureCancelSameThread() { AbstractDirectTask task = new AbstractDirectTask(Functions.EMPTY_RUNNABLE, true) { private static final long serialVersionUID = 208585707945686116L; }; final Boolean[] interrupted = { null }; FutureTask<Void> ft = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null) { @Override public boolean cancel(boolean mayInterruptIfRunning) { interrupted[0] = mayInterruptIfRunning; return super.cancel(mayInterruptIfRunning); } }; assertFalse(task.isDisposed()); task.setFuture(ft); task.runner = Thread.currentThread(); assertFalse(task.isDisposed()); task.dispose(); assertTrue(task.isDisposed()); assertFalse(interrupted[0]); } @Test public void finished() { AbstractDirectTask task = new AbstractDirectTask(Functions.EMPTY_RUNNABLE, true) { private static final long serialVersionUID = 208585707945686116L; }; final Boolean[] interrupted = { null }; FutureTask<Void> ft = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null) { @Override public boolean cancel(boolean mayInterruptIfRunning) { interrupted[0] = mayInterruptIfRunning; return super.cancel(mayInterruptIfRunning); } }; task.set(AbstractDirectTask.FINISHED); task.setFuture(ft); assertTrue(task.isDisposed()); assertNull(interrupted[0]); task.dispose(); assertTrue(task.isDisposed()); assertNull(interrupted[0]); } @Test public void finishedCancel() { AbstractDirectTask task = new AbstractDirectTask(Functions.EMPTY_RUNNABLE, true) { private static final long serialVersionUID = 208585707945686116L; }; final Boolean[] interrupted = { null }; FutureTask<Void> ft = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null) { @Override public boolean cancel(boolean mayInterruptIfRunning) { interrupted[0] = mayInterruptIfRunning; return super.cancel(mayInterruptIfRunning); } }; task.set(AbstractDirectTask.FINISHED); assertTrue(task.isDisposed()); task.dispose(); assertTrue(task.isDisposed()); task.setFuture(ft); assertTrue(task.isDisposed()); assertNull(interrupted[0]); assertTrue(task.isDisposed()); assertNull(interrupted[0]); } @Test public void disposeSetFutureRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final AbstractDirectTask task = new AbstractDirectTask(Functions.EMPTY_RUNNABLE, true) { private static final long serialVersionUID = 208585707945686116L; }; final Boolean[] interrupted = { null }; final FutureTask<Void> ft = new FutureTask<Void>(Functions.EMPTY_RUNNABLE, null) { @Override public boolean cancel(boolean mayInterruptIfRunning) { interrupted[0] = mayInterruptIfRunning; return super.cancel(mayInterruptIfRunning); } }; Runnable r1 = new Runnable() { @Override public void run() { task.dispose(); } }; Runnable r2 = new Runnable() { @Override public void run() { task.setFuture(ft); } }; TestHelper.race(r1, r2); } } static
AbstractDirectTaskTest
java
apache__maven
its/core-it-support/core-it-plugins/maven-it-plugin-artifact/src/main/java/org/apache/maven/plugin/coreit/InstallMojo.java
{ "start": 1398, "end": 2435 }
class ____ extends AbstractRepoMojo { /** * The artifact installer. */ @Component private ArtifactInstaller installer; /** * Runs this mojo. * * @throws MojoExecutionException If any artifact could not be installed. */ public void execute() throws MojoExecutionException { getLog().info("[MAVEN-CORE-IT-LOG] Installing project artifacts"); try { if (isPomArtifact()) { installer.install(pomFile, mainArtifact, localRepository); } else { installer.install(mainArtifact.getFile(), mainArtifact, localRepository); } if (attachedArtifacts != null) { for (Artifact attachedArtifact : attachedArtifacts) { installer.install(attachedArtifact.getFile(), attachedArtifact, localRepository); } } } catch (Exception e) { throw new MojoExecutionException("Failed to install artifacts", e); } } }
InstallMojo
java
spring-projects__spring-security
access/src/main/java/org/springframework/security/access/prepost/PrePostAdviceReactiveMethodInterceptor.java
{ "start": 2469, "end": 7973 }
class ____ implements MethodInterceptor { private Authentication anonymous = new AnonymousAuthenticationToken("key", "anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); private final MethodSecurityMetadataSource attributeSource; private final PreInvocationAuthorizationAdvice preInvocationAdvice; private final PostInvocationAuthorizationAdvice postAdvice; private static final String COROUTINES_FLOW_CLASS_NAME = "kotlinx.coroutines.flow.Flow"; private static final int RETURN_TYPE_METHOD_PARAMETER_INDEX = -1; /** * Creates a new instance * @param attributeSource the {@link MethodSecurityMetadataSource} to use * @param preInvocationAdvice the {@link PreInvocationAuthorizationAdvice} to use * @param postInvocationAdvice the {@link PostInvocationAuthorizationAdvice} to use */ public PrePostAdviceReactiveMethodInterceptor(MethodSecurityMetadataSource attributeSource, PreInvocationAuthorizationAdvice preInvocationAdvice, PostInvocationAuthorizationAdvice postInvocationAdvice) { Assert.notNull(attributeSource, "attributeSource cannot be null"); Assert.notNull(preInvocationAdvice, "preInvocationAdvice cannot be null"); Assert.notNull(postInvocationAdvice, "postInvocationAdvice cannot be null"); this.attributeSource = attributeSource; this.preInvocationAdvice = preInvocationAdvice; this.postAdvice = postInvocationAdvice; } @Override public Object invoke(final MethodInvocation invocation) { Method method = invocation.getMethod(); Class<?> returnType = method.getReturnType(); boolean isSuspendingFunction = KotlinDetector.isSuspendingFunction(method); boolean hasFlowReturnType = COROUTINES_FLOW_CLASS_NAME .equals(new MethodParameter(method, RETURN_TYPE_METHOD_PARAMETER_INDEX).getParameterType().getName()); boolean hasReactiveReturnType = Publisher.class.isAssignableFrom(returnType) || isSuspendingFunction || hasFlowReturnType; Assert.state(hasReactiveReturnType, () -> "The returnType " + returnType + " on " + method + " must return an instance of org.reactivestreams.Publisher " + "(i.e. Mono / Flux) or the function must be a Kotlin coroutine " + "function in order to support Reactor Context"); Class<?> targetClass = invocation.getThis().getClass(); Collection<ConfigAttribute> attributes = this.attributeSource.getAttributes(method, targetClass); PreInvocationAttribute preAttr = findPreInvocationAttribute(attributes); // @formatter:off Mono<Authentication> toInvoke = ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication) .defaultIfEmpty(this.anonymous) .filter((auth) -> this.preInvocationAdvice.before(auth, invocation, preAttr)) .switchIfEmpty(Mono.defer(() -> Mono.error(new AccessDeniedException("Denied")))); // @formatter:on PostInvocationAttribute attr = findPostInvocationAttribute(attributes); if (Mono.class.isAssignableFrom(returnType)) { return toInvoke.flatMap((auth) -> PrePostAdviceReactiveMethodInterceptor.<Mono<?>>proceed(invocation) .map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r)); } if (Flux.class.isAssignableFrom(returnType)) { return toInvoke.flatMapMany((auth) -> PrePostAdviceReactiveMethodInterceptor.<Flux<?>>proceed(invocation) .map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r)); } if (hasFlowReturnType) { if (isSuspendingFunction) { return toInvoke .flatMapMany((auth) -> Flux.from(PrePostAdviceReactiveMethodInterceptor.proceed(invocation)) .map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r)); } else { ReactiveAdapter adapter = ReactiveAdapterRegistry.getSharedInstance().getAdapter(returnType); Assert.state(adapter != null, () -> "The returnType " + returnType + " on " + method + " must have a org.springframework.core.ReactiveAdapter registered"); Flux<?> response = toInvoke.flatMapMany((auth) -> Flux .from(adapter.toPublisher(PrePostAdviceReactiveMethodInterceptor.flowProceed(invocation))) .map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r)); return KotlinDelegate.asFlow(response); } } return toInvoke.flatMap((auth) -> Mono.from(PrePostAdviceReactiveMethodInterceptor.proceed(invocation)) .map((r) -> (attr != null) ? this.postAdvice.after(auth, invocation, attr, r) : r)); } private static <T extends Publisher<?>> @Nullable T proceed(final MethodInvocation invocation) { try { return (T) invocation.proceed(); } catch (Throwable throwable) { throw Exceptions.propagate(throwable); } } private static @Nullable Object flowProceed(final MethodInvocation invocation) { try { return invocation.proceed(); } catch (Throwable throwable) { throw Exceptions.propagate(throwable); } } private static @Nullable PostInvocationAttribute findPostInvocationAttribute(Collection<ConfigAttribute> config) { for (ConfigAttribute attribute : config) { if (attribute instanceof PostInvocationAttribute) { return (PostInvocationAttribute) attribute; } } return null; } private static @Nullable PreInvocationAttribute findPreInvocationAttribute(Collection<ConfigAttribute> config) { for (ConfigAttribute attribute : config) { if (attribute instanceof PreInvocationAttribute) { return (PreInvocationAttribute) attribute; } } return null; } /** * Inner
PrePostAdviceReactiveMethodInterceptor
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest150.java
{ "start": 235, "end": 2293 }
class ____ extends TestCase { public void test_false() throws Exception { WallProvider provider = new MySqlWallProvider(); provider.getConfig().setSelectLimit(100); String sql = "select\n" + "a.main_card_no as card_no, a.city, a.bussiness_type, 'main' as card_type,\n" + "c.company_name as company, a.status_flag,\n" + "a.card_balance as balance from oil_card_main a left join oil_company c on c.company_id=a.company_id\n" + "\n" + "union all\n" + "\n" + "select\n" + "b.card_no,b.city,b.bussiness_type,'secon' as card_type,c.company_name as company,\n" + "b.status_flag,b.card_balance as balance\n" + "from oil_card_associate b left join oil_card_main a\n" + "on a.main_card_no = b.main_card_no\n" + "left join oil_company c on c.company_id=a.company_id"; // assertTrue( // provider.checkValid(sql) // ); WallCheckResult result = provider.check(sql); assertEquals(0, result.getViolations().size()); String wsql = result .getStatementList().get(0).toString(); assertEquals("SELECT a.main_card_no AS card_no, a.city, a.bussiness_type, 'main' AS card_type, c.company_name AS company\n" + "\t, a.status_flag, a.card_balance AS balance\n" + "FROM oil_card_main a\n" + "\tLEFT JOIN oil_company c ON c.company_id = a.company_id\n" + "UNION ALL\n" + "SELECT b.card_no, b.city, b.bussiness_type, 'secon' AS card_type, c.company_name AS company\n" + "\t, b.status_flag, b.card_balance AS balance\n" + "FROM oil_card_associate b\n" + "\tLEFT JOIN oil_card_main a ON a.main_card_no = b.main_card_no\n" + "\tLEFT JOIN oil_company c ON c.company_id = a.company_id\n" + "LIMIT 100", wsql); } }
MySqlWallTest150
java
google__dagger
hilt-android/main/java/dagger/hilt/android/AndroidEntryPoint.java
{ "start": 2305, "end": 2356 }
interface ____ { /** * The base
AndroidEntryPoint
java
spring-projects__spring-boot
module/spring-boot-amqp/src/main/java/org/springframework/boot/amqp/autoconfigure/RabbitAutoConfiguration.java
{ "start": 6338, "end": 7917 }
class ____ { @Bean @ConditionalOnMissingBean RabbitTemplateConfigurer rabbitTemplateConfigurer(RabbitProperties properties, ObjectProvider<MessageConverter> messageConverter, ObjectProvider<RabbitTemplateRetrySettingsCustomizer> retrySettingsCustomizers) { RabbitTemplateConfigurer configurer = new RabbitTemplateConfigurer(properties); configurer.setMessageConverter(messageConverter.getIfUnique()); configurer.setRetrySettingsCustomizers(retrySettingsCustomizers.orderedStream().toList()); return configurer; } @Bean @ConditionalOnSingleCandidate(ConnectionFactory.class) @ConditionalOnMissingBean(RabbitOperations.class) RabbitTemplate rabbitTemplate(RabbitTemplateConfigurer configurer, ConnectionFactory connectionFactory, ObjectProvider<RabbitTemplateCustomizer> customizers) { RabbitTemplate template = new RabbitTemplate(); configurer.configure(template, connectionFactory); customizers.orderedStream().forEach((customizer) -> customizer.customize(template)); return template; } @Bean @ConditionalOnSingleCandidate(ConnectionFactory.class) @ConditionalOnBooleanProperty(name = "spring.rabbitmq.dynamic", matchIfMissing = true) @ConditionalOnMissingBean AmqpAdmin amqpAdmin(ConnectionFactory connectionFactory) { return new RabbitAdmin(connectionFactory); } } @Configuration(proxyBeanMethods = false) @ConditionalOnClass(RabbitMessagingTemplate.class) @ConditionalOnMissingBean(RabbitMessagingTemplate.class) @Import(RabbitTemplateConfiguration.class) protected static
RabbitTemplateConfiguration
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/vectors/es818/ES818BinaryFlatVectorsScorer.java
{ "start": 7068, "end": 10940 }
class ____ extends UpdateableRandomVectorScorer.AbstractUpdateableRandomVectorScorer { private final ES818BinaryQuantizedVectorsWriter.OffHeapBinarizedQueryVectorValues queryVectors; private final BinarizedByteVectorValues targetVectors; private final VectorSimilarityFunction similarityFunction; private final byte[] quantizedQuery; private OptimizedScalarQuantizer.QuantizationResult queryCorrections = null; private int currentOrdinal = -1; BinarizedRandomVectorScorer( ES818BinaryQuantizedVectorsWriter.OffHeapBinarizedQueryVectorValues queryVectors, BinarizedByteVectorValues targetVectors, VectorSimilarityFunction similarityFunction ) { super(targetVectors); this.queryVectors = queryVectors; this.quantizedQuery = new byte[queryVectors.quantizedDimension()]; this.targetVectors = targetVectors; this.similarityFunction = similarityFunction; } @Override public float score(int targetOrd) throws IOException { if (queryCorrections == null) { throw new IllegalStateException("score() called before setScoringOrdinal()"); } return quantizedScore( targetVectors.dimension(), similarityFunction, targetVectors.getCentroidDP(), quantizedQuery, queryCorrections, targetVectors.vectorValue(targetOrd), targetVectors.getCorrectiveTerms(targetOrd) ); } @Override public void setScoringOrdinal(int i) throws IOException { if (i == currentOrdinal) { return; } System.arraycopy(queryVectors.vectorValue(i), 0, quantizedQuery, 0, quantizedQuery.length); queryCorrections = queryVectors.getCorrectiveTerms(i); currentOrdinal = i; } } private static float quantizedScore( int dims, VectorSimilarityFunction similarityFunction, float centroidDp, byte[] q, OptimizedScalarQuantizer.QuantizationResult queryCorrections, byte[] d, OptimizedScalarQuantizer.QuantizationResult indexCorrections ) { float qcDist = ESVectorUtil.ipByteBinByte(q, d); float x1 = indexCorrections.quantizedComponentSum(); float ax = indexCorrections.lowerInterval(); // Here we assume `lx` is simply bit vectors, so the scaling isn't necessary float lx = indexCorrections.upperInterval() - ax; float ay = queryCorrections.lowerInterval(); float ly = (queryCorrections.upperInterval() - ay) * FOUR_BIT_SCALE; float y1 = queryCorrections.quantizedComponentSum(); float score = ax * ay * dims + ay * lx * x1 + ax * ly * y1 + lx * ly * qcDist; // For euclidean, we need to invert the score and apply the additional correction, which is // assumed to be the squared l2norm of the centroid centered vectors. if (similarityFunction == EUCLIDEAN) { score = queryCorrections.additionalCorrection() + indexCorrections.additionalCorrection() - 2 * score; return Math.max(1 / (1f + score), 0); } else { // For cosine and max inner product, we need to apply the additional correction, which is // assumed to be the non-centered dot-product between the vector and the centroid score += queryCorrections.additionalCorrection() + indexCorrections.additionalCorrection() - centroidDp; if (similarityFunction == MAXIMUM_INNER_PRODUCT) { return VectorUtil.scaleMaxInnerProductScore(score); } return Math.max((1f + score) / 2f, 0); } } }
BinarizedRandomVectorScorer
java
google__auto
value/src/main/java/com/google/auto/value/extension/AutoValueExtension.java
{ "start": 16113, "end": 17460 }
class ____ its dependencies, but not on other {@code @AutoValue} classes * that might be compiled at the same time. The constraints that an isolating extension must * respect are the same as those that Gradle imposes on an isolating annotation processor. * * @see <a * href="https://docs.gradle.org/current/userguide/java_plugin.html#isolating_annotation_processors">Gradle * definition of isolating processors</a> */ ISOLATING } /** * Determines the incremental type of this Extension. * * <p>The {@link ProcessingEnvironment} can be used, among other things, to obtain the processor * options, using {@link ProcessingEnvironment#getOptions()}. * * <p>The actual incremental type of the AutoValue processor as a whole will be the loosest * incremental types of the Extensions present in the annotation processor path. The default * returned value is {@link IncrementalExtensionType#UNKNOWN}, which will disable incremental * annotation processing entirely. */ public IncrementalExtensionType incrementalType(ProcessingEnvironment processingEnvironment) { return IncrementalExtensionType.UNKNOWN; } /** * Analogous to {@link Processor#getSupportedOptions()}, here to allow extensions to report their * own. * * <p>By default, if the extension
and
java
apache__camel
core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ManagedRecipientListMBean.java
{ "start": 1021, "end": 2720 }
interface ____ extends ManagedProcessorMBean, ManagedExtendedInformation { @ManagedAttribute(description = "The language for the expression") String getExpressionLanguage(); @ManagedAttribute(description = "Expression that returns which endpoints (url) to send the message to (the recipients).", mask = true) String getExpression(); @ManagedAttribute(description = "The uri delimiter to use") String getUriDelimiter(); @ManagedAttribute(description = "Sets the maximum size used by the ProducerCache which is used to cache and reuse producers") Integer getCacheSize(); @ManagedAttribute(description = "If enabled then the aggregate method on AggregationStrategy can be called concurrently.") Boolean isParallelAggregate(); @ManagedAttribute(description = "If enabled then sending messages to the recipient lists occurs concurrently.") Boolean isParallelProcessing(); @ManagedAttribute(description = "If enabled then Camel will process replies out-of-order, eg in the order they come back.") Boolean isStreaming(); @ManagedAttribute(description = "Will now stop further processing if an exception or failure occurred during processing.") Boolean isStopOnException(); @ManagedAttribute(description = "Shares the UnitOfWork with the parent and the resource exchange") Boolean isShareUnitOfWork(); @ManagedAttribute(description = "The total timeout specified in millis, when using parallel processing.") Long getTimeout(); @Override @ManagedOperation(description = "Statistics of the endpoints which has been sent to") TabularData extendedInformation(); }
ManagedRecipientListMBean
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RTransactionRx.java
{ "start": 1051, "end": 4966 }
interface ____ { /** * Returns transactional object holder instance by name. * * @param <V> type of value * @param name - name of object * @return Bucket object */ <V> RBucketRx<V> getBucket(String name); /** * Returns transactional object holder instance by name * using provided codec for object. * * @param <V> type of value * @param name - name of object * @param codec - codec for values * @return Bucket object */ <V> RBucketRx<V> getBucket(String name, Codec codec); /** * Returns transactional map instance by name. * * @param <K> type of key * @param <V> type of value * @param name - name of object * @return Map object */ <K, V> RMapRx<K, V> getMap(String name); /** * Returns transactional map instance by name * using provided codec for both map keys and values. * * @param <K> type of key * @param <V> type of value * @param name - name of object * @param codec - codec for keys and values * @return Map object */ <K, V> RMapRx<K, V> getMap(String name, Codec codec); /** * Returns transactional set instance by name. * * @param <V> type of value * @param name - name of object * @return Set object */ <V> RSetRx<V> getSet(String name); /** * Returns transactional set instance by name * using provided codec for set objects. * * @param <V> type of value * @param name - name of object * @param codec - codec for values * @return Set object */ <V> RSetRx<V> getSet(String name, Codec codec); /** * Returns transactional set-based cache instance by <code>name</code>. * Supports value eviction with a given TTL value. * * <p>If eviction is not required then it's better to use regular map {@link #getSet(String)}.</p> * * @param <V> type of value * @param name - name of object * @return SetCache object */ <V> RSetCacheRx<V> getSetCache(String name); /** * Returns transactional set-based cache instance by <code>name</code>. * Supports value eviction with a given TTL value. * * <p>If eviction is not required then it's better to use regular map {@link #getSet(String, Codec)}.</p> * * @param <V> type of value * @param name - name of object * @param codec - codec for values * @return SetCache object */ <V> RSetCacheRx<V> getSetCache(String name, Codec codec); /** * Returns transactional map-based cache instance by name. * Supports entry eviction with a given MaxIdleTime and TTL settings. * <p> * If eviction is not required then it's better to use regular map {@link #getMap(String)}.</p> * * @param <K> type of key * @param <V> type of value * @param name - name of object * @return MapCache object */ <K, V> RMapCacheRx<K, V> getMapCache(String name); /** * Returns transactional map-based cache instance by <code>name</code> * using provided <code>codec</code> for both cache keys and values. * Supports entry eviction with a given MaxIdleTime and TTL settings. * <p> * If eviction is not required then it's better to use regular map {@link #getMap(String, Codec)}. * * @param <K> type of key * @param <V> type of value * @param name - object name * @param codec - codec for keys and values * @return MapCache object */ <K, V> RMapCacheRx<K, V> getMapCache(String name, Codec codec); /** * Commits all changes made on this transaction. * * @return void */ Completable commit(); /** * Rollback all changes made on this transaction. * @return void */ Completable rollback(); }
RTransactionRx
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MissingFailTest.java
{ "start": 7306, "end": 7410 }
class ____ { /** Sample inner class. */ public static
MissingFailPositiveCases3
java
apache__flink
flink-kubernetes/src/test/java/org/apache/flink/kubernetes/kubeclient/decorators/PodTemplateMountDecoratorTest.java
{ "start": 2104, "end": 6044 }
class ____ extends KubernetesJobManagerTestBase { private static final String POD_TEMPLATE_FILE_NAME = "testing-pod-template.yaml"; private static final String POD_TEMPLATE_DATA = "taskmanager pod template data"; private PodTemplateMountDecorator podTemplateMountDecorator; @Override protected void setupFlinkConfig() { super.setupFlinkConfig(); this.flinkConfig.set( KubernetesConfigOptions.TASK_MANAGER_POD_TEMPLATE, new File(flinkConfDir, POD_TEMPLATE_FILE_NAME).getAbsolutePath()); } @Override protected void onSetup() throws Exception { super.onSetup(); this.podTemplateMountDecorator = new PodTemplateMountDecorator(kubernetesJobManagerParameters); } @Test void testBuildAccompanyingKubernetesResourcesAddsPodTemplateAsConfigMap() throws IOException { KubernetesTestUtils.createTemporyFile( POD_TEMPLATE_DATA, flinkConfDir, POD_TEMPLATE_FILE_NAME); final List<HasMetadata> additionalResources = podTemplateMountDecorator.buildAccompanyingKubernetesResources(); assertThat(additionalResources).hasSize(1); final ConfigMap resultConfigMap = (ConfigMap) additionalResources.get(0); final Map<String, String> resultData = resultConfigMap.getData(); assertThat(resultData.get(TASK_MANAGER_POD_TEMPLATE_FILE_NAME)) .isEqualTo(POD_TEMPLATE_DATA); } @Test void testDecoratorShouldFailWhenPodTemplateFileNotExist() { final String msg = String.format( "Pod template file %s does not exist.", new File(flinkConfDir, POD_TEMPLATE_FILE_NAME)); assertThatThrownBy( () -> podTemplateMountDecorator.buildAccompanyingKubernetesResources(), "Decorator should fail when the pod template file does not exist.") .satisfies(FlinkAssertions.anyCauseMatches(msg)); } @Test void testDecoratedFlinkPodWithTaskManagerPodTemplate() throws Exception { KubernetesTestUtils.createTemporyFile( POD_TEMPLATE_DATA, flinkConfDir, POD_TEMPLATE_FILE_NAME); final FlinkPod resultFlinkPod = podTemplateMountDecorator.decorateFlinkPod(baseFlinkPod); final List<KeyToPath> expectedKeyToPaths = Collections.singletonList( new KeyToPathBuilder() .withKey(TASK_MANAGER_POD_TEMPLATE_FILE_NAME) .withPath(TASK_MANAGER_POD_TEMPLATE_FILE_NAME) .build()); final List<Volume> expectedVolumes = getExpectedVolumes(expectedKeyToPaths); assertThat(resultFlinkPod.getPodWithoutMainContainer().getSpec().getVolumes()) .containsExactlyInAnyOrderElementsOf(expectedVolumes); final List<VolumeMount> expectedVolumeMounts = Collections.singletonList( new VolumeMountBuilder() .withName(Constants.POD_TEMPLATE_VOLUME) .withMountPath(Constants.POD_TEMPLATE_DIR_IN_POD) .build()); assertThat(resultFlinkPod.getMainContainer().getVolumeMounts()) .containsExactlyInAnyOrderElementsOf(expectedVolumeMounts); } private List<Volume> getExpectedVolumes(List<KeyToPath> keyToPaths) { return Collections.singletonList( new VolumeBuilder() .withName(Constants.POD_TEMPLATE_VOLUME) .withNewConfigMap() .withName(Constants.POD_TEMPLATE_CONFIG_MAP_PREFIX + CLUSTER_ID) .withItems(keyToPaths) .endConfigMap() .build()); } }
PodTemplateMountDecoratorTest
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/response/RestResponseResource.java
{ "start": 747, "end": 5324 }
class ____ { @GET @Path("rest-response") public RestResponse<String> getString() { return RestResponse.ok("Hello"); } @GET @Path("rest-response-empty") public RestResponse<String> empty() { return RestResponse.status(499); } @GET @Path("response-empty") public Response emptyResponse() { return Response.status(499).build(); } @GET @Path("rest-response-wildcard") public RestResponse<?> wildcard() { return RestResponse.ResponseBuilder.ok("Hello").header("content-type", "text/plain").build(); } @GET @Path("rest-response-location") public RestResponse<?> location() { final var location = UriBuilder.fromResource(RestResponseResource.class).path("{language}") .queryParam("user", "John") .build("en/us"); return RestResponse.ResponseBuilder.ok("Hello").location(location).build(); } @GET @Path("rest-response-content-location") public RestResponse<?> contentLocation() { final var location = UriBuilder.fromResource(RestResponseResource.class).path("{language}") .queryParam("user", "John") .build("en/us"); return RestResponse.ResponseBuilder.ok("Hello").contentLocation(location).build(); } @GET @Path("rest-response-full") @SuppressWarnings("deprecation") public RestResponse<String> getResponse() throws URISyntaxException { CacheControl cc = new CacheControl(); cc.setMaxAge(42); cc.setPrivate(true); return RestResponse.ResponseBuilder.ok("Hello") .allow("FOO", "BAR") .cacheControl(cc) .contentLocation(new URI("http://example.com/content")) .cookie(new NewCookie("Flavour", "Praliné")) .encoding("Stef-Encoding") .expires(Date.from(Instant.parse("2021-01-01T00:00:00Z"))) .header("X-Stef", "FroMage") .language(Locale.FRENCH) .lastModified(Date.from(Instant.parse("2021-01-02T00:00:00Z"))) .link("http://example.com/link", "stef") .location(new URI("http://example.com/location")) .tag("yourit") .type("text/stef") .variants(Variant.languages(Locale.ENGLISH, Locale.GERMAN).build()) .build(); } @GET @Path("response-uni") public Response getResponseUniString() { return Response.ok(Uni.createFrom().item("Hello")).build(); } @GET @Path("rest-response-uni") public RestResponse<Uni<String>> getUniString() { return RestResponse.ok(Uni.createFrom().item("Hello")); } @GET @Path("rest-response-exception") public String getRestResponseException() { throw new UnknownCheeseException1("Cheddar"); } @GET @Path("uni-rest-response-exception") public String getUniRestResponseException() { throw new UnknownCheeseException2("Cheddar"); } @ServerExceptionMapper public RestResponse<String> mapException(UnknownCheeseException1 x) { return RestResponse.status(Response.Status.NOT_FOUND, "Unknown cheese: " + x.name); } @ServerExceptionMapper public Uni<RestResponse<String>> mapExceptionAsync(UnknownCheeseException2 x) { return Uni.createFrom().item(RestResponse.status(Response.Status.NOT_FOUND, "Unknown cheese: " + x.name)); } @ServerRequestFilter(preMatching = true) public RestResponse<String> restResponseRequestFilter(ContainerRequestContext ctx) { if (ctx.getUriInfo().getPath().equals("/rest-response-request-filter")) { return RestResponse.ok("RestResponse request filter"); } return null; } @ServerRequestFilter(preMatching = true) public Optional<RestResponse<String>> optionalRestResponseRequestFilter(ContainerRequestContext ctx) { if (ctx.getUriInfo().getPath().equals("/optional-rest-response-request-filter")) { return Optional.of(RestResponse.ok("Optional<RestResponse> request filter")); } return Optional.empty(); } @ServerRequestFilter(preMatching = true) public Uni<RestResponse<String>> uniRestResponseRequestFilter(ContainerRequestContext ctx) { if (ctx.getUriInfo().getPath().equals("/uni-rest-response-request-filter")) { return Uni.createFrom().item(RestResponse.ok("Uni<RestResponse> request filter")); } return null; } }
RestResponseResource
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/script/MockScriptEngine.java
{ "start": 22763, "end": 23447 }
class ____ extends SimilarityScript { private final Function<Map<String, Object>, Object> script; MockSimilarityScript(Function<Map<String, Object>, Object> script) { this.script = script; } @Override public double execute(double weight, Query query, Field field, Term term, Doc doc) { Map<String, Object> map = new HashMap<>(); map.put("weight", weight); map.put("query", query); map.put("field", field); map.put("term", term); map.put("doc", doc); return ((Number) script.apply(map)).doubleValue(); } } public
MockSimilarityScript
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/InlineTrivialConstantTest.java
{ "start": 2227, "end": 2346 }
class ____ { private static final String LAUNCH_CODES = ""; } static
WrongName
java
playframework__playframework
persistence/play-java-jpa/src/main/java/play/db/jpa/DefaultJPAConfig.java
{ "start": 441, "end": 941 }
class ____ implements JPAConfig { private Set<JPAConfig.PersistenceUnit> persistenceUnits; public DefaultJPAConfig(Set<JPAConfig.PersistenceUnit> persistenceUnits) { this.persistenceUnits = persistenceUnits; } public DefaultJPAConfig(JPAConfig.PersistenceUnit... persistenceUnits) { this(ImmutableSet.copyOf(persistenceUnits)); } @Override public Set<JPAConfig.PersistenceUnit> persistenceUnits() { return persistenceUnits; } @Singleton public static
DefaultJPAConfig
java
apache__spark
common/network-shuffle/src/main/java/org/apache/spark/network/shuffle/protocol/DiagnoseCorruption.java
{ "start": 1031, "end": 4139 }
class ____ extends BlockTransferMessage { public final String appId; public final String execId; public final int shuffleId; public final long mapId; public final int reduceId; public final long checksum; public final String algorithm; public DiagnoseCorruption( String appId, String execId, int shuffleId, long mapId, int reduceId, long checksum, String algorithm) { this.appId = appId; this.execId = execId; this.shuffleId = shuffleId; this.mapId = mapId; this.reduceId = reduceId; this.checksum = checksum; this.algorithm = algorithm; } @Override protected Type type() { return Type.DIAGNOSE_CORRUPTION; } @Override public String toString() { return "DiagnoseCorruption[appId=" + appId + ",execId=" + execId + ",shuffleId=" + shuffleId + ",mapId=" + mapId + ",reduceId=" + reduceId + ",checksum=" + checksum + ",algorithm=" + algorithm + "]"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DiagnoseCorruption that = (DiagnoseCorruption) o; if (checksum != that.checksum) return false; if (shuffleId != that.shuffleId) return false; if (mapId != that.mapId) return false; if (reduceId != that.reduceId) return false; if (!algorithm.equals(that.algorithm)) return false; if (!appId.equals(that.appId)) return false; if (!execId.equals(that.execId)) return false; return true; } @Override public int hashCode() { int result = appId.hashCode(); result = 31 * result + execId.hashCode(); result = 31 * result + Integer.hashCode(shuffleId); result = 31 * result + Long.hashCode(mapId); result = 31 * result + Integer.hashCode(reduceId); result = 31 * result + Long.hashCode(checksum); result = 31 * result + algorithm.hashCode(); return result; } @Override public int encodedLength() { return Encoders.Strings.encodedLength(appId) + Encoders.Strings.encodedLength(execId) + 4 /* encoded length of shuffleId */ + 8 /* encoded length of mapId */ + 4 /* encoded length of reduceId */ + 8 /* encoded length of checksum */ + Encoders.Strings.encodedLength(algorithm); /* encoded length of algorithm */ } @Override public void encode(ByteBuf buf) { Encoders.Strings.encode(buf, appId); Encoders.Strings.encode(buf, execId); buf.writeInt(shuffleId); buf.writeLong(mapId); buf.writeInt(reduceId); buf.writeLong(checksum); Encoders.Strings.encode(buf, algorithm); } public static DiagnoseCorruption decode(ByteBuf buf) { String appId = Encoders.Strings.decode(buf); String execId = Encoders.Strings.decode(buf); int shuffleId = buf.readInt(); long mapId = buf.readLong(); int reduceId = buf.readInt(); long checksum = buf.readLong(); String algorithm = Encoders.Strings.decode(buf); return new DiagnoseCorruption(appId, execId, shuffleId, mapId, reduceId, checksum, algorithm); } }
DiagnoseCorruption