language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/InternalDistributionBwcSetupPlugin.java
{ "start": 2187, "end": 17939 }
class ____ implements Plugin<Project> { private final ObjectFactory objectFactory; private ProviderFactory providerFactory; private JavaToolchainService toolChainService; private FileSystemOperations fileSystemOperations; @Inject public InternalDistributionBwcSetupPlugin( ObjectFactory objectFactory, ProviderFactory providerFactory, FileSystemOperations fileSystemOperations ) { this.objectFactory = objectFactory; this.providerFactory = providerFactory; this.fileSystemOperations = fileSystemOperations; } @Override public void apply(Project project) { project.getRootProject().getPluginManager().apply(GlobalBuildInfoPlugin.class); project.getPlugins().apply(JvmToolchainsPlugin.class); toolChainService = project.getExtensions().getByType(JavaToolchainService.class); var buildParams = loadBuildParams(project).get(); Boolean isCi = buildParams.getCi(); buildParams.getBwcVersions().forPreviousUnreleased((BwcVersions.UnreleasedVersionInfo unreleasedVersion) -> { configureBwcProject( project.project(unreleasedVersion.gradleProjectPath()), buildParams, unreleasedVersion, providerFactory, objectFactory, toolChainService, isCi, fileSystemOperations ); }); // Also set up the "main" project which is just used for arbitrary overrides. See InternalDistributionDownloadPlugin. if (System.getProperty("tests.bwc.main.version") != null) { configureBwcProject( project.project(":distribution:bwc:main"), buildParams, new BwcVersions.UnreleasedVersionInfo( Version.fromString(System.getProperty("tests.bwc.main.version")), "main", ":distribution:bwc:main" ), providerFactory, objectFactory, toolChainService, isCi, fileSystemOperations ); } } private static void configureBwcProject( Project project, BuildParameterExtension buildParams, BwcVersions.UnreleasedVersionInfo versionInfo, ProviderFactory providerFactory, ObjectFactory objectFactory, JavaToolchainService toolChainService, Boolean isCi, FileSystemOperations fileSystemOperations ) { ProjectLayout layout = project.getLayout(); Provider<BwcVersions.UnreleasedVersionInfo> versionInfoProvider = providerFactory.provider(() -> versionInfo); Provider<File> checkoutDir = versionInfoProvider.map( info -> new File(layout.getBuildDirectory().get().getAsFile(), "bwc/checkout-" + info.branch()) ); BwcSetupExtension bwcSetupExtension = project.getExtensions() .create( "bwcSetup", BwcSetupExtension.class, project, objectFactory, providerFactory, toolChainService, versionInfoProvider, checkoutDir, isCi ); BwcGitExtension gitExtension = project.getPlugins().apply(InternalBwcGitPlugin.class).getGitExtension(); Provider<Version> bwcVersion = versionInfoProvider.map(info -> info.version()); gitExtension.setBwcVersion(versionInfoProvider.map(info -> info.version())); gitExtension.setBwcBranch(versionInfoProvider.map(info -> info.branch())); gitExtension.getCheckoutDir().set(checkoutDir); // we want basic lifecycle tasks like `clean` here. project.getPlugins().apply(LifecycleBasePlugin.class); TaskProvider<Task> buildBwcTaskProvider = project.getTasks().register("buildBwc"); List<DistributionProject> distributionProjects = resolveArchiveProjects(checkoutDir.get(), bwcVersion.get()); // Setup gradle user home directory // We don't use a normal `Copy` task here as snapshotting the entire gradle user home is very expensive. This task is cheap, so // up-to-date checking doesn't buy us much project.getTasks().register("setupGradleUserHome", task -> { File gradleUserHome = project.getGradle().getGradleUserHomeDir(); String projectName = project.getName(); task.doLast(t -> { fileSystemOperations.copy(copy -> { String absoluteGradleUserHomePath = gradleUserHome.getAbsolutePath(); copy.into(absoluteGradleUserHomePath + "-" + projectName); copy.from(absoluteGradleUserHomePath, copySpec -> { copySpec.include("gradle.properties"); copySpec.include("init.d/*"); }); }); }); }); for (DistributionProject distributionProject : distributionProjects) { createBuildBwcTask( bwcSetupExtension, buildParams, project, bwcVersion, distributionProject.name, distributionProject.projectPath, distributionProject.expectedBuildArtifact, buildBwcTaskProvider, distributionProject.getAssembleTaskName() ); registerBwcDistributionArtifacts(project, distributionProject); } // Create build tasks for the JDBC driver used for compatibility testing String jdbcProjectDir = "x-pack/plugin/sql/jdbc"; DistributionProjectArtifact jdbcProjectArtifact = new DistributionProjectArtifact( new File(checkoutDir.get(), jdbcProjectDir + "/build/distributions/x-pack-sql-jdbc-" + bwcVersion.get() + "-SNAPSHOT.jar"), null ); createBuildBwcTask( bwcSetupExtension, buildParams, project, bwcVersion, "jdbc", jdbcProjectDir, jdbcProjectArtifact, buildBwcTaskProvider, "assemble" ); // for versions before 8.7.0, we do not need to set up stable API bwc if (bwcVersion.get().before(Version.fromString("8.7.0"))) { return; } for (Project stableApiProject : resolveStableProjects(project)) { String relativeDir = project.getRootProject().relativePath(stableApiProject.getProjectDir()); DistributionProjectArtifact stableAnalysisPluginProjectArtifact = new DistributionProjectArtifact( new File( checkoutDir.get(), relativeDir + "/build/distributions/elasticsearch-" + stableApiProject.getName() + "-" + bwcVersion.get() + "-SNAPSHOT.jar" ), null ); createBuildBwcTask( bwcSetupExtension, buildParams, project, bwcVersion, stableApiProject.getName(), "libs/" + stableApiProject.getName(), stableAnalysisPluginProjectArtifact, buildBwcTaskProvider, "assemble" ); } } private static void registerBwcDistributionArtifacts(Project bwcProject, DistributionProject distributionProject) { String projectName = distributionProject.name; String buildBwcTask = buildBwcTaskName(projectName); registerDistributionArchiveArtifact(bwcProject, distributionProject, buildBwcTask); File expectedExpandedDistDirectory = distributionProject.expectedBuildArtifact.expandedDistDir; if (expectedExpandedDistDirectory != null) { String expandedDistConfiguration = "expanded-" + projectName; bwcProject.getConfigurations().create(expandedDistConfiguration); bwcProject.getArtifacts().add(expandedDistConfiguration, expectedExpandedDistDirectory, artifact -> { artifact.setName("elasticsearch"); artifact.builtBy(buildBwcTask); artifact.setType("directory"); }); } } private static void registerDistributionArchiveArtifact( Project bwcProject, DistributionProject distributionProject, String buildBwcTask ) { File distFile = distributionProject.expectedBuildArtifact.distFile; String artifactFileName = distFile.getName(); String artifactName = artifactFileName.contains("oss") ? "elasticsearch-oss" : "elasticsearch"; String suffix = artifactFileName.endsWith("tar.gz") ? "tar.gz" : artifactFileName.substring(artifactFileName.length() - 3); int x86ArchIndex = artifactFileName.indexOf("x86_64"); int aarch64ArchIndex = artifactFileName.indexOf("aarch64"); bwcProject.getConfigurations().create(distributionProject.name); bwcProject.getArtifacts().add(distributionProject.name, distFile, artifact -> { artifact.setName(artifactName); artifact.builtBy(buildBwcTask); artifact.setType(suffix); String classifier = ""; if (x86ArchIndex != -1) { int osIndex = artifactFileName.lastIndexOf('-', x86ArchIndex - 2); classifier = "-" + artifactFileName.substring(osIndex + 1, x86ArchIndex - 1) + "-x86_64"; } else if (aarch64ArchIndex != -1) { int osIndex = artifactFileName.lastIndexOf('-', aarch64ArchIndex - 2); classifier = "-" + artifactFileName.substring(osIndex + 1, aarch64ArchIndex - 1) + "-aarch64"; } artifact.setClassifier(classifier); }); } private static List<DistributionProject> resolveArchiveProjects(File checkoutDir, Version bwcVersion) { List<String> projects = new ArrayList<>(); if (bwcVersion.onOrAfter("7.13.0")) { projects.addAll(asList("deb", "rpm")); projects.addAll(asList("windows-zip", "darwin-tar", "linux-tar")); projects.addAll(asList("darwin-aarch64-tar", "linux-aarch64-tar")); } else { projects.addAll(asList("deb", "rpm", "oss-deb", "oss-rpm")); if (bwcVersion.onOrAfter("7.0.0")) { // starting with 7.0 we bundle a jdk which means we have platform-specific archives projects.addAll(asList("oss-windows-zip", "windows-zip", "oss-darwin-tar", "darwin-tar", "oss-linux-tar", "linux-tar")); // We support aarch64 for linux and mac starting from 7.12 if (bwcVersion.onOrAfter("7.12.0")) { projects.addAll(asList("oss-darwin-aarch64-tar", "oss-linux-aarch64-tar", "darwin-aarch64-tar", "linux-aarch64-tar")); } } else { // prior to 7.0 we published only a single zip and tar archives for oss and default distributions projects.addAll(asList("oss-zip", "zip", "tar", "oss-tar")); } } return projects.stream().map(name -> { String baseDir = "distribution" + (name.endsWith("zip") || name.endsWith("tar") ? "/archives" : "/packages"); String classifier = ""; String extension = name; if (bwcVersion.onOrAfter("7.0.0")) { if (name.contains("zip") || name.contains("tar")) { int index = name.lastIndexOf('-'); String baseName = name.startsWith("oss-") ? name.substring(4, index) : name.substring(0, index); classifier = "-" + baseName + (name.contains("aarch64") ? "-aarch64" : "-x86_64"); extension = name.substring(index + 1); if (extension.equals("tar")) { extension += ".gz"; } } else if (name.contains("deb")) { classifier = "-amd64"; } else if (name.contains("rpm")) { classifier = "-x86_64"; } } return new DistributionProject(name, baseDir, bwcVersion, classifier, extension, checkoutDir); }).collect(Collectors.toList()); } private static List<Project> resolveStableProjects(Project project) { Set<String> stableProjectNames = Set.of("logging", "plugin-api", "plugin-analysis-api"); return project.findProject(":libs") .getSubprojects() .stream() .filter(subproject -> stableProjectNames.contains(subproject.getName())) .toList(); } public static String buildBwcTaskName(String projectName) { return "buildBwc" + stream(projectName.split("-")).map(i -> i.substring(0, 1).toUpperCase(Locale.ROOT) + i.substring(1)) .collect(Collectors.joining()); } static void createBuildBwcTask( BwcSetupExtension bwcSetupExtension, BuildParameterExtension buildParams, Project project, Provider<Version> bwcVersion, String projectName, String projectPath, DistributionProjectArtifact projectArtifact, TaskProvider<Task> bwcTaskProvider, String assembleTaskName ) { String bwcTaskName = buildBwcTaskName(projectName); bwcSetupExtension.bwcTask(bwcTaskName, c -> { boolean useNativeExpanded = projectArtifact.expandedDistDir != null; boolean isReleaseBuild = System.getProperty("tests.bwc.snapshot", "true").equals("false"); File expectedOutputFile = useNativeExpanded ? new File(projectArtifact.expandedDistDir, "elasticsearch-" + bwcVersion.get() + (isReleaseBuild ? "" : "-SNAPSHOT")) : projectArtifact.distFile; c.getInputs().file(new File(project.getBuildDir(), "refspec")).withPathSensitivity(PathSensitivity.RELATIVE); if (useNativeExpanded) { c.getOutputs().dir(expectedOutputFile); } else { c.getOutputs().files(expectedOutputFile); } c.getOutputs().doNotCacheIf("BWC distribution caching is disabled for local builds", task -> buildParams.getCi() == false); c.getArgs().add("-p"); c.getArgs().add(projectPath); c.getArgs().add(assembleTaskName); if (project.getGradle().getStartParameter().isBuildCacheEnabled()) { c.getArgs().add("--build-cache"); } File rootDir = project.getRootDir(); c.doLast(new Action<Task>() { @Override public void execute(Task task) { if (expectedOutputFile.exists() == false) { Path relativeOutputPath = rootDir.toPath().relativize(expectedOutputFile.toPath()); final String message = "Building %s didn't generate expected artifact [%s]. The working branch may be " + "out-of-date - try merging in the latest upstream changes to the branch."; throw new InvalidUserDataException(message.formatted(bwcVersion.get(), relativeOutputPath)); } } }); }); bwcTaskProvider.configure(t -> t.dependsOn(bwcTaskName)); } /** * Represents a distribution project (distribution/**) * we build from a bwc Version in a cloned repository */ private static
InternalDistributionBwcSetupPlugin
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessarilyFullyQualifiedTest.java
{ "start": 3062, "end": 3146 }
interface ____ { java.util.List foo(); public abstract
Test
java
apache__camel
components/camel-lra/src/test/java/org/apache/camel/service/lra/LRACreditIT.java
{ "start": 5436, "end": 5845 }
class ____ { private Set<String> orders = new HashSet<>(); public synchronized void newOrder(String id) { orders.add(id); } public synchronized void cancelOrder(String id) { orders.remove(id); } public synchronized Set<String> getOrders() { return new TreeSet<>(orders); } } public static
OrderManagerService
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/function/array/ArrayPositionsTest.java
{ "start": 1653, "end": 6722 }
class ____ { @BeforeEach public void prepareData(SessionFactoryScope scope) { scope.inTransaction( em -> { em.persist( new EntityWithArrays( 1L, new String[]{} ) ); em.persist( new EntityWithArrays( 2L, new String[]{ "abc", null, "def", "abc" } ) ); em.persist( new EntityWithArrays( 3L, null ) ); } ); } @AfterEach public void cleanup(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testPositions(SessionFactoryScope scope) { scope.inSession( em -> { //tag::hql-array-positions-example[] List<int[]> results = em.createQuery( "select array_positions(e.theArray, 'abc') from EntityWithArrays e order by e.id", int[].class ) .getResultList(); //end::hql-array-positions-example[] assertEquals( 3, results.size() ); assertArrayEquals( new int[0], results.get( 0 ) ); assertArrayEquals( new int[]{ 1, 4 }, results.get( 1 ) ); assertNull( results.get( 2 ) ); } ); } @Test public void testPositionsNotFound(SessionFactoryScope scope) { scope.inSession( em -> { List<int[]> results = em.createQuery( "select array_positions(e.theArray, 'xyz') from EntityWithArrays e order by e.id", int[].class ) .getResultList(); assertEquals( 3, results.size() ); assertArrayEquals( new int[0], results.get( 0 ) ); assertArrayEquals( new int[0], results.get( 1 ) ); assertNull( results.get( 2 ) ); } ); } @Test public void testPositionsNull(SessionFactoryScope scope) { scope.inSession( em -> { List<int[]> results = em.createQuery( "select array_positions(e.theArray, null) from EntityWithArrays e order by e.id", int[].class ) .getResultList(); assertEquals( 3, results.size() ); assertArrayEquals( new int[0], results.get( 0 ) ); assertArrayEquals( new int[]{ 2 }, results.get( 1 ) ); assertNull( results.get( 2 ) ); } ); } @Test @Jira("https://hibernate.atlassian.net/browse/HHH-19490") public void testPositionsParam(SessionFactoryScope scope) { scope.inSession( em -> { List<int[]> results = em.createQuery( "select array_positions(e.theArray, ?1) from EntityWithArrays e order by e.id", int[].class ) .setParameter( 1, "abc" ) .getResultList(); assertEquals( 3, results.size() ); assertArrayEquals( new int[0], results.get( 0 ) ); assertArrayEquals( new int[]{ 1, 4 }, results.get( 1 ) ); assertNull( results.get( 2 ) ); } ); } @Test public void testPositionsList(SessionFactoryScope scope) { scope.inSession( em -> { List<List<Integer>> results = em.createQuery( "select array_positions_list(e.theArray, null) from EntityWithArrays e order by e.id" ) .getResultList(); assertEquals( 3, results.size() ); assertEquals( List.of(), results.get( 0 ) ); assertEquals( List.of( 2 ), results.get( 1 ) ); assertNull( results.get( 2 ) ); } ); } @Test public void testNodeBuilderArray(SessionFactoryScope scope) { scope.inSession( em -> { final NodeBuilder cb = (NodeBuilder) em.getCriteriaBuilder(); final JpaCriteriaQuery<Tuple> cq = cb.createTupleQuery(); final JpaRoot<EntityWithArrays> root = cq.from( EntityWithArrays.class ); cq.multiselect( root.get( "id" ), cb.arrayPositions( root.<String[]>get( "theArray" ), cb.literal( "xyz" ) ), cb.arrayPositions( root.get( "theArray" ), "xyz" ), cb.arrayPositionsList( root.<String[]>get( "theArray" ), cb.literal( "xyz" ) ), cb.arrayPositionsList( root.get( "theArray" ), "xyz" ) ); em.createQuery( cq ).getResultList(); // Should all fail to compile // cb.arrayPositions( root.<Integer[]>get( "theArray" ), cb.literal( "xyz" ) ); // cb.arrayPositions( root.<Integer[]>get( "theArray" ), "xyz" ); // cb.arrayPositionsList( root.<Integer[]>get( "theArray" ), cb.literal( "xyz" ) ); // cb.arrayPositionsList( root.<Integer[]>get( "theArray" ), "xyz" ); } ); } @Test public void testNodeBuilderCollection(SessionFactoryScope scope) { scope.inSession( em -> { final NodeBuilder cb = (NodeBuilder) em.getCriteriaBuilder(); final JpaCriteriaQuery<Tuple> cq = cb.createTupleQuery(); final JpaRoot<EntityWithArrays> root = cq.from( EntityWithArrays.class ); cq.multiselect( root.get( "id" ), cb.collectionPositions( root.<Collection<String>>get( "theCollection" ), cb.literal( "xyz" ) ), cb.collectionPositions( root.get( "theCollection" ), "xyz" ), cb.collectionPositionsList( root.<Collection<String>>get( "theCollection" ), cb.literal( "xyz" ) ), cb.collectionPositionsList( root.get( "theCollection" ), "xyz" ) ); em.createQuery( cq ).getResultList(); // Should all fail to compile // cb.collectionPositions( root.<Collection<Integer>>get( "theCollection" ), cb.literal( "xyz" ) ); // cb.collectionPositions( root.<Collection<Integer>>get( "theCollection" ), "xyz" ); // cb.collectionPositionsList( root.<Collection<Integer>>get( "theCollection" ), cb.literal( "xyz" ) ); // cb.collectionPositionsList( root.<Collection<Integer>>get( "theCollection" ), "xyz" ); } ); } }
ArrayPositionsTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/char2darray/Char2DArrayAssert_doesNotContain_at_Index_Test.java
{ "start": 1112, "end": 1564 }
class ____ extends Char2DArrayAssertBaseTest { private final Index index = someIndex(); @Override protected Char2DArrayAssert invoke_api_method() { return assertions.doesNotContain(new char[] { '8', '9' }, index); } @Override protected void verify_internal_effects() { verify(arrays).assertDoesNotContain(getInfo(assertions), getActual(assertions), new char[] { '8', '9' }, index); } }
Char2DArrayAssert_doesNotContain_at_Index_Test
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/TestDataFileReflect.java
{ "start": 5695, "end": 6869 }
class ____ */ @Test void nestedClass() throws IOException { File file = new File(DIR.getPath(), "testNull.avro"); CheckList<BazRecord> check = new CheckList<>(); try (FileOutputStream fos = new FileOutputStream(file)) { Schema schema = ReflectData.get().getSchema(BazRecord.class); try (DataFileWriter<BazRecord> writer = new DataFileWriter<>(new ReflectDatumWriter<>(schema))) { writer.create(schema, fos); // test writing to a file write(writer, new BazRecord(10), check); write(writer, new BazRecord(20), check); } } ReflectDatumReader<BazRecord> din = new ReflectDatumReader<>(); try (SeekableFileInput sin = new SeekableFileInput(file)) { try (DataFileReader<BazRecord> reader = new DataFileReader<>(sin, din)) { int count = 0; for (BazRecord datum : reader) { check.assertEquals(datum, count++); } assertEquals(count, check.size()); } } } private <T> void write(DataFileWriter<T> writer, T o, CheckList<T> l) throws IOException { writer.append(l.addAndReturn(o)); } @SuppressWarnings("serial") private static
works
java
quarkusio__quarkus
devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java
{ "start": 3549, "end": 10894 }
class ____ extends QuarkusTask { public static final String IO_QUARKUS_DEVMODE_ARGS = "io.quarkus.devmode-args"; private final Configuration quarkusDevConfiguration; private final SourceSet mainSourceSet; private final ObjectFactory objectFactory; private final CompilerOptions compilerOptions = new CompilerOptions(); private final ExtensionDevModeJvmOptionFilter extensionJvmOptions = new ExtensionDevModeJvmOptionFilter(); private final Property<File> workingDirectory; private final MapProperty<String, String> environmentVariables; private final Property<Boolean> forceC2; private final Property<Boolean> shouldPropagateJavaCompilerArgs; private final ListProperty<String> args; private final ListProperty<String> jvmArgs; private final Property<Boolean> openJavaLang; private final ListProperty<String> modules; private final ListProperty<String> compilerArgs; private final ListProperty<String> tests; private final Set<File> filesIncludedInClasspath = new HashSet<>(); @SuppressWarnings("unused") @Inject public QuarkusDev(Configuration quarkusDevConfiguration, QuarkusPluginExtension extension) { this("Development mode: enables hot deployment with background compilation", quarkusDevConfiguration, extension); } public QuarkusDev( String name, Configuration quarkusDevConfiguration, @SuppressWarnings("unused") QuarkusPluginExtension extension) { super(name); this.quarkusDevConfiguration = quarkusDevConfiguration; mainSourceSet = getProject().getExtensions().getByType(SourceSetContainer.class) .getByName(SourceSet.MAIN_SOURCE_SET_NAME); objectFactory = getProject().getObjects(); workingDirectory = objectFactory.property(File.class); workingDirectory.convention(getProject().provider(() -> getProject().getLayout().getProjectDirectory().getAsFile())); environmentVariables = objectFactory.mapProperty(String.class, String.class); forceC2 = objectFactory.property(Boolean.class); shouldPropagateJavaCompilerArgs = objectFactory.property(Boolean.class); shouldPropagateJavaCompilerArgs.convention(true); args = objectFactory.listProperty(String.class); compilerArgs = objectFactory.listProperty(String.class); jvmArgs = objectFactory.listProperty(String.class); openJavaLang = objectFactory.property(Boolean.class); openJavaLang.convention(false); modules = objectFactory.listProperty(String.class); tests = objectFactory.listProperty(String.class); } /** * The dependency Configuration associated with this task. Used * for up-to-date checks * * @return quarkusDevConfiguration returns the configuration */ @SuppressWarnings("unused") @CompileClasspath public Configuration getQuarkusDevConfiguration() { return this.quarkusDevConfiguration; } /** * The JVM sources (Java, Kotlin, ..) for the project * * @return the FileCollection of all java source files present in the source directories */ @Optional @InputFiles @PathSensitive(PathSensitivity.RELATIVE) public FileCollection getSources() { return mainSourceSet.getAllJava().getSourceDirectories(); } /** * The JVM classes directory (compilation output) * * @return the FileCollection of all java source files present in the source directories */ @Optional @InputFiles @PathSensitive(PathSensitivity.RELATIVE) public FileCollection getCompilationOutput() { return mainSourceSet.getOutput().getClassesDirs(); } /** * The directory to be used as the working dir for the dev process. * * Defaults to the project directory. * * @return workingDirectory */ @Input public Property<File> getWorkingDirectory() { return workingDirectory; } /** * @deprecated See {@link #workingDirectory} */ @Deprecated public void setWorkingDir(String workingDir) { workingDirectory.set(getProject().file(workingDir)); } @Input public MapProperty<String, String> getEnvironmentVariables() { return environmentVariables; } @Internal public Map<String, String> getEnvVars() { return environmentVariables.get(); } @Input @Optional public Property<Boolean> getForceC2() { return forceC2; } @Input public ListProperty<String> getJvmArguments() { return jvmArgs; } @Internal public List<String> getJvmArgs() { return jvmArgs.get(); } @SuppressWarnings("unused") @Option(description = "Set JVM arguments", option = "jvm-args") public void setJvmArgs(List<String> jvmArgs) { this.jvmArgs.set(jvmArgs); } @Input public ListProperty<String> getArguments() { return args; } @Option(description = "Modules to add to the application", option = "modules") public void setModules(List<String> modules) { this.modules.set(modules); } @Input public ListProperty<String> getModules() { return modules; } @Option(description = "Open Java Lang module", option = "open-lang-package") public void setOpenJavaLang(Boolean openJavaLang) { this.openJavaLang.set(openJavaLang); } @Input public Property<Boolean> getOpenJavaLang() { return openJavaLang; } @SuppressWarnings("unused") @Internal public List<String> getArgs() { return args.get(); } public void setArgs(List<String> args) { this.args.set(args); } @SuppressWarnings("unused") @Option(description = "Set application arguments", option = "quarkus-args") public void setArgsString(String argsString) { this.setArgs(Arrays.asList(Commandline.translateCommandline(argsString))); } @Input public ListProperty<String> getCompilerArguments() { return compilerArgs; } @Internal public List<String> getCompilerArgs() { return getCompilerArguments().get(); } @SuppressWarnings("unused") @Option(description = "Additional parameters to pass to javac when recompiling changed source files", option = "compiler-args") public void setCompilerArgs(List<String> compilerArgs) { getCompilerArguments().set(compilerArgs); } @SuppressWarnings("unused") @Internal public CompilerOptions getCompilerOptions() { return this.compilerOptions; } @SuppressWarnings("unused") public QuarkusDev compilerOptions(Action<CompilerOptions> action) { action.execute(compilerOptions); return this; } @SuppressWarnings("unused") @Internal public ExtensionDevModeJvmOptionFilter getExtensionJvmOptions() { return this.extensionJvmOptions; } @SuppressWarnings("unused") public QuarkusDev extensionJvmOptions(Action<ExtensionDevModeJvmOptionFilter> action) { action.execute(extensionJvmOptions); return this; } @Input public ListProperty<String> getTests() { return tests; } @SuppressWarnings("unused") @Option(description = "Sets test
QuarkusDev
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/superdao/generic/SuperRepoTest.java
{ "start": 493, "end": 926 }
class ____ { @Test @WithClasses({ Book.class, SuperRepo.class, Repo.class }) void testQueryMethod() { // System.out.println( TestUtil.getMetaModelSourceAsString( SuperRepo.class ) ); System.out.println( TestUtil.getMetaModelSourceAsString( Repo.class ) ); assertMetamodelClassGeneratedFor( Book.class ); // assertMetamodelClassGeneratedFor( SuperRepo.class ); assertMetamodelClassGeneratedFor( Repo.class ); } }
SuperRepoTest
java
netty__netty
resolver-dns/src/main/java/io/netty/resolver/dns/DnsServerAddressStreamProviders.java
{ "start": 5667, "end": 7763 }
class ____ { // We use 5 minutes which is the same as what OpenJDK is using in sun.net.dns.ResolverConfigurationImpl. private static final long REFRESH_INTERVAL = TimeUnit.MINUTES.toNanos(5); // TODO(scott): how is this done on Windows? This may require a JNI call to GetNetworkParams // https://msdn.microsoft.com/en-us/library/aa365968(VS.85).aspx. static final DnsServerAddressStreamProvider DEFAULT_DNS_SERVER_ADDRESS_STREAM_PROVIDER = new DnsServerAddressStreamProvider() { private volatile DnsServerAddressStreamProvider currentProvider = provider(); private final AtomicLong lastRefresh = new AtomicLong(System.nanoTime()); @Override public DnsServerAddressStream nameServerAddressStream(String hostname) { long last = lastRefresh.get(); DnsServerAddressStreamProvider current = currentProvider; if (System.nanoTime() - last > REFRESH_INTERVAL) { // This is slightly racy which means it will be possible still use the old configuration // for a small amount of time, but that's ok. if (lastRefresh.compareAndSet(last, System.nanoTime())) { current = currentProvider = provider(); } } return current.nameServerAddressStream(hostname); } private DnsServerAddressStreamProvider provider() { // If on windows just use the DefaultDnsServerAddressStreamProvider.INSTANCE as otherwise // we will log some error which may be confusing. return PlatformDependent.isWindows() ? DefaultDnsServerAddressStreamProvider.INSTANCE : UnixResolverDnsServerAddressStreamProvider.parseSilently(); } }; } }
DefaultProviderHolder
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/SharedStateRegistryTest.java
{ "start": 18576, "end": 19714 }
class ____ implements TestStreamStateHandle { private static final long serialVersionUID = 4468635881465159780L; private SharedStateRegistryKey key; private boolean discarded; TestSharedState(String key) { this.key = new SharedStateRegistryKey(key); this.discarded = false; } public SharedStateRegistryKey getRegistrationKey() { return key; } @Override public void discardState() throws Exception { this.discarded = true; } @Override public long getStateSize() { return key.toString().length(); } @Override public int hashCode() { return key.hashCode(); } @Override public FSDataInputStream openInputStream() throws IOException { throw new UnsupportedOperationException(); } @Override public Optional<byte[]> asBytesIfInMemory() { return Optional.empty(); } public boolean isDiscarded() { return discarded; } } }
TestSharedState
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/RestRegistry.java
{ "start": 2818, "end": 3724 }
class ____&gt;</tt> is enclosed the name. */ String getOutType(); /** * Optional description about this rest service. */ String getDescription(); } /** * Adds a new REST service to the registry. * * @param consumer the consumer * @param contractFirst is the rest service based on code-first or contract-first * @param url the absolute url of the REST service * @param baseUrl the base url of the REST service * @param basePath the base path * @param uriTemplate the uri template * @param method the HTTP method * @param consumes optional details about what media-types the REST service accepts * @param produces optional details about what media-types the REST service returns * @param inType optional detail input binding to a FQN
name
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/kstream/internals/KTableKTableLeftJoin.java
{ "start": 2512, "end": 3116 }
class ____ extends KTableKTableAbstractJoinValueGetterSupplier<K, VOut, V1, V2> { KTableKTableLeftJoinValueGetterSupplier(final KTableValueGetterSupplier<K, V1> valueGetterSupplier1, final KTableValueGetterSupplier<K, V2> valueGetterSupplier2) { super(valueGetterSupplier1, valueGetterSupplier2); } public KTableValueGetter<K, VOut> get() { return new KTableKTableLeftJoinValueGetter(valueGetterSupplier1.get(), valueGetterSupplier2.get()); } } private
KTableKTableLeftJoinValueGetterSupplier
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/action/TransportUpdateConnectorConfigurationAction.java
{ "start": 817, "end": 1863 }
class ____ extends HandledTransportAction< UpdateConnectorConfigurationAction.Request, ConnectorUpdateActionResponse> { protected final ConnectorIndexService connectorIndexService; @Inject public TransportUpdateConnectorConfigurationAction(TransportService transportService, ActionFilters actionFilters, Client client) { super( UpdateConnectorConfigurationAction.NAME, transportService, actionFilters, UpdateConnectorConfigurationAction.Request::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.connectorIndexService = new ConnectorIndexService(client); } @Override protected void doExecute( Task task, UpdateConnectorConfigurationAction.Request request, ActionListener<ConnectorUpdateActionResponse> listener ) { connectorIndexService.updateConnectorConfiguration(request, listener.map(r -> new ConnectorUpdateActionResponse(r.getResult()))); } }
TransportUpdateConnectorConfigurationAction
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/dos/BiggerDataTest.java
{ "start": 921, "end": 1233 }
class ____ { public int id; public String name; public String description; public String subtitle; public String logo; public Integer subjectCode; // nullable public int[] topicIds; public LinkedHashSet<Integer> subTopicIds; } static
Event
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/Murmur3.java
{ "start": 862, "end": 1675 }
class ____ taken from Hive org.apache.hive.common.util; * https://github.com/apache/hive/blob/master/storage-api/src/java/org/apache/hive/common/util/Murmur3.java * Commit: dffa3a16588bc8e95b9d0ab5af295a74e06ef702 * * * Murmur3 is successor to Murmur2 fast non-crytographic hash algorithms. * * Murmur3 32 and 128 bit variants. * 32-bit Java port of https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp#94 * 128-bit Java port of https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp#255 * * This is a public domain code with no copyrights. * From homepage of MurmurHash (https://code.google.com/p/smhasher/), * "All MurmurHash versions are public domain software, and the author disclaims all copyright * to their code." */ @SuppressWarnings("fallthrough") public
was
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/server/util/matcher/IpAddressServerWebExchangeMatcherTests.java
{ "start": 1402, "end": 6502 }
class ____ { @Test public void matchesWhenIpv6RangeAndIpv6AddressThenTrue() throws UnknownHostException { ServerWebExchange ipv6Exchange = exchange("fe80::21f:5bff:fe33:bd68"); ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("fe80::21f:5bff:fe33:bd68") .matches(ipv6Exchange) .block(); assertThat(matches.isMatch()).isTrue(); } @Test public void matchesWhenIpv6RangeAndIpv4AddressThenFalse() throws UnknownHostException { ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("fe80::21f:5bff:fe33:bd68") .matches(ipv4Exchange) .block(); assertThat(matches.isMatch()).isFalse(); } @Test public void matchesWhenIpv4RangeAndIpv4AddressThenTrue() throws UnknownHostException { ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("192.168.1.104") .matches(ipv4Exchange) .block(); assertThat(matches.isMatch()).isTrue(); } @Test public void matchesWhenIpv4SubnetAndIpv4AddressThenTrue() throws UnknownHostException { ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("192.168.1.0/24"); assertThat(matcher.matches(ipv4Exchange).block().isMatch()).isTrue(); } @Test public void matchesWhenIpv4SubnetAndIpv4AddressThenFalse() throws UnknownHostException { ServerWebExchange ipv4Exchange = exchange("192.168.1.104"); IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("192.168.1.128/25"); assertThat(matcher.matches(ipv4Exchange).block().isMatch()).isFalse(); } @Test public void matchesWhenIpv6SubnetAndIpv6AddressThenTrue() throws UnknownHostException { ServerWebExchange ipv6Exchange = exchange("2001:DB8:0:FFFF:FFFF:FFFF:FFFF:FFFF"); IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("2001:DB8::/48"); assertThat(matcher.matches(ipv6Exchange).block().isMatch()).isTrue(); } @Test public void matchesWhenIpv6SubnetAndIpv6AddressThenFalse() throws UnknownHostException { ServerWebExchange ipv6Exchange = exchange("2001:DB8:1:0:0:0:0:0"); IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("2001:DB8::/48"); assertThat(matcher.matches(ipv6Exchange).block().isMatch()).isFalse(); } @Test public void matchesWhenZeroMaskAndAnythingThenTrue() throws UnknownHostException { IpAddressServerWebExchangeMatcher matcher = new IpAddressServerWebExchangeMatcher("0.0.0.0/0"); assertThat(matcher.matches(exchange("123.4.5.6")).block().isMatch()).isTrue(); assertThat(matcher.matches(exchange("192.168.0.159")).block().isMatch()).isTrue(); matcher = new IpAddressServerWebExchangeMatcher("192.168.0.159/0"); assertThat(matcher.matches(exchange("123.4.5.6")).block().isMatch()).isTrue(); assertThat(matcher.matches(exchange("192.168.0.159")).block().isMatch()).isTrue(); } @Test public void matchesWhenIpv4UnresolvedThenTrue() throws UnknownHostException { ServerWebExchange ipv4Exchange = exchange("192.168.1.104", true); ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("192.168.1.104") .matches(ipv4Exchange) .block(); assertThat(matches.isMatch()).isTrue(); } @Test public void matchesWhenIpv6UnresolvedThenTrue() throws UnknownHostException { ServerWebExchange ipv6Exchange = exchange("fe80::21f:5bff:fe33:bd68", true); ServerWebExchangeMatcher.MatchResult matches = new IpAddressServerWebExchangeMatcher("fe80::21f:5bff:fe33:bd68") .matches(ipv6Exchange) .block(); assertThat(matches.isMatch()).isTrue(); } @Test public void constructorWhenIpv4AddressMaskTooLongThenIllegalArgumentException() { String ipv4AddressWithTooLongMask = "192.168.1.104/33"; assertThatIllegalArgumentException() .isThrownBy(() -> new IpAddressServerWebExchangeMatcher(ipv4AddressWithTooLongMask)) .withMessage(String.format("IP address %s is too short for bitmask of length %d", "192.168.1.104", 33)); } @Test public void constructorWhenIpv6AddressMaskTooLongThenIllegalArgumentException() { String ipv6AddressWithTooLongMask = "fe80::21f:5bff:fe33:bd68/129"; assertThatIllegalArgumentException() .isThrownBy(() -> new IpAddressServerWebExchangeMatcher(ipv6AddressWithTooLongMask)) .withMessage(String.format("IP address %s is too short for bitmask of length %d", "fe80::21f:5bff:fe33:bd68", 129)); } private static ServerWebExchange exchange(String ipAddress) throws UnknownHostException { return exchange(ipAddress, false); } private static ServerWebExchange exchange(String ipAddress, boolean unresolved) throws UnknownHostException { return MockServerWebExchange .builder(MockServerHttpRequest.get("/") .remoteAddress(unresolved ? InetSocketAddress.createUnresolved(ipAddress, 8080) : new InetSocketAddress(InetAddress.getByName(ipAddress), 8080))) .build(); } }
IpAddressServerWebExchangeMatcherTests
java
quarkusio__quarkus
extensions/spring-data-rest/deployment/src/test/java/io/quarkus/spring/data/rest/paged/DefaultPagedResourceTest.java
{ "start": 833, "end": 12511 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(AbstractEntity.class, Record.class, DefaultRecordsRepository.class) .addAsResource("application.properties") .addAsResource("import.sql")); @Test void shouldList() { Response response = given().accept("application/json") .when().get("/default-records") .thenReturn(); assertThat(response.statusCode()).isEqualTo(200); assertThat(response.body().jsonPath().getList("id")).contains(1, 2); assertThat(response.body().jsonPath().getList("name")).contains("first", "second"); Map<String, String> expectedLinks = new HashMap<>(2); expectedLinks.put("first", "/default-records?page=0&size=20"); expectedLinks.put("last", "/default-records?page=0&size=20"); assertLinks(response.headers(), expectedLinks); } @Test void shouldListHal() { given().accept("application/hal+json") .when().get("/default-records") .then().statusCode(200) .and().body("_embedded.default-records.id", hasItems(1, 2)) .and().body("_embedded.default-records.name", hasItems("first", "second")) .and() .body("_embedded.default-records._links.add.href", hasItems(endsWith("/default-records"), endsWith("/default-records"))) .and() .body("_embedded.default-records._links.list.href", hasItems(endsWith("/default-records"), endsWith("/default-records"))) .and() .body("_embedded.default-records._links.self.href", hasItems(endsWith("/default-records/1"), endsWith("/default-records/2"))) .and() .body("_embedded.default-records._links.update.href", hasItems(endsWith("/default-records/1"), endsWith("/default-records/2"))) .and() .body("_embedded.default-records._links.remove.href", hasItems(endsWith("/default-records/1"), endsWith("/default-records/2"))) .and().body("_links.add.href", endsWith("/default-records")) .and().body("_links.list.href", endsWith("/default-records")) .and().body("_links.first.href", endsWith("/default-records?page=0&size=20")) .and().body("_links.last.href", endsWith("/default-records?page=0&size=20")); } @Test void shouldListFirstPage() { Response initResponse = given().accept("application/json") .when().get("/default-records") .thenReturn(); List<Integer> ids = initResponse.body().jsonPath().getList("id"); List<String> names = initResponse.body().jsonPath().getList("name"); int lastPage = ids.size() - 1; Response response = given().accept("application/json") .and().queryParam("page", 0) .and().queryParam("size", 1) .when().get("/default-records") .thenReturn(); assertThat(response.statusCode()).isEqualTo(200); assertThat(response.body().jsonPath().getList("id")).containsOnly(ids.get(0)); assertThat(response.body().jsonPath().getList("name")).containsOnly(names.get(0)); Map<String, String> expectedLinks = new HashMap<>(3); expectedLinks.put("first", "/default-records?page=0&size=1"); expectedLinks.put("last", "/default-records?page=" + lastPage + "&size=1"); expectedLinks.put("next", "/default-records?page=1&size=1"); assertLinks(response.headers(), expectedLinks); } @Test void shouldListFirstPageHal() { Response initResponse = given().accept("application/json") .when().get("/default-records") .thenReturn(); List<Integer> ids = initResponse.body().jsonPath().getList("id"); List<String> names = initResponse.body().jsonPath().getList("name"); int lastPage = ids.size() - 1; given().accept("application/hal+json") .and().queryParam("page", 0) .and().queryParam("size", 1) .when().get("/default-records") .then().statusCode(200) .and().body("_embedded.default-records.id", contains(ids.get(0))) .and().body("_embedded.default-records.name", contains(names.get(0))) .and() .body("_embedded.default-records._links.add.href", hasItems(endsWith("/default-records"), endsWith("/default-records"))) .and() .body("_embedded.default-records._links.list.href", hasItems(endsWith("/default-records"), endsWith("/default-records"))) .and() .body("_embedded.default-records._links.self.href", contains(endsWith("/default-records/" + ids.get(0)))) .and() .body("_embedded.default-records._links.update.href", contains(endsWith("/default-records/" + ids.get(0)))) .and() .body("_embedded.default-records._links.remove.href", contains(endsWith("/default-records/" + ids.get(0)))) .and().body("_links.add.href", endsWith("/default-records")) .and().body("_links.list.href", endsWith("/default-records")) .and().body("_links.first.href", endsWith("/default-records?page=0&size=1")) .and().body("_links.last.href", endsWith("/default-records?page=" + lastPage + "&size=1")) .and().body("_links.next.href", endsWith("/default-records?page=1&size=1")); } @Test void shouldListLastPage() { Response initResponse = given().accept("application/json") .when().get("/default-records") .thenReturn(); List<Integer> ids = initResponse.body().jsonPath().getList("id"); List<String> names = initResponse.body().jsonPath().getList("name"); int lastPage = ids.size() - 1; Response response = given().accept("application/json") .and().queryParam("page", lastPage) .and().queryParam("size", 1) .when().get("/default-records") .thenReturn(); assertThat(response.statusCode()).isEqualTo(200); assertThat(response.body().jsonPath().getList("id")).containsOnly(ids.get(lastPage)); assertThat(response.body().jsonPath().getList("name")).containsOnly(names.get(lastPage)); Map<String, String> expectedLinks = new HashMap<>(3); expectedLinks.put("first", "/default-records?page=0&size=1"); expectedLinks.put("last", "/default-records?page=" + lastPage + "&size=1"); expectedLinks.put("previous", "/default-records?page=" + (lastPage - 1) + "&size=1"); assertLinks(response.headers(), expectedLinks); } @Test void shouldListLastPageHal() { Response initResponse = given().accept("application/json") .when().get("/default-records") .thenReturn(); List<Integer> ids = initResponse.body().jsonPath().getList("id"); List<String> names = initResponse.body().jsonPath().getList("name"); int lastPage = ids.size() - 1; given().accept("application/hal+json") .and().queryParam("page", lastPage) .and().queryParam("size", 1) .when().get("/default-records") .then().statusCode(200) .and().body("_embedded.default-records.id", contains(ids.get(lastPage))) .and().body("_embedded.default-records.name", contains(names.get(lastPage))) .and() .body("_embedded.default-records._links.add.href", hasItems(endsWith("/default-records"), endsWith("/default-records"))) .and() .body("_embedded.default-records._links.list.href", hasItems(endsWith("/default-records"), endsWith("/default-records"))) .and() .body("_embedded.default-records._links.self.href", contains(endsWith("/default-records/" + ids.get(lastPage)))) .and() .body("_embedded.default-records._links.update.href", contains(endsWith("/default-records/" + ids.get(lastPage)))) .and() .body("_embedded.default-records._links.remove.href", contains(endsWith("/default-records/" + ids.get(lastPage)))) .and().body("_links.add.href", endsWith("/default-records")) .and().body("_links.list.href", endsWith("/default-records")) .and().body("_links.first.href", endsWith("/default-records?page=0&size=1")) .and().body("_links.last.href", endsWith("/default-records?page=" + lastPage + "&size=1")) .and().body("_links.previous.href", endsWith("/default-records?page=" + (lastPage - 1) + "&size=1")); } @Test void shouldNotGetNonExistentPage() { given().accept("application/json") .and().queryParam("page", 100) .when().get("/default-records") .then().statusCode(200) .and().body("id", is(empty())); } @Test void shouldNotGetNegativePageOrSize() { given().accept("application/json") .and().queryParam("page", -1) .and().queryParam("size", -1) .when().get("/default-records") .then().statusCode(200) // Invalid page and size parameters are replaced with defaults .and().body("id", hasItems(1, 2)); } @Test void shouldListAscending() { Response response = given().accept("application/json") .when().get("/default-records?sort=name,id") .thenReturn(); List<String> actualNames = response.body().jsonPath().getList("name"); List<String> expectedNames = new LinkedList<>(actualNames); expectedNames.sort(Comparator.naturalOrder()); assertThat(actualNames).isEqualTo(expectedNames); } @Test void shouldListDescending() { Response response = given().accept("application/json") .when().get("/default-records?sort=-name,id") .thenReturn(); List<String> actualNames = response.body().jsonPath().getList("name"); List<String> expectedNames = new LinkedList<>(actualNames); expectedNames.sort(Comparator.reverseOrder()); assertThat(actualNames).isEqualTo(expectedNames); } private void assertLinks(Headers headers, Map<String, String> expectedLinks) { List<Link> links = new LinkedList<>(); for (Header header : headers.getList("Link")) { links.add(Link.valueOf(header.getValue())); } assertThat(links).hasSize(expectedLinks.size()); for (Map.Entry<String, String> expectedLink : expectedLinks.entrySet()) { assertThat(links).anySatisfy(link -> { assertThat(link.getUri().toString()).endsWith(expectedLink.getValue()); assertThat(link.getRel()).isEqualTo(expectedLink.getKey()); }); } } }
DefaultPagedResourceTest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/beanparam/BeanFormParamTest.java
{ "start": 1507, "end": 2189 }
class ____ { private final String param1; private final String param2; private final Param param3; public BeanWithFormParams(String param1, String param2, Param param3) { this.param1 = param1; this.param2 = param2; this.param3 = param3; } @FormParam("param1") public String getParam1() { return param1; } @FormParam("param2") public String getParam2() { return param2; } @FormParam("param3") public Param getParam3() { return param3; } } @Path("/form") public static
BeanWithFormParams
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/util/KeyedMultiInputStreamOperatorTestHarness.java
{ "start": 1559, "end": 2610 }
class ____<KEY, OUT> extends MultiInputStreamOperatorTestHarness<OUT> { public KeyedMultiInputStreamOperatorTestHarness( StreamOperatorFactory<OUT> operator, TypeInformation<KEY> keyType) throws Exception { this(operator, 1, 1, 0); config.setStateKeySerializer( keyType.createSerializer(executionConfig.getSerializerConfig())); config.serializeAllConfigs(); } public KeyedMultiInputStreamOperatorTestHarness( StreamOperatorFactory<OUT> operatorFactory, int maxParallelism, int numSubtasks, int subtaskIndex) throws Exception { super(operatorFactory, maxParallelism, numSubtasks, subtaskIndex); } public void setKeySelector(int idx, KeySelector<?, KEY> keySelector) { ClosureCleaner.clean(keySelector, ExecutionConfig.ClosureCleanerLevel.RECURSIVE, false); config.setStatePartitioner(idx, keySelector); config.serializeAllConfigs(); } }
KeyedMultiInputStreamOperatorTestHarness
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/custom/response/CustomResponseParser.java
{ "start": 684, "end": 1066 }
interface ____ extends ToXContentFragment, NamedWriteable { InferenceServiceResults parse(HttpResult response) throws IOException; /** * Returns the configured embedding type for this response parser. This should be overridden for text embedding parsers. */ default CustomServiceEmbeddingType getEmbeddingType() { return null; } }
CustomResponseParser
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointSamplingTest.java
{ "start": 1170, "end": 2737 }
class ____ extends ContextTestSupport { private static String beforeThreadName; private static String afterThreadName; @Test public void testAsyncEndpoint() throws Exception { getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel"); getMockEndpoint("mock:result").expectedBodiesReceived("Bye Camel"); String reply = template.requestBody("direct:start", "Hello Camel", String.class); assertEquals("Bye Camel", reply); assertMockEndpointsSatisfied(); assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should use different threads"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.addComponent("async", new MyAsyncComponent()); from("direct:start").to("mock:before").to("log:before").process(new Processor() { public void process(Exchange exchange) { beforeThreadName = Thread.currentThread().getName(); } }).sample().to("async:bye:camel").end().to("log:after").to("mock:after").process(new Processor() { public void process(Exchange exchange) { afterThreadName = Thread.currentThread().getName(); } }).to("mock:result"); } }; } }
AsyncEndpointSamplingTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestFileCreationEmpty.java
{ "start": 1170, "end": 3248 }
class ____ { private boolean isConcurrentModificationException = false; /** * This test creates three empty files and lets their leases expire. * This triggers release of the leases. * The empty files are supposed to be closed by that * without causing ConcurrentModificationException. */ @Test public void testLeaseExpireEmptyFiles() throws Exception { final Thread.UncaughtExceptionHandler oldUEH = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { if (e instanceof ConcurrentModificationException) { LeaseManager.LOG.error("t=" + t, e); isConcurrentModificationException = true; } } }); System.out.println("testLeaseExpireEmptyFiles start"); final long leasePeriod = 1000; final int DATANODE_NUM = 3; final Configuration conf = new HdfsConfiguration(); conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 1000); conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1); // create cluster MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(DATANODE_NUM).build(); try { cluster.waitActive(); DistributedFileSystem dfs = cluster.getFileSystem(); // create a new file. TestFileCreation.createFile(dfs, new Path("/foo"), DATANODE_NUM); TestFileCreation.createFile(dfs, new Path("/foo2"), DATANODE_NUM); TestFileCreation.createFile(dfs, new Path("/foo3"), DATANODE_NUM); // set the soft and hard limit to be 1 second so that the // namenode triggers lease recovery cluster.setLeasePeriod(leasePeriod, leasePeriod); // wait for the lease to expire try {Thread.sleep(5 * leasePeriod);} catch (InterruptedException e) {} assertFalse(isConcurrentModificationException); } finally { Thread.setDefaultUncaughtExceptionHandler(oldUEH); cluster.shutdown(); } } }
TestFileCreationEmpty
java
elastic__elasticsearch
x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/search/aggregations/support/GeoShapeValuesSource.java
{ "start": 1324, "end": 1917 }
class ____ extends GeoShapeValuesSource { protected final IndexShapeFieldData<GeoShapeValues> indexFieldData; public Fielddata(IndexShapeFieldData<GeoShapeValues> indexFieldData) { this.indexFieldData = indexFieldData; } @Override public SortedBinaryDocValues bytesValues(LeafReaderContext context) { return indexFieldData.load(context).getBytesValues(); } public GeoShapeValues shapeValues(LeafReaderContext context) { return indexFieldData.load(context).getShapeValues(); } } }
Fielddata
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/ldap/ContextSourceSettingPostProcessor.java
{ "start": 1565, "end": 3651 }
class ____ implements BeanFactoryPostProcessor, Ordered { private static final String REQUIRED_CONTEXT_SOURCE_CLASS_NAME = "org.springframework.ldap.core.support.BaseLdapPathContextSource"; /** * If set to true, a bean parser has indicated that the default context source name * needs to be set */ private boolean defaultNameRequired; ContextSourceSettingPostProcessor() { } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory bf) throws BeansException { Class<?> contextSourceClass = getContextSourceClass(); String[] sources = bf.getBeanNamesForType(contextSourceClass, false, false); if (sources.length == 0) { throw new ApplicationContextException("No BaseLdapPathContextSource instances found. Have you " + "added an <" + Elements.LDAP_SERVER + " /> element to your application context? If you have " + "declared an explicit bean, do not use lazy-init"); } if (!bf.containsBean(BeanIds.CONTEXT_SOURCE) && this.defaultNameRequired) { if (sources.length > 1) { throw new ApplicationContextException("More than one BaseLdapPathContextSource instance found. " + "Please specify a specific server id using the 'server-ref' attribute when configuring your <" + Elements.LDAP_PROVIDER + "> " + "or <" + Elements.LDAP_USER_SERVICE + ">."); } bf.registerAlias(sources[0], BeanIds.CONTEXT_SOURCE); } } private Class<?> getContextSourceClass() throws LinkageError { try { return ClassUtils.forName(REQUIRED_CONTEXT_SOURCE_CLASS_NAME, ClassUtils.getDefaultClassLoader()); } catch (ClassNotFoundException ex) { throw new ApplicationContextException("Couldn't locate: " + REQUIRED_CONTEXT_SOURCE_CLASS_NAME + ". " + " If you are using LDAP with Spring Security, please ensure that you include the spring-ldap " + "jar file in your application", ex); } } public void setDefaultNameRequired(boolean defaultNameRequired) { this.defaultNameRequired = defaultNameRequired; } @Override public int getOrder() { return LOWEST_PRECEDENCE; } }
ContextSourceSettingPostProcessor
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptivebatch/DummySpeculativeExecutionHandler.java
{ "start": 1411, "end": 2452 }
class ____ implements SpeculativeExecutionHandler { @Override public void init( ExecutionGraph executionGraph, ComponentMainThreadExecutor mainThreadExecutor, MetricGroup metricGroup) { // do nothing } @Override public void stopSlowTaskDetector() { // do nothing } @Override public void notifyTaskFinished( Execution execution, Function<ExecutionVertexID, CompletableFuture<?>> cancelPendingExecutionsFunction) { // do nothing } @Override public void notifyTaskFailed(Execution execution) { // do nothing } @Override public boolean handleTaskFailure( Execution failedExecution, @Nullable Throwable error, BiConsumer<Execution, Throwable> handleLocalExecutionAttemptFailure) { return false; } @Override public void resetForNewExecution(ExecutionVertexID executionVertexId) { // do nothing } }
DummySpeculativeExecutionHandler
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/stream/ClientStreamFactory.java
{ "start": 1299, "end": 1573 }
interface ____ { ClientStream createClientStream( AbstractConnectionClient client, FrameworkModel frameworkModel, Executor executor, TripleClientCall clientCall, TripleWriteQueue writeQueue); }
ClientStreamFactory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/ConcreteProxyTest.java
{ "start": 12396, "end": 12888 }
class ____ { @Id private Long id; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) private SingleBase single; public SingleParent() { } public SingleParent(Long id, SingleBase single) { this.id = id; this.single = single; } public SingleBase getSingle() { return single; } } @Entity(name = "SingleBase") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name = "disc_col") @ConcreteProxy public static
SingleParent
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/support/FluentQuerySupport.java
{ "start": 1357, "end": 1631 }
class ____ some state and convenience methods for building and executing fluent queries. * * @param <R> The resulting type of the query. * @author Greg Turnquist * @author Jens Schauder * @author Mark Paluch * @author Christoph Strobl * @since 2.6 */ abstract
containing
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateClosedCorrelationKeyTest.java
{ "start": 1220, "end": 5162 }
class ____ extends ContextTestSupport { @Override public boolean isUseRouteBuilder() { return false; } @Test public void testAggregateClosedCorrelationKey() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start").aggregate(header("id"), new BodyInAggregatingStrategy()).completionSize(2) .closeCorrelationKeyOnCompletion(1000).to("mock:result"); } }); context.start(); getMockEndpoint("mock:result").expectedBodiesReceived("A+B"); template.sendBodyAndHeader("direct:start", "A", "id", 1); template.sendBodyAndHeader("direct:start", "B", "id", 1); // should be closed try { template.sendBodyAndHeader("direct:start", "C", "id", 1); fail("Should throw an exception"); } catch (CamelExecutionException e) { ClosedCorrelationKeyException cause = assertIsInstanceOf(ClosedCorrelationKeyException.class, e.getCause()); assertEquals("1", cause.getCorrelationKey()); assertTrue(cause.getMessage().startsWith("The correlation key [1] has been closed.")); } assertMockEndpointsSatisfied(); } @Test public void testAggregateClosedCorrelationKeyCache() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start").aggregate(header("id"), new BodyInAggregatingStrategy()).completionSize(2) .closeCorrelationKeyOnCompletion(2).to("mock:result"); } }); context.start(); getMockEndpoint("mock:result").expectedBodiesReceived("A+B", "C+D", "E+F"); template.sendBodyAndHeader("direct:start", "A", "id", 1); template.sendBodyAndHeader("direct:start", "B", "id", 1); template.sendBodyAndHeader("direct:start", "C", "id", 2); template.sendBodyAndHeader("direct:start", "D", "id", 2); template.sendBodyAndHeader("direct:start", "E", "id", 3); template.sendBodyAndHeader("direct:start", "F", "id", 3); Thread.sleep(200); // 2 of them should now be closed int closed = 0; // should NOT be closed because only 2 and 3 is remembered as they are // the two last used try { template.sendBodyAndHeader("direct:start", "G", "id", 1); } catch (CamelExecutionException e) { closed++; ClosedCorrelationKeyException cause = assertIsInstanceOf(ClosedCorrelationKeyException.class, e.getCause()); assertEquals("1", cause.getCorrelationKey()); assertTrue(cause.getMessage().startsWith("The correlation key [1] has been closed.")); } // should be closed try { template.sendBodyAndHeader("direct:start", "H", "id", 2); } catch (CamelExecutionException e) { closed++; ClosedCorrelationKeyException cause = assertIsInstanceOf(ClosedCorrelationKeyException.class, e.getCause()); assertEquals("2", cause.getCorrelationKey()); assertTrue(cause.getMessage().startsWith("The correlation key [2] has been closed.")); } // should be closed try { template.sendBodyAndHeader("direct:start", "I", "id", 3); } catch (CamelExecutionException e) { closed++; ClosedCorrelationKeyException cause = assertIsInstanceOf(ClosedCorrelationKeyException.class, e.getCause()); assertEquals("3", cause.getCorrelationKey()); assertTrue(cause.getMessage().startsWith("The correlation key [3] has been closed.")); } assertMockEndpointsSatisfied(); assertEquals(2, closed, "There should be 2 closed"); } }
AggregateClosedCorrelationKeyTest
java
elastic__elasticsearch
x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/session/ListCursorTests.java
{ "start": 634, "end": 2067 }
class ____ extends AbstractSqlWireSerializingTestCase<ListCursor> { public static ListCursor randomPagingListCursor() { int size = between(1, 100); int depth = between(1, 20); List<List<?>> values = new ArrayList<>(size); for (int i = 0; i < size; i++) { values.add(Arrays.asList(randomArray(depth, s -> new Object[depth], () -> randomByte()))); } return new ListCursor(values, between(1, 20), depth); } @Override protected ListCursor mutateInstance(ListCursor instance) { return new ListCursor(instance.data(), randomValueOtherThan(instance.pageSize(), () -> between(1, 20)), instance.columnCount()); } @Override protected ListCursor createTestInstance() { return randomPagingListCursor(); } @Override protected Writeable.Reader<ListCursor> instanceReader() { return ListCursor::new; } @Override protected ListCursor copyInstance(ListCursor instance, TransportVersion version) throws IOException { /* Randomly choose between internal protocol round trip and String based * round trips used to toXContent. */ if (randomBoolean()) { return copyWriteable(instance, getNamedWriteableRegistry(), ListCursor::new, version); } return (ListCursor) CursorTests.decodeFromString(Cursors.encodeToString(instance, randomZone())); } }
ListCursorTests
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/google/MapGenerators.java
{ "start": 3188, "end": 3676 }
class ____ extends TestUnhashableCollectionGenerator<Collection<UnhashableObject>> { @Override public Collection<UnhashableObject> create(UnhashableObject[] elements) { ImmutableMap.Builder<Integer, UnhashableObject> builder = ImmutableMap.builder(); int key = 1; for (UnhashableObject value : elements) { builder.put(key++, value); } return builder.buildOrThrow().values(); } } public static
ImmutableMapUnhashableValuesGenerator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnitAmbiguousTestClassTest.java
{ "start": 872, "end": 1320 }
class ____ { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(JUnitAmbiguousTestClass.class, getClass()); @Test public void positive() { compilationHelper .addSourceLines( "Positive.java", """ import org.junit.Test; import junit.framework.TestCase; // BUG: Diagnostic contains: public
JUnitAmbiguousTestClassTest
java
spring-projects__spring-data-jpa
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/QueryEnhancerFactories.java
{ "start": 997, "end": 1675 }
class ____ { private static final Log LOG = LogFactory.getLog(QueryEnhancerFactories.class); static final boolean jSqlParserPresent = ClassUtils.isPresent("net.sf.jsqlparser.parser.JSqlParser", QueryEnhancerFactory.class.getClassLoader()); static { if (jSqlParserPresent) { LOG.info("JSqlParser is in classpath; If applicable, JSqlParser will be used"); } if (PersistenceProvider.ECLIPSELINK.isPresent()) { LOG.info("EclipseLink is in classpath; If applicable, EQL parser will be used."); } if (PersistenceProvider.HIBERNATE.isPresent()) { LOG.info("Hibernate is in classpath; If applicable, HQL parser will be used."); } }
QueryEnhancerFactories
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/OptionConverter.java
{ "start": 5855, "end": 7242 }
class ____ Level.toLevel(value, defaultValue); } } Level result = defaultValue; final String clazz = value.substring(hashIndex + 1); final String levelName = value.substring(0, hashIndex); // This is degenerate case but you never know. if ("NULL".equalsIgnoreCase(levelName)) { return null; } LOGGER.debug("toLevel" + ":class=[" + clazz + "]" + ":pri=[" + levelName + "]"); try { final Class<?> customLevel = Loader.loadClass(clazz); // get a ref to the specified class' static method // toLevel(String, org.apache.log4j.Level) final Class<?>[] paramTypes = new Class[] {String.class, Level.class}; final java.lang.reflect.Method toLevelMethod = customLevel.getMethod("toLevel", paramTypes); // now call the toLevel method, passing level string + default final Object[] params = new Object[] {levelName, defaultValue}; final Object o = toLevelMethod.invoke(null, params); result = (Level) o; } catch (ClassNotFoundException e) { LOGGER.warn("custom level class [" + clazz + "] not found."); } catch (NoSuchMethodException e) { LOGGER.warn( "custom level class [" + clazz + "]" + " does not have a
return
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeStaticTest.java
{ "start": 1725, "end": 2137 }
class ____ { private static final Duration MY_DURATION = Duration.ofMillis(1); public Duration d() { return MY_DURATION; } } """) .doTest(); } @Test public void instantWithPureMethod() { helper .addInputLines( "Test.java", """ import java.time.Instant;
Test
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/annotations/DialectOverride.java
{ "start": 5048, "end": 5375 }
interface ____ { GeneratedColumn[] value(); } /** * Specializes a {@link org.hibernate.annotations.DiscriminatorFormula} * in a certain dialect. */ @Target(TYPE) @Retention(RUNTIME) @Repeatable(DiscriminatorFormulas.class) @OverridesAnnotation(org.hibernate.annotations.DiscriminatorFormula.class) @
GeneratedColumns
java
apache__camel
test-infra/camel-test-infra-pinecone/src/main/java/org/apache/camel/test/infra/pinecone/common/PineconeProperties.java
{ "start": 871, "end": 1261 }
class ____ { public static final String PINECONE_ENDPOINT_URL = "pinecone.endpoint.url"; public static final String PINECONE_ENDPOINT_HOST = "pinecone.endpoint.host"; public static final String PINECONE_ENDPOINT_PORT = "pinecone.endpoint.port"; public static final String PINECONE_CONTAINER = "pinecone.container"; private PineconeProperties() { } }
PineconeProperties
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverterTests.java
{ "start": 1367, "end": 5000 }
class ____ { private static final MediaType RSS_XML_UTF8 = new MediaType(MediaType.APPLICATION_RSS_XML, StandardCharsets.UTF_8); private final RssChannelHttpMessageConverter converter = new RssChannelHttpMessageConverter(); @Test void canReadAndWrite() { assertThat(converter.canRead(Channel.class, MediaType.APPLICATION_RSS_XML)).isTrue(); assertThat(converter.canRead(Channel.class, RSS_XML_UTF8)).isTrue(); assertThat(converter.canWrite(Channel.class, MediaType.APPLICATION_RSS_XML)).isTrue(); assertThat(converter.canWrite(Channel.class, RSS_XML_UTF8)).isTrue(); } @Test void read() throws IOException { InputStream inputStream = getClass().getResourceAsStream("rss.xml"); MockHttpInputMessage inputMessage = new MockHttpInputMessage(inputStream); inputMessage.getHeaders().setContentType(RSS_XML_UTF8); Channel result = converter.read(Channel.class, inputMessage); assertThat(result.getTitle()).isEqualTo("title"); assertThat(result.getLink()).isEqualTo("https://example.com"); assertThat(result.getDescription()).isEqualTo("description"); List<?> items = result.getItems(); assertThat(items).hasSize(2); Item item1 = (Item) items.get(0); assertThat(item1.getTitle()).isEqualTo("title1"); Item item2 = (Item) items.get(1); assertThat(item2.getTitle()).isEqualTo("title2"); } @Test void write() throws IOException { Channel channel = new Channel("rss_2.0"); channel.setTitle("title"); channel.setLink("https://example.com"); channel.setDescription("description"); Item item1 = new Item(); item1.setTitle("title1"); Item item2 = new Item(); item2.setTitle("title2"); List<Item> items = new ArrayList<>(2); items.add(item1); items.add(item2); channel.setItems(items); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(channel, null, outputMessage); assertThat(outputMessage.getHeaders().getContentType()) .as("Invalid content-type") .isEqualTo(RSS_XML_UTF8); String expected = "<rss version=\"2.0\">" + "<channel><title>title</title><link>https://example.com</link><description>description</description>" + "<item><title>title1</title></item>" + "<item><title>title2</title></item>" + "</channel></rss>"; assertThat(XmlContent.of(outputMessage.getBodyAsString(StandardCharsets.UTF_8))) .isSimilarToIgnoringWhitespace(expected); } @Test void writeOtherCharset() throws IOException { Channel channel = new Channel("rss_2.0"); channel.setTitle("title"); channel.setLink("https://example.com"); channel.setDescription("description"); String encoding = "ISO-8859-1"; channel.setEncoding(encoding); Item item1 = new Item(); item1.setTitle("title1"); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); converter.write(channel, null, outputMessage); assertThat(outputMessage.getHeaders().getContentType()) .as("Invalid content-type") .isEqualTo(new MediaType("application", "rss+xml", Charset.forName(encoding))); } @Test void writeOtherContentTypeParameters() throws IOException { Channel channel = new Channel("rss_2.0"); channel.setTitle("title"); channel.setLink("https://example.com"); channel.setDescription("description"); MockHttpOutputMessage message = new MockHttpOutputMessage(); converter.write(channel, new MediaType("application", "rss+xml", singletonMap("x", "y")), message); assertThat(message.getHeaders().getContentType().getParameters()) .as("Invalid content-type") .hasSize(2) .containsEntry("x", "y") .containsEntry("charset", "UTF-8"); } }
RssChannelHttpMessageConverterTests
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/math/Truncate.java
{ "start": 1113, "end": 1801 }
class ____ extends BinaryOptionalNumericFunction implements OptionalArgument { public Truncate(Source source, Expression left, Expression right) { super(source, left, right); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, Truncate::new, left(), right()); } @Override protected BinaryOptionalMathOperation operation() { return BinaryOptionalMathOperation.TRUNCATE; } @Override protected final Expression replacedChildrenInstance(List<Expression> newChildren) { return new Truncate(source(), newChildren.get(0), right() == null ? null : newChildren.get(1)); } }
Truncate
java
apache__camel
components/camel-azure/camel-azure-files/src/main/java/org/apache/camel/component/file/azure/NormalizedOperations.java
{ "start": 1282, "end": 2379 }
class ____ implements RemoteFileOperations<ShareFileItem> { private final Logger log = LoggerFactory.getLogger(getClass()); private final RemoteFileConfiguration configuration; protected NormalizedOperations(RemoteFileConfiguration configuration) { this.configuration = configuration; } @Override public final boolean buildDirectory(String directory, boolean absolute) throws GenericFileOperationFailedException { log.trace("buildDirectory({},{})", directory, absolute); // by observation OS-specific path separator can appear directory = configuration.normalizePath(directory); if (absolute) { return buildDirectory(directory); } else { // wishful thinking, we inherited a wide contract // but our needs are narrower. We will see.... throw new IllegalArgumentException("Relative path: " + directory); } } /** Normalized form of {@link #buildDirectory(String, boolean)}. */ protected abstract boolean buildDirectory(String path); }
NormalizedOperations
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/metrics/KafkaMetric.java
{ "start": 1007, "end": 4385 }
class ____ implements Metric { private final MetricName metricName; private final Object lock; private final Time time; private final MetricValueProvider<?> metricValueProvider; private volatile MetricConfig config; // public for testing /** * Create a metric to monitor an object that implements MetricValueProvider. * @param lock The lock used to prevent race condition * @param metricName The name of the metric * @param valueProvider The metric value provider associated with this metric * @param config The configuration of the metric * @param time The time instance to use with the metrics */ public KafkaMetric(Object lock, MetricName metricName, MetricValueProvider<?> valueProvider, MetricConfig config, Time time) { this.metricName = metricName; this.lock = lock; this.metricValueProvider = Objects.requireNonNull(valueProvider, "valueProvider must not be null"); this.config = config; this.time = time; } /** * Get the configuration of this metric. * This is supposed to be used by server only. * @return Return the config of this metric */ public MetricConfig config() { return this.config; } /** * Get the metric name * @return Return the name of this metric */ @Override public MetricName metricName() { return this.metricName; } /** * Take the metric and return the value via {@link MetricValueProvider#value(MetricConfig, long)}. * * @return Return the metric value */ @Override public Object metricValue() { long now = time.milliseconds(); synchronized (this.lock) { return metricValueProvider.value(config, now); } } /** * The method determines if the metric value provider is of type Measurable. * * @return true if the metric value provider is of type Measurable, false otherwise. */ public boolean isMeasurable() { return this.metricValueProvider instanceof Measurable; } /** * Get the underlying metric provider, which should be a {@link Measurable} * @return Return the metric provider * @throws IllegalStateException if the underlying metric is not a {@link Measurable}. */ public Measurable measurable() { if (isMeasurable()) return (Measurable) metricValueProvider; else throw new IllegalStateException("Not a measurable: " + this.metricValueProvider.getClass()); } /** * Take the metric and return the value, where the underlying metric provider should be a {@link Measurable} * @param timeMs The time that this metric is taken * @return Return the metric value if it's measurable, otherwise 0 */ double measurableValue(long timeMs) { synchronized (this.lock) { if (isMeasurable()) return ((Measurable) metricValueProvider).measure(config, timeMs); else return 0; } } /** * Set the metric config. * This is supposed to be used by server only. * @param config configuration for this metrics */ public void config(MetricConfig config) { synchronized (lock) { this.config = config; } } }
KafkaMetric
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/ModelDescriptor.java
{ "start": 1759, "end": 6335 }
class ____ { private final @Nullable Schema inputSchema; private final @Nullable Schema outputSchema; private final Map<String, String> modelOptions; private final @Nullable String comment; protected ModelDescriptor( @Nullable Schema inputSchema, @Nullable Schema outputSchema, Map<String, String> modelOptions, @Nullable String comment) { this.inputSchema = inputSchema; this.outputSchema = outputSchema; this.modelOptions = modelOptions; this.comment = comment; } /** Converts this descriptor into a {@link CatalogModel}. */ public CatalogModel toCatalogModel() { final Schema inputSchema = getInputSchema() .orElseThrow( () -> new ValidationException( "Input schema missing in ModelDescriptor. Input schema cannot be null.")); final Schema outputSchema = getOutputSchema() .orElseThrow( () -> new ValidationException( "Output schema missing in ModelDescriptor. Output schema cannot be null.")); return CatalogModel.of(inputSchema, outputSchema, modelOptions, comment); } /** Converts this immutable instance into a mutable {@link Builder}. */ public Builder toBuilder() { return new Builder(this); } // --------------------------------------------------------------------------------------------- /** Returns a map of string-based model options. */ Map<String, String> getOptions() { return Map.copyOf(modelOptions); } /** Get the unresolved input schema of the model. */ Optional<Schema> getInputSchema() { return Optional.ofNullable(inputSchema); } /** Get the unresolved output schema of the model. */ Optional<Schema> getOutputSchema() { return Optional.ofNullable(outputSchema); } /** Get comment of the model. */ Optional<String> getComment() { return Optional.ofNullable(comment); } // --------------------------------------------------------------------------------------------- /** * Creates a new {@link Builder} for the model with the given provider option. * * @param provider string value of provider for the model. */ public static Builder forProvider(String provider) { Preconditions.checkNotNull(provider, "Model descriptors require a provider value."); final Builder descriptorBuilder = new Builder(); descriptorBuilder.option(FactoryUtil.PROVIDER, provider); return descriptorBuilder; } @Override public String toString() { final String serializedOptions = modelOptions.entrySet().stream() .map( entry -> String.format( " '%s' = '%s'", EncodingUtils.escapeSingleQuotes(entry.getKey()), EncodingUtils.escapeSingleQuotes(entry.getValue()))) .collect(Collectors.joining(String.format(",%n"))); return String.format( "%s%n%s%nCOMMENT '%s'%nWITH (%n%s%n)", inputSchema != null ? inputSchema : "", outputSchema != null ? outputSchema : "", comment != null ? comment : "", serializedOptions); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ModelDescriptor that = (ModelDescriptor) o; return Objects.equals(inputSchema, that.inputSchema) && Objects.equals(outputSchema, that.outputSchema) && modelOptions.equals(that.modelOptions) && Objects.equals(comment, that.comment); } @Override public int hashCode() { return Objects.hash(inputSchema, outputSchema, modelOptions, comment); } // --------------------------------------------------------------------------------------------- /** Builder for {@link ModelDescriptor}. */ @PublicEvolving public static
ModelDescriptor
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/decorators/validation/DecoratorWithAsyncObserverTest.java
{ "start": 629, "end": 1153 }
class ____ { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(MyDecorator.class, Converter.class) .shouldFail() .build(); @Test public void trigger() { Throwable error = container.getFailure(); assertNotNull(error); assertInstanceOf(DefinitionException.class, error); assertTrue(error.getMessage().contains("Decorator declares an async observer method")); }
DecoratorWithAsyncObserverTest
java
apache__camel
test-infra/camel-test-infra-zookeeper/src/main/java/org/apache/camel/test/infra/zookeeper/common/ZooKeeperProperties.java
{ "start": 872, "end": 1104 }
class ____ { public static final String CONNECTION_STRING = "zookeeper.connection.string"; public static final String ZOOKEEPER_CONTAINER = "zookeeper.container"; private ZooKeeperProperties() { } }
ZooKeeperProperties
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/leaderelection/DefaultLeaderElectionServiceTest.java
{ "start": 2083, "end": 68600 }
class ____ { @RegisterExtension public final TestingFatalErrorHandlerExtension fatalErrorHandlerExtension = new TestingFatalErrorHandlerExtension(); @Test void testOnGrantAndRevokeLeadership() throws Exception { final AtomicReference<LeaderInformationRegister> storedLeaderInformation = new AtomicReference<>(LeaderInformationRegister.empty()); new Context(storedLeaderInformation) { { runTestWithSynchronousEventHandling( () -> { // grant leadership final UUID leaderSessionID = UUID.randomUUID(); grantLeadership(leaderSessionID); applyToBothContenderContexts( ctx -> { ctx.contender.waitForLeader(); assertThat(ctx.contender.getLeaderSessionID()) .isEqualTo( leaderElectionService.getLeaderSessionID( ctx.componentId)) .isEqualTo(leaderSessionID); final LeaderInformation expectedLeaderInformationInHaBackend = LeaderInformation.known( leaderSessionID, ctx.address); assertThat( storedLeaderInformation .get() .forComponentId(ctx.componentId)) .as( "The HA backend should have its leader information updated.") .hasValue(expectedLeaderInformationInHaBackend); }); revokeLeadership(); applyToBothContenderContexts( ctx -> { ctx.contender.waitForRevokeLeader(); assertThat(ctx.contender.getLeaderSessionID()).isNull(); assertThat( leaderElectionService.getLeaderSessionID( ctx.componentId)) .isNull(); final LeaderInformation expectedLeaderInformationInHaBackend = LeaderInformation.known( leaderSessionID, ctx.address); assertThat( storedLeaderInformation .get() .forComponentId(ctx.componentId)) .as( "External storage is not touched by the leader session because the leadership is already lost.") .hasValue(expectedLeaderInformationInHaBackend); }); }); } }; } @Test void testErrorOnComponentIdReuse() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> assertThatThrownBy( () -> leaderElectionService.createLeaderElection( contenderContext0.componentId)) .isInstanceOf(IllegalStateException.class)); } }; } /** * Tests that we can shut down the DefaultLeaderElectionService if the used {@link * LeaderElectionDriver} holds an internal lock. See FLINK-20008 for more details. */ @Test void testCloseGrantDeadlock() throws Exception { final OneShotLatch closeReachedLatch = new OneShotLatch(); final OneShotLatch closeContinueLatch = new OneShotLatch(); final OneShotLatch grantReachedLatch = new OneShotLatch(); final OneShotLatch grantContinueLatch = new OneShotLatch(); final CompletableFuture<Void> driverCloseTriggered = new CompletableFuture<>(); final AtomicBoolean leadershipGranted = new AtomicBoolean(); final TestingLeaderElectionDriver.Builder driverBuilder = TestingLeaderElectionDriver.newBuilder(leadershipGranted) .setCloseConsumer( lock -> { closeReachedLatch.trigger(); closeContinueLatch.await(); try { lock.lock(); driverCloseTriggered.complete(null); } finally { lock.unlock(); } }); final TestingLeaderElectionDriver.Factory driverFactory = new TestingLeaderElectionDriver.Factory(driverBuilder); try (final DefaultLeaderElectionService testInstance = new DefaultLeaderElectionService( driverFactory, fatalErrorHandlerExtension.getTestingFatalErrorHandler())) { // creating the LeaderElection is necessary to instantiate the driver final LeaderElection leaderElection = testInstance.createLeaderElection("component-id"); leaderElection.startLeaderElection(TestingGenericLeaderContender.newBuilder().build()); final TestingLeaderElectionDriver driver = driverFactory.assertAndGetOnlyCreatedDriver(); final Thread closeThread = new Thread( () -> { try { leaderElection.close(); } catch (Exception e) { throw new RuntimeException(e); } }, "CloseThread"); // triggers close that acquires the DefaultLeaderElectionService lock closeThread.start(); closeReachedLatch.await(); final Thread grantThread = new Thread( () -> { try { // simulates the grant process being triggered from the HA // backend's side where the same lock that is acquired during // the driver's process is also acquired while handling a // leadership event processing driver.getLock().lock(); grantReachedLatch.trigger(); grantContinueLatch.awaitQuietly(); // grants leadership leadershipGranted.set(true); testInstance.onGrantLeadership(UUID.randomUUID()); } finally { driver.getLock().unlock(); } }, "GrantThread"); // triggers the service acquiring the leadership and, as a consequence, acquiring the // driver's lock grantThread.start(); grantReachedLatch.await(); // continue both processes which shouldn't result in a deadlock grantContinueLatch.trigger(); closeContinueLatch.trigger(); closeThread.join(); grantThread.join(); assertThatFuture(driverCloseTriggered).eventuallySucceeds(); } } @Test void testLazyDriverInstantiation() throws Exception { final AtomicBoolean driverCreated = new AtomicBoolean(); try (final DefaultLeaderElectionService testInstance = new DefaultLeaderElectionService( listener -> { driverCreated.set(true); return TestingLeaderElectionDriver.newNoOpBuilder().build(listener); }, fatalErrorHandlerExtension.getTestingFatalErrorHandler(), Executors.newDirectExecutorService())) { assertThat(driverCreated) .as("The driver shouldn't have been created during service creation.") .isFalse(); try (final LeaderElection leaderElection = testInstance.createLeaderElection("component-id")) { assertThat(driverCreated) .as( "The driver shouldn't have been created during LeaderElection creation.") .isFalse(); leaderElection.startLeaderElection( TestingGenericLeaderContender.newBuilder().build()); assertThat(driverCreated) .as( "The driver should have been created when registering the contender in the LeaderElection.") .isTrue(); } } } @Test void testReuseOfServiceIsRestricted() throws Exception { final DefaultLeaderElectionService testInstance = new DefaultLeaderElectionService( new TestingLeaderElectionDriver.Factory( TestingLeaderElectionDriver.newNoOpBuilder())); // The driver hasn't started, yet, which prevents the service from going into running state. // This results in the close method not having any effect. testInstance.close(); assertThatThrownBy(() -> testInstance.createLeaderElection("component-id")) .as( "Registering a contender on a closed service should have resulted in an IllegalStateException.") .isInstanceOf(IllegalStateException.class); } /** * The leadership can be granted as soon as the driver is instantiated. We need to make sure * that the event is still handled properly while registering the contender. */ @Test void testMultipleDriverCreations() throws Exception { final AtomicInteger closeCount = new AtomicInteger(0); final TestingLeaderElectionDriver.Factory driverFactory = new TestingLeaderElectionDriver.Factory( TestingLeaderElectionDriver.newNoOpBuilder() .setCloseConsumer(ignoredLock -> closeCount.incrementAndGet())); try (final DefaultLeaderElectionService testInstance = new DefaultLeaderElectionService(driverFactory)) { final String componentId = "component_id"; final int numberOfStartCloseSessions = 2; for (int i = 1; i <= numberOfStartCloseSessions; i++) { assertThat(driverFactory.getCreatedDriverCount()).isEqualTo(i - 1); assertThat(closeCount).hasValue(i - 1); try (final LeaderElection leaderElection = testInstance.createLeaderElection(componentId)) { leaderElection.startLeaderElection( TestingGenericLeaderContender.newBuilder().build()); } assertThat(driverFactory.getCreatedDriverCount()).isEqualTo(i); assertThat(closeCount).hasValue(i); } } } /** * The leadership can be granted as soon as the driver is instantiated. We need to make sure * that the event is still handled properly while registering the contender. */ @Test void testGrantCallWhileInstantiatingDriver() throws Exception { final UUID expectedLeaderSessionID = UUID.randomUUID(); final TestingLeaderElectionDriver.Builder driverBuilder = TestingLeaderElectionDriver.newNoOpBuilder(); try (final DefaultLeaderElectionService testInstance = new DefaultLeaderElectionService( listener -> { final OneShotLatch waitForGrantTriggerLatch = new OneShotLatch(); // calling the grant from a separate thread will let the thread // end in the service's lock until the registration of the // contender is done CompletableFuture.runAsync( () -> { waitForGrantTriggerLatch.trigger(); listener.onGrantLeadership(expectedLeaderSessionID); }); waitForGrantTriggerLatch.await(); // we can't ensure easily that the future finally called the // method that triggers the grant event: Waiting for the method // to return would lead to a deadlock because the grant // processing is going to wait for the // DefaultLeaderElectionService#lock before it can submit the // event processing. Adding a short sleep here is a nasty // workaround to simulate the race condition. Thread.sleep(100); return driverBuilder.build(listener); }, fatalErrorHandlerExtension.getTestingFatalErrorHandler(), Executors.newDirectExecutorService())) { final LeaderElection leaderElection = testInstance.createLeaderElection(createRandomComponentId()); final TestingContender testingContender = new TestingContender("unused-address", leaderElection); testingContender.startLeaderElection(); testingContender.waitForLeader(); assertThat(testingContender.getLeaderSessionID()).isEqualTo(expectedLeaderSessionID); leaderElection.close(); } } @Test void testDelayedGrantCallAfterContenderRegistration() throws Exception { final TestingLeaderElectionDriver.Factory driverFactory = new TestingLeaderElectionDriver.Factory( TestingLeaderElectionDriver.newNoOpBuilder()); final ManuallyTriggeredScheduledExecutorService leaderEventOperationExecutor = new ManuallyTriggeredScheduledExecutorService(); try (final DefaultLeaderElectionService leaderElectionService = new DefaultLeaderElectionService( driverFactory, fatalErrorHandlerExtension.getTestingFatalErrorHandler(), leaderEventOperationExecutor)) { final AtomicBoolean firstContenderReceivedGrant = new AtomicBoolean(false); final LeaderContender firstContender = TestingGenericLeaderContender.newBuilder() .setGrantLeadershipConsumer( ignoredSessionID -> firstContenderReceivedGrant.set(true)) .build(); final AtomicBoolean secondContenderReceivedGrant = new AtomicBoolean(false); final LeaderContender secondContender = TestingGenericLeaderContender.newBuilder() .setGrantLeadershipConsumer( ignoredSessionID -> secondContenderReceivedGrant.set(true)) .build(); try (final LeaderElection firstLeaderElection = leaderElectionService.createLeaderElection("component_id_0")) { firstLeaderElection.startLeaderElection(firstContender); assertThat(driverFactory.getCreatedDriverCount()) .as( "A single driver should have been created when registering the contender.") .isEqualTo(1); leaderElectionService.onGrantLeadership(UUID.randomUUID()); assertThat(firstContenderReceivedGrant).isFalse(); try (final LeaderElection secondLeaderElection = leaderElectionService.createLeaderElection("component_id_1")) { secondLeaderElection.startLeaderElection(secondContender); assertThat(secondContenderReceivedGrant).isFalse(); leaderEventOperationExecutor.trigger(); assertThat(firstContenderReceivedGrant).isTrue(); assertThat(secondContenderReceivedGrant).isTrue(); } } } } @Test void testDelayedGrantCallAfterContenderBeingDeregisteredAgain() throws Exception { final TestingLeaderElectionDriver.Factory driverFactory = new TestingLeaderElectionDriver.Factory( TestingLeaderElectionDriver.newNoOpBuilder()); final ManuallyTriggeredScheduledExecutorService leaderEventOperationExecutor = new ManuallyTriggeredScheduledExecutorService(); try (final DefaultLeaderElectionService leaderElectionService = new DefaultLeaderElectionService( driverFactory, fatalErrorHandlerExtension.getTestingFatalErrorHandler(), leaderEventOperationExecutor)) { final AtomicBoolean leadershipGrantForwardedToContender = new AtomicBoolean(false); final LeaderContender leaderContender = TestingGenericLeaderContender.newBuilder() .setGrantLeadershipConsumer( ignoredSessionID -> leadershipGrantForwardedToContender.set(true)) .build(); try (final LeaderElection leaderElection = leaderElectionService.createLeaderElection("component_id")) { leaderElection.startLeaderElection(leaderContender); assertThat(driverFactory.getCreatedDriverCount()) .as( "A single driver should have been created when registering the contender.") .isEqualTo(1); leaderElectionService.onGrantLeadership(UUID.randomUUID()); } leaderEventOperationExecutor.trigger(); assertThat(leadershipGrantForwardedToContender).isFalse(); } } @Test void testDelayedRevokeCallAfterContenderBeingDeregisteredAgain() throws Exception { new Context() { { runTestWithManuallyTriggeredEvents( executorService -> { final UUID expectedSessionID = UUID.randomUUID(); grantLeadership(expectedSessionID); executorService.trigger(); final LeaderElection leaderElection = leaderElectionService.createLeaderElection( createRandomComponentId()); final AtomicInteger revokeCallCount = new AtomicInteger(); final LeaderContender contender = TestingGenericLeaderContender.newBuilder() .setRevokeLeadershipRunnable( revokeCallCount::incrementAndGet) .build(); leaderElection.startLeaderElection(contender); executorService.trigger(); assertThat(revokeCallCount) .as("No revocation should have been triggered, yet.") .hasValue(0); revokeLeadership(); assertThat(revokeCallCount) .as("A revocation was triggered but not processed, yet.") .hasValue(0); leaderElection.close(); assertThat(revokeCallCount) .as( "A revocation should have been triggered and immediately processed through the close call.") .hasValue(1); executorService.triggerAll(); assertThat(revokeCallCount) .as( "The leadership revocation event that was triggered by the HA backend shouldn't have been forwarded to the contender, anymore.") .hasValue(1); }); } }; } @Test void testDriverShutdownFailsWithContenderStillBeingRegistered() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> assertThatThrownBy(leaderElectionService::close) .as( "The LeaderContender needs to be deregistered before closing the driver.") .isInstanceOf(IllegalStateException.class)); } }; } @Test void testProperCleanupOnLeaderElectionCloseWhenHoldingTheLeadership() throws Exception { final AtomicReference<LeaderInformationRegister> storedLeaderInformation = new AtomicReference<>(); new Context(storedLeaderInformation) { { runTestWithSynchronousEventHandling( () -> { final UUID leaderSessionID = UUID.randomUUID(); grantLeadership(leaderSessionID); applyToBothContenderContexts( ctx -> { assertThat(ctx.contender.getLeaderSessionID()) .isEqualTo(leaderSessionID); assertThat( leaderElectionService.getLeaderSessionID( ctx.componentId)) .isEqualTo(leaderSessionID); assertThat( leaderElectionService.getLeaderSessionID( ctx.componentId)) .isEqualTo(leaderSessionID); assertThat( storedLeaderInformation .get() .forComponentId(ctx.componentId)) .hasValue( LeaderInformation.known( leaderSessionID, ctx.address)); ctx.leaderElection.close(); assertThat(ctx.contender.getLeaderSessionID()) .as( "The LeaderContender should have been informed about the leadership loss.") .isNull(); assertThat( leaderElectionService.getLeaderSessionID( ctx.componentId)) .as( "The LeaderElectionService should have its internal state cleaned.") .isNull(); }); assertThat(storedLeaderInformation.get().getRegisteredComponentIds()) .as("The HA backend's data should have been cleaned.") .isEmpty(); }); } }; } @Test void testSingleLeaderInformationChangedAndShouldBeCorrected() throws Exception { final AtomicReference<LeaderInformationRegister> storedLeaderInformation = new AtomicReference<>(); new Context(storedLeaderInformation) { { runTestWithSynchronousEventHandling( () -> { final UUID leaderSessionID = UUID.randomUUID(); grantLeadership(leaderSessionID); final LeaderInformation expectedLeaderInformation = LeaderInformation.known( leaderSessionID, contenderContext0.address); // Leader information changed on external storage. It should be // corrected. storedLeaderInformation.set(LeaderInformationRegister.empty()); leaderElectionService.onLeaderInformationChange( contenderContext0.componentId, LeaderInformation.empty()); assertThat( storedLeaderInformation .get() .forComponentId(contenderContext0.componentId)) .as("Removed leader information should have been reset.") .hasValue(expectedLeaderInformation); final LeaderInformation faultyLeaderInformation = LeaderInformation.known(UUID.randomUUID(), "faulty-address"); storedLeaderInformation.set( LeaderInformationRegister.of( contenderContext0.componentId, faultyLeaderInformation)); leaderElectionService.onLeaderInformationChange( contenderContext0.componentId, faultyLeaderInformation); assertThat( storedLeaderInformation .get() .forComponentId(contenderContext0.componentId)) .as("Overwritten leader information should have been reset.") .hasValue(expectedLeaderInformation); }); } }; } @Test void testAllLeaderInformationChangeEventWithPartialCorrection() throws Exception { final AtomicReference<LeaderInformationRegister> storedLeaderInformation = new AtomicReference<>(); new Context(storedLeaderInformation) { { runTestWithSynchronousEventHandling( () -> { final UUID leaderSessionID = UUID.randomUUID(); grantLeadership(leaderSessionID); final LeaderInformationRegister correctLeaderInformationRegister = storedLeaderInformation.get(); assertThat(correctLeaderInformationRegister.getRegisteredComponentIds()) .containsExactlyInAnyOrder( contenderContext0.componentId, contenderContext1.componentId); // change LeaderInformation partially on external storage final String componentIdWithChange = contenderContext0.componentId; final String componentIdWithoutChange = contenderContext1.componentId; final LeaderInformationRegister partiallyChangedLeaderInformationRegister = LeaderInformationRegister.clear( correctLeaderInformationRegister, componentIdWithChange); storedLeaderInformation.set(partiallyChangedLeaderInformationRegister); leaderElectionService.onLeaderInformationChange( partiallyChangedLeaderInformationRegister); assertThat( storedLeaderInformation .get() .forComponentId(componentIdWithChange)) .as("Removed leader information should have been reset.") .hasValue( correctLeaderInformationRegister.forComponentIdOrEmpty( componentIdWithChange)); assertThat( storedLeaderInformation .get() .forComponentId(componentIdWithoutChange)) .hasValue( correctLeaderInformationRegister.forComponentIdOrEmpty( componentIdWithoutChange)); }); } }; } @Test void testAllLeaderInformationChangeEventWithUnknownComponentId() throws Exception { final AtomicReference<LeaderInformationRegister> storedLeaderInformation = new AtomicReference<>(); new Context(storedLeaderInformation) { { runTestWithSynchronousEventHandling( () -> { final UUID leaderSessionID = UUID.randomUUID(); grantLeadership(leaderSessionID); final LeaderInformationRegister correctLeaderInformationRegister = storedLeaderInformation.get(); assertThat(correctLeaderInformationRegister.getRegisteredComponentIds()) .containsExactlyInAnyOrder( contenderContext0.componentId, contenderContext1.componentId); // change LeaderInformation only affects an unregistered componentId final String unknownComponentId = createRandomComponentId(); final LeaderInformationRegister partiallyChangedLeaderInformationRegister = LeaderInformationRegister.merge( correctLeaderInformationRegister, unknownComponentId, LeaderInformation.known( UUID.randomUUID(), "address-for-" + unknownComponentId)); storedLeaderInformation.set(partiallyChangedLeaderInformationRegister); leaderElectionService.onLeaderInformationChange( partiallyChangedLeaderInformationRegister); assertThat(storedLeaderInformation.get()) .as( "The HA backend shouldn't have been touched by the service.") .isSameAs(partiallyChangedLeaderInformationRegister); }); } }; } @Test void testHasLeadershipAsyncWithLeadershipButNoGrantEventProcessed() throws Exception { new Context() { { runTestWithManuallyTriggeredEvents( executorService -> { final UUID expectedSessionID = UUID.randomUUID(); grantLeadership(expectedSessionID); applyToBothContenderContexts( ctx -> { final CompletableFuture<Boolean> validSessionFuture = leaderElectionService.hasLeadershipAsync( ctx.componentId, expectedSessionID); final CompletableFuture<Boolean> invalidSessionFuture = leaderElectionService.hasLeadershipAsync( ctx.componentId, UUID.randomUUID()); executorService.triggerAll(); assertThatFuture(validSessionFuture) .eventuallySucceeds() .isEqualTo(true); assertThatFuture(invalidSessionFuture) .eventuallySucceeds() .isEqualTo(false); }); }); } }; } @Test void testHasLeadershipAsyncWithLeadershipAndGrantEventProcessed() throws Exception { new Context() { { runTestWithManuallyTriggeredEvents( executorService -> { final UUID expectedSessionID = UUID.randomUUID(); grantLeadership(expectedSessionID); applyToBothContenderContexts( ctx -> assertThat(ctx.contender.getLeaderSessionID()).isNull()); executorService.trigger(); applyToBothContenderContexts( ctx -> { assertThat(ctx.contender.getLeaderSessionID()) .isEqualTo(expectedSessionID); final CompletableFuture<Boolean> validSessionFuture = leaderElectionService.hasLeadershipAsync( ctx.componentId, expectedSessionID); final CompletableFuture<Boolean> invalidSessionFuture = leaderElectionService.hasLeadershipAsync( ctx.componentId, UUID.randomUUID()); executorService.triggerAll(); assertThatFuture(validSessionFuture) .eventuallySucceeds() .isEqualTo(true); assertThatFuture(invalidSessionFuture) .eventuallySucceeds() .isEqualTo(false); }); }); } }; } @Test void testHasLeadershipAsyncWithLeadershipLostButNoRevokeEventProcessed() throws Exception { new Context() { { runTestWithManuallyTriggeredEvents( executorService -> { final UUID expectedSessionID = UUID.randomUUID(); grantLeadership(expectedSessionID); executorService.trigger(); revokeLeadership(); applyToBothContenderContexts( ctx -> { final CompletableFuture<Boolean> validSessionFuture = leaderElectionService.hasLeadershipAsync( ctx.componentId, expectedSessionID); final CompletableFuture<Boolean> invalidSessionFuture = leaderElectionService.hasLeadershipAsync( ctx.componentId, UUID.randomUUID()); executorService.triggerAll(); assertThatFuture(validSessionFuture) .eventuallySucceeds() .as( "No operation should be handled anymore after the HA backend " + "indicated leadership loss even if the onRevokeLeadership wasn't " + "processed, yet, because some other process could have picked up " + "the leadership in the meantime already based on the HA " + "backend's decision.") .isEqualTo(false); assertThatFuture(invalidSessionFuture) .eventuallySucceeds() .isEqualTo(false); }); }); } }; } @Test void testHasLeadershipAsyncWithLeadershipLostAndRevokeEventProcessed() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> { final UUID expectedSessionID = UUID.randomUUID(); grantLeadership(expectedSessionID); revokeLeadership(); applyToBothContenderContexts( ctx -> { assertThatFuture( leaderElectionService.hasLeadershipAsync( ctx.componentId, expectedSessionID)) .eventuallySucceeds() .isEqualTo(false); assertThatFuture( leaderElectionService.hasLeadershipAsync( ctx.componentId, UUID.randomUUID())) .eventuallySucceeds() .isEqualTo(false); }); }); } }; } @Test void testHasLeadershipAsyncAfterLeaderElectionClose() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> { final UUID expectedSessionID = UUID.randomUUID(); grantLeadership(expectedSessionID); applyToBothContenderContexts( ctx -> { ctx.leaderElection.close(); assertThatFuture( leaderElectionService.hasLeadershipAsync( ctx.componentId, expectedSessionID)) .eventuallySucceeds() .isEqualTo(false); }); }); } }; } @Test void testLeaderInformationChangedIfNotBeingLeader() throws Exception { final AtomicReference<LeaderInformationRegister> storedLeaderInformation = new AtomicReference<>(); new Context(storedLeaderInformation) { { runTestWithSynchronousEventHandling( () -> { final LeaderInformation differentLeaderInformation = LeaderInformation.known(UUID.randomUUID(), "different-address"); storedLeaderInformation.set( LeaderInformationRegister.of( contenderContext0.componentId, differentLeaderInformation)); leaderElectionService.onLeaderInformationChange( contenderContext0.componentId, differentLeaderInformation); assertThat( storedLeaderInformation .get() .forComponentId(contenderContext0.componentId)) .as("The external storage shouldn't have been changed.") .hasValue(differentLeaderInformation); }); } }; } @Test void testOnGrantLeadershipIsIgnoredAfterLeaderElectionClose() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> { closeLeaderElectionInBothContexts(); grantLeadership(); applyToBothContenderContexts( ctx -> { assertThat( leaderElectionService.getLeaderSessionID( ctx.componentId)) .as( "The grant event shouldn't have been processed by the LeaderElectionService.") .isNull(); assertThat(ctx.contender.getLeaderSessionID()) .as( "The grant event shouldn't have been forwarded to the contender.") .isNull(); }); }); } }; } @Test void testOnLeaderInformationChangeIsIgnoredAfterLeaderElectionBeingClosed() throws Exception { testLeadershipChangeEventHandlingBeingIgnoredAfterLeaderElectionClose( (listener, componentIds, externalStorage) -> componentIds.forEach( c -> listener.onLeaderInformationChange( c, externalStorage.forComponentIdOrEmpty(c)))); } @Test void testAllLeaderInformationChangeIsIgnoredAfterLeaderElectionBeingClosed() throws Exception { testLeadershipChangeEventHandlingBeingIgnoredAfterLeaderElectionClose( (listener, ignoredComponentIds, externalStorage) -> listener.onLeaderInformationChange(externalStorage)); } private void testLeadershipChangeEventHandlingBeingIgnoredAfterLeaderElectionClose( TriConsumer<LeaderElectionDriver.Listener, Iterable<String>, LeaderInformationRegister> callback) throws Exception { final AtomicReference<LeaderInformationRegister> storedLeaderInformation = new AtomicReference<>(); new Context(storedLeaderInformation) { { runTestWithSynchronousEventHandling( () -> { grantLeadership(); assertThat(storedLeaderInformation.get().getRegisteredComponentIds()) .containsExactlyInAnyOrder( contenderContext0.componentId, contenderContext1.componentId); contenderContext0.leaderElection.close(); // another contender adds its information to the external storage // having additional data stored in the register helps to check whether // the register was touched later on (the empty // LeaderInformationRegister is implemented as a singleton which would // prevent us from checking the identity of the external storage at the // end of the test) final String otherComponentId = createRandomComponentId(); final LeaderInformation otherLeaderInformation = LeaderInformation.known( UUID.randomUUID(), "address-for-" + otherComponentId); final LeaderInformationRegister registerWithUnknownContender = LeaderInformationRegister.of( otherComponentId, otherLeaderInformation); storedLeaderInformation.set(registerWithUnknownContender); callback.accept( leaderElectionService, Arrays.asList( contenderContext0.componentId, contenderContext1.componentId), storedLeaderInformation.get()); final LeaderInformationRegister correctedExternalStorage = storedLeaderInformation.get(); assertThat(correctedExternalStorage.getRegisteredComponentIds()) .as( "Only the still registered contender and the unknown one should have corrected its LeaderInformation.") .containsExactlyInAnyOrder( contenderContext1.componentId, otherComponentId); contenderContext1.leaderElection.close(); final LeaderInformationRegister leftOverData = storedLeaderInformation.get(); callback.accept( leaderElectionService, Collections.singleton(contenderContext1.componentId), leftOverData); assertThat(storedLeaderInformation.get().getRegisteredComponentIds()) .as( "The following identity check does only make sense if we're not using an empty register.") .hasSize(1); assertThat(storedLeaderInformation.get()) .as("The external storage shouldn't have been touched.") .isSameAs(leftOverData); }); } }; } @Test void testOnRevokeLeadershipIsTriggeredAfterLeaderElectionClose() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> { grantLeadership(); final UUID oldSessionId = leaderElectionService.getLeaderSessionID( contenderContext0.componentId); applyToBothContenderContexts( ctx -> { assertThat(ctx.contender.getLeaderSessionID()) .isEqualTo(oldSessionId); ctx.leaderElection.close(); assertThat(ctx.contender.getLeaderSessionID()) .as( "LeaderContender should have been revoked as part of the close call.") .isNull(); }); }); } }; } @Test void testOldConfirmLeaderInformationWhileHavingNewLeadership() throws Exception { final AtomicReference<LeaderInformationRegister> storedLeaderInformation = new AtomicReference<>(); new Context(storedLeaderInformation) { { runTestWithSynchronousEventHandling( () -> { final UUID currentLeaderSessionId = UUID.randomUUID(); grantLeadership(currentLeaderSessionId); final LeaderInformationRegister initiallyStoredData = storedLeaderInformation.get(); applyToBothContenderContexts( ctx -> { final LeaderInformation expectedLeaderInformation = LeaderInformation.known( currentLeaderSessionId, ctx.address); assertThat( storedLeaderInformation .get() .forComponentId(ctx.componentId)) .hasValue(expectedLeaderInformation); // Old confirm call should be ignored. ctx.leaderElection.confirmLeadershipAsync( UUID.randomUUID(), ctx.address); assertThat( leaderElectionService.getLeaderSessionID( ctx.componentId)) .isEqualTo(currentLeaderSessionId); }); assertThat(storedLeaderInformation.get()) .as( "The leader information in the external storage shouldn't have been updated.") .isSameAs(initiallyStoredData); }); } }; } @Test void testOldConfirmationWhileHavingLeadershipLost() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> { final UUID currentLeaderSessionId = UUID.randomUUID(); grantLeadership(currentLeaderSessionId); revokeLeadership(); applyToBothContenderContexts( ctx -> { // Old confirm call should be ignored. ctx.leaderElection.confirmLeadershipAsync( currentLeaderSessionId, ctx.address); assertThat( leaderElectionService.getLeaderSessionID( ctx.componentId)) .isNull(); }); }); } }; } @Test void testErrorForwarding() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> { final Exception testException = new Exception("test leader exception"); leaderElectionService.onError(testException); applyToBothContenderContexts( contenderContext -> { assertThat(contenderContext.contender.getError()) .isNotNull() .hasCause(testException); contenderContext.contender.clearError(); }); }); } }; } @Test void testErrorIsIgnoredAfterLeaderElectionBeingClosed() throws Exception { new Context() { { runTestWithSynchronousEventHandling( () -> { closeLeaderElectionInBothContexts(); final Exception testException = new Exception("test leader exception"); leaderElectionService.onError(testException); applyToBothContenderContexts( ctx -> assertThat(ctx.contender.getError()) .as("No error should have been forwarded.") .isNull()); assertThat( fatalErrorHandlerExtension .getTestingFatalErrorHandler() .getException()) .as( "The fallback error handler should have caught the error in this case.") .isEqualTo(testException); fatalErrorHandlerExtension.getTestingFatalErrorHandler().clearError(); }); } }; } @Test void testGrantDoesNotBlockNotifyLeaderInformationChange() throws Exception { testLeaderEventDoesNotBlockLeaderInformationChangeEventHandling( (listener, componentId, storedLeaderInformation) -> { listener.onLeaderInformationChange( componentId, storedLeaderInformation.forComponentIdOrEmpty(componentId)); }); } @Test void testGrantDoesNotBlockNotifyAllKnownLeaderInformation() throws Exception { testLeaderEventDoesNotBlockLeaderInformationChangeEventHandling( (listener, componentId, storedLeaderInformation) -> { listener.onLeaderInformationChange(storedLeaderInformation); }); } private void testLeaderEventDoesNotBlockLeaderInformationChangeEventHandling( TriConsumer<LeaderElectionDriver.Listener, String, LeaderInformationRegister> callback) throws Exception { final AtomicReference<LeaderInformationRegister> storedLeaderInformation = new AtomicReference<>(); new Context(storedLeaderInformation) { { runTestWithManuallyTriggeredEvents( executorService -> { grantLeadership(); final LeaderInformation changedLeaderInformation = LeaderInformation.known( UUID.randomUUID(), contenderContext0.address); storedLeaderInformation.set( LeaderInformationRegister.of( contenderContext0.componentId, changedLeaderInformation)); callback.accept( leaderElectionService, contenderContext0.componentId, storedLeaderInformation.get()); assertThat(storedLeaderInformation.get().hasNoLeaderInformation()) .as( "The blocked leadership grant event shouldn't have blocked the processing of the LeaderInformation change event.") .isTrue(); }); } }; } @Test void testOnGrantLeadershipAsyncDoesNotBlock() throws Exception { testNonBlockingCall( latch -> TestingGenericLeaderContender.newBuilder() .setGrantLeadershipConsumer( ignoredSessionID -> latch.awaitQuietly()) .build(), (leadershipGranted, listener) -> { leadershipGranted.set(true); listener.onGrantLeadership(UUID.randomUUID()); }); } @Test void testOnRevokeLeadershipDoesNotBlock() throws Exception { testNonBlockingCall( latch -> TestingGenericLeaderContender.newBuilder() .setRevokeLeadershipRunnable(latch::awaitQuietly) .build(), (leadershipGranted, listener) -> { leadershipGranted.set(true); listener.onGrantLeadership(UUID.randomUUID()); leadershipGranted.set(false); // this call should not block the test execution listener.onRevokeLeadership(); }); } private void testNonBlockingCall( Function<OneShotLatch, TestingGenericLeaderContender> contenderCreator, BiConsumer<AtomicBoolean, LeaderElectionDriver.Listener> listenerAction) throws Exception { final OneShotLatch latch = new OneShotLatch(); final TestingGenericLeaderContender contender = contenderCreator.apply(latch); final AtomicBoolean leadershipGranted = new AtomicBoolean(false); final TestingLeaderElectionDriver.Factory driverFactory = new TestingLeaderElectionDriver.Factory( TestingLeaderElectionDriver.newBuilder( leadershipGranted, new AtomicReference<>(), new AtomicBoolean())); final DefaultLeaderElectionService testInstance = new DefaultLeaderElectionService( driverFactory, fatalErrorHandlerExtension.getTestingFatalErrorHandler()); final LeaderElection leaderElection = testInstance.createLeaderElection(createRandomComponentId()); leaderElection.startLeaderElection(contender); listenerAction.accept(leadershipGranted, testInstance); latch.trigger(); leaderElection.close(); testInstance.close(); } /** * This test is used to verify FLINK-36451 where we observed concurrent nested locks being * acquired from the {@link LeaderContender} and from the {@link DefaultLeaderElectionService}. */ @Test void testNestedDeadlockInLeadershipConfirmation() throws Exception { final AtomicReference<LeaderInformationRegister> leaderInformationStorage = new AtomicReference<>(LeaderInformationRegister.empty()); try (final DefaultLeaderElectionService testInstance = new DefaultLeaderElectionService( TestingLeaderElectionDriver.newBuilder( new AtomicBoolean(false), leaderInformationStorage, new AtomicBoolean(false)) ::build)) { final String componentId = "test-component"; final LeaderElection leaderElection = testInstance.createLeaderElection(componentId); // we need the lock to be acquired once for the leadership grant and once for the // revocation final CountDownLatch contenderLockAcquireLatch = new CountDownLatch(2); final OneShotLatch grantReceivedLatch = new OneShotLatch(); final AtomicBoolean contenderLeadership = new AtomicBoolean(false); final TestingGenericLeaderContender leaderContender = TestingGenericLeaderContender.newBuilder() .setPreLockAcquireAction(contenderLockAcquireLatch::countDown) .setGrantLeadershipConsumer( ignoredSessionId -> { contenderLeadership.set(true); grantReceivedLatch.trigger(); }) .setRevokeLeadershipRunnable(() -> contenderLeadership.set(false)) .build(); leaderElection.startLeaderElection(leaderContender); final UUID leaderSessionId = UUID.randomUUID(); testInstance.onGrantLeadership(leaderSessionId); grantReceivedLatch.await(); final CompletableFuture<Void> revocationFuture; final CompletableFuture<Void> confirmLeadershipFuture; synchronized (leaderContender.getLock()) { revocationFuture = CompletableFuture.runAsync(testInstance::onRevokeLeadership); contenderLockAcquireLatch.await(); confirmLeadershipFuture = leaderElection.confirmLeadershipAsync(leaderSessionId, "random-address"); } assertThatFuture(revocationFuture).eventuallySucceeds(); assertThatFuture(confirmLeadershipFuture).eventuallySucceeds(); assertThat(contenderLeadership).isFalse(); assertThat(leaderInformationStorage.get().forComponentId(componentId).isEmpty()) .as( "The LeaderInformation is empty because the leadership confirmation succeeded the " + "leadership revocation which resulted in no leader information being written out to " + "the HA backend.") .isTrue(); // not closing the LeaderElection instance would leave the DefaultLeaderElectionService // in an inconsistent state causing an error when closing the service leaderElection.close(); } } private static String createRandomComponentId() { return String.format("component-id-%s", UUID.randomUUID()); } private
DefaultLeaderElectionServiceTest
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/WithPublicStringConstructorProperties.java
{ "start": 960, "end": 1282 }
class ____ { private @Nullable String a; public WithPublicStringConstructorProperties() { } public WithPublicStringConstructorProperties(String a) { this.a = a; } public @Nullable String getA() { return this.a; } public void setA(@Nullable String a) { this.a = a; } }
WithPublicStringConstructorProperties
java
micronaut-projects__micronaut-core
http-server/src/main/java/io/micronaut/http/server/exceptions/UnsatisfiedRouteHandler.java
{ "start": 1144, "end": 1876 }
class ____ extends ErrorExceptionHandler<UnsatisfiedRouteException> { /** * Constructor. * @param responseProcessor Error Response Processor */ public UnsatisfiedRouteHandler(ErrorResponseProcessor<?> responseProcessor) { super(responseProcessor); } @Override @NonNull protected Error error(UnsatisfiedRouteException exception) { return new Error() { @Override public String getMessage() { return exception.getMessage(); } @Override public Optional<String> getPath() { return Optional.of('/' + exception.getArgument().getName()); } }; } }
UnsatisfiedRouteHandler
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/ViewBrokerStatsDataRequestHeader.java
{ "start": 1388, "end": 1951 }
class ____ implements CommandCustomHeader { @CFNotNull private String statsName; @CFNotNull private String statsKey; @Override public void checkFields() throws RemotingCommandException { } public String getStatsName() { return statsName; } public void setStatsName(String statsName) { this.statsName = statsName; } public String getStatsKey() { return statsKey; } public void setStatsKey(String statsKey) { this.statsKey = statsKey; } }
ViewBrokerStatsDataRequestHeader
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/protocol/impl/pb/RouterHeartbeatResponsePBImpl.java
{ "start": 1590, "end": 2617 }
class ____ extends RouterHeartbeatResponse implements PBRecord { private FederationProtocolPBTranslator<RouterHeartbeatResponseProto, Builder, RouterHeartbeatResponseProtoOrBuilder> translator = new FederationProtocolPBTranslator<RouterHeartbeatResponseProto, Builder, RouterHeartbeatResponseProtoOrBuilder>( RouterHeartbeatResponseProto.class); public RouterHeartbeatResponsePBImpl() { } @Override public RouterHeartbeatResponseProto getProto() { return this.translator.build(); } @Override public void setProto(Message proto) { this.translator.setProto(proto); } @Override public void readInstance(String base64String) throws IOException { this.translator.readInstance(base64String); } @Override public boolean getStatus() { return this.translator.getProtoOrBuilder().getStatus(); } @Override public void setStatus(boolean result) { this.translator.getBuilder().setStatus(result); } }
RouterHeartbeatResponsePBImpl
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/fileContext/ITestS3AFileContextCreateMkdir.java
{ "start": 1028, "end": 1449 }
class ____ extends FileContextCreateMkdirBaseTest { @BeforeEach public void setUp() throws Exception { Configuration conf = setPerformanceFlags( new Configuration(), null); fc = S3ATestUtils.createTestFileContext(conf); super.setUp(); } @Override public void tearDown() throws Exception { if (fc != null) { super.tearDown(); } } }
ITestS3AFileContextCreateMkdir
java
apache__avro
lang/java/perf/src/main/java/org/apache/avro/perf/test/basic/StringTest.java
{ "start": 2337, "end": 3201 }
class ____ extends BasicState { private String[] testData; private Encoder encoder; public TestStateEncode() { super(); } /** * Setup each trial * * @throws IOException Could not setup test data */ @Setup(Level.Trial) public void doSetupTrial() throws Exception { this.encoder = super.newEncoder(false, getNullOutputStream()); this.testData = new String[getBatchSize()]; for (int i = 0; i < testData.length; i++) { testData[i] = randomString(); } } private String randomString() { final char[] data = new char[super.getRandom().nextInt(70)]; for (int j = 0; j < data.length; j++) { data[j] = (char) ('a' + super.getRandom().nextInt('z' - 'a')); } return new String(data); } } @State(Scope.Thread) public static
TestStateEncode
java
netty__netty
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2ConnectionHandler.java
{ "start": 2921, "end": 9315 }
class ____ extends ByteToMessageDecoder implements Http2LifecycleManager, ChannelOutboundHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(Http2ConnectionHandler.class); private static final Http2Headers HEADERS_TOO_LARGE_HEADERS = ReadOnlyHttp2Headers.serverHeaders(false, HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.codeAsText()); private static final ByteBuf HTTP_1_X_BUF = Unpooled.unreleasableBuffer( Unpooled.wrappedBuffer(new byte[] {'H', 'T', 'T', 'P', '/', '1', '.'})).asReadOnly(); private final Http2ConnectionDecoder decoder; private final Http2ConnectionEncoder encoder; private final Http2Settings initialSettings; private final boolean decoupleCloseAndGoAway; private final boolean flushPreface; private ChannelFutureListener closeListener; private BaseDecoder byteDecoder; private long gracefulShutdownTimeoutMillis; protected Http2ConnectionHandler(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder, Http2Settings initialSettings) { this(decoder, encoder, initialSettings, false); } protected Http2ConnectionHandler(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder, Http2Settings initialSettings, boolean decoupleCloseAndGoAway) { this(decoder, encoder, initialSettings, decoupleCloseAndGoAway, true); } protected Http2ConnectionHandler(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder, Http2Settings initialSettings, boolean decoupleCloseAndGoAway, boolean flushPreface) { this.initialSettings = checkNotNull(initialSettings, "initialSettings"); this.decoder = checkNotNull(decoder, "decoder"); this.encoder = checkNotNull(encoder, "encoder"); this.decoupleCloseAndGoAway = decoupleCloseAndGoAway; this.flushPreface = flushPreface; if (encoder.connection() != decoder.connection()) { throw new IllegalArgumentException("Encoder and Decoder do not share the same connection object"); } } /** * Get the amount of time (in milliseconds) this endpoint will wait for all streams to be closed before closing * the connection during the graceful shutdown process. Returns -1 if this connection is configured to wait * indefinitely for all streams to close. */ public long gracefulShutdownTimeoutMillis() { return gracefulShutdownTimeoutMillis; } /** * Set the amount of time (in milliseconds) this endpoint will wait for all streams to be closed before closing * the connection during the graceful shutdown process. * @param gracefulShutdownTimeoutMillis the amount of time (in milliseconds) this endpoint will wait for all * streams to be closed before closing the connection during the graceful shutdown process. */ public void gracefulShutdownTimeoutMillis(long gracefulShutdownTimeoutMillis) { if (gracefulShutdownTimeoutMillis < -1) { throw new IllegalArgumentException("gracefulShutdownTimeoutMillis: " + gracefulShutdownTimeoutMillis + " (expected: -1 for indefinite or >= 0)"); } this.gracefulShutdownTimeoutMillis = gracefulShutdownTimeoutMillis; } public Http2Connection connection() { return encoder.connection(); } public Http2ConnectionDecoder decoder() { return decoder; } public Http2ConnectionEncoder encoder() { return encoder; } private boolean prefaceSent() { return byteDecoder != null && byteDecoder.prefaceSent(); } /** * Handles the client-side (cleartext) upgrade from HTTP to HTTP/2. * Reserves local stream 1 for the HTTP/2 response. */ public void onHttpClientUpgrade() throws Http2Exception { if (connection().isServer()) { throw connectionError(PROTOCOL_ERROR, "Client-side HTTP upgrade requested for a server"); } if (!prefaceSent()) { // If the preface was not sent yet it most likely means the handler was not added to the pipeline before // calling this method. throw connectionError(INTERNAL_ERROR, "HTTP upgrade must occur after preface was sent"); } if (decoder.prefaceReceived()) { throw connectionError(PROTOCOL_ERROR, "HTTP upgrade must occur before HTTP/2 preface is received"); } // Create a local stream used for the HTTP cleartext upgrade. connection().local().createStream(HTTP_UPGRADE_STREAM_ID, true); } /** * Handles the server-side (cleartext) upgrade from HTTP to HTTP/2. * @param settings the settings for the remote endpoint. */ public void onHttpServerUpgrade(Http2Settings settings) throws Http2Exception { if (!connection().isServer()) { throw connectionError(PROTOCOL_ERROR, "Server-side HTTP upgrade requested for a client"); } if (!prefaceSent()) { // If the preface was not sent yet it most likely means the handler was not added to the pipeline before // calling this method. throw connectionError(INTERNAL_ERROR, "HTTP upgrade must occur after preface was sent"); } if (decoder.prefaceReceived()) { throw connectionError(PROTOCOL_ERROR, "HTTP upgrade must occur before HTTP/2 preface is received"); } // Apply the settings but no ACK is necessary. encoder.remoteSettings(settings); // Create a stream in the half-closed state. connection().remote().createStream(HTTP_UPGRADE_STREAM_ID, true); } @Override public void flush(ChannelHandlerContext ctx) { try { // Trigger pending writes in the remote flow controller. encoder.flowController().writePendingBytes(); ctx.flush(); } catch (Http2Exception e) { onError(ctx, true, e); } catch (Throwable cause) { onError(ctx, true, connectionError(INTERNAL_ERROR, cause, "Error flushing")); } } private abstract
Http2ConnectionHandler
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/aroundconstruct/AroundConstructReturningObjectTest.java
{ "start": 570, "end": 1122 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(MyTransactional.class, SimpleBean.class, SimpleInterceptor.class); public static AtomicBoolean INTERCEPTOR_CALLED = new AtomicBoolean(false); @Test public void testInterception() { SimpleBean simpleBean = Arc.container().instance(SimpleBean.class).get(); assertNotNull(simpleBean); assertTrue(INTERCEPTOR_CALLED.get()); } @Singleton @MyTransactional static
AroundConstructReturningObjectTest
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/AnonymousConfigurerTests.java
{ "start": 6103, "end": 6618 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((authorize) -> authorize .anyRequest().permitAll() ) .anonymous(withDefaults()); // @formatter:on return http.build(); } @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager(PasswordEncodedUser.user()); } } @Configuration @EnableWebMvc @EnableWebSecurity static
AnonymousWithDefaultsInLambdaConfig
java
micronaut-projects__micronaut-core
function-client/src/main/java/io/micronaut/function/client/FunctionDiscoveryClient.java
{ "start": 690, "end": 801 }
interface ____ discovery functions, either remote or local. * * @author graemerocher * @since 1.0 */ public
for
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/foreignkeys/Customer.java
{ "start": 183, "end": 645 }
class ____ { private Long id; private String name; List<CustomerInventory> inventory; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<CustomerInventory> getInventory() { return inventory; } public void setInventory(List<CustomerInventory> inventory) { this.inventory = inventory; } }
Customer
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/ingest/Processor.java
{ "start": 4871, "end": 5070 }
class ____ holds services that can be used by processor factories to create processor instances * and that gets passed around to all {@link org.elasticsearch.plugins.IngestPlugin}s. */
that
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/junit/UnusedStubbingsFinder.java
{ "start": 577, "end": 3232 }
class ____ { /** * Gets all unused stubbings for given set of mock objects, in order. * Stubbings explicitily marked as LENIENT are not included. */ public UnusedStubbings getUnusedStubbings(Iterable<Object> mocks) { return new UnusedStubbings( AllInvocationsFinder.findStubbings(mocks).stream() .filter(UnusedStubbingReporting::shouldBeReported) .collect(Collectors.toList())); } /** * Gets unused stubbings per location. This method is less accurate than {@link #getUnusedStubbings(Iterable)}. * It considers that stubbings with the same location (e.g. ClassFile + line number) are the same. * This is not completely accurate because a stubbing declared in a setup or constructor * is created per each test method. Because those are different test methods, * different mocks are created, different 'Invocation' instance is backing the 'Stubbing' instance. * In certain scenarios (detecting unused stubbings by JUnit runner), we need this exact level of accuracy. * Stubbing declared in constructor but realized in % of test methods is considered as 'used' stubbing. * There are high level unit tests that demonstrate this scenario. */ public Collection<Invocation> getUnusedStubbingsByLocation(Iterable<Object> mocks) { Set<Stubbing> stubbings = AllInvocationsFinder.findStubbings(mocks); // 1st pass, collect all the locations of the stubbings that were used // note that those are _not_ locations where the stubbings was used Set<String> locationsOfUsedStubbings = new HashSet<>(); for (Stubbing s : stubbings) { if (!UnusedStubbingReporting.shouldBeReported(s)) { String location = s.getInvocation().getLocation().toString(); locationsOfUsedStubbings.add(location); } } // 2nd pass, collect unused stubbings by location // If the location matches we assume the stubbing was used in at least one test method // Also, using map to deduplicate reported unused stubbings // if unused stubbing appear in the setup method / constructor we don't want to report it // per each test case Map<String, Invocation> out = new LinkedHashMap<>(); for (Stubbing s : stubbings) { String location = s.getInvocation().getLocation().toString(); if (!locationsOfUsedStubbings.contains(location)) { out.put(location, s.getInvocation()); } } return out.values(); } }
UnusedStubbingsFinder
java
apache__flink
flink-connectors/flink-connector-files/src/test/java/org/apache/flink/connector/file/sink/utils/FileSinkTestUtils.java
{ "start": 1521, "end": 1647 }
class ____ { /** A type of testing {@link InProgressFileWriter.PendingFileRecoverable}. */ public static
FileSinkTestUtils
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JavaUtilDateCheckerTest.java
{ "start": 2581, "end": 2818 }
class ____ { public void doSomething(Date date) { Instant instant = date.toInstant(); Date date2 = Date.from(instant); } } """) .doTest(); } }
Test
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/tvf/common/WindowTimerService.java
{ "start": 1147, "end": 2101 }
interface ____<W> { /** * The shift timezone of the window, if the proctime or rowtime type is TIMESTAMP_LTZ, the shift * timezone is the timezone user configured in TableConfig, other cases the timezone is UTC * which means never shift when assigning windows. */ ZoneId getShiftTimeZone(); /** Returns the current processing time. */ long currentProcessingTime(); /** Returns the current event-time watermark. */ long currentWatermark(); /** * Registers a window timer to be fired when processing time passes the window. The window you * pass here will be provided when the timer fires. */ void registerProcessingTimeWindowTimer(W window); /** * Registers a window timer to be fired when event time watermark passes the window. The window * you pass here will be provided when the timer fires. */ void registerEventTimeWindowTimer(W window); }
WindowTimerService
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/repository/OracleJoinResolveTest_2_join.java
{ "start": 402, "end": 1826 }
class ____ extends TestCase { protected SchemaRepository repository = new SchemaRepository(JdbcConstants.ORACLE); protected void setUp() throws Exception { repository.console("create table t_user (uid number(20, 0), gid number(20, 0), name varchar2(20))"); repository.console("create table t_group (id number(20, 0), name varchar2(20))"); } public void test_for_issue() throws Exception { assertEquals("SELECT a.uid, a.gid, a.name, b.id, b.name\n" + "FROM t_user a\n" + "\tINNER JOIN t_group b\n" + "WHERE a.uid = b.id", repository.resolve("select * from t_user a inner join t_group b where a.uid = id")); String sql = "select a.* from t_user a inner join t_group b where a.uid = id"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE); SchemaStatVisitor schemaStatVisitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ORACLE); schemaStatVisitor.setRepository(repository); for (SQLStatement stmt : statementList) { stmt.accept(schemaStatVisitor); } assertTrue(schemaStatVisitor.containsColumn("t_user", "*")); assertTrue(schemaStatVisitor.containsColumn("t_user", "uid")); assertTrue(schemaStatVisitor.containsColumn("t_group", "id")); } }
OracleJoinResolveTest_2_join
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/query/GeoShapeQueryBuilder.java
{ "start": 1589, "end": 7551 }
class ____ extends AbstractGeometryQueryBuilder<GeoShapeQueryBuilder> { public static final String NAME = "geo_shape"; protected static final ParseField STRATEGY_FIELD = new ParseField("strategy"); private SpatialStrategy strategy; /** * Creates a new GeoShapeQueryBuilder whose Query will be against the given * field name using the given Shape * * @param fieldName * Name of the field that will be queried * @param shape * Shape used in the Query */ public GeoShapeQueryBuilder(String fieldName, Geometry shape) { super(fieldName, shape); } /** * Creates a new GeoShapeQueryBuilder whose Query will be against the given * field name and will use the Shape found with the given shape id and supplier * @param fieldName Name of the field that will be queried * @param shapeSupplier A shape supplier * @param indexedShapeId The indexed id of a shape */ public GeoShapeQueryBuilder(String fieldName, Supplier<Geometry> shapeSupplier, String indexedShapeId) { super(fieldName, shapeSupplier, indexedShapeId); } /** * Creates a new GeoShapeQueryBuilder whose Query will be against the given * field name and will use the Shape found with the given ID * * @param fieldName * Name of the field that will be filtered * @param indexedShapeId * ID of the indexed Shape that will be used in the Query */ public GeoShapeQueryBuilder(String fieldName, String indexedShapeId) { super(fieldName, indexedShapeId); } public GeoShapeQueryBuilder(StreamInput in) throws IOException { super(in); strategy = in.readOptionalWriteable(SpatialStrategy::readFromStream); } @Override protected void doWriteTo(StreamOutput out) throws IOException { super.doWriteTo(out); out.writeOptionalWriteable(strategy); } @Override public String getWriteableName() { return NAME; } /** * Sets the relation of query shape and indexed shape. * * @param relation relation of the shapes * @return this */ @Override public GeoShapeQueryBuilder relation(ShapeRelation relation) { if (relation == null) { throw new IllegalArgumentException("No Shape Relation defined"); } if (SpatialStrategy.TERM.equals(strategy) && relation != ShapeRelation.INTERSECTS) { throw new IllegalArgumentException( "current strategy [" + strategy.getStrategyName() + "] only supports relation [" + ShapeRelation.INTERSECTS.getRelationName() + "] found relation [" + relation.getRelationName() + "]" ); } this.relation = relation; return this; } /** * Defines which spatial strategy will be used for building the geo shape * Query. When not set, the strategy that will be used will be the one that * is associated with the geo shape field in the mappings. * * @param strategy * The spatial strategy to use for building the geo shape Query * @return this */ public GeoShapeQueryBuilder strategy(SpatialStrategy strategy) { if (strategy == SpatialStrategy.TERM && relation != ShapeRelation.INTERSECTS) { throw new IllegalArgumentException( "strategy [" + strategy.getStrategyName() + "] only supports relation [" + ShapeRelation.INTERSECTS.getRelationName() + "] found relation [" + relation.getRelationName() + "]" ); } this.strategy = strategy; return this; } /** * @return The spatial strategy to use for building the geo shape Query */ public SpatialStrategy strategy() { return strategy; } @Override public void doShapeQueryXContent(XContentBuilder builder, Params params) throws IOException { if (strategy != null) { builder.field(STRATEGY_FIELD.getPreferredName(), strategy.getStrategyName()); } } @Override protected GeoShapeQueryBuilder newShapeQueryBuilder(String fieldName, Geometry shape) { return new GeoShapeQueryBuilder(fieldName, shape); } @Override protected GeoShapeQueryBuilder newShapeQueryBuilder(String fieldName, Supplier<Geometry> shapeSupplier, String indexedShapeId) { return new GeoShapeQueryBuilder(fieldName, shapeSupplier, indexedShapeId); } @Override public Query buildShapeQuery(SearchExecutionContext context, MappedFieldType fieldType) { if ((fieldType instanceof GeoShapeQueryable) == false) { throw new QueryShardException( context, "Field [" + fieldName + "] is of unsupported type [" + fieldType.typeName() + "] for [" + NAME + "] query" ); } final GeoShapeQueryable ft = (GeoShapeQueryable) fieldType; return new ConstantScoreQuery(ft.geoShapeQuery(context, fieldType.name(), strategy, relation, shape)); } @Override protected boolean doEquals(GeoShapeQueryBuilder other) { return super.doEquals((AbstractGeometryQueryBuilder) other) && Objects.equals(strategy, other.strategy); } @Override protected int doHashCode() { return Objects.hash(super.doHashCode(), strategy); } @Override protected GeoShapeQueryBuilder doRewrite(QueryRewriteContext queryRewriteContext) throws IOException { GeoShapeQueryBuilder builder = (GeoShapeQueryBuilder) super.doRewrite(queryRewriteContext); builder.strategy(strategy); return builder; } private static
GeoShapeQueryBuilder
java
spring-projects__spring-boot
module/spring-boot-mongodb/src/test/java/org/springframework/boot/mongodb/health/MongoHealthIndicatorTests.java
{ "start": 1464, "end": 3075 }
class ____ { @Test @SuppressWarnings("unchecked") void mongoIsUp() { Document commandResult = mock(Document.class); given(commandResult.getInteger("maxWireVersion")).willReturn(10); MongoClient mongoClient = mock(MongoClient.class); MongoIterable<String> databaseNames = mock(MongoIterable.class); willAnswer((invocation) -> { ((Consumer<String>) invocation.getArgument(0)).accept("db"); return null; }).given(databaseNames).forEach(any()); given(mongoClient.listDatabaseNames()).willReturn(databaseNames); MongoDatabase mongoDatabase = mock(MongoDatabase.class); given(mongoClient.getDatabase("db")).willReturn(mongoDatabase); given(mongoDatabase.runCommand(Document.parse("{ hello: 1 }"))).willReturn(commandResult); MongoHealthIndicator healthIndicator = new MongoHealthIndicator(mongoClient); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.UP); assertThat(health.getDetails()).containsEntry("maxWireVersion", 10); assertThat(health.getDetails()).containsEntry("databases", List.of("db")); then(commandResult).should().getInteger("maxWireVersion"); } @Test void mongoIsDown() { MongoClient mongoClient = mock(MongoClient.class); given(mongoClient.listDatabaseNames()).willThrow(new MongoException("Connection failed")); MongoHealthIndicator healthIndicator = new MongoHealthIndicator(mongoClient); Health health = healthIndicator.health(); assertThat(health.getStatus()).isEqualTo(Status.DOWN); assertThat((String) health.getDetails().get("error")).contains("Connection failed"); } }
MongoHealthIndicatorTests
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/xprocessing/XCodeBlocks.java
{ "start": 4118, "end": 8151 }
class ____ the single {@link * javax.inject.Provider#get()} method implemented by {@code body}. */ public static XCodeBlock anonymousProvider(XTypeName providedType, XCodeBlock body) { return toXPoet( CodeBlock.of( "$L", anonymousClassBuilder("") .superclass(toJavaPoet(daggerProviderOf(providedType))) .addMethod( methodBuilder("get") .addAnnotation(Override.class) .addModifiers(PUBLIC) .returns(toJavaPoet(providedType)) .addCode(toJavaPoet(body)) .build()) .build())); } /** Returns {@code expression} cast to a type. */ public static XCodeBlock cast(XCodeBlock expression, XClassName castTo) { return XCodeBlock.ofCast(castTo, expression); } public static XCodeBlock type(XType type) { return XCodeBlock.of("%T", type.asTypeName()); } public static XCodeBlock staticReferenceOf(XTypeElement typeElement) { if (typeElement.isKotlinObject() && !typeElement.isCompanionObject()) { // Call through the singleton instance. // See: https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#static-methods XCodeBlock.Builder builder = XCodeBlock.builder(); toJavaPoet(builder).add("$T.INSTANCE", toJavaPoet(typeElement.asClassName())); toKotlinPoet(builder).add("%T", toKotlinPoet(typeElement.asClassName())); return builder.build(); } return XCodeBlock.of("%T", typeElement.asClassName()); } public static XCodeBlock stringLiteral(String toWrap) { return XCodeBlock.of("%S", toWrap); } public static XCodeBlock join(Iterable<XCodeBlock> codeBlocks, String separator) { return stream(codeBlocks).collect(joining(separator)); } public static Collector<XCodeBlock, ?, XCodeBlock> joining(String separator) { return Collector.of( () -> new XCodeBlockJoiner(separator, XCodeBlock.builder()), XCodeBlockJoiner::add, XCodeBlockJoiner::merge, XCodeBlockJoiner::join); } public static Collector<XCodeBlock, ?, XCodeBlock> joining( String separator, String prefix, String suffix) { XCodeBlock.Builder builder = XCodeBlock.builder(); if (prefix != null && !prefix.isEmpty()) { builder.add("%L", prefix); } return Collector.of( () -> new XCodeBlockJoiner(separator, builder), XCodeBlockJoiner::add, XCodeBlockJoiner::merge, joiner -> { if (suffix != null && !suffix.isEmpty()) { builder.add("%L", suffix); } return joiner.join(); }); } public static boolean isEmpty(XCodeBlock codeBlock) { // TODO(bcorso): Take into account kotlin code blocks. return toJavaPoet(codeBlock).isEmpty(); } public static XCodeBlock ofJavaClassLiteral(XTypeName typeName) { XCodeBlock.Builder builder = XCodeBlock.builder(); toJavaPoet(builder).add("$T.class", toJavaPoet(typeName)); toKotlinPoet(builder).add("%T::class.java", toKotlinPoet(typeName)); return builder.build(); } public static XCodeBlock ofLocalVal( String name, XTypeName typeName, String format, Object... args) { return ofLocalVal(name, typeName, XCodeBlock.of(format, args)); } public static XCodeBlock ofLocalVal(String name, XTypeName typeName, XCodeBlock initialization) { return XCodeBlock.builder() .addLocalVariable(name, typeName, /* isMutable= */ false, initialization) .build(); } public static XCodeBlock ofLocalVar( String name, XTypeName typeName, String format, Object... args) { return ofLocalVar(name, typeName, XCodeBlock.of(format, args)); } public static XCodeBlock ofLocalVar(String name, XTypeName typeName, XCodeBlock initialization) { return XCodeBlock.builder() .addLocalVariable(name, typeName, /* isMutable= */ true, initialization) .build(); } private static final
with
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/KeyFieldBasedPartitioner.java
{ "start": 1778, "end": 2009 }
class ____<K2, V2> extends org.apache.hadoop.mapreduce.lib.partition.KeyFieldBasedPartitioner<K2, V2> implements Partitioner<K2, V2> { public void configure(JobConf job) { super.setConf(job); } }
KeyFieldBasedPartitioner
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/dao/gpu/TestGpuDeviceInformationParser.java
{ "start": 1288, "end": 7255 }
class ____ { private static final double DELTA = 1e-6; @Test public void testParse() throws IOException, YarnException { File f = new File("src/test/resources/nvidia-smi-sample-output.xml"); String s = FileUtils.readFileToString(f, StandardCharsets.UTF_8); GpuDeviceInformationParser parser = new GpuDeviceInformationParser(); GpuDeviceInformation info = parser.parseXml(s); assertEquals("375.66", info.getDriverVersion()); assertEquals(2, info.getGpus().size()); assertFirstGpu(info.getGpus().get(0)); assertSecondGpu(info.getGpus().get(1)); } @Test public void testParseExcerpt() throws IOException, YarnException { File f = new File("src/test/resources/nvidia-smi-output-excerpt.xml"); String s = FileUtils.readFileToString(f, StandardCharsets.UTF_8); GpuDeviceInformationParser parser = new GpuDeviceInformationParser(); GpuDeviceInformation info = parser.parseXml(s); assertEquals("375.66", info.getDriverVersion()); assertEquals(2, info.getGpus().size()); assertFirstGpu(info.getGpus().get(0)); assertSecondGpu(info.getGpus().get(1)); } @Test public void testParseConsecutivelyWithSameParser() throws IOException, YarnException { File f = new File("src/test/resources/nvidia-smi-sample-output.xml"); String s = FileUtils.readFileToString(f, StandardCharsets.UTF_8); for (int i = 0; i < 3; i++) { GpuDeviceInformationParser parser = new GpuDeviceInformationParser(); GpuDeviceInformation info = parser.parseXml(s); assertEquals("375.66", info.getDriverVersion()); assertEquals(2, info.getGpus().size()); assertFirstGpu(info.getGpus().get(0)); assertSecondGpu(info.getGpus().get(1)); } } @Test public void testParseEmptyString() throws YarnException { assertThrows(YarnException.class, () -> { GpuDeviceInformationParser parser = new GpuDeviceInformationParser(); parser.parseXml(""); }); } @Test public void testParseInvalidRootElement() throws YarnException { assertThrows(YarnException.class, () -> { GpuDeviceInformationParser parser = new GpuDeviceInformationParser(); parser.parseXml("<nvidia_smiiiii></nvidia_smiiiii"); }); } @Test public void testParseMissingTags() throws IOException, YarnException { File f = new File("src/test/resources/nvidia-smi-output-missing-tags.xml"); String s = FileUtils.readFileToString(f, StandardCharsets.UTF_8); GpuDeviceInformationParser parser = new GpuDeviceInformationParser(); GpuDeviceInformation info = parser.parseXml(s); assertEquals("375.66", info.getDriverVersion()); assertEquals(1, info.getGpus().size()); PerGpuDeviceInformation gpu = info.getGpus().get(0); assertEquals("N/A", gpu.getProductName()); assertEquals("N/A", gpu.getUuid()); assertEquals(-1, gpu.getMinorNumber()); assertNull(gpu.getGpuMemoryUsage()); assertNull(gpu.getTemperature()); assertNull(gpu.getGpuUtilizations()); } @Test public void testParseMissingInnerTags() throws IOException, YarnException { File f =new File("src/test/resources/nvidia-smi-output-missing-tags2.xml"); String s = FileUtils.readFileToString(f, StandardCharsets.UTF_8); GpuDeviceInformationParser parser = new GpuDeviceInformationParser(); GpuDeviceInformation info = parser.parseXml(s); assertEquals("375.66", info.getDriverVersion()); assertEquals(2, info.getGpus().size()); PerGpuDeviceInformation gpu = info.getGpus().get(0); assertEquals("Tesla P100-PCIE-12GB", gpu.getProductName()); assertEquals("GPU-28604e81-21ec-cc48-6759-bf2648b22e16", gpu.getUuid()); assertEquals(0, gpu.getMinorNumber()); assertEquals(-1, gpu.getGpuMemoryUsage().getTotalMemoryMiB()); assertEquals(-1, (long) gpu.getGpuMemoryUsage().getUsedMemoryMiB()); assertEquals(-1, (long) gpu.getGpuMemoryUsage().getAvailMemoryMiB()); assertEquals(0f, gpu.getGpuUtilizations().getOverallGpuUtilization(), DELTA); assertEquals(Float.MIN_VALUE, gpu.getTemperature().getCurrentGpuTemp(), DELTA); assertEquals(Float.MIN_VALUE, gpu.getTemperature().getMaxGpuTemp(), DELTA); assertEquals(Float.MIN_VALUE, gpu.getTemperature().getSlowThresholdGpuTemp(), DELTA); assertSecondGpu(info.getGpus().get(1)); } private void assertFirstGpu(PerGpuDeviceInformation gpu) { assertEquals("Tesla P100-PCIE-12GB", gpu.getProductName()); assertEquals("GPU-28604e81-21ec-cc48-6759-bf2648b22e16", gpu.getUuid()); assertEquals(0, gpu.getMinorNumber()); assertEquals(11567, gpu.getGpuMemoryUsage().getTotalMemoryMiB()); assertEquals(11400, (long) gpu.getGpuMemoryUsage().getUsedMemoryMiB()); assertEquals(167, (long) gpu.getGpuMemoryUsage().getAvailMemoryMiB()); assertEquals(33.4f, gpu.getGpuUtilizations().getOverallGpuUtilization(), DELTA); assertEquals(31f, gpu.getTemperature().getCurrentGpuTemp(), DELTA); assertEquals(80f, gpu.getTemperature().getMaxGpuTemp(), DELTA); assertEquals(88f, gpu.getTemperature().getSlowThresholdGpuTemp(), DELTA); } private void assertSecondGpu(PerGpuDeviceInformation gpu) { assertEquals("Tesla P100-PCIE-12GB_2", gpu.getProductName()); assertEquals("GPU-46915a82-3fd2-8e11-ae26-a80b607c04f3", gpu.getUuid()); assertEquals(1, gpu.getMinorNumber()); assertEquals(12290, gpu.getGpuMemoryUsage().getTotalMemoryMiB()); assertEquals(11800, (long) gpu.getGpuMemoryUsage().getUsedMemoryMiB()); assertEquals(490, (long) gpu.getGpuMemoryUsage().getAvailMemoryMiB()); assertEquals(10.3f, gpu.getGpuUtilizations().getOverallGpuUtilization(), DELTA); assertEquals(34f, gpu.getTemperature().getCurrentGpuTemp(), DELTA); assertEquals(85f, gpu.getTemperature().getMaxGpuTemp(), DELTA); assertEquals(82f, gpu.getTemperature().getSlowThresholdGpuTemp(), DELTA); } }
TestGpuDeviceInformationParser
java
quarkusio__quarkus
extensions/liquibase/liquibase/deployment/src/test/java/io/quarkus/liquibase/test/LiquibaseExtensionConfigNamedDataSourceWithoutLiquibaseTest.java
{ "start": 623, "end": 1647 }
class ____ { @Inject @LiquibaseDataSource("users") LiquibaseFactory liquibaseFactory; @Inject LiquibaseExtensionConfigFixture fixture; @Inject @DataSource("users") AgroalDataSource usersDataSource; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClass(LiquibaseExtensionConfigFixture.class) .addAsResource("db/changeLog.xml", "db/changeLog.xml") .addAsResource("config-for-named-datasource-without-liquibase.properties", "application.properties")); @Test @DisplayName("Reads predefined default liquibase configuration for named datasource correctly") public void testLiquibaseDefaultConfigInjection() throws Exception { fixture.assertDefaultConfigurationSettings(liquibaseFactory.getConfiguration()); assertFalse(fixture.migrateAtStart("users")); } }
LiquibaseExtensionConfigNamedDataSourceWithoutLiquibaseTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/annotations/SQLDeleteAll.java
{ "start": 979, "end": 1632 }
class ____ to verify that the operation was successful. * * @see Expectation.None * @see Expectation.RowCount * @see Expectation.OutParameter */ Class<? extends Expectation> verify() default Expectation.class; /** * A {@link ResultCheckStyle} used to verify that the operation was successful. * * @deprecated use {@link #verify()} with an {@link Expectation} class */ @Deprecated(since = "6.5", forRemoval = true) ResultCheckStyle check() default ResultCheckStyle.NONE; /** * The name of the table affected. Never required. * * @return the name of the secondary table * * @since 6.2 */ String table() default ""; }
used
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/json/SerializedThrowableDeserializer.java
{ "start": 1530, "end": 2406 }
class ____ extends StdDeserializer<SerializedThrowable> { private static final long serialVersionUID = 1L; public SerializedThrowableDeserializer() { super(SerializedThrowable.class); } @Override public SerializedThrowable deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { final JsonNode root = p.readValueAsTree(); final byte[] serializedException = root.get(FIELD_NAME_SERIALIZED_THROWABLE).binaryValue(); try { return InstantiationUtil.deserializeObject( serializedException, ClassLoader.getSystemClassLoader()); } catch (ClassNotFoundException e) { throw new IOException( "Failed to deserialize " + SerializedThrowable.class.getCanonicalName(), e); } } }
SerializedThrowableDeserializer
java
micronaut-projects__micronaut-core
inject-java-test/src/test/groovy/io/micronaut/inject/visitor/beans/builder/TestBuildMe4.java
{ "start": 245, "end": 566 }
class ____ { private final String name; private final int age; private TestBuildMe4(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public static final
TestBuildMe4
java
spring-projects__spring-boot
module/spring-boot-http-client/src/test/java/org/springframework/boot/http/client/reactive/ReactorClientHttpConnectorBuilderTests.java
{ "start": 1498, "end": 4058 }
class ____ extends AbstractClientHttpConnectorBuilderTests<ReactorClientHttpConnector> { ReactorClientHttpConnectorBuilderTests() { super(ReactorClientHttpConnector.class, ClientHttpConnectorBuilder.reactor()); } @Test void withHttpClientFactory() { boolean[] called = new boolean[1]; Supplier<HttpClient> httpClientFactory = () -> { called[0] = true; return HttpClient.create(); }; ClientHttpConnectorBuilder.reactor().withHttpClientFactory(httpClientFactory).build(); assertThat(called).containsExactly(true); } @Test void withReactorResourceFactory() { ReactorResourceFactory resourceFactory = spy(new ReactorResourceFactory()); ClientHttpConnectorBuilder.reactor().withReactorResourceFactory(resourceFactory).build(); then(resourceFactory).should().getConnectionProvider(); then(resourceFactory).should().getLoopResources(); } @Test void withCustomizers() { List<HttpClient> httpClients = new ArrayList<>(); UnaryOperator<HttpClient> httpClientCustomizer1 = (httpClient) -> { httpClients.add(httpClient); return httpClient; }; UnaryOperator<HttpClient> httpClientCustomizer2 = (httpClient) -> { httpClients.add(httpClient); return httpClient; }; ClientHttpConnectorBuilder.reactor() .withHttpClientCustomizer(httpClientCustomizer1) .withHttpClientCustomizer(httpClientCustomizer2) .build(); assertThat(httpClients).hasSize(2); } @Test void with() { boolean[] called = new boolean[1]; Supplier<HttpClient> httpClientFactory = () -> { called[0] = true; return HttpClient.create(); }; ClientHttpConnectorBuilder.reactor() .with((builder) -> builder.withHttpClientFactory(httpClientFactory)) .build(); assertThat(called).containsExactly(true); } @Override protected long connectTimeout(ReactorClientHttpConnector connector) { HttpClient httpClient = (HttpClient) ReflectionTestUtils.getField(connector, "httpClient"); assertThat(httpClient).isNotNull(); Object connectTimeout = httpClient.configuration().options().get(ChannelOption.CONNECT_TIMEOUT_MILLIS); assertThat(connectTimeout).isNotNull(); return (int) connectTimeout; } @Override protected long readTimeout(ReactorClientHttpConnector connector) { HttpClient httpClient = (HttpClient) ReflectionTestUtils.getField(connector, "httpClient"); assertThat(httpClient).isNotNull(); Duration responseTimeout = httpClient.configuration().responseTimeout(); assertThat(responseTimeout).isNotNull(); return (int) responseTimeout.toMillis(); } }
ReactorClientHttpConnectorBuilderTests
java
alibaba__nacos
sys/src/main/java/com/alibaba/nacos/sys/filter/NacosPackageExcludeFilter.java
{ "start": 757, "end": 989 }
interface ____ { /** * Get the responsible module package prefix of filter. * * @return package prefix */ String getResponsiblePackagePrefix(); /** * According the
NacosPackageExcludeFilter
java
google__dagger
hilt-android/main/java/dagger/hilt/android/internal/managers/ActivityRetainedComponentManager.java
{ "start": 2193, "end": 2323 }
interface ____ { ActivityRetainedLifecycle getActivityRetainedLifecycle(); } static final
ActivityRetainedLifecycleEntryPoint
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/db/jdbc/FactoryMethodConnectionSourceTest.java
{ "start": 5301, "end": 5483 }
class ____ { public static String factoryMethod01() { return "hello"; } } @SuppressWarnings("unused") protected static final
BadReturnTypeFactory
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/services/VersionResolverException.java
{ "start": 1008, "end": 1175 }
class ____ extends MavenException { public VersionResolverException(String message, Throwable cause) { super(message, cause); } }
VersionResolverException
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/MappedSuperclassGenericEmbeddableQueryParamTest.java
{ "start": 4282, "end": 4350 }
class ____ extends BaseEntity<SecondEntityAttribute> { } }
SecondEntity
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/GuavaEventbusComponentBuilderFactory.java
{ "start": 1392, "end": 1908 }
interface ____ { /** * Guava EventBus (camel-guava-eventbus) * Send and receive messages to/from Guava EventBus. * * Category: messaging * Since: 2.10 * Maven coordinates: org.apache.camel:camel-guava-eventbus * * @return the dsl builder */ static GuavaEventbusComponentBuilder guavaEventbus() { return new GuavaEventbusComponentBuilderImpl(); } /** * Builder for the Guava EventBus component. */
GuavaEventbusComponentBuilderFactory
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpConsumerDoneFileNameStepwiseIT.java
{ "start": 871, "end": 1125 }
class ____ extends FtpConsumerDoneFileNameIT { @Override protected String getFtpUrl() { return "ftp://admin@localhost:{{ftp.server.port}}/done?password=admin&initialDelay=0&delay=100&stepwise=true"; } }
FtpConsumerDoneFileNameStepwiseIT
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/OpenshiftDeploymentconfigsComponentBuilderFactory.java
{ "start": 1469, "end": 2118 }
interface ____ { /** * OpenShift Deployment Configs (camel-kubernetes) * Perform operations on OpenShift Deployment Configs and get notified on * Deployment Config changes. * * Category: container,cloud * Since: 3.18 * Maven coordinates: org.apache.camel:camel-kubernetes * * @return the dsl builder */ static OpenshiftDeploymentconfigsComponentBuilder openshiftDeploymentconfigs() { return new OpenshiftDeploymentconfigsComponentBuilderImpl(); } /** * Builder for the OpenShift Deployment Configs component. */
OpenshiftDeploymentconfigsComponentBuilderFactory
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/calcite/runtime/SqlFunctions.java
{ "start": 132729, "end": 134169 }
class ____ the standard Gregorian calendar which switches from * the Julian calendar to the Gregorian calendar in October 1582. For compatibility with * ISO-8601, converts the internal representation to use the proleptic Gregorian calendar. */ public static long toLong(java.util.Date v) { return DateTimeUtils.utilDateToUnixTimestamp(v, LOCAL_TZ); } /** * Converts a SQL TIMESTAMP value from the Java type ({@link Timestamp}) to the internal * representation type (number of milliseconds since January 1st, 1970 as {@code long}). * * <p>Since a time zone is not available, converts the timestamp to represent the same date and * time as a Unix timestamp in UTC as the {@link Timestamp} value in the local time zone. * * @see #toLong(Timestamp, TimeZone) * @see #internalToTimestamp(Long) converse method */ public static long toLong(Timestamp v) { return toLong(v, LOCAL_TZ); } /** * Converts a SQL TIMESTAMP value from the Java type ({@link Timestamp}) to the internal * representation type (number of milliseconds since January 1st, 1970 as {@code long}). * * <p>For backwards compatibility, time zone offsets are calculated in relation to the local * time zone instead of UTC. Providing the default time zone or {@code null} will return the * timestamp unmodified. * * <p>The {@link Timestamp}
uses
java
apache__dubbo
dubbo-registry/dubbo-registry-nacos/src/main/java/org/apache/dubbo/registry/nacos/NacosServiceDiscovery.java
{ "start": 9389, "end": 10746 }
class ____ implements EventListener { private final Set<ServiceInstancesChangedListener> listeners = new ConcurrentHashSet<>(); @Override public void onEvent(Event e) { if (e instanceof NamingEvent) { for (ServiceInstancesChangedListener listener : listeners) { NamingEvent event = (NamingEvent) e; handleEvent(event, listener); } } } public void addListener(ServiceInstancesChangedListener listener) { listeners.add(listener); } public void removeListener(ServiceInstancesChangedListener listener) { listeners.remove(listener); } public boolean isEmpty() { return listeners.isEmpty(); } } @Override public URL getUrl() { return registryURL; } private void handleEvent(NamingEvent event, ServiceInstancesChangedListener listener) { String serviceName = event.getServiceName(); List<ServiceInstance> serviceInstances = event.getInstances().stream() .map((i) -> NacosNamingServiceUtils.toServiceInstance(registryURL, i)) .collect(Collectors.toList()); listener.onEvent(new ServiceInstancesChangedEvent(serviceName, serviceInstances)); } }
NacosEventListener
java
apache__camel
components/camel-kamelet/src/test/java/org/apache/camel/component/kamelet/KameletRouteTest.java
{ "start": 1113, "end": 2511 }
class ____ extends CamelTestSupport { @Test public void testSingle() { String body = UUID.randomUUID().toString(); assertThat( fluentTemplate.toF("direct:single").withBody(body).request(String.class)).isEqualTo("a-" + body); } @Test public void testChain() { String body = UUID.randomUUID().toString(); assertThat( fluentTemplate.toF("direct:chain").withBody(body).request(String.class)).isEqualTo("b-a-" + body); } // ********************************************** // // test set-up // // ********************************************** @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { routeTemplate("echo") .templateParameter("prefix") .from("kamelet:source") .setBody().simple("{{prefix}}-${body}"); from("direct:single").routeId("test") .to("kamelet:echo?prefix=a") .log("${body}"); from("direct:chain") .to("kamelet:echo/1?prefix=a") .to("kamelet:echo/2?prefix=b") .log("${body}"); } }; } }
KameletRouteTest
java
quarkusio__quarkus
extensions/hibernate-validator/runtime/src/main/java/io/quarkus/hibernate/validator/runtime/jaxrs/ViolationReport.java
{ "start": 302, "end": 1455 }
class ____ { private String title; private int status; private List<Violation> violations; /** * Requires no-args constructor for some serializers. */ public ViolationReport() { } public ViolationReport(String title, Response.Status status, List<Violation> violations) { this.title = title; this.status = status.getStatusCode(); this.violations = violations; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public List<Violation> getViolations() { return violations; } public void setViolations(List<Violation> violations) { this.violations = violations; } @Override public String toString() { return "ViolationReport{" + "title='" + title + '\'' + ", status=" + status + ", violations=" + violations + '}'; } public static
ViolationReport
java
google__dagger
javatests/dagger/internal/codegen/MembersInjectionTest.java
{ "start": 17447, "end": 18561 }
interface ____ {", " A a();", " void inject(B b);", " }", "}"); XTypeSpec generatedInjectType = XTypeSpecs.classBuilder("GeneratedInjectType") .addFunction( constructorBuilder() .addAnnotation(XClassName.get("javax.inject", "Inject")) .build()) .build(); CompilerTests.daggerCompiler(nestedTypesFile) .withProcessingOptions(compilerMode.processorOptions()) .withProcessingSteps(() -> new GeneratingProcessingStep("test", generatedInjectType)) .compile( subject -> { subject.hasErrorCount(0); subject.generatedSource( goldenFileRule.goldenSource("test/OuterType_B_MembersInjector")); }); } @Test public void lowerCaseNamedMembersInjector_forLowerCaseType() { Source foo = CompilerTests.javaSource( "test.foo", "package test;", "", "import javax.inject.Inject;", "", "
SimpleComponent
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/mapping/AggregateColumn.java
{ "start": 726, "end": 4802 }
class ____ extends Column { private final Component component; public AggregateColumn(Column column, Component component) { setLength( column.getLength() ); setPrecision( column.getPrecision() ); setScale( column.getScale() ); setArrayLength( column.getArrayLength() ); setValue( column.getValue() ); setTypeIndex( column.getTypeIndex() ); setName( column.getQuotedName() ); setNullable( column.isNullable() ); setUnique( column.isUnique() ); setUniqueKeyName( column.getUniqueKeyName() ); setSqlType( column.getSqlType() ); setSqlTypeCode( column.getSqlTypeCode() ); uniqueInteger = column.uniqueInteger; //usually useless for ( CheckConstraint constraint : column.getCheckConstraints() ) { addCheckConstraint( constraint ); } setComment( column.getComment() ); setCollation( column.getCollation() ); setDefaultValue( column.getDefaultValue() ); setGeneratedAs( column.getGeneratedAs() ); setAssignmentExpression( column.getAssignmentExpression() ); setCustomRead( column.getCustomRead() ); setCustomWrite( column.getCustomWrite() ); this.component = component; } public Component getComponent() { return component; } public SelectablePath getSelectablePath() { return getSelectablePath( component ); } private static SelectablePath getSelectablePath(Component component) { final var aggregateColumn = component.getAggregateColumn(); final var parent = component.getParentAggregateColumn(); final String simpleAggregateName = aggregateColumn.getQuotedName(); return parent == null ? new SelectablePath( simpleAggregateName ) : getSelectablePath( parent.getComponent() ).append( simpleAggregateName ); } public String getAggregateReadExpressionTemplate(Dialect dialect) { return getAggregateReadExpressionTemplate( dialect, component ); } private static String getAggregateReadExpressionTemplate(Dialect dialect, Component component) { final var aggregateColumn = component.getAggregateColumn(); final var parent = component.getParentAggregateColumn(); final String simpleAggregateName = aggregateColumn.getQuotedName( dialect ); // If the aggregate column is an array, drop the parent read expression, because this is a NestedColumnReference // and will require special rendering return parent == null || isArray( aggregateColumn ) ? getRootAggregateSelectableExpression( aggregateColumn, simpleAggregateName ) : dialect.getAggregateSupport() .aggregateComponentCustomReadExpression( "", "", getAggregateReadExpressionTemplate( dialect, parent.getComponent() ), simpleAggregateName, parent, aggregateColumn ); } private static String getRootAggregateSelectableExpression(AggregateColumn aggregateColumn, String simpleAggregateName) { return isArray( aggregateColumn ) ? Template.TEMPLATE : Template.TEMPLATE + "." + simpleAggregateName; } private static boolean isArray(AggregateColumn aggregateColumn) { return switch ( aggregateColumn.getTypeCode() ) { case JSON_ARRAY, XML_ARRAY, STRUCT_ARRAY, STRUCT_TABLE -> true; default -> false; }; } public String getAggregateAssignmentExpressionTemplate(Dialect dialect) { return getAggregateAssignmentExpressionTemplate( dialect, component ); } private static String getAggregateAssignmentExpressionTemplate(Dialect dialect, Component component) { final var aggregateColumn = component.getAggregateColumn(); final var parent = component.getParentAggregateColumn(); final String simpleAggregateName = aggregateColumn.getQuotedName( dialect ); return parent == null ? Template.TEMPLATE + "." + simpleAggregateName : dialect.getAggregateSupport() .aggregateComponentAssignmentExpression( getAggregateAssignmentExpressionTemplate( dialect, parent.getComponent() ), simpleAggregateName, parent, aggregateColumn ); } /** * Shallow copy, the value is not copied */ @Override public AggregateColumn clone() { return new AggregateColumn( this, component ); } }
AggregateColumn
java
alibaba__fastjson
src/test/java/com/alibaba/fastjson/deserializer/issue2711/User.java
{ "start": 61, "end": 614 }
class ____ { Long id; String name; public User(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
User
java
alibaba__nacos
logger-adapter-impl/logback-adapter-12/src/main/java/com/alibaba/nacos/logger/adapter/logback12/NacosClientPropertyAction.java
{ "start": 1260, "end": 2627 }
class ____ extends Action { private static final String DEFAULT_VALUE_ATTRIBUTE = "defaultValue"; private static final String SOURCE_ATTRIBUTE = "source"; private final NacosLoggingProperties loggingProperties; NacosClientPropertyAction(NacosLoggingProperties loggingProperties) { this.loggingProperties = loggingProperties; } @Override public void begin(InterpretationContext ic, String elementName, Attributes attributes) throws ActionException { String name = attributes.getValue(NAME_ATTRIBUTE); String source = attributes.getValue(SOURCE_ATTRIBUTE); ActionUtil.Scope scope = ActionUtil.stringToScope(attributes.getValue(SCOPE_ATTRIBUTE)); String defaultValue = attributes.getValue(DEFAULT_VALUE_ATTRIBUTE); if (OptionHelper.isEmpty(name)) { addError("The \"name\" and \"source\" attributes of <nacosClientProperty> must be set"); } ActionUtil.setProperty(ic, name, getValue(source, defaultValue), scope); } @Override public void end(InterpretationContext ic, String name) throws ActionException { } private String getValue(String source, String defaultValue) { return null == loggingProperties ? defaultValue : loggingProperties.getValue(source, defaultValue); } }
NacosClientPropertyAction
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/localdate/LocalDateAsset_hasDayOfMonth_Test.java
{ "start": 1054, "end": 1940 }
class ____ { @Test void should_pass_if_actual_is_on_given_day() { // GIVEN LocalDate actual = LocalDate.of(2022, 1, 1); // WHEN/THEN then(actual).hasDayOfMonth(1); } @Test void should_fail_if_actual_is_not_on_given_day() { // GIVEN LocalDate actual = LocalDate.of(2022, 1, 1); int expectedDay = 2; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).hasDayOfMonth(expectedDay)); // THEN then(assertionError).hasMessage(shouldHaveDateField(actual, "day", expectedDay).create()); } @Test void should_fail_if_actual_is_null() { // GIVEN LocalDate actual = null; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).hasDayOfMonth(LocalDate.now().getDayOfMonth())); // THEN then(assertionError).hasMessage(actualIsNull()); } }
LocalDateAsset_hasDayOfMonth_Test
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/MemoryMappedFileManagerTest.java
{ "start": 1321, "end": 3528 }
class ____ { @TempDir File tempDir; @Test void testRemapAfterInitialMapSizeExceeded() throws IOException { final int mapSize = 64; // very small, on purpose final File file = new File(tempDir, "memory-mapped-file.bin"); final boolean append = false; final boolean immediateFlush = false; try (final MemoryMappedFileManager manager = MemoryMappedFileManager.getFileManager( file.getAbsolutePath(), append, immediateFlush, mapSize, null, null)) { byte[] msg; for (int i = 0; i < 1000; i++) { msg = ("Message " + i + "\n").getBytes(); manager.write(msg, 0, msg.length, false); } } try (final BufferedReader reader = new BufferedReader(new FileReader(file))) { String line = reader.readLine(); for (int i = 0; i < 1000; i++) { assertNotNull(line, "line"); assertTrue(line.contains("Message " + i), "line incorrect"); line = reader.readLine(); } } } @Test void testAppendDoesNotOverwriteExistingFile() throws IOException { final File file = new File(tempDir, "memory-mapped-file.bin"); final int initialLength = 4 * 1024; // create existing file try (final FileOutputStream fos = new FileOutputStream(file)) { fos.write(new byte[initialLength], 0, initialLength); fos.flush(); } assertEquals(initialLength, file.length(), "all flushed to disk"); final boolean isAppend = true; final boolean immediateFlush = false; try (final MemoryMappedFileManager manager = MemoryMappedFileManager.getFileManager( file.getAbsolutePath(), isAppend, immediateFlush, MemoryMappedFileManager.DEFAULT_REGION_LENGTH, null, null)) { manager.writeBytes(new byte[initialLength], 0, initialLength); } final int expected = initialLength * 2; assertEquals(expected, file.length(), "appended, not overwritten"); } }
MemoryMappedFileManagerTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/jdbc/TransactionalSqlScriptsTests.java
{ "start": 1238, "end": 1511 }
class ____ extends AbstractTransactionalTests { @Test void classLevelScripts() { assertNumUsers(1); } @Test @Sql({ "recreate-schema.sql", "data.sql", "data-add-dogbert.sql" }) void methodLevelScripts() { assertNumUsers(2); } @Nested
TransactionalSqlScriptsTests
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/FloatArraySerializerTest.java
{ "start": 202, "end": 944 }
class ____ extends TestCase { public void test_0() { Assert.assertEquals("[]", JSON.toJSONString(new float[0])); Assert.assertEquals("{\"value\":null}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue)); Assert.assertEquals("{\"value\":[]}", JSON.toJSONString(new Entity(), SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty)); Assert.assertEquals("[1.0,2.0]", JSON.toJSONString(new float[] { 1, 2 })); Assert.assertEquals("[1.0,2.0,3.0]", JSON.toJSONString(new float[] { 1, 2, 3 })); Assert.assertEquals("[1.0,2.0,3.0,null,null]", JSON.toJSONString(new float[] { 1, 2, 3, Float.NaN, Float.NaN })); } public static
FloatArraySerializerTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_lixianfeng.java
{ "start": 476, "end": 1062 }
class ____ { private Long id; private String name; private List<Long> catIds; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Long> getCatIds() { return catIds; } public void setCatIds(List<Long> catIds) { this.catIds = catIds; } } }
Te
java
apache__logging-log4j2
log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/JsonTemplateLayoutGcFreeTest.java
{ "start": 1039, "end": 1762 }
class ____ { @Test void test_no_allocation_during_steady_state_logging() throws Exception { GcFreeLoggingTestUtil.runTest(getClass()); } /** * This code runs in a separate process, instrumented with the Google Allocation Instrumenter. */ public static void main(final String[] args) throws Exception { System.setProperty("log4j.layout.jsonTemplate.recyclerFactory", "threadLocal"); System.setProperty("log4j2.garbagefree.threadContextMap", "true"); System.setProperty("log4j2.clock", "SystemMillisClock"); GcFreeLoggingTestUtil.executeLogging("gcFreeJsonTemplateLayoutLogging.xml", JsonTemplateLayoutGcFreeTest.class); } }
JsonTemplateLayoutGcFreeTest
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/util/KotlinReflectionUtils.java
{ "start": 2758, "end": 6072 }
class ____ a {@code DefaultImpls} class * generated by the Kotlin compiler. * * <p>See * <a href="https://kotlinlang.org/docs/interfaces.html#jvm-default-method-generation-for-interface-functions">Kotlin documentation</a> * for details. */ public static boolean isKotlinInterfaceDefaultImplsClass(Class<?> clazz) { if (!isKotlinType(clazz) || !DEFAULT_IMPLS_CLASS_NAME.equals(clazz.getSimpleName()) || !isStatic(clazz)) { return false; } Class<?> enclosingClass = clazz.getEnclosingClass(); if (enclosingClass != null && enclosingClass.isInterface()) { return Arrays.stream(clazz.getDeclaredMethods()) // .anyMatch(method -> isCompilerGeneratedDefaultMethod(method, enclosingClass)); } return false; } private static boolean isCompilerGeneratedDefaultMethod(Method method, Class<?> enclosingClass) { if (isStatic(method) && method.getParameterCount() > 0) { var parameterTypes = method.getParameterTypes(); if (parameterTypes[0] == enclosingClass) { var originalParameterTypes = copyWithoutFirst(parameterTypes); return findMethod(enclosingClass, method.getName(), originalParameterTypes).isPresent(); } } return false; } private static Class<?>[] copyWithoutFirst(Class<?>[] values) { if (values.length == 1) { return EMPTY_CLASS_ARRAY; } var result = new Class<?>[values.length - 1]; System.arraycopy(values, 1, result, 0, result.length); return result; } private static boolean isKotlinType(Class<?> clazz) { return kotlinMetadata != null // && clazz.getDeclaredAnnotation(kotlinMetadata) != null; } public static Class<?> getKotlinSuspendingFunctionReturnType(Method method) { requireKotlinReflect(method); return KotlinSuspendingFunctionUtils.getReturnType(method); } public static Type getKotlinSuspendingFunctionGenericReturnType(Method method) { requireKotlinReflect(method); return KotlinSuspendingFunctionUtils.getGenericReturnType(method); } public static Parameter[] getKotlinSuspendingFunctionParameters(Method method) { requireKotlinReflect(method); return KotlinSuspendingFunctionUtils.getParameters(method); } public static Class<?>[] getKotlinSuspendingFunctionParameterTypes(Method method) { requireKotlinReflect(method); return KotlinSuspendingFunctionUtils.getParameterTypes(method); } public static @Nullable Object invokeKotlinSuspendingFunction(Method method, @Nullable Object target, @Nullable Object[] args) { requireKotlinReflect(method); requireKotlinxCoroutines(method); return KotlinSuspendingFunctionUtils.invoke(method, target, args); } private static void requireKotlinReflect(Method method) { requireDependency(method, kotlinReflectPresent, "org.jetbrains.kotlin:kotlin-reflect"); } private static void requireKotlinxCoroutines(Method method) { requireDependency(method, kotlinxCoroutinesPresent, "org.jetbrains.kotlinx:kotlinx-coroutines-core"); } private static void requireDependency(Method method, boolean condition, String dependencyNotation) { Preconditions.condition(condition, () -> ("Kotlin suspending function [%s] requires %s to be on the classpath or module path. " + "Please add a corresponding dependency.").formatted(method.toGenericString(), dependencyNotation)); } private KotlinReflectionUtils() { } }
is
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/aot/ContextAotProcessor.java
{ "start": 1739, "end": 2008 }
class ____ extends AbstractAotProcessor<ClassName> { private final Class<?> applicationClass; /** * Create a new processor for the specified application entry point and * common settings. * @param applicationClass the application entry point (
ContextAotProcessor
java
redisson__redisson
redisson-micronaut/redisson-micronaut-40/src/main/java/org/redisson/micronaut/cache/RedissonSyncCache.java
{ "start": 1143, "end": 4210 }
class ____ extends AbstractMapBasedSyncCache<RMap<Object, Object>> { private final ConversionService conversionService; private final ExecutorService executorService; private final BaseCacheConfiguration configuration; private final RMapCache<Object, Object> mapCache; private final RMap<Object, Object> map; public RedissonSyncCache(ConversionService conversionService, RMapCache<Object, Object> mapCache, RMap<Object, Object> map, ExecutorService executorService, BaseCacheConfiguration configuration) { super(conversionService, map); this.executorService = executorService; this.configuration = configuration; this.mapCache = mapCache; this.map = map; this.conversionService = conversionService; if (configuration.getMaxSize() != 0) { mapCache.setMaxSize(configuration.getMaxSize()); } } @Override public String getName() { return getNativeCache().getName(); } @NonNull @Override public <T> Optional<T> putIfAbsent(@NonNull Object key, @NonNull T value) { ArgumentUtils.requireNonNull("key", key); ArgumentUtils.requireNonNull("value", value); T res; if (mapCache != null) { res = (T) mapCache.putIfAbsent(key, value, configuration.getExpireAfterWrite().toMillis(), TimeUnit.MILLISECONDS, configuration.getExpireAfterAccess().toMillis(), TimeUnit.MILLISECONDS); } else { res = (T) mapCache.putIfAbsent(key, value); } return Optional.ofNullable(res); } @NonNull @Override public <T> T putIfAbsent(@NonNull Object key, @NonNull Supplier<T> value) { ArgumentUtils.requireNonNull("key", key); ArgumentUtils.requireNonNull("value", value); T val = value.get(); T res; if (mapCache != null) { res = (T) mapCache.putIfAbsent(key, val, configuration.getExpireAfterWrite().toMillis(), TimeUnit.MILLISECONDS, configuration.getExpireAfterAccess().toMillis(), TimeUnit.MILLISECONDS); } else { res = (T) mapCache.putIfAbsent(key, value); } return Optional.ofNullable(res).orElse(val); } @Override public void put(@NonNull Object key, @NonNull Object value) { ArgumentUtils.requireNonNull("key", key); ArgumentUtils.requireNonNull("value", value); if (mapCache != null) { mapCache.fastPut(key, value, configuration.getExpireAfterWrite().toMillis(), TimeUnit.MILLISECONDS, configuration.getExpireAfterAccess().toMillis(), TimeUnit.MILLISECONDS); } else { mapCache.fastPut(key, value); } } @NonNull @Override public AsyncCache<RMap<Object, Object>> async() { return new RedissonAsyncCache(mapCache, map, executorService, conversionService, configuration); } }
RedissonSyncCache
java
google__gson
gson/src/test/java/com/google/gson/internal/GsonBuildConfigTest.java
{ "start": 803, "end": 991 }
class ____ { @Test public void testEnsureGsonBuildConfigGetsUpdatedToMavenVersion() { assertThat("${project.version}").isNotEqualTo(GsonBuildConfig.VERSION); } }
GsonBuildConfigTest
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/parallel/Resources.java
{ "start": 628, "end": 2240 }
class ____ { /** * Represents Java's system properties: {@value} * * @see System#getProperties() * @see System#setProperties(java.util.Properties) */ public static final String SYSTEM_PROPERTIES = "java.lang.System.properties"; /** * Represents the standard output stream of the current process: {@value} * * @see System#out * @see System#setOut(java.io.PrintStream) */ public static final String SYSTEM_OUT = "java.lang.System.out"; /** * Represents the standard error stream of the current process: {@value} * * @see System#err * @see System#setErr(java.io.PrintStream) */ public static final String SYSTEM_ERR = "java.lang.System.err"; /** * Represents the default locale for the current instance of the JVM: * {@value} * * @since 5.4 * @see java.util.Locale#setDefault(java.util.Locale) */ @API(status = STABLE, since = "5.10") public static final String LOCALE = "java.util.Locale.default"; /** * Represents the default time zone for the current instance of the JVM: * {@value} * * @since 5.4 * @see java.util.TimeZone#setDefault(java.util.TimeZone) */ @API(status = STABLE, since = "5.10") public static final String TIME_ZONE = "java.util.TimeZone.default"; /** * Represents the global resource lock: {@value} * * @since 5.8 * @see Isolated * @see org.junit.platform.engine.support.hierarchical.ExclusiveResource */ @API(status = STABLE, since = "5.10") public static final String GLOBAL = "org.junit.platform.engine.support.hierarchical.ExclusiveResource.GLOBAL_KEY"; private Resources() { /* no-op */ } }
Resources
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/params/converter/TypedArgumentConverterTests.java
{ "start": 6027, "end": 7056 }
class ____ { @ParameterizedTest @NullSource void nullStringToInteger(@StringLength Integer length) { assertThat(length).isEqualTo(0); } @ParameterizedTest @NullSource void nullStringToPrimitiveInt(@StringLength int length) { assertThat(length).isEqualTo(0); } @ParameterizedTest @NullSource void nullStringToPrimitiveLong(@StringLength long length) { assertThat(length).isEqualTo(0); } @ParameterizedTest @ValueSource(strings = "enigma") void stringToInteger(@StringLength Integer length) { assertThat(length).isEqualTo(6); } @ParameterizedTest @ValueSource(strings = "enigma") void stringToPrimitiveInt(@StringLength int length) { assertThat(length).isEqualTo(6); } @ParameterizedTest @ValueSource(strings = "enigma") void stringToPrimitiveLong(@StringLength long length) { assertThat(length).isEqualTo(6); } } @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @ConvertWith(StringLengthArgumentConverter.class) private @
IntegrationTests