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
grpc__grpc-java
binder/src/androidTest/java/io/grpc/binder/HostServices.java
{ "start": 2063, "end": 2473 }
class ____ { @Nullable abstract Executor transactionExecutor(); @Nullable abstract Supplier<IBinder> rawBinderSupplier(); @Nullable abstract ServerFactory serverFactory(); public abstract Builder toBuilder(); public static Builder builder() { return new AutoValue_HostServices_ServiceParams.Builder(); } @AutoValue.Builder public abstract static
ServiceParams
java
apache__kafka
streams/examples/src/main/java/org/apache/kafka/streams/examples/pageview/PageViewTypedDemo.java
{ "start": 3928, "end": 4157 }
class ____ implements {@link JSONSerdeCompatible}. Note that the classes also need to * be registered in the {@code @JsonSubTypes} annotation on {@link JSONSerdeCompatible}. * * @param <T> The concrete type of the
that
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/IgnoredPureGetterTest.java
{ "start": 8764, "end": 9116 }
class ____ { void test(TestProtoMessage message) {} } """) .doTest(); } @Test public void protoInstanceMethodsFlagged() { helper .addSourceLines( "Test.java", """ import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;
Test
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/class_/ClassAssert_isSealed_Test.java
{ "start": 2392, "end": 2461 }
class ____ permits NonSealedClass { } private non-sealed
SealedClass
java
micronaut-projects__micronaut-core
http-client/src/test/groovy/io/micronaut/http/client/docs/streaming/HeadlineClient.java
{ "start": 898, "end": 1193 }
interface ____ { @Get(value = "/headlines", processes = MediaType.APPLICATION_JSON_STREAM) // <1> Flux<Headline> streamHeadlines(); // <2> // end::class[] @Get(value = "/headlines", processes = MediaType.APPLICATION_JSON_STREAM) // <1> Flux<Headline> streamFlux(); }
HeadlineClient
java
apache__maven
impl/maven-core/src/test/java/org/apache/maven/plugin/PluginParameterExpressionEvaluatorV4Test.java
{ "start": 3796, "end": 19572 }
class ____ extends AbstractCoreMavenComponentTestCase { private static final String FS = File.separator; @Inject PlexusContainer container; private Path rootDirectory; @Test public void testPluginDescriptorExpressionReference() throws Exception { Session session = newSession(); MojoExecution exec = newMojoExecution(session); Object result = new PluginParameterExpressionEvaluatorV4(session, null, exec).evaluate("${mojo.plugin.descriptor}"); System.out.println("Result: " + result); assertSame( exec.getPlugin().getDescriptor(), result, "${mojo.plugin.descriptor} expression does not return plugin descriptor."); } @Test public void testPluginArtifactsExpressionReference() throws Exception { Session session = newSession(); MojoExecution exec = newMojoExecution(session); @SuppressWarnings("unchecked") Collection<Artifact> depResults = (Collection<Artifact>) new PluginParameterExpressionEvaluatorV4(session, null, exec).evaluate("${mojo.plugin.dependencies}"); System.out.println("Result: " + depResults); assertNotNull(depResults); assertEquals(1, depResults.size()); assertEquals( exec.getPlugin().getArtifact().key(), depResults.iterator().next().key(), "dependency artifact is wrong."); } @Test public void testPluginArtifactMapExpressionReference() throws Exception { Session session = newSession(); MojoExecution exec = newMojoExecution(session); @SuppressWarnings("unchecked") Map<String, org.apache.maven.api.Dependency> depResults = (Map<String, org.apache.maven.api.Dependency>) new PluginParameterExpressionEvaluatorV4(session, null, exec) .evaluate("${mojo.plugin.dependenciesMap}"); System.out.println("Result: " + depResults); assertNotNull(depResults); assertEquals(1, depResults.size()); assertTrue(depResults.containsKey("org.myco.plugins:my-plugin")); assertEquals( exec.getPlugin().getArtifact().key(), depResults.get("org.myco.plugins:my-plugin").key(), "dependency artifact is wrong."); } @Test public void testPluginArtifactIdExpressionReference() throws Exception { Session session = newSession(); MojoExecution exec = newMojoExecution(session); Object result = new PluginParameterExpressionEvaluatorV4(session, null, exec) .evaluate("${mojo.plugin.artifact.artifactId}"); System.out.println("Result: " + result); assertSame( exec.getPlugin().getArtifact().getArtifactId(), result, "${plugin.artifactId} expression does not return plugin descriptor's artifactId."); } @Test public void testValueExtractionWithAPomValueContainingAPath() throws Exception { String expected = getTestFile("target/test-classes/target/classes").getCanonicalPath(); Build build = new Build(); build.setDirectory(expected.substring(0, expected.length() - "/classes".length())); Model model = new Model(); model.setBuild(build); MavenProject project = new MavenProject(model); project.setFile(new File("pom.xml").getCanonicalFile()); ExpressionEvaluator expressionEvaluator = createExpressionEvaluator(project, new Properties()); Object value = expressionEvaluator.evaluate("${project.build.directory}/classes"); String actual = new File(value.toString()).getCanonicalPath(); assertEquals(expected, actual); } @Test public void testEscapedVariablePassthrough() throws Exception { String var = "${var}"; MavenProject project = createDefaultProject(); project.setVersion("1"); ExpressionEvaluator ee = createExpressionEvaluator(project, new Properties()); Object value = ee.evaluate("$" + var); assertEquals(var, value); } @Test public void testEscapedVariablePassthroughInLargerExpression() throws Exception { String var = "${var}"; String key = var + " with version: ${project.version}"; MavenProject project = createDefaultProject(); project.setVersion("1"); ExpressionEvaluator ee = createExpressionEvaluator(project, new Properties()); Object value = ee.evaluate("$" + key); assertEquals("${var} with version: 1", value); } @Test public void testMultipleSubExpressionsInLargerExpression() throws Exception { String key = "${project.artifactId} with version: ${project.version}"; MavenProject project = createDefaultProject(); project.setArtifactId("test"); project.setVersion("1"); ExpressionEvaluator ee = createExpressionEvaluator(project, new Properties()); Object value = ee.evaluate(key); assertEquals("test with version: 1", value); } @Test public void testMissingPOMPropertyRefInLargerExpression() throws Exception { String expr = "/path/to/someproject-${baseVersion}"; MavenProject project = createDefaultProject(); ExpressionEvaluator ee = createExpressionEvaluator(project, new Properties()); Object value = ee.evaluate(expr); assertEquals(expr, value); } @Test public void testPOMPropertyExtractionWithMissingProjectWithDotNotation() throws Exception { String key = "m2.name"; String checkValue = "value"; MavenProject project = createDefaultProject(); project.getModel().getProperties().setProperty(key, checkValue); ExpressionEvaluator ee = createExpressionEvaluator(project, new Properties()); Object value = ee.evaluate("${" + key + "}"); assertEquals(checkValue, value); } @Test public void testValueExtractionFromSystemPropertiesWithMissingProject() throws Exception { String sysprop = "PPEET_sysprop1"; Properties executionProperties = new Properties(); if (executionProperties.getProperty(sysprop) == null) { executionProperties.setProperty(sysprop, "value"); } ExpressionEvaluator ee = createExpressionEvaluator(null, executionProperties); Object value = ee.evaluate("${" + sysprop + "}"); assertEquals("value", value); } @Test public void testValueExtractionFromSystemPropertiesWithMissingProjectWithDotNotation() throws Exception { String sysprop = "PPEET.sysprop2"; Properties executionProperties = new Properties(); if (executionProperties.getProperty(sysprop) == null) { executionProperties.setProperty(sysprop, "value"); } ExpressionEvaluator ee = createExpressionEvaluator(null, executionProperties); Object value = ee.evaluate("${" + sysprop + "}"); assertEquals("value", value); } @SuppressWarnings("deprecation") private static MavenSession createSession(PlexusContainer container, ArtifactRepository repo, Properties properties) throws CycleDetectedException, DuplicateProjectException, NoLocalRepositoryManagerException { MavenExecutionRequest request = new DefaultMavenExecutionRequest() .setSystemProperties(properties) .setGoals(Collections.emptyList()) .setBaseDirectory(new File("")) .setLocalRepository(repo); DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(h -> false); // no close handle repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory() .newInstance(repositorySession, new LocalRepository(repo.getUrl()))); MavenSession session = new MavenSession(container, repositorySession, request, new DefaultMavenExecutionResult()); session.setProjects(Collections.emptyList()); return session; } @Test public void testTwoExpressions() throws Exception { MavenProject project = createDefaultProject(); Build build = project.getBuild(); build.setDirectory("expected-directory"); build.setFinalName("expected-finalName"); ExpressionEvaluator expressionEvaluator = createExpressionEvaluator(project, new Properties()); Object value = expressionEvaluator.evaluate("${project.build.directory}" + FS + "${project.build.finalName}"); assertEquals("expected-directory" + File.separatorChar + "expected-finalName", value); } @Test public void testShouldExtractPluginArtifacts() throws Exception { ExpressionEvaluator ee = createExpressionEvaluator(createDefaultProject(), new Properties()); Object value = ee.evaluate("${mojo.plugin.dependencies}"); assertInstanceOf(Collection.class, value); @SuppressWarnings("unchecked") Collection<Artifact> artifacts = (Collection<Artifact>) value; assertEquals(1, artifacts.size()); Artifact result = artifacts.iterator().next(); assertEquals("org.myco.plugins", result.getGroupId()); } @Test void testRootDirectoryNotPrefixed() throws Exception { ExpressionEvaluator ee = createExpressionEvaluator(createDefaultProject(), new Properties()); assertNull(ee.evaluate("${rootDirectory}")); } @Test void testRootDirectoryWithNull() throws Exception { ExpressionEvaluator ee = createExpressionEvaluator(createDefaultProject(), new Properties()); Exception e = assertThrows(Exception.class, () -> ee.evaluate("${session.rootDirectory}")); e = assertInstanceOf(IntrospectionException.class, e.getCause()); e = assertInstanceOf(IllegalStateException.class, e.getCause()); assertEquals(RootLocator.UNABLE_TO_FIND_ROOT_PROJECT_MESSAGE, e.getMessage()); } @Test void testRootDirectory() throws Exception { this.rootDirectory = Paths.get("myRootDirectory"); ExpressionEvaluator ee = createExpressionEvaluator(createDefaultProject(), new Properties()); assertInstanceOf(Path.class, ee.evaluate("${session.rootDirectory}")); } private MavenProject createDefaultProject() { MavenProject project = new MavenProject(new Model()); project.setFile(new File("pom.xml").getAbsoluteFile()); return project; } private ExpressionEvaluator createExpressionEvaluator(MavenProject project, Properties executionProperties) throws Exception { ArtifactRepository repo = getLocalRepository(); MutablePlexusContainer container = (MutablePlexusContainer) getContainer(); MavenSession mavenSession = createSession(container, repo, executionProperties); mavenSession.setCurrentProject(project); mavenSession.getRequest().setRootDirectory(rootDirectory); mavenSession.getRequest().setTopDirectory(rootDirectory); DefaultSession session = new DefaultSession( mavenSession, mock(RepositorySystem.class), null, null, new DefaultLookup(container), null); MojoExecution mojoExecution = newMojoExecution(session); return new PluginParameterExpressionEvaluatorV4( session, project != null ? new DefaultProject(session, project) : null, mojoExecution); } private MojoExecution newMojoExecution(Session session) { PluginDescriptor pd = new PluginDescriptor(); pd.setArtifactId("my-plugin"); pd.setGroupId("org.myco.plugins"); pd.setVersion("1"); DefaultArtifact artifact = new DefaultArtifact( pd.getGroupId(), pd.getArtifactId(), pd.getVersion(), "compile", "maven-plugin", "", new DefaultArtifactHandler("maven-plugin")); pd.setPluginArtifact(artifact); pd.setArtifacts(Collections.singletonList(artifact)); DefaultDependencyNode node = new DefaultDependencyNode( new org.eclipse.aether.graph.Dependency(RepositoryUtils.toArtifact(artifact), "compile")); pd.setDependencyNode(node); MojoDescriptor md = new MojoDescriptor(); md.setGoal("my-goal"); md.setPluginDescriptor(pd); pd.addComponentDescriptor(md); return new DefaultMojoExecution( InternalMavenSession.from(session), new org.apache.maven.plugin.MojoExecution(md)); } private DefaultSession newSession() throws Exception { DefaultSession session = new DefaultSession( newMavenSession(), mock(RepositorySystem.class), null, null, new DefaultLookup(container), null); return session; } private MavenSession newMavenSession() throws Exception { return createMavenSession(null); } @Test public void testUri() throws Exception { Path path = Paths.get("").toAbsolutePath(); MavenSession mavenSession = createMavenSession(null); mavenSession.getRequest().setTopDirectory(path); mavenSession.getRequest().setRootDirectory(path); Object result = new PluginParameterExpressionEvaluatorV4(mavenSession.getSession(), null) .evaluate("${session.rootDirectory.uri}"); assertEquals(path.toUri(), result); } @Test public void testPath() throws Exception { Path path = Paths.get("").toAbsolutePath(); MavenSession mavenSession = createMavenSession(null); mavenSession.getRequest().setTopDirectory(path); mavenSession.getRequest().setRootDirectory(path); Object result = new PluginParameterExpressionEvaluatorV4(mavenSession.getSession(), null) .evaluate("${session.rootDirectory/target}"); assertEquals(path.resolve("target"), result); } @Test public void testPluginInjection() throws Exception { Path path = Paths.get("rép➜α").toAbsolutePath(); MavenSession mavenSession = createMavenSession(null); mavenSession.getRequest().setTopDirectory(path); mavenSession.getRequest().setRootDirectory(path); PluginParameterExpressionEvaluatorV4 evaluator = new PluginParameterExpressionEvaluatorV4(mavenSession.getSession(), null); DefaultPlexusConfiguration configuration = new DefaultPlexusConfiguration("config"); configuration.addChild("uri", "${session.rootDirectory.uri}"); configuration.addChild("path", "${session.rootDirectory}"); configuration.addChild("uriString", "${session.rootDirectory.uri.string}"); configuration.addChild("uriAsciiString", "${session.rootDirectory.uri.ASCIIString}"); configuration.addChild("pathString", "${session.rootDirectory.string}"); Mojo mojo = new Mojo(); new EnhancedComponentConfigurator().configureComponent(mojo, configuration, evaluator, null); assertEquals( Objects.equals(path.toUri().toString(), path.toUri().toASCIIString()), !Os.isFamily(Os.FAMILY_WINDOWS)); assertEquals(mojo.uri, path.toUri()); assertEquals(mojo.path, path); assertEquals(mojo.uriString, path.toUri().toString()); assertEquals(mojo.uriAsciiString, path.toUri().toASCIIString()); assertEquals(mojo.pathString, path.toString()); } @Override protected String getProjectsDirectory() { // TODO Auto-generated method stub return null; } public static
PluginParameterExpressionEvaluatorV4Test
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/lucene/uid/VersionsAndSeqNoResolver.java
{ "start": 5285, "end": 11086 }
class ____ { public final int docId; public final long seqNo; public final LeafReaderContext context; DocIdAndSeqNo(int docId, long seqNo, LeafReaderContext context) { this.docId = docId; this.seqNo = seqNo; this.context = context; } } /** * Load the internal doc ID and version for the uid from the reader, returning<ul> * <li>null if the uid wasn't found, * <li>a doc ID and a version otherwise * </ul> */ public static DocIdAndVersion timeSeriesLoadDocIdAndVersion(IndexReader reader, BytesRef term, boolean loadSeqNo) throws IOException { PerThreadIDVersionAndSeqNoLookup[] lookups = getLookupState(reader, false); List<LeafReaderContext> leaves = reader.leaves(); // iterate backwards to optimize for the frequently updated documents // which are likely to be in the last segments for (int i = leaves.size() - 1; i >= 0; i--) { final LeafReaderContext leaf = leaves.get(i); PerThreadIDVersionAndSeqNoLookup lookup = lookups[leaf.ord]; DocIdAndVersion result = lookup.lookupVersion(term, loadSeqNo, leaf); if (result != null) { return result; } } return null; } /** * A special variant of loading docid and version in case of time series indices. * <p> * Makes use of the fact that timestamp is part of the id, the existence of @timestamp field and * that segments are sorted by {@link org.elasticsearch.cluster.metadata.DataStream#TIMESERIES_LEAF_READERS_SORTER}. * This allows this method to know whether there is no document with the specified id without loading the docid for * the specified id. * * @param reader The reader load docid, version and seqno from. * @param uid The term that describes the uid of the document to load docid, version and seqno for. * @param id The id that contains the encoded timestamp. The timestamp is used to skip checking the id for entire segments. * @param loadSeqNo Whether to load sequence number from _seq_no doc values field. * @param useSyntheticId Whether the id is a synthetic (true) or standard (false ) document id. * @return the internal doc ID and version for the specified term from the specified reader or * returning <code>null</code> if no document was found for the specified id * @throws IOException In case of an i/o related failure */ public static DocIdAndVersion timeSeriesLoadDocIdAndVersion( IndexReader reader, BytesRef uid, String id, boolean loadSeqNo, boolean useSyntheticId ) throws IOException { final long timestamp; if (useSyntheticId) { assert uid.equals(new BytesRef(Base64.getUrlDecoder().decode(id))); timestamp = TsidExtractingIdFieldMapper.extractTimestampFromSyntheticId(uid); } else { byte[] idAsBytes = Base64.getUrlDecoder().decode(id); timestamp = TsidExtractingIdFieldMapper.extractTimestampFromId(idAsBytes); } PerThreadIDVersionAndSeqNoLookup[] lookups = getLookupState(reader, true); List<LeafReaderContext> leaves = reader.leaves(); // iterate in default order, the segments should be sorted by DataStream#TIMESERIES_LEAF_READERS_SORTER long prevMaxTimestamp = Long.MAX_VALUE; for (final LeafReaderContext leaf : leaves) { PerThreadIDVersionAndSeqNoLookup lookup = lookups[leaf.ord]; assert lookup.loadedTimestampRange; assert prevMaxTimestamp >= lookup.maxTimestamp; if (timestamp < lookup.minTimestamp) { continue; } if (timestamp > lookup.maxTimestamp) { return null; } DocIdAndVersion result = lookup.lookupVersion(uid, loadSeqNo, leaf); if (result != null) { return result; } prevMaxTimestamp = lookup.maxTimestamp; } return null; } public static DocIdAndVersion loadDocIdAndVersionUncached(IndexReader reader, BytesRef term, boolean loadSeqNo) throws IOException { List<LeafReaderContext> leaves = reader.leaves(); for (int i = leaves.size() - 1; i >= 0; i--) { final LeafReaderContext leaf = leaves.get(i); PerThreadIDVersionAndSeqNoLookup lookup = new PerThreadIDVersionAndSeqNoLookup(leaf.reader(), false, false); DocIdAndVersion result = lookup.lookupVersion(term, loadSeqNo, leaf); if (result != null) { return result; } } return null; } /** * Loads the internal docId and sequence number of the latest copy for a given uid from the provided reader. * The result is either null or the live and latest version of the given uid. */ public static DocIdAndSeqNo loadDocIdAndSeqNo(IndexReader reader, BytesRef term) throws IOException { final PerThreadIDVersionAndSeqNoLookup[] lookups = getLookupState(reader, false); final List<LeafReaderContext> leaves = reader.leaves(); // iterate backwards to optimize for the frequently updated documents // which are likely to be in the last segments for (int i = leaves.size() - 1; i >= 0; i--) { final LeafReaderContext leaf = leaves.get(i); final PerThreadIDVersionAndSeqNoLookup lookup = lookups[leaf.ord]; final DocIdAndSeqNo result = lookup.lookupSeqNo(term, leaf); if (result != null) { return result; } } return null; } }
DocIdAndSeqNo
java
quarkusio__quarkus
integration-tests/gradle/src/main/resources/inject-bean-from-test-config/application/src/test/java/org/acme/ExampleResourceTest.java
{ "start": 402, "end": 717 }
class ____ { @Inject LibraryTestBean libraryBean; @Test public void testHelloEndpoint() { given() .when().get("/hello") .then() .statusCode(200) .body(is("hello")); assertEquals("test", libraryBean.getValue()); } }
ExampleResourceTest
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/analysis/PostAnalyzer.java
{ "start": 1214, "end": 1596 }
class ____ to add implicit blocks to the query based on the user request * that help with the query execution not its semantics. * * This could have been done in the optimizer however due to its wrapping nature (which is clunky to do with rules) * and since the optimized is not parameterized, making this a separate step (similar to the pre-analyzer) is more natural. */ public
is
java
apache__camel
core/camel-main/src/generated/java/org/apache/camel/main/KubernetesConfigMapVaultConfigurationConfigurer.java
{ "start": 716, "end": 7097 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.vault.KubernetesConfigMapVaultConfiguration target = (org.apache.camel.vault.KubernetesConfigMapVaultConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "awsvaultconfiguration": case "awsVaultConfiguration": target.setAwsVaultConfiguration(property(camelContext, org.apache.camel.vault.AwsVaultConfiguration.class, value)); return true; case "azurevaultconfiguration": case "azureVaultConfiguration": target.setAzureVaultConfiguration(property(camelContext, org.apache.camel.vault.AzureVaultConfiguration.class, value)); return true; case "configmaps": target.setConfigmaps(property(camelContext, java.lang.String.class, value)); return true; case "cyberarkvaultconfiguration": case "cyberArkVaultConfiguration": target.setCyberArkVaultConfiguration(property(camelContext, org.apache.camel.vault.CyberArkVaultConfiguration.class, value)); return true; case "gcpvaultconfiguration": case "gcpVaultConfiguration": target.setGcpVaultConfiguration(property(camelContext, org.apache.camel.vault.GcpVaultConfiguration.class, value)); return true; case "hashicorpvaultconfiguration": case "hashicorpVaultConfiguration": target.setHashicorpVaultConfiguration(property(camelContext, org.apache.camel.vault.HashicorpVaultConfiguration.class, value)); return true; case "ibmsecretsmanagervaultconfiguration": case "iBMSecretsManagerVaultConfiguration": target.setIBMSecretsManagerVaultConfiguration(property(camelContext, org.apache.camel.vault.IBMSecretsManagerVaultConfiguration.class, value)); return true; case "kubernetesconfigmapvaultconfiguration": case "kubernetesConfigMapVaultConfiguration": target.setKubernetesConfigMapVaultConfiguration(property(camelContext, org.apache.camel.vault.KubernetesConfigMapVaultConfiguration.class, value)); return true; case "kubernetesvaultconfiguration": case "kubernetesVaultConfiguration": target.setKubernetesVaultConfiguration(property(camelContext, org.apache.camel.vault.KubernetesVaultConfiguration.class, value)); return true; case "refreshenabled": case "refreshEnabled": target.setRefreshEnabled(property(camelContext, boolean.class, value)); return true; case "springcloudconfigconfiguration": case "springCloudConfigConfiguration": target.setSpringCloudConfigConfiguration(property(camelContext, org.apache.camel.vault.SpringCloudConfigConfiguration.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "awsvaultconfiguration": case "awsVaultConfiguration": return org.apache.camel.vault.AwsVaultConfiguration.class; case "azurevaultconfiguration": case "azureVaultConfiguration": return org.apache.camel.vault.AzureVaultConfiguration.class; case "configmaps": return java.lang.String.class; case "cyberarkvaultconfiguration": case "cyberArkVaultConfiguration": return org.apache.camel.vault.CyberArkVaultConfiguration.class; case "gcpvaultconfiguration": case "gcpVaultConfiguration": return org.apache.camel.vault.GcpVaultConfiguration.class; case "hashicorpvaultconfiguration": case "hashicorpVaultConfiguration": return org.apache.camel.vault.HashicorpVaultConfiguration.class; case "ibmsecretsmanagervaultconfiguration": case "iBMSecretsManagerVaultConfiguration": return org.apache.camel.vault.IBMSecretsManagerVaultConfiguration.class; case "kubernetesconfigmapvaultconfiguration": case "kubernetesConfigMapVaultConfiguration": return org.apache.camel.vault.KubernetesConfigMapVaultConfiguration.class; case "kubernetesvaultconfiguration": case "kubernetesVaultConfiguration": return org.apache.camel.vault.KubernetesVaultConfiguration.class; case "refreshenabled": case "refreshEnabled": return boolean.class; case "springcloudconfigconfiguration": case "springCloudConfigConfiguration": return org.apache.camel.vault.SpringCloudConfigConfiguration.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.vault.KubernetesConfigMapVaultConfiguration target = (org.apache.camel.vault.KubernetesConfigMapVaultConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "awsvaultconfiguration": case "awsVaultConfiguration": return target.getAwsVaultConfiguration(); case "azurevaultconfiguration": case "azureVaultConfiguration": return target.getAzureVaultConfiguration(); case "configmaps": return target.getConfigmaps(); case "cyberarkvaultconfiguration": case "cyberArkVaultConfiguration": return target.getCyberArkVaultConfiguration(); case "gcpvaultconfiguration": case "gcpVaultConfiguration": return target.getGcpVaultConfiguration(); case "hashicorpvaultconfiguration": case "hashicorpVaultConfiguration": return target.getHashicorpVaultConfiguration(); case "ibmsecretsmanagervaultconfiguration": case "iBMSecretsManagerVaultConfiguration": return target.getIBMSecretsManagerVaultConfiguration(); case "kubernetesconfigmapvaultconfiguration": case "kubernetesConfigMapVaultConfiguration": return target.getKubernetesConfigMapVaultConfiguration(); case "kubernetesvaultconfiguration": case "kubernetesVaultConfiguration": return target.getKubernetesVaultConfiguration(); case "refreshenabled": case "refreshEnabled": return target.isRefreshEnabled(); case "springcloudconfigconfiguration": case "springCloudConfigConfiguration": return target.getSpringCloudConfigConfiguration(); default: return null; } } }
KubernetesConfigMapVaultConfigurationConfigurer
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/EnhancerImpl.java
{ "start": 4973, "end": 5530 }
class ____ bytecode is being enhanced. * @param originalBytes The class's original (pre-enhancement) byte code * * @return The enhanced bytecode. Could be the same as the original bytecode if the original was * already enhanced or we could not enhance it for some reason. * * @throws EnhancementException Indicates a problem performing the enhancement */ @Override public byte[] enhance(String className, byte[] originalBytes) throws EnhancementException { //Classpool#describe does not accept '/' in the description name as it expects a
whose
java
spring-projects__spring-boot
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/jmx/JmxOperationResponseMapper.java
{ "start": 842, "end": 1355 }
interface ____ { /** * Map the response type to its JMX compliant counterpart. * @param responseType the operation's response type * @return the JMX compliant type */ Class<?> mapResponseType(Class<?> responseType); /** * Map the operation's response so that it can be consumed by a JMX compliant client. * @param response the operation's response * @return the {@code response}, in a JMX compliant format */ @Nullable Object mapResponse(@Nullable Object response); }
JmxOperationResponseMapper
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/integration/MockitoSpyBeanWithMultipleExistingBeansAndExplicitQualifierIntegrationTests.java
{ "start": 2173, "end": 2708 }
class ____ { @Qualifier("stringService") @MockitoSpyBean StringExampleGenericService spy; @Autowired ExampleGenericServiceCaller caller; @Test void test() { assertIsSpy(spy); assertMockName(spy, "stringService"); assertThat(caller.sayGreeting()).isEqualTo("I say two 123"); then(spy).should().greeting(); } @Configuration(proxyBeanMethods = false) @Import({ ExampleGenericServiceCaller.class, IntegerExampleGenericService.class }) static
MockitoSpyBeanWithMultipleExistingBeansAndExplicitQualifierIntegrationTests
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/enums/EnumDeserializationTest.java
{ "start": 3656, "end": 3813 }
enum ____ { A, B, C; @Override public String toString() { return name().toLowerCase(); }; } static
Enum1161
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/env/NodeEnvironmentTests.java
{ "start": 15597, "end": 36889 }
class ____ { int value = 0; } final NodeEnvironment env = newNodeEnvironment(); final int shards = randomIntBetween(2, 10); final Int[] counts = new Int[shards]; final AtomicInteger[] countsAtomic = new AtomicInteger[shards]; final AtomicInteger[] flipFlop = new AtomicInteger[shards]; for (int i = 0; i < counts.length; i++) { counts[i] = new Int(); countsAtomic[i] = new AtomicInteger(); flipFlop[i] = new AtomicInteger(); } final int threads = randomIntBetween(2, 5); final int iters = scaledRandomIntBetween(10000, 100000); startInParallel(threads, tid -> { for (int i = 0; i < iters; i++) { int shard = randomIntBetween(0, counts.length - 1); try { try (ShardLock autoCloses = env.shardLock(new ShardId("foo", "fooUUID", shard), "1", scaledRandomIntBetween(0, 10))) { counts[shard].value++; countsAtomic[shard].incrementAndGet(); assertEquals(flipFlop[shard].incrementAndGet(), 1); assertEquals(flipFlop[shard].decrementAndGet(), 0); } } catch (ShardLockObtainFailedException ex) { // ok } } }); assertTrue("LockedShards: " + env.lockedShards(), env.lockedShards().isEmpty()); for (int i = 0; i < counts.length; i++) { assertTrue(counts[i].value > 0); assertEquals(flipFlop[i].get(), 0); assertEquals(counts[i].value, countsAtomic[i].get()); } env.close(); } public void testCustomDataPaths() throws Exception { String[] dataPaths = tmpPaths(); NodeEnvironment env = newNodeEnvironment(dataPaths, "/tmp", Settings.EMPTY); Index index = new Index("myindex", "myindexUUID"); ShardId sid = new ShardId(index, 0); assertThat(env.availableShardPaths(sid), equalTo(env.availableShardPaths(sid))); assertThat( env.resolveCustomLocation("/tmp/foo", sid).toAbsolutePath(), equalTo(PathUtils.get("/tmp/foo/0/" + index.getUUID() + "/0").toAbsolutePath()) ); assertThat( "shard paths with a custom data_path should contain only regular paths", env.availableShardPaths(sid), equalTo(stringsToPaths(dataPaths, "indices/" + index.getUUID() + "/0")) ); assertThat( "index paths uses the regular template", env.indexPaths(index), equalTo(stringsToPaths(dataPaths, "indices/" + index.getUUID())) ); assertThat(env.availableShardPaths(sid), equalTo(env.availableShardPaths(sid))); assertThat( env.resolveCustomLocation("/tmp/foo", sid).toAbsolutePath(), equalTo(PathUtils.get("/tmp/foo/0/" + index.getUUID() + "/0").toAbsolutePath()) ); assertThat( "shard paths with a custom data_path should contain only regular paths", env.availableShardPaths(sid), equalTo(stringsToPaths(dataPaths, "indices/" + index.getUUID() + "/0")) ); assertThat( "index paths uses the regular template", env.indexPaths(index), equalTo(stringsToPaths(dataPaths, "indices/" + index.getUUID())) ); env.close(); } public void testExistingTempFiles() throws IOException { String[] paths = tmpPaths(); // simulate some previous left over temp files for (String path : randomSubsetOf(randomIntBetween(1, paths.length), paths)) { final Path dataPath = PathUtils.get(path); Files.createDirectories(dataPath); Files.createFile(dataPath.resolve(NodeEnvironment.TEMP_FILE_NAME)); if (randomBoolean()) { Files.createFile(dataPath.resolve(NodeEnvironment.TEMP_FILE_NAME + ".tmp")); } if (randomBoolean()) { Files.createFile(dataPath.resolve(NodeEnvironment.TEMP_FILE_NAME + ".final")); } } NodeEnvironment env = newNodeEnvironment(paths, Settings.EMPTY); env.close(); // check we clean up for (String path : paths) { final Path dataPath = PathUtils.get(path); final Path tempFile = dataPath.resolve(NodeEnvironment.TEMP_FILE_NAME); assertFalse(tempFile + " should have been cleaned", Files.exists(tempFile)); final Path srcTempFile = dataPath.resolve(NodeEnvironment.TEMP_FILE_NAME + ".src"); assertFalse(srcTempFile + " should have been cleaned", Files.exists(srcTempFile)); final Path targetTempFile = dataPath.resolve(NodeEnvironment.TEMP_FILE_NAME + ".target"); assertFalse(targetTempFile + " should have been cleaned", Files.exists(targetTempFile)); } } public void testEnsureNoShardDataOrIndexMetadata() throws IOException { Settings settings = buildEnvSettings(Settings.EMPTY); Index index = new Index("test", "testUUID"); // build settings using same path.data as original but without data and master roles Settings noDataNoMasterSettings = Settings.builder() .put(settings) .put(NodeRoles.removeRoles(nonDataNode(settings), Set.of(DiscoveryNodeRole.MASTER_ROLE))) .build(); // test that we can create data=false and master=false with no meta information newNodeEnvironment(noDataNoMasterSettings).close(); Path indexPath; try (NodeEnvironment env = newNodeEnvironment(settings)) { for (Path path : env.indexPaths(index)) { Files.createDirectories(path.resolve(MetadataStateFormat.STATE_DIR_NAME)); } indexPath = env.indexPaths(index)[0]; } verifyFailsOnMetadata(noDataNoMasterSettings, indexPath); // build settings using same path.data as original but without data role Settings noDataSettings = nonDataNode(settings); String shardDataDirName = Integer.toString(randomInt(10)); // test that we can create data=false env with only meta information. Also create shard data for following asserts try (NodeEnvironment env = newNodeEnvironment(noDataSettings)) { for (Path path : env.indexPaths(index)) { Files.createDirectories(path.resolve(shardDataDirName)); } } verifyFailsOnShardData(noDataSettings, indexPath, shardDataDirName); // assert that we get the stricter message on meta-data when both conditions fail verifyFailsOnMetadata(noDataNoMasterSettings, indexPath); // build settings using same path.data as original but without master role Settings noMasterSettings = nonMasterNode(settings); // test that we can create master=false env regardless of data. newNodeEnvironment(noMasterSettings).close(); // test that we can create data=true, master=true env. Also remove state dir to leave only shard data for following asserts try (NodeEnvironment env = newNodeEnvironment(settings)) { for (Path path : env.indexPaths(index)) { Files.delete(path.resolve(MetadataStateFormat.STATE_DIR_NAME)); } } // assert that we fail on shard data even without the metadata dir. verifyFailsOnShardData(noDataSettings, indexPath, shardDataDirName); verifyFailsOnShardData(noDataNoMasterSettings, indexPath, shardDataDirName); } public void testBlocksDowngradeToVersionWithMultipleNodesInDataPath() throws IOException { final Settings settings = buildEnvSettings(Settings.EMPTY); for (int i = 0; i < 2; i++) { // ensure the file gets created again if missing try (NodeEnvironment env = newNodeEnvironment(settings)) { for (Path dataPath : env.nodeDataPaths()) { final Path nodesPath = dataPath.resolve("nodes"); assertTrue(Files.isRegularFile(nodesPath)); assertThat( Files.readString(nodesPath, StandardCharsets.UTF_8), allOf( containsString("written by Elasticsearch"), containsString("prevent a downgrade"), containsString("data loss") ) ); Files.delete(nodesPath); } } } } public void testIndexCompatibilityChecks() throws IOException { final Settings settings = buildEnvSettings(Settings.EMPTY); try (NodeEnvironment env = newNodeEnvironment(settings)) { try ( PersistedClusterStateService.Writer writer = new PersistedClusterStateService( env.nodeDataPaths(), env.nodeId(), xContentRegistry(), new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), () -> 0L, ESTestCase::randomBoolean ).createWriter() ) { writer.writeFullStateAndCommit( 1L, ClusterState.builder(ClusterName.DEFAULT) .metadata( Metadata.builder() .persistentSettings(Settings.builder().put(Metadata.SETTING_READ_ONLY_SETTING.getKey(), true).build()) .build() ) .build() ); } Version oldVersion = Version.fromId(between(1, Version.CURRENT.minimumCompatibilityVersion().id - 1)); IndexVersion oldIndexVersion = IndexVersion.fromId(between(1, IndexVersions.MINIMUM_COMPATIBLE.id() - 1)); Version previousNodeVersion = Version.fromId(between(Version.CURRENT.minimumCompatibilityVersion().id, Version.CURRENT.id - 1)); overrideOldestIndexVersion(oldIndexVersion, previousNodeVersion, env.nodeDataPaths()); IllegalStateException ex = expectThrows( IllegalStateException.class, "Must fail the check on index that's too old", () -> checkForIndexCompatibility(logger, env.dataPaths()) ); assertThat( ex.getMessage(), allOf( containsString("Cannot start this node"), containsString("it holds metadata for indices with version [" + oldIndexVersion.toReleaseVersion() + "]"), containsString( "Revert this node to version [" + (previousNodeVersion.onOrAfter(Version.CURRENT.minimumCompatibilityVersion()) ? previousNodeVersion : Version.CURRENT.minimumCompatibilityVersion()) + "]" ) ) ); // This should work overrideOldestIndexVersion(IndexVersions.MINIMUM_COMPATIBLE, previousNodeVersion, env.nodeDataPaths()); checkForIndexCompatibility(logger, env.dataPaths()); // Trying to boot with newer version should pass this check overrideOldestIndexVersion(NodeMetadataTests.tooNewIndexVersion(), previousNodeVersion, env.nodeDataPaths()); checkForIndexCompatibility(logger, env.dataPaths()); // Simulate empty old index version, attempting to upgrade before 7.17 removeOldestIndexVersion(oldVersion, env.nodeDataPaths()); ex = expectThrows( IllegalStateException.class, "Must fail the check on index that's too old", () -> checkForIndexCompatibility(logger, env.dataPaths()) ); assertThat( ex.getMessage(), allOf( startsWith("cannot upgrade a node from version [" + oldVersion + "] directly"), containsString("upgrade to version [" + Build.current().minWireCompatVersion()) ) ); } } public void testSymlinkDataDirectory() throws Exception { Path tempDir = createTempDir().toAbsolutePath(); Path dataPath = tempDir.resolve("data"); Files.createDirectories(dataPath); Path symLinkPath = tempDir.resolve("data_symlink"); try { Files.createSymbolicLink(symLinkPath, dataPath); } catch (FileSystemException e) { if (IOUtils.WINDOWS && "A required privilege is not held by the client".equals(e.getReason())) { throw new AssumptionViolatedException("Symlinks on Windows need admin privileges", e); } else { throw e; } } NodeEnvironment env = newNodeEnvironment(new String[] { symLinkPath.toString() }, "/tmp", Settings.EMPTY); assertTrue(Files.exists(symLinkPath)); env.close(); } public void testGetBestDowngradeVersion() { int prev = Version.CURRENT.minimumCompatibilityVersion().major; int last = Version.CURRENT.minimumCompatibilityVersion().minor; int old = prev - 1; assumeTrue("The current compatibility rules are active only from 8.x onward", prev >= 7); assertEquals(Version.CURRENT.major - 1, prev); assertEquals( "From an old major, recommend prev.last", NodeEnvironment.getBestDowngradeVersion(BuildVersion.fromString(old + ".0.0")), BuildVersion.fromString(prev + "." + last + ".0") ); if (last >= 1) { assertEquals( "From an old minor of the previous major, recommend prev.last", NodeEnvironment.getBestDowngradeVersion(BuildVersion.fromString(prev + "." + (last - 1) + ".0")), BuildVersion.fromString(prev + "." + last + ".0") ); } assertEquals( "From an old patch of prev.last, return that version itself", NodeEnvironment.getBestDowngradeVersion(BuildVersion.fromString(prev + "." + last + ".1")), BuildVersion.fromString(prev + "." + last + ".1") ); assertEquals( "From the first version of this major, return that version itself", NodeEnvironment.getBestDowngradeVersion(BuildVersion.fromString(Version.CURRENT.major + ".0.0")), BuildVersion.fromString(Version.CURRENT.major + ".0.0") ); } private void verifyFailsOnShardData(Settings settings, Path indexPath, String shardDataDirName) { IllegalStateException ex = expectThrows( IllegalStateException.class, "Must fail creating NodeEnvironment on a data path that has shard data if node does not have data role", () -> newNodeEnvironment(settings).close() ); assertThat(ex.getMessage(), containsString(indexPath.resolve(shardDataDirName).toAbsolutePath().toString())); assertThat(ex.getMessage(), startsWith("node does not have the data role but has shard data")); } private void verifyFailsOnMetadata(Settings settings, Path indexPath) { IllegalStateException ex = expectThrows( IllegalStateException.class, "Must fail creating NodeEnvironment on a data path that has index metadata if node does not have data and master roles", () -> newNodeEnvironment(settings).close() ); assertThat(ex.getMessage(), containsString(indexPath.resolve(MetadataStateFormat.STATE_DIR_NAME).toAbsolutePath().toString())); assertThat(ex.getMessage(), startsWith("node does not have the data and master roles but has index metadata")); } /** * Converts an array of Strings to an array of Paths, adding an additional child if specified */ private Path[] stringsToPaths(String[] strings, String additional) { Path[] locations = new Path[strings.length]; for (int i = 0; i < strings.length; i++) { locations[i] = PathUtils.get(strings[i], additional); } return locations; } @Override public String[] tmpPaths() { final int numPaths = randomIntBetween(1, 3); final String[] absPaths = new String[numPaths]; for (int i = 0; i < numPaths; i++) { absPaths[i] = createTempDir().toAbsolutePath().toString(); } return absPaths; } @Override public NodeEnvironment newNodeEnvironment() throws IOException { return newNodeEnvironment(Settings.EMPTY); } @Override public NodeEnvironment newNodeEnvironment(Settings settings) throws IOException { Settings build = buildEnvSettings(settings); return new NodeEnvironment(build, TestEnvironment.newEnvironment(build)); } public Settings buildEnvSettings(Settings settings) { return Settings.builder() .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString()) .putList(Environment.PATH_DATA_SETTING.getKey(), tmpPaths()) .put(settings) .build(); } public NodeEnvironment newNodeEnvironment(String[] dataPaths, Settings settings) throws IOException { Settings build = Settings.builder() .put(settings) .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString()) .putList(Environment.PATH_DATA_SETTING.getKey(), dataPaths) .build(); return new NodeEnvironment(build, TestEnvironment.newEnvironment(build)); } public NodeEnvironment newNodeEnvironment(String[] dataPaths, String sharedDataPath, Settings settings) throws IOException { Settings build = Settings.builder() .put(settings) .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toAbsolutePath().toString()) .put(Environment.PATH_SHARED_DATA_SETTING.getKey(), sharedDataPath) .putList(Environment.PATH_DATA_SETTING.getKey(), dataPaths) .build(); return new NodeEnvironment(build, TestEnvironment.newEnvironment(build)); } private static void overrideOldestIndexVersion(IndexVersion oldestIndexVersion, Version previousNodeVersion, Path... dataPaths) throws IOException { for (final Path dataPath : dataPaths) { final Path indexPath = dataPath.resolve(METADATA_DIRECTORY_NAME); if (Files.exists(indexPath)) { try (DirectoryReader reader = DirectoryReader.open(new NIOFSDirectory(dataPath.resolve(METADATA_DIRECTORY_NAME)))) { final Map<String, String> userData = reader.getIndexCommit().getUserData(); final IndexWriterConfig indexWriterConfig = new IndexWriterConfig(new KeywordAnalyzer()); try ( IndexWriter indexWriter = new IndexWriter( new NIOFSDirectory(dataPath.resolve(METADATA_DIRECTORY_NAME)), indexWriterConfig ) ) { final Map<String, String> commitData = new HashMap<>(userData); commitData.put(NODE_VERSION_KEY, Integer.toString(previousNodeVersion.id)); commitData.put(OLDEST_INDEX_VERSION_KEY, Integer.toString(oldestIndexVersion.id())); indexWriter.setLiveCommitData(commitData.entrySet()); indexWriter.commit(); } } } } } private static void removeOldestIndexVersion(Version oldVersion, Path... dataPaths) throws IOException { for (final Path dataPath : dataPaths) { final Path indexPath = dataPath.resolve(METADATA_DIRECTORY_NAME); if (Files.exists(indexPath)) { try (DirectoryReader reader = DirectoryReader.open(new NIOFSDirectory(dataPath.resolve(METADATA_DIRECTORY_NAME)))) { final Map<String, String> userData = reader.getIndexCommit().getUserData(); final IndexWriterConfig indexWriterConfig = new IndexWriterConfig(new KeywordAnalyzer()); try ( IndexWriter indexWriter = new IndexWriter( new NIOFSDirectory(dataPath.resolve(METADATA_DIRECTORY_NAME)), indexWriterConfig ) ) { final Map<String, String> commitData = new HashMap<>(userData); commitData.put(NODE_VERSION_KEY, Integer.toString(oldVersion.id)); commitData.remove(OLDEST_INDEX_VERSION_KEY); indexWriter.setLiveCommitData(commitData.entrySet()); indexWriter.commit(); } } } } } }
Int
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/tools/picocli/CommandLine.java
{ "start": 77991, "end": 78618 }
class ____ { * &#064;Parameters(type = BigDecimal.class, description = "Any number of input numbers") * private List&lt;BigDecimal&gt; files = new ArrayList&lt;BigDecimal&gt;(); * * &#064;Option(names = { "-h", "--help", "-?", "-help"}, help = true, description = "Display this help and exit") * private boolean help; * } * </pre><p> * A field cannot be annotated with both {@code @Parameters} and {@code @Option} or a {@code ParameterException} * is thrown.</p> */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @
MyCalcParameters
java
google__guava
android/guava-tests/benchmark/com/google/common/util/concurrent/MonitorBasedPriorityBlockingQueue.java
{ "start": 1555, "end": 1796 }
class ____ not permit {@code null} elements. A priority queue relying on * {@linkplain Comparable natural ordering} also does not permit insertion of non-comparable objects * (doing so results in {@code ClassCastException}). * * <p>This
does
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/GeoRadiusStoreArgs.java
{ "start": 571, "end": 840 }
class ____<K> implements CompositeArgument { private K storeKey; private K storeDistKey; private Long count; private Sort sort = Sort.none; /** * Builder entry points for {@link GeoRadiusStoreArgs}. */ public static
GeoRadiusStoreArgs
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/schedulers/SchedulerTestHelper.java
{ "start": 3212, "end": 3716 }
class ____<T> extends DefaultSubscriber<T> { CountDownLatch completed = new CountDownLatch(1); int errorCount; int nextCount; Throwable error; @Override public void onComplete() { } @Override public void onError(Throwable e) { errorCount++; error = e; completed.countDown(); } @Override public void onNext(T t) { nextCount++; } } }
CapturingObserver
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SqlStoredComponentBuilderFactory.java
{ "start": 1401, "end": 1907 }
interface ____ { /** * SQL Stored Procedure (camel-sql) * Perform SQL queries as a JDBC Stored Procedures using Spring JDBC. * * Category: database * Since: 2.17 * Maven coordinates: org.apache.camel:camel-sql * * @return the dsl builder */ static SqlStoredComponentBuilder sqlStored() { return new SqlStoredComponentBuilderImpl(); } /** * Builder for the SQL Stored Procedure component. */
SqlStoredComponentBuilderFactory
java
apache__camel
components/camel-smooks/src/test/java/org/apache/camel/component/smooks/Coordinate.java
{ "start": 854, "end": 1987 }
class ____ { private Integer x; private Integer y; public Coordinate() { } public Coordinate(final int x, final int y) { this.x = x; this.y = y; } public Integer getX() { return x; } public void setX(Integer x) { this.x = x; } public Integer getY() { return y; } public void setY(Integer y) { this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Coordinate other = (Coordinate) obj; if (!x.equals(other.x)) return false; if (!y.equals(other.y)) return false; return true; } public String toString() { return "Coordinate [x=" + x + ", y=" + y + "]"; } }
Coordinate
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/LiteralSerializationTests.java
{ "start": 468, "end": 904 }
class ____ extends AbstractExpressionSerializationTests<Literal> { @Override protected Literal createTestInstance() { return LiteralTests.randomLiteral(); } @Override protected Literal mutateInstance(Literal instance) throws IOException { return LiteralTests.mutateLiteral(instance); } @Override protected boolean alwaysEmptySource() { return true; } }
LiteralSerializationTests
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java
{ "start": 3870, "end": 4862 }
class ____ the type it is interested in so is chosen in preference to // any 'default' ones ctx.addPropertyAccessor(new StringyPropertyAccessor()); Expression expr = parser.parseRaw("new String('hello').flibbles"); Integer i = expr.getValue(ctx, Integer.class); assertThat((int) i).isEqualTo(7); // The reflection one will be used for other properties... expr = parser.parseRaw("new String('hello').CASE_INSENSITIVE_ORDER"); Object o = expr.getValue(ctx); assertThat(o).isNotNull(); SpelExpression flibbleexpr = parser.parseRaw("new String('hello').flibbles"); flibbleexpr.setValue(ctx, 99); i = flibbleexpr.getValue(ctx, Integer.class); assertThat((int) i).isEqualTo(99); // Cannot set it to a string value assertThatSpelEvaluationException().isThrownBy(() -> flibbleexpr.setValue(ctx, "not allowed")); // message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property // 'flibbles': 'Cannot set flibbles to an object of type '
as
java
qos-ch__slf4j
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLoggerFactory.java
{ "start": 1534, "end": 2672 }
class ____ implements ILoggerFactory { ConcurrentMap<String, Logger> loggerMap; public SimpleLoggerFactory() { loggerMap = new ConcurrentHashMap<>(); SimpleLogger.lazyInit(); } /** * Return an appropriate {@link SimpleLogger} instance by name. * * This method will call {@link #createLogger(String)} if the logger * has not been created yet. */ public Logger getLogger(String name) { return loggerMap.computeIfAbsent(name, this::createLogger); } /** * Actually creates the logger for the given name. */ protected Logger createLogger(String name) { return new SimpleLogger(name); } /** * Clear the internal logger cache. * * This method is intended to be called by classes (in the same package or * subclasses) for testing purposes. This method is internal. It can be * modified, renamed or removed at any time without notice. * * You are strongly discouraged from calling this method in production code. */ protected void reset() { loggerMap.clear(); } }
SimpleLoggerFactory
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/sequencedmultisetstate/TimeSelector.java
{ "start": 1083, "end": 1611 }
interface ____ extends Serializable { long getTimestamp(long elementTimestamp); static TimeSelector getTimeDomain(TimeDomain timeDomain) { switch (timeDomain) { case EVENT_TIME: return elementTimestamp -> elementTimestamp; case PROCESSING_TIME: return elementTimestamp -> SystemClock.getInstance().absoluteTimeMillis(); default: throw new IllegalStateException("unknown time domain: " + timeDomain); } } }
TimeSelector
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/sort/BucketedSort.java
{ "start": 27244, "end": 28259 }
class ____ extends BucketedSort.Leaf { protected Leaf(LeafReaderContext ctx) { super(ctx); } /** * Return the value for of this sort for the document to which * we just {@link #advanceExact(int) moved}. This should be fast * because it is called twice per competitive hit when in heap * mode, once for {@link #docBetterThan(long)} and once * for {@link #setIndexToDocValue(long)}. */ protected abstract int docValue(); @Override public final void setScorer(Scorable scorer) {} @Override protected final void setIndexToDocValue(long index) { values.set(index, docValue()); } @Override protected final boolean docBetterThan(long index) { return getOrder().reverseMul() * Integer.compare(docValue(), values.get(index)) < 0; } } } }
Leaf
java
elastic__elasticsearch
modules/transport-netty4/src/test/java/org/elasticsearch/http/netty4/Netty4HttpRequestTests.java
{ "start": 1007, "end": 3365 }
class ____ extends ESTestCase { public void testEmptyFullContent() { final var request = new Netty4HttpRequest(0, new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"), HttpBody.empty()); assertFalse(request.hasContent()); } public void testEmptyStreamContent() { final var request = new Netty4HttpRequest( 0, new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"), new FakeHttpBodyStream() ); assertFalse(request.hasContent()); } public void testNonEmptyFullContent() { final var len = between(1, 1024); final var request = new Netty4HttpRequest( 0, new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, "/", new DefaultHttpHeaders().add(HttpHeaderNames.CONTENT_LENGTH, len) ), HttpBody.fromBytesReference(new BytesArray(new byte[len])) ); assertTrue(request.hasContent()); } public void testNonEmptyStreamContent() { final var len = between(1, 1024); final var nettyRequestWithLen = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); HttpUtil.setContentLength(nettyRequestWithLen, len); final var requestWithLen = new Netty4HttpRequest(0, nettyRequestWithLen, new FakeHttpBodyStream()); assertTrue(requestWithLen.hasContent()); final var nettyChunkedRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", new DefaultHttpHeaders()); HttpUtil.setTransferEncodingChunked(nettyChunkedRequest, true); final var chunkedRequest = new Netty4HttpRequest(0, nettyChunkedRequest, new FakeHttpBodyStream()); assertTrue(chunkedRequest.hasContent()); } public void testReplaceContent() { final var len = between(1, 1024); final var nettyRequestWithLen = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"); HttpUtil.setContentLength(nettyRequestWithLen, len); final var streamRequest = new Netty4HttpRequest(0, nettyRequestWithLen, new FakeHttpBodyStream()); streamRequest.setBody(HttpBody.fromBytesReference(randomBytesReference(len))); assertTrue(streamRequest.hasContent()); } }
Netty4HttpRequestTests
java
google__dagger
javatests/dagger/functional/builder/BuilderTest.java
{ "start": 3377, "end": 4086 }
interface ____ extends TestChildComponentWithBuilderInterface.SharedBuilder< Builder, TestChildComponentWithBuilderInterface, StringModule, IntModuleIncludingDoubleAndFloat> { @Override Builder setM2(IntModuleIncludingDoubleAndFloat m2); // Test covariant overrides @Override void setM3(DoubleModule doubleModule); // Test simple overrides allowed void set(ByteModule byteModule); // Note we're missing LongModule -- it's implicit } } @Component( modules = {StringModule.class, IntModuleIncludingDoubleAndFloat.class, LongModule.class}, dependencies = DepComponent.class) abstract static
Builder
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/cdi/PersonRepository.java
{ "start": 769, "end": 854 }
interface ____ { List<Person> findAll(); void save(Person person); }
PersonRepository
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/rules/action/PutQueryRuleActionResponseSerializingTests.java
{ "start": 573, "end": 1484 }
class ____ extends AbstractBWCWireSerializationTestCase<PutQueryRuleAction.Response> { @Override protected Writeable.Reader<PutQueryRuleAction.Response> instanceReader() { return PutQueryRuleAction.Response::new; } @Override protected PutQueryRuleAction.Response createTestInstance() { return new PutQueryRuleAction.Response(randomFrom(DocWriteResponse.Result.values())); } @Override protected PutQueryRuleAction.Response mutateInstance(PutQueryRuleAction.Response instance) throws IOException { return new PutQueryRuleAction.Response(randomValueOtherThan(instance.result, () -> randomFrom(DocWriteResponse.Result.values()))); } @Override protected PutQueryRuleAction.Response mutateInstanceForVersion(PutQueryRuleAction.Response instance, TransportVersion version) { return instance; } }
PutQueryRuleActionResponseSerializingTests
java
quarkusio__quarkus
extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/JKSKeyStoreWithOverriddenCredentialsProviderTest.java
{ "start": 1004, "end": 2273 }
class ____ { private static final String configuration = """ quarkus.tls.key-store.jks.path=target/certs/test-credentials-provider-keystore.jks quarkus.tls.key-store.jks.password=secret123! quarkus.tls.key-store.credentials-provider.name=tls """; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addClass(MyCredentialProvider.class) .add(new StringAsset(configuration), "application.properties")); @Inject TlsConfigurationRegistry certificates; @Test void test() throws KeyStoreException, CertificateParsingException { TlsConfiguration def = certificates.getDefault().orElseThrow(); X509Certificate certificate = (X509Certificate) def.getKeyStore().getCertificate("test-credentials-provider"); assertThat(certificate).isNotNull(); assertThat(certificate.getSubjectAlternativeNames()).anySatisfy(l -> { assertThat(l.get(0)).isEqualTo(2); assertThat(l.get(1)).isEqualTo("localhost"); }); } @ApplicationScoped public static
JKSKeyStoreWithOverriddenCredentialsProviderTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/ContainerLogsUtils.java
{ "start": 2068, "end": 7765 }
class ____ { public static final Logger LOG = LoggerFactory.getLogger(ContainerLogsUtils.class); /** * Finds the local directories that logs for the given container are stored * on. */ public static List<File> getContainerLogDirs(ContainerId containerId, String remoteUser, Context context) throws YarnException { Container container = context.getContainers().get(containerId); Application application = getApplicationForContainer(containerId, context); checkAccess(remoteUser, application, context); // It is not required to have null check for container ( container == null ) // and throw back exception.Because when container is completed, NodeManager // remove container information from its NMContext.Configuring log // aggregation to false, container log view request is forwarded to NM. NM // does not have completed container information,but still NM serve request for // reading container logs. if (container != null) { checkState(container.getContainerState()); } return getContainerLogDirs(containerId, context.getLocalDirsHandler()); } static List<File> getContainerLogDirs(ContainerId containerId, LocalDirsHandlerService dirsHandler) throws YarnException { List<String> logDirs = dirsHandler.getLogDirsForRead(); List<File> containerLogDirs = new ArrayList<File>(logDirs.size()); for (String logDir : logDirs) { logDir = new File(logDir).toURI().getPath(); String appIdStr = containerId .getApplicationAttemptId().getApplicationId().toString(); File appLogDir = new File(logDir, appIdStr); containerLogDirs.add(new File(appLogDir, containerId.toString())); } return containerLogDirs; } /** * Finds the log file with the given filename for the given container. */ public static File getContainerLogFile(ContainerId containerId, String fileName, String remoteUser, Context context) throws YarnException { Container container = context.getContainers().get(containerId); Application application = getApplicationForContainer(containerId, context); checkAccess(remoteUser, application, context); if (container != null) { checkState(container.getContainerState()); } try { LocalDirsHandlerService dirsHandler = context.getLocalDirsHandler(); String relativeContainerLogDir = ContainerLaunch.getRelativeContainerLogDir( application.getAppId().toString(), containerId.toString()); Path logPath = dirsHandler.getLogPathToRead( relativeContainerLogDir + Path.SEPARATOR + fileName); URI logPathURI = new File(logPath.toString()).toURI(); File logFile = new File(logPathURI.getPath()); return logFile; } catch (IOException e) { LOG.warn("Failed to find log file", e); throw new NotFoundException("Cannot find this log on the local disk."); } } private static Application getApplicationForContainer(ContainerId containerId, Context context) { ApplicationId applicationId = containerId.getApplicationAttemptId() .getApplicationId(); Application application = context.getApplications().get( applicationId); if (application == null) { throw new NotFoundException( "Unknown container. Container either has not started or " + "has already completed or " + "doesn't belong to this node at all."); } return application; } private static void checkAccess(String remoteUser, Application application, Context context) throws YarnException { UserGroupInformation callerUGI = null; if (remoteUser != null) { callerUGI = UserGroupInformation.createRemoteUser(remoteUser); } if (callerUGI != null && !context.getApplicationACLsManager().checkAccess(callerUGI, ApplicationAccessType.VIEW_APP, application.getUser(), application.getAppId())) { throw new YarnException( "User [" + remoteUser + "] is not authorized to view the logs for application " + application.getAppId()); } } private static void checkState(ContainerState state) { if (state == ContainerState.NEW || state == ContainerState.LOCALIZING || state == ContainerState.SCHEDULED) { throw new NotFoundException("Container is not yet running. Current state is " + state); } if (state == ContainerState.LOCALIZATION_FAILED) { throw new NotFoundException("Container wasn't started. Localization failed."); } } public static FileInputStream openLogFileForRead(String containerIdStr, File logFile, Context context) throws IOException { ContainerId containerId = ContainerId.fromString(containerIdStr); ApplicationId applicationId = containerId.getApplicationAttemptId() .getApplicationId(); String user = context.getApplications().get( applicationId).getUser(); try { return SecureIOUtils.openForRead(logFile, user, null); } catch (IOException e) { if (e.getMessage().contains( "did not match expected owner '" + user + "'")) { LOG.error( "Exception reading log file " + logFile.getAbsolutePath(), e); throw new IOException("Exception reading log file. Application submitted by '" + user + "' doesn't own requested log file : " + logFile.getName(), e); } else { throw new IOException("Exception reading log file. It might be because log " + "file was aggregated : " + logFile.getName(), e); } } } }
ContainerLogsUtils
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/spatial/SpatialExtentCartesianPointDocValuesAggregator.java
{ "start": 1263, "end": 1837 }
class ____ extends SpatialExtentAggregator { public static SpatialExtentState initSingle() { return new SpatialExtentState(PointType.CARTESIAN); } public static SpatialExtentGroupingState initGrouping() { return new SpatialExtentGroupingState(PointType.CARTESIAN); } public static void combine(SpatialExtentState current, long v) { current.add(v); } public static void combine(SpatialExtentGroupingState current, int groupId, long v) { current.add(groupId, v); } }
SpatialExtentCartesianPointDocValuesAggregator
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/ClientThrottlingIntercept.java
{ "start": 2089, "end": 6322 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger( ClientThrottlingIntercept.class); private static ClientThrottlingIntercept singleton = null; private ClientThrottlingAnalyzer readThrottler = null; private ClientThrottlingAnalyzer writeThrottler = null; // Hide default constructor private ClientThrottlingIntercept() { readThrottler = new ClientThrottlingAnalyzer("read"); writeThrottler = new ClientThrottlingAnalyzer("write"); LOG.debug("Client-side throttling is enabled for the WASB file system."); } static synchronized void initializeSingleton() { if (singleton == null) { singleton = new ClientThrottlingIntercept(); } } static void hook(OperationContext context) { context.getErrorReceivingResponseEventHandler().addListener( new ErrorReceivingResponseEventHandler()); context.getSendingRequestEventHandler().addListener( new SendingRequestEventHandler()); context.getResponseReceivedEventHandler().addListener( new ResponseReceivedEventHandler()); } private static void updateMetrics(HttpURLConnection conn, RequestResult result) { BlobOperationDescriptor.OperationType operationType = BlobOperationDescriptor.getOperationType(conn); int status = result.getStatusCode(); long contentLength = 0; // If the socket is terminated prior to receiving a response, the HTTP // status may be 0 or -1. A status less than 200 or greater than or equal // to 500 is considered an error. boolean isFailedOperation = (status < HttpURLConnection.HTTP_OK || status >= java.net.HttpURLConnection.HTTP_INTERNAL_ERROR); switch (operationType) { case AppendBlock: case PutBlock: case PutPage: contentLength = BlobOperationDescriptor.getContentLengthIfKnown(conn, operationType); if (contentLength > 0) { singleton.writeThrottler.addBytesTransferred(contentLength, isFailedOperation); } break; case GetBlob: contentLength = BlobOperationDescriptor.getContentLengthIfKnown(conn, operationType); if (contentLength > 0) { singleton.readThrottler.addBytesTransferred(contentLength, isFailedOperation); } break; default: break; } } /** * Called when a network error occurs before the HTTP status and response * headers are received. Client-side throttling uses this to collect metrics. * * @param event The connection, operation, and request state. */ public static void errorReceivingResponse(ErrorReceivingResponseEvent event) { updateMetrics((HttpURLConnection) event.getConnectionObject(), event.getRequestResult()); } /** * Called before the Azure Storage SDK sends a request. Client-side throttling * uses this to suspend the request, if necessary, to minimize errors and * maximize throughput. * * @param event The connection, operation, and request state. */ public static void sendingRequest(SendingRequestEvent event) { BlobOperationDescriptor.OperationType operationType = BlobOperationDescriptor.getOperationType( (HttpURLConnection) event.getConnectionObject()); switch (operationType) { case GetBlob: singleton.readThrottler.suspendIfNecessary(); break; case AppendBlock: case PutBlock: case PutPage: singleton.writeThrottler.suspendIfNecessary(); break; default: break; } } /** * Called after the Azure Storage SDK receives a response. Client-side * throttling uses this to collect metrics. * * @param event The connection, operation, and request state. */ public static void responseReceived(ResponseReceivedEvent event) { updateMetrics((HttpURLConnection) event.getConnectionObject(), event.getRequestResult()); } /** * The ErrorReceivingResponseEvent is fired when the Azure Storage SDK * encounters a network error before the HTTP status and response headers are * received. */ @InterfaceAudience.Private static
ClientThrottlingIntercept
java
bumptech__glide
integration/sqljournaldiskcache/src/main/java/com/bumptech/glide/integration/sqljournaldiskcache/EvictionManager.java
{ "start": 5452, "end": 5697 }
class ____ implements Handler.Callback { @Override public boolean handleMessage(Message msg) { if (msg.what != MessageIds.EVICT) { return false; } evictOnWorkThread(); return true; } } }
EvictionCallback
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/Herder.java
{ "start": 3290, "end": 17613 }
interface ____ { void start(); void stop(); /** * @return whether the worker is ready; i.e., it has completed all initialization and startup * steps such as creating internal topics, joining a cluster, etc. */ boolean isReady(); /** * Check for worker health; i.e., its ability to service external requests from the user such * as creating, reconfiguring, and deleting connectors * @param callback callback to invoke once worker health is assured */ void healthCheck(Callback<Void> callback); /** * Get a list of connectors currently running in this cluster. This is a full list of connectors in the cluster gathered * from the current configuration. * * @param callback callback to invoke with the full list of connector names * @throws org.apache.kafka.connect.runtime.distributed.RequestTargetException if this node can not resolve the request * (e.g., because it has not joined the cluster or does not have configs in sync with the group) and it is * not the leader or the task owner (e.g., task restart must be handled by the worker which owns the task) * @throws org.apache.kafka.connect.errors.ConnectException if this node is the leader, but still cannot resolve the * request (e.g., it is not in sync with other worker's config state) */ void connectors(Callback<Collection<String>> callback); /** * Get the definition and status of a connector. */ void connectorInfo(String connName, Callback<ConnectorInfo> callback); /** * Get the configuration for a connector. * @param connName name of the connector * @param callback callback to invoke with the configuration */ void connectorConfig(String connName, Callback<Map<String, String>> callback); /** * Set the configuration for a connector. This supports creation and updating. * @param connName name of the connector * @param config the connector's configuration * @param allowReplace if true, allow overwriting previous configs; if false, throw {@link AlreadyExistsException} * if a connector with the same name already exists * @param callback callback to invoke when the configuration has been written */ void putConnectorConfig(String connName, Map<String, String> config, boolean allowReplace, Callback<Created<ConnectorInfo>> callback); /** * Set the configuration for a connector, along with a target state optionally. This supports creation and updating. * @param connName name of the connector * @param config the connector's configuration * @param targetState the desired target state for the connector; may be {@code null} if no target state change is desired. Note that the default * target state is {@link TargetState#STARTED} if no target state exists previously * @param allowReplace if true, allow overwriting previous configs; if false, throw {@link AlreadyExistsException} * if a connector with the same name already exists * @param callback callback to invoke when the configuration has been written */ void putConnectorConfig(String connName, Map<String, String> config, TargetState targetState, boolean allowReplace, Callback<Created<ConnectorInfo>> callback); /** * Patch the configuration for a connector. * @param connName name of the connector * @param configPatch the connector's configuration patch. * @param callback callback to invoke when the configuration has been written */ void patchConnectorConfig(String connName, Map<String, String> configPatch, Callback<Created<ConnectorInfo>> callback); /** * Delete a connector and its configuration. * @param connName name of the connector * @param callback callback to invoke when the configuration has been written */ void deleteConnectorConfig(String connName, Callback<Created<ConnectorInfo>> callback); /** * Requests reconfiguration of the tasks of a connector. This should only be triggered by * {@link HerderConnectorContext}. * * @param connName name of the connector that should be reconfigured */ void requestTaskReconfiguration(String connName); /** * Get the configurations for the current set of tasks of a connector. * @param connName name of the connector * @param callback callback to invoke upon completion */ void taskConfigs(String connName, Callback<List<TaskInfo>> callback); /** * Set the configurations for the tasks of a connector. This should always include all tasks in the connector; if * there are existing configurations and fewer are provided, this will reduce the number of tasks, and if more are * provided it will increase the number of tasks. * @param connName connector to update * @param configs list of configurations * @param callback callback to invoke upon completion * @param requestSignature the signature of the request made for this task (re-)configuration; * may be null if no signature was provided */ void putTaskConfigs(String connName, List<Map<String, String>> configs, Callback<Void> callback, InternalRequestSignature requestSignature); /** * Fence out any older task generations for a source connector, and then write a record to the config topic * indicating that it is safe to bring up a new generation of tasks. If that record is already present, do nothing * and invoke the callback successfully. * @param connName the name of the connector to fence out, which must refer to a source connector; if the * connector does not exist or is not a source connector, the callback will be invoked with an error * @param callback callback to invoke upon completion * @param requestSignature the signature of the request made for this connector; * may be null if no signature was provided */ void fenceZombieSourceTasks(String connName, Callback<Void> callback, InternalRequestSignature requestSignature); /** * Get a list of connectors currently running in this cluster. * @return A list of connector names */ Collection<String> connectors(); /** * Get the definition and status of a connector. * @param connName name of the connector */ ConnectorInfo connectorInfo(String connName); /** * Lookup the current status of a connector. * @param connName name of the connector */ ConnectorStateInfo connectorStatus(String connName); /** * Lookup the set of topics currently used by a connector. * * @param connName name of the connector * @return the set of active topics */ ActiveTopicsInfo connectorActiveTopics(String connName); /** * Request to asynchronously reset the active topics for the named connector. * * @param connName name of the connector */ void resetConnectorActiveTopics(String connName); /** * Return a reference to the status backing store used by this herder. * * @return the status backing store used by this herder */ StatusBackingStore statusBackingStore(); /** * Lookup the status of a task. * @param id id of the task */ ConnectorStateInfo.TaskState taskStatus(ConnectorTaskId id); /** * Validate the provided connector config values against the configuration definition. * @param connectorConfig the provided connector config values * @param callback the callback to invoke after validation has completed (successfully or not) */ void validateConnectorConfig(Map<String, String> connectorConfig, Callback<ConfigInfos> callback); /** * Validate the provided connector config values against the configuration definition. * @param connectorConfig the provided connector config values * @param callback the callback to invoke after validation has completed (successfully or not) * @param doLog if true log all the connector configurations at INFO level; if false, no connector configurations are logged. * Note that logging of configuration is not necessary in every endpoint that uses this method. */ default void validateConnectorConfig(Map<String, String> connectorConfig, Callback<ConfigInfos> callback, boolean doLog) { validateConnectorConfig(connectorConfig, callback); } /** * Restart the task with the given id. * @param id id of the task * @param cb callback to invoke upon completion */ void restartTask(ConnectorTaskId id, Callback<Void> cb); /** * Restart the connector. * @param connName name of the connector * @param cb callback to invoke upon completion */ void restartConnector(String connName, Callback<Void> cb); /** * Restart the connector. * @param delayMs delay before restart * @param connName name of the connector * @param cb callback to invoke upon completion * @return The id of the request */ HerderRequest restartConnector(long delayMs, String connName, Callback<Void> cb); /** * Restart the connector and optionally its tasks. * @param request the details of the restart request * @param cb callback to invoke upon completion with the connector state info */ void restartConnectorAndTasks(RestartRequest request, Callback<ConnectorStateInfo> cb); /** * Stop the connector. This call will asynchronously suspend processing by the connector and * shut down all of its tasks. * @param connector name of the connector * @param cb callback to invoke upon completion */ void stopConnector(String connector, Callback<Void> cb); /** * Pause the connector. This call will asynchronously suspend processing by the connector and all * of its tasks. * <p> * Note that, unlike {@link #stopConnector(String, Callback)}, tasks for this connector will not * be shut down and none of their resources will be de-allocated. Instead, they will be left in an * "idling" state where no data is polled from them (if source tasks) or given to them (if sink tasks), * but all internal state kept by the tasks and their resources is left intact and ready to begin * processing records again as soon as the connector is {@link #resumeConnector(String) resumed}. * @param connector name of the connector */ void pauseConnector(String connector); /** * Resume the connector. This call will asynchronously start the connector and its tasks (if * not started already). * @param connector name of the connector */ void resumeConnector(String connector); /** * Returns a handle to the plugin factory used by this herder and its worker. * * @return a reference to the plugin factory. */ Plugins plugins(); /** * Get the cluster ID of the Kafka cluster backing this Connect cluster. * @return the cluster ID of the Kafka cluster backing this connect cluster */ String kafkaClusterId(); /** * Returns the configuration of a plugin * @param pluginName the name of the plugin * @return the list of ConfigKeyInfo of the plugin */ List<ConfigKeyInfo> connectorPluginConfig(String pluginName); List<ConfigKeyInfo> connectorPluginConfig(String pluginName, VersionRange version); /** * Get the current offsets for a connector. * @param connName the name of the connector whose offsets are to be retrieved * @param cb callback to invoke upon completion */ void connectorOffsets(String connName, Callback<ConnectorOffsets> cb); /** * Alter a connector's offsets. * @param connName the name of the connector whose offsets are to be altered * @param offsets a mapping from partitions to offsets that need to be written * @param cb callback to invoke upon completion */ void alterConnectorOffsets(String connName, Map<Map<String, ?>, Map<String, ?>> offsets, Callback<Message> cb); /** * Reset a connector's offsets. * @param connName the name of the connector whose offsets are to be reset * @param cb callback to invoke upon completion */ void resetConnectorOffsets(String connName, Callback<Message> cb); /** * Get the level for a logger. * @param logger the name of the logger to retrieve the level for; may not be null * @return the level for the logger, or null if no logger with the given name exists */ LoggerLevel loggerLevel(String logger); /** * Get the levels for all known loggers. * @return a map of logger name to {@link LoggerLevel}; may be empty, but never null */ Map<String, LoggerLevel> allLoggerLevels(); /** * Set the level for a logging namespace (i.e., a specific logger and all of its children) on this * worker. Changes should only last over the lifetime of the worker, and should be wiped if/when * the worker is restarted. * @param namespace the logging namespace to alter; may not be null * @param level the new level to set for the namespace; may not be null * @return all loggers that were affected by this action; may be empty (including if the specified * level is not a valid logging level), but never null */ List<String> setWorkerLoggerLevel(String namespace, String level); /** * Set the level for a logging namespace (i.e., a specific logger and all of its children) for all workers * in the cluster. Changes should only last over the lifetime of workers, and should be wiped if/when * workers are restarted. * @param namespace the logging namespace to alter; may not be null * @param level the new level to set for the namespace; may not be null */ void setClusterLoggerLevel(String namespace, String level); /** * Get the ConnectMetrics from the worker for this herder * @return the ConnectMetrics */ ConnectMetrics connectMetrics();
Herder
java
spring-projects__spring-framework
spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java
{ "start": 17780, "end": 18516 }
class ____ { @Test void transactionAttributeDeclaredOnGroovyClass() { TransactionAttribute getAgeAttr = getTransactionAttribute(GroovyTestBean.class, ITestBean1.class, "getAge"); assertThat(getAgeAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); TransactionAttribute getNameAttr = getTransactionAttribute(GroovyTestBean.class, ITestBean1.class, "getName"); assertThat(getNameAttr.getPropagationBehavior()).isEqualTo(TransactionAttribute.PROPAGATION_REQUIRED); Method getMetaClassMethod = getMethod(GroovyObject.class, "getMetaClass"); assertThat(attributeSource.getTransactionAttribute(getMetaClassMethod, GroovyTestBean.class)).isNull(); } @Transactional static
GroovyTests
java
apache__camel
components/camel-kubernetes/src/test/java/org/apache/camel/component/kubernetes/consumer/integration/configmaps/KubernetesConfigMapsConsumerLabelsIT.java
{ "start": 1634, "end": 2565 }
class ____ extends KubernetesConsumerTestSupport { @Test public void labelsTest() throws Exception { result.expectedBodiesReceived("ConfigMap cm4 " + ns2 + " ADDED"); createConfigMap(ns2, "cm1", null); createConfigMap(ns2, "cm2", Map.of("otherKey", "otherValue")); createConfigMap(ns1, "cm3", LABELS); createConfigMap(ns2, "cm4", LABELS); result.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { fromF("kubernetes-config-maps://%s?oauthToken=%s&namespace=%s&labelKey=%s&labelValue=%s", host, authToken, ns2, "testkey", "testvalue") .process(new KubernetesProcessor()) .to(result); } }; } }
KubernetesConfigMapsConsumerLabelsIT
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/tier/remote/RemoteTierConsumerAgentTest.java
{ "start": 2120, "end": 5183 }
class ____ { @TempDir private File tempFolder; private String remoteStoragePath; @BeforeEach void before() { remoteStoragePath = Path.fromLocalFile(tempFolder).getPath(); } @Test void testGetEmptyBuffer() { TieredStoragePartitionId partitionId = new TieredStoragePartitionId(new ResultPartitionID()); RemoteTierConsumerAgent remoteTierConsumerAgent = new RemoteTierConsumerAgent( Collections.singletonList( new TieredStorageConsumerSpec( 0, partitionId, new TieredStorageInputChannelId(0), new ResultSubpartitionIndexSet(0))), new RemoteStorageScanner(remoteStoragePath), new TestingPartitionFileReader.Builder().build(), 1024); assertThat( remoteTierConsumerAgent.getNextBuffer( partitionId, new TieredStorageSubpartitionId(0), 0)) .isEmpty(); } @Test void testGetBuffer() { int bufferSize = 10; TieredStoragePartitionId partitionId = new TieredStoragePartitionId(new ResultPartitionID()); PartitionFileReader partitionFileReader = new TestingPartitionFileReader.Builder() .setReadBufferSupplier( (bufferIndex, segmentId) -> new PartitionFileReader.ReadBufferResult( Collections.singletonList( BufferBuilderTestUtils.buildSomeBuffer( bufferSize)), false, null)) .build(); RemoteTierConsumerAgent remoteTierConsumerAgent = new RemoteTierConsumerAgent( Collections.singletonList( new TieredStorageConsumerSpec( 0, partitionId, new TieredStorageInputChannelId(0), new ResultSubpartitionIndexSet(0))), new RemoteStorageScanner(remoteStoragePath), partitionFileReader, 1024); Optional<Buffer> optionalBuffer = remoteTierConsumerAgent.getNextBuffer( partitionId, new TieredStorageSubpartitionId(0), 0); assertThat(optionalBuffer) .hasValueSatisfying( buffer -> assertThat(buffer.readableBytes()).isEqualTo(bufferSize)); } }
RemoteTierConsumerAgentTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/server/Server.java
{ "start": 1593, "end": 3036 }
class ____ standard configuration, logging and {@link Service} * lifecyle management. * <p> * A Server normally has a home directory, a configuration directory, a temp * directory and logs directory. * <p> * The Server configuration is loaded from 2 overlapped files, * <code>#SERVER#-default.xml</code> and <code>#SERVER#-site.xml</code>. The * default file is loaded from the classpath, the site file is laoded from the * configuration directory. * <p> * The Server collects all configuration properties prefixed with * <code>#SERVER#</code>. The property names are then trimmed from the * <code>#SERVER#</code> prefix. * <p> * The Server log configuration is loaded from the * <code>#SERVICE#-log4j.properties</code> file in the configuration directory. * <p> * The lifecycle of server is defined in by {@link Server.Status} enum. * When a server is create, its status is UNDEF, when being initialized it is * BOOTING, once initialization is complete by default transitions to NORMAL. * The <code>#SERVER#.startup.status</code> configuration property can be used * to specify a different startup status (NORMAL, ADMIN or HALTED). * <p> * Services classes are defined in the <code>#SERVER#.services</code> and * <code>#SERVER#.services.ext</code> properties. They are loaded in order * (services first, then services.ext). * <p> * Before initializing the services, they are traversed and duplicate service *
provides
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletImpl.java
{ "start": 2719, "end": 5189 }
class ____<T extends __> implements _Child { private final String name; private final T parent; // short cut for parent element private final EnumSet<EOpt> opts; // element options private boolean started = false; private boolean attrsClosed = false; EImp(String name, T parent, EnumSet<EOpt> opts) { this.name = name; this.parent = parent; this.opts = opts; } @Override public T __() { closeAttrs(); --nestLevel; printEndTag(name, opts); return parent; } protected void _p(boolean quote, Object... args) { closeAttrs(); for (Object s : args) { if (!opts.contains(PRE)) { indent(opts); } out.print(quote ? escapeHtml4(String.valueOf(s)) : String.valueOf(s)); if (!opts.contains(INLINE) && !opts.contains(PRE)) { out.println(); } } } protected void _v(Class<? extends SubView> cls) { closeAttrs(); subView(cls); } protected void closeAttrs() { if (!attrsClosed) { startIfNeeded(); ++nestLevel; out.print('>'); if (!opts.contains(INLINE) && !opts.contains(PRE)) { out.println(); } attrsClosed = true; } } protected void addAttr(String name, String value) { checkState(!attrsClosed, "attribute added after content"); startIfNeeded(); printAttr(name, value); } protected void addAttr(String name, Object value) { addAttr(name, String.valueOf(value)); } protected void addMediaAttr(String name, EnumSet<Media> media) { // 6.13 comma-separated list addAttr(name, CJ.join(media)); } protected void addRelAttr(String name, EnumSet<LinkType> types) { // 6.12 space-separated list addAttr(name, SJ.join(types)); } private void startIfNeeded() { if (!started) { printStartTag(name, opts); started = true; } } protected void _inline(boolean choice) { if (choice) { opts.add(INLINE); } else { opts.remove(INLINE); } } protected void _endTag(boolean choice) { if (choice) { opts.add(ENDTAG); } else { opts.remove(ENDTAG); } } protected void _pre(boolean choice) { if (choice) { opts.add(PRE); } else { opts.remove(PRE); } } } public
EImp
java
alibaba__druid
core/src/test/java/com/alibaba/druid/sql/DeleteTest.java
{ "start": 231, "end": 566 }
class ____ { @Test public void test() { String sql = "delete a from users a force index(a1) where id < 10"; List<SQLStatement> stmt = SQLUtils.parseStatements(sql, DbType.mysql); System.out.println(stmt.get(0)); System.out.println(SQLUtils.toSQLString(stmt.get(0), DbType.mysql)); } }
DeleteTest
java
apache__camel
components/camel-undertow/src/test/java/org/apache/camel/component/undertow/rest/RestUndertowContentTypeTest.java
{ "start": 1349, "end": 4597 }
class ____ extends BaseUndertowTest { @Test public void testProducerNoContentType() { String out = fluentTemplate.withHeader(Exchange.HTTP_METHOD, "post").withBody("{ \"name\": \"Donald Duck\" }") .to("http://localhost:" + getPort() + "/users/123/update") .request(String.class); assertEquals("{ \"status\": \"ok\" }", out); } @Test public void testProducerContentTypeValid() { String out = fluentTemplate.withHeader(Exchange.CONTENT_TYPE, "application/json") .withHeader(Exchange.HTTP_METHOD, "post").withBody("{ \"name\": \"Donald Duck\" }") .to("http://localhost:" + getPort() + "/users/123/update").request(String.class); assertEquals("{ \"status\": \"ok\" }", out); } @Test public void testProducerContentTypeInvalid() { fluentTemplate = fluentTemplate.withHeader(Exchange.CONTENT_TYPE, "application/xml") .withHeader(Exchange.HTTP_METHOD, "post") .withBody("<name>Donald Duck</name>") .to("http://localhost:" + getPort() + "/users/123/update"); Exception ex = assertThrows(CamelExecutionException.class, () -> fluentTemplate.request(String.class)); HttpOperationFailedException cause = assertIsInstanceOf(HttpOperationFailedException.class, ex.getCause()); assertEquals(415, cause.getStatusCode()); assertEquals("", cause.getResponseBody()); } @Test public void testProducerMultiContentTypeValid() { String out = fluentTemplate.withHeader("Accept", "application/csv") .withHeader(Exchange.HTTP_METHOD, "get") .to("http://localhost:" + getPort() + "/users").request(String.class); assertEquals("Email,FirstName,LastName\ndonald.duck@disney.com,Donald,Duck", out); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { restConfiguration().component("undertow").host("localhost").port(getPort()) // turn on client request validation .clientRequestValidation(true); // use the rest DSL to define the rest services rest("/users").post("/{id}/update").consumes("application/json").produces("application/json").to("direct:update"); from("direct:update") .setBody(constant("{ \"status\": \"ok\" }")); rest("/users").get().produces("application/json,application/csv").to("direct:users"); from("direct:users") .choice() .when(simple("${header.Accept} == 'application/csv'")) .setBody(constant("Email,FirstName,LastName\ndonald.duck@disney.com,Donald,Duck")) .setHeader(Exchange.CONTENT_TYPE, constant("application/csv")) .otherwise() .setBody(constant( "{\"email\": \"donald.duck@disney.com\", \"firstname\": \"Donald\", \"lastname\": \"Duck\"}")); } }; } }
RestUndertowContentTypeTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerSafeMode.java
{ "start": 3746, "end": 23709 }
enum ____ { PENDING_THRESHOLD, /** Pending on more safe blocks or live datanode. */ EXTENSION, /** In extension period. */ OFF /** Safe mode is off. */ } static final Logger LOG = LoggerFactory.getLogger(BlockManagerSafeMode.class); static final Step STEP_AWAITING_REPORTED_BLOCKS = new Step(StepType.AWAITING_REPORTED_BLOCKS); private final BlockManager blockManager; private final Namesystem namesystem; private final boolean haEnabled; private volatile BMSafeModeStatus status = BMSafeModeStatus.OFF; /** Safe mode threshold condition %.*/ private final float threshold; /** Number of blocks needed to satisfy safe mode threshold condition. */ private long blockThreshold; /** Total number of blocks. */ private long blockTotal; /** Number of safe blocks. */ private long blockSafe; /** Safe mode minimum number of datanodes alive. */ private final int datanodeThreshold; /** Min replication required by safe mode. */ private final int safeReplication; /** Threshold for populating needed replication queues. */ private final float replQueueThreshold; /** Number of blocks needed before populating replication queues. */ private long blockReplQueueThreshold; /** How long (in ms) is the extension period. */ @VisibleForTesting final long extension; /** Timestamp of the first time when thresholds are met. */ private final AtomicLong reachedTime = new AtomicLong(); /** Timestamp of the safe mode initialized. */ private long startTime; /** the safe mode monitor thread. */ private final Daemon smmthread; /** time of the last status printout */ private long lastStatusReport; /** Counter for tracking startup progress of reported blocks. */ private Counter awaitingReportedBlocksCounter; /** Keeps track of how many bytes are in Future Generation blocks. */ private final LongAdder bytesInFutureBlocks = new LongAdder(); private final LongAdder bytesInFutureECBlockGroups = new LongAdder(); /** Reports if Name node was started with Rollback option. */ private final boolean inRollBack; BlockManagerSafeMode(BlockManager blockManager, Namesystem namesystem, boolean haEnabled, Configuration conf) { this.blockManager = blockManager; this.namesystem = namesystem; this.haEnabled = haEnabled; this.threshold = conf.getFloat(DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY, DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_DEFAULT); if (this.threshold > 1.0) { LOG.warn("The threshold value shouldn't be greater than 1, " + "threshold: {}", threshold); } this.datanodeThreshold = conf.getInt( DFS_NAMENODE_SAFEMODE_MIN_DATANODES_KEY, DFS_NAMENODE_SAFEMODE_MIN_DATANODES_DEFAULT); int minReplication = conf.getInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_DEFAULT); // DFS_NAMENODE_SAFEMODE_REPLICATION_MIN_KEY is an expert level setting, // setting this lower than the min replication is not recommended // and/or dangerous for production setups. // When it's unset, safeReplication will use dfs.namenode.replication.min this.safeReplication = conf.getInt(DFSConfigKeys.DFS_NAMENODE_SAFEMODE_REPLICATION_MIN_KEY, minReplication); // default to safe mode threshold (i.e., don't populate queues before // leaving safe mode) this.replQueueThreshold = conf.getFloat(DFS_NAMENODE_REPL_QUEUE_THRESHOLD_PCT_KEY, threshold); this.extension = conf.getTimeDuration(DFS_NAMENODE_SAFEMODE_EXTENSION_KEY, DFS_NAMENODE_SAFEMODE_EXTENSION_DEFAULT, MILLISECONDS); this.inRollBack = isInRollBackMode(NameNode.getStartupOption(conf)); this.smmthread = new Daemon(new SafeModeMonitor(conf)); LOG.info("{} = {}", DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY, threshold); LOG.info("{} = {}", DFS_NAMENODE_SAFEMODE_MIN_DATANODES_KEY, datanodeThreshold); LOG.info("{} = {}", DFS_NAMENODE_SAFEMODE_EXTENSION_KEY, extension); } /** * Initialize the safe mode information. * @param total initial total blocks */ void activate(long total) { assert namesystem.hasWriteLock(RwLockMode.BM); assert status == BMSafeModeStatus.OFF; startTime = monotonicNow(); setBlockTotal(total); if (areThresholdsMet()) { boolean exitResult = leaveSafeMode(false); Preconditions.checkState(exitResult, "Failed to leave safe mode."); } else { // enter safe mode status = BMSafeModeStatus.PENDING_THRESHOLD; initializeReplQueuesIfNecessary(); reportStatus("STATE* Safe mode ON.", true); lastStatusReport = monotonicNow(); } } /** * @return true if it stays in start up safe mode else false. */ boolean isInSafeMode() { if (status != BMSafeModeStatus.OFF) { doConsistencyCheck(); return true; } else { return false; } } /** * The transition of the safe mode state machine. * If safe mode is not currently on, this is a no-op. */ void checkSafeMode() { assert namesystem.hasWriteLock(RwLockMode.BM); if (namesystem.inTransitionToActive()) { return; } switch (status) { case PENDING_THRESHOLD: if (areThresholdsMet()) { if (blockTotal > 0 && extension > 0) { // PENDING_THRESHOLD -> EXTENSION status = BMSafeModeStatus.EXTENSION; reachedTime.set(monotonicNow()); smmthread.start(); initializeReplQueuesIfNecessary(); reportStatus("STATE* Safe mode extension entered.", true); } else { // TODO: let the smmthread to leave the safemode. // PENDING_THRESHOLD -> OFF leaveSafeMode(false); } } else { initializeReplQueuesIfNecessary(); reportStatus("STATE* Safe mode ON.", false); } break; case EXTENSION: reportStatus("STATE* Safe mode ON.", false); break; case OFF: break; default: assert false : "Non-recognized block manager safe mode status: " + status; } } /** * Adjust the total number of blocks safe and expected during safe mode. * If safe mode is not currently on, this is a no-op. * @param deltaSafe the change in number of safe blocks * @param deltaTotal the change in number of total blocks expected */ void adjustBlockTotals(int deltaSafe, int deltaTotal) { assert namesystem.hasWriteLock(RwLockMode.BM); if (!isSafeModeTrackingBlocks()) { return; } long newBlockTotal; synchronized (this) { LOG.debug("Adjusting block totals from {}/{} to {}/{}", blockSafe, blockTotal, blockSafe + deltaSafe, blockTotal + deltaTotal); assert blockSafe + deltaSafe >= 0 : "Can't reduce blockSafe " + blockSafe + " by " + deltaSafe + ": would be negative"; assert blockTotal + deltaTotal >= 0 : "Can't reduce blockTotal " + blockTotal + " by " + deltaTotal + ": would be negative"; blockSafe += deltaSafe; newBlockTotal = blockTotal + deltaTotal; } setBlockTotal(newBlockTotal); checkSafeMode(); } /** * Should we track blocks in safe mode. * <p/> * Never track blocks incrementally in non-HA code. * <p/> * In the HA case, the StandbyNode can be in safemode while the namespace * is modified by the edit log tailer. In this case, the number of total * blocks changes as edits are processed (eg blocks are added and deleted). * However, we don't want to do the incremental tracking during the * startup-time loading process -- only once the initial total has been * set after the image has been loaded. */ boolean isSafeModeTrackingBlocks() { assert namesystem.hasWriteLock(RwLockMode.BM); return haEnabled && status != BMSafeModeStatus.OFF; } /** * Set total number of blocks. */ void setBlockTotal(long total) { assert namesystem.hasWriteLock(RwLockMode.BM); synchronized (this) { this.blockTotal = total; this.blockThreshold = (long) (total * threshold); } this.blockReplQueueThreshold = (long) (total * replQueueThreshold); } String getSafeModeTip() { StringBuilder msg = new StringBuilder(); boolean isBlockThresholdMet = false; synchronized (this) { isBlockThresholdMet = (blockSafe >= blockThreshold); if (!isBlockThresholdMet) { msg.append(String.format( "The reported blocks %d needs additional %d" + " blocks to reach the threshold %.4f of total blocks %d.%n", blockSafe, (blockThreshold - blockSafe), threshold, blockTotal)); } else { msg.append(String.format( "The reported blocks %d has reached the threshold %.4f of total" + " blocks %d. ", blockSafe, threshold, blockTotal)); } } if (datanodeThreshold > 0) { if (isBlockThresholdMet) { int numLive = blockManager.getDatanodeManager().getNumLiveDataNodes(); if (numLive < datanodeThreshold) { msg.append(String.format( "The number of live datanodes %d needs an additional %d live " + "datanodes to reach the minimum number %d.%n", numLive, (datanodeThreshold - numLive), datanodeThreshold)); } else { msg.append(String.format( "The number of live datanodes %d has reached the minimum number" + " %d. ", numLive, datanodeThreshold)); } } else { msg.append("The number of live datanodes is not calculated ") .append("since reported blocks hasn't reached the threshold. "); } } else { msg.append("The minimum number of live datanodes is not required. "); } if (getBytesInFuture() > 0) { msg.append("Name node detected blocks with generation stamps in future. ") .append("This means that Name node metadata is inconsistent. This ") .append("can happen if Name node metadata files have been manually ") .append("replaced. Exiting safe mode will cause loss of ") .append(getBytesInFuture()) .append(" byte(s). Please restart name node with right metadata ") .append("or use \"hdfs dfsadmin -safemode forceExit\" if you ") .append("are certain that the NameNode was started with the correct ") .append("FsImage and edit logs. If you encountered this during ") .append("a rollback, it is safe to exit with -safemode forceExit."); return msg.toString(); } final String turnOffTip = "Safe mode will be turned off automatically "; switch(status) { case PENDING_THRESHOLD: msg.append(turnOffTip).append("once the thresholds have been reached."); break; case EXTENSION: msg.append("In safe mode extension. ").append(turnOffTip).append("in ") .append(timeToLeaveExtension() / 1000).append(" seconds."); break; case OFF: msg.append(turnOffTip).append("soon."); break; default: assert false : "Non-recognized block manager safe mode status: " + status; } return msg.toString(); } /** * Leave start up safe mode. * * @param force - true to force exit * @return true if it leaves safe mode successfully else false */ boolean leaveSafeMode(boolean force) { assert namesystem.hasWriteLock(RwLockMode.BM) : "Leaving safe mode needs write lock!"; final long bytesInFuture = getBytesInFuture(); if (bytesInFuture > 0) { if (force) { LOG.warn("Leaving safe mode due to forceExit. This will cause a data " + "loss of {} byte(s).", bytesInFuture); bytesInFutureBlocks.reset(); bytesInFutureECBlockGroups.reset(); } else { LOG.error("Refusing to leave safe mode without a force flag. " + "Exiting safe mode will cause a deletion of {} byte(s). Please " + "use -forceExit flag to exit safe mode forcefully if data loss is" + " acceptable.", bytesInFuture); return false; } } else if (force) { LOG.warn("forceExit used when normal exist would suffice. Treating " + "force exit as normal safe mode exit."); } // if not done yet, initialize replication queues. // In the standby, do not populate repl queues if (!blockManager.isPopulatingReplQueues() && blockManager.shouldPopulateReplQueues()) { blockManager.initializeReplQueues(); } if (status != BMSafeModeStatus.OFF) { NameNode.stateChangeLog.info("STATE* Safe mode is OFF"); } status = BMSafeModeStatus.OFF; final long timeInSafemode = monotonicNow() - startTime; NameNode.stateChangeLog.info("STATE* Leaving safe mode after {} secs", timeInSafemode / 1000); NameNode.getNameNodeMetrics().setSafeModeTime(timeInSafemode); final NetworkTopology nt = blockManager.getDatanodeManager() .getNetworkTopology(); NameNode.stateChangeLog.info("STATE* Network topology has {} racks and {}" + " datanodes", nt.getNumOfRacks(), nt.getNumOfLeaves()); NameNode.stateChangeLog.info("STATE* UnderReplicatedBlocks has {} blocks", blockManager.numOfUnderReplicatedBlocks()); namesystem.startSecretManagerIfNecessary(); // If startup has not yet completed, end safemode phase. StartupProgress prog = NameNode.getStartupProgress(); if (prog.getStatus(Phase.SAFEMODE) != Status.COMPLETE) { prog.endStep(Phase.SAFEMODE, BlockManagerSafeMode.STEP_AWAITING_REPORTED_BLOCKS); prog.endPhase(Phase.SAFEMODE); } namesystem.checkAndProvisionSnapshotTrashRoots(); return true; } /** * Increment number of safe blocks if the current block is contiguous * and it has reached minimal replication or * if the current block is striped and the number of its actual data blocks * reaches the number of data units specified by the erasure coding policy. * If safe mode is not currently on, this is a no-op. * @param storageNum current number of replicas or number of internal blocks * of a striped block group * @param storedBlock current storedBlock which is either a * BlockInfoContiguous or a BlockInfoStriped */ synchronized void incrementSafeBlockCount(int storageNum, BlockInfo storedBlock) { assert namesystem.hasWriteLock(RwLockMode.BM); if (status == BMSafeModeStatus.OFF) { return; } final int safeNumberOfNodes = storedBlock.isStriped() ? ((BlockInfoStriped)storedBlock).getRealDataBlockNum() : safeReplication; if (storageNum == safeNumberOfNodes) { this.blockSafe++; // Report startup progress only if we haven't completed startup yet. StartupProgress prog = NameNode.getStartupProgress(); if (prog.getStatus(Phase.SAFEMODE) != Status.COMPLETE) { if (this.awaitingReportedBlocksCounter == null) { this.awaitingReportedBlocksCounter = prog.getCounter(Phase.SAFEMODE, STEP_AWAITING_REPORTED_BLOCKS); } this.awaitingReportedBlocksCounter.increment(); } checkSafeMode(); } } /** * Decrement number of safe blocks if the current block is contiguous * and it has just fallen below minimal replication or * if the current block is striped and its actual data blocks has just fallen * below the number of data units specified by erasure coding policy. * If safe mode is not currently on, this is a no-op. */ synchronized void decrementSafeBlockCount(BlockInfo b) { assert namesystem.hasWriteLock(RwLockMode.BM); if (status == BMSafeModeStatus.OFF) { return; } final int safeNumberOfNodes = b.isStriped() ? ((BlockInfoStriped)b).getRealDataBlockNum() : safeReplication; BlockInfo storedBlock = blockManager.getStoredBlock(b); if (storedBlock.isComplete() && blockManager.countNodes(b).liveReplicas() == safeNumberOfNodes - 1) { this.blockSafe--; assert blockSafe >= 0; checkSafeMode(); } } /** * Check if the block report replica has a generation stamp (GS) in future. * If safe mode is not currently on, this is a no-op. * * @param brr block report replica which belongs to no file in BlockManager */ void checkBlocksWithFutureGS(BlockReportReplica brr) { assert namesystem.hasWriteLock(RwLockMode.BM); if (status == BMSafeModeStatus.OFF) { return; } if (!blockManager.getShouldPostponeBlocksFromFuture() && !inRollBack && blockManager.isGenStampInFuture(brr)) { if (blockManager.getBlockIdManager().isStripedBlock(brr)) { bytesInFutureECBlockGroups.add(brr.getBytesOnDisk()); } else { bytesInFutureBlocks.add(brr.getBytesOnDisk()); } } } /** * Returns the number of bytes that reside in blocks with Generation Stamps * greater than generation stamp known to Namenode. * * @return Bytes in future */ long getBytesInFuture() { return getBytesInFutureBlocks() + getBytesInFutureECBlockGroups(); } long getBytesInFutureBlocks() { return bytesInFutureBlocks.longValue(); } long getBytesInFutureECBlockGroups() { return bytesInFutureECBlockGroups.longValue(); } void close() { assert namesystem.hasWriteLock(RwLockMode.GLOBAL) : "Closing bmSafeMode needs write lock!"; try { smmthread.interrupt(); smmthread.join(3000); } catch (InterruptedException ignored) { } } /** * Get time (counting in milliseconds) left to leave extension period. * It should leave safemode at once if blockTotal = 0 rather than wait * extension time (30s by default). * * Negative value indicates the extension period has passed. */ private long timeToLeaveExtension() { return blockTotal > 0 ? reachedTime.get() + extension - monotonicNow() : 0; } /** * Returns true if Namenode was started with a RollBack option. * * @param option - StartupOption * @return boolean */ private static boolean isInRollBackMode(StartupOption option) { return (option == StartupOption.ROLLBACK) || (option == StartupOption.ROLLINGUPGRADE && option.getRollingUpgradeStartupOption() == RollingUpgradeStartupOption.ROLLBACK); } /** Check if we are ready to initialize replication queues. */ private void initializeReplQueuesIfNecessary() { assert namesystem.hasWriteLock(RwLockMode.BM); // Whether it has reached the threshold for initializing replication queues. boolean canInitializeReplQueues = blockManager.shouldPopulateReplQueues() && blockSafe >= blockReplQueueThreshold; if (canInitializeReplQueues && !blockManager.isPopulatingReplQueues() && !haEnabled) { blockManager.initializeReplQueues(); } } /** * @return true if both block and datanode threshold are met else false. */ private boolean areThresholdsMet() { assert namesystem.hasWriteLock(RwLockMode.BM); // Calculating the number of live datanodes is time-consuming // in large clusters. Skip it when datanodeThreshold is zero. // We need to evaluate getNumLiveDataNodes only when // (blockSafe >= blockThreshold) is true and hence moving evaluation // of datanodeNum conditional to isBlockThresholdMet as well synchronized (this) { boolean isBlockThresholdMet = (blockSafe >= blockThreshold); boolean isDatanodeThresholdMet = true; if (isBlockThresholdMet && datanodeThreshold > 0) { int datanodeNum = blockManager.getDatanodeManager(). getNumLiveDataNodes(); isDatanodeThresholdMet = (datanodeNum >= datanodeThreshold); } return isBlockThresholdMet && isDatanodeThresholdMet; } } /** * Checks consistency of the
BMSafeModeStatus
java
google__dagger
javatests/dagger/internal/codegen/ScopingValidationTest.java
{ "start": 28667, "end": 29046 }
interface ____ {", " SimpleType type();", "}"); Source mediumLifetime = CompilerTests.javaSource( "test.ComponentMedium", "package test;", "", "import dagger.Component;", "", "@ScopeB", "@Component(dependencies = ComponentLong.class)", "
ComponentLong
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/SchedulerTestingUtils.java
{ "start": 4775, "end": 25428 }
class ____ { private static final long DEFAULT_CHECKPOINT_TIMEOUT_MS = 10 * 60 * 1000; private static final long RETRY_INTERVAL_MILLIS = 10L; private static final int RETRY_ATTEMPTS = 6000; private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(300); private SchedulerTestingUtils() {} public static DefaultScheduler createScheduler( final JobGraph jobGraph, final ComponentMainThreadExecutor mainThreadExecutor, final ScheduledExecutorService executorService) throws Exception { return new DefaultSchedulerBuilder(jobGraph, mainThreadExecutor, executorService).build(); } public static void enableCheckpointing(final JobGraph jobGraph) { enableCheckpointing(jobGraph, null, null); } public static void enableCheckpointing( final JobGraph jobGraph, @Nullable StateBackend stateBackend, @Nullable CheckpointStorage checkpointStorage) { enableCheckpointing( jobGraph, stateBackend, checkpointStorage, Long.MAX_VALUE, // disable periodical checkpointing false); } public static void enableCheckpointing( final JobGraph jobGraph, @Nullable StateBackend stateBackend, @Nullable CheckpointStorage checkpointStorage, long checkpointInterval, boolean enableCheckpointsAfterTasksFinish) { final CheckpointCoordinatorConfiguration config = new CheckpointCoordinatorConfiguration.CheckpointCoordinatorConfigurationBuilder() .setCheckpointInterval(checkpointInterval) .setCheckpointTimeout(DEFAULT_CHECKPOINT_TIMEOUT_MS) .setMinPauseBetweenCheckpoints(0) .setMaxConcurrentCheckpoints(1) .setCheckpointRetentionPolicy( CheckpointRetentionPolicy.NEVER_RETAIN_AFTER_TERMINATION) .setExactlyOnce(false) .setUnalignedCheckpointsEnabled(false) .setTolerableCheckpointFailureNumber(0) .setCheckpointIdOfIgnoredInFlightData(0) .setEnableCheckpointsAfterTasksFinish(enableCheckpointsAfterTasksFinish) .build(); SerializedValue<StateBackend> serializedStateBackend = null; if (stateBackend != null) { try { serializedStateBackend = new SerializedValue<>(stateBackend); } catch (IOException e) { throw new RuntimeException("could not serialize state backend", e); } } SerializedValue<CheckpointStorage> serializedCheckpointStorage = null; if (checkpointStorage != null) { try { serializedCheckpointStorage = new SerializedValue<>(checkpointStorage); } catch (IOException e) { throw new RuntimeException("could not serialize checkpoint storage", e); } } jobGraph.setSnapshotSettings( new JobCheckpointingSettings( config, serializedStateBackend, TernaryBoolean.UNDEFINED, serializedCheckpointStorage, null)); } public static Collection<ExecutionAttemptID> getAllCurrentExecutionAttempts( SchedulerNG scheduler) { return StreamSupport.stream( scheduler .requestJob() .getArchivedExecutionGraph() .getAllExecutionVertices() .spliterator(), false) .map((vertex) -> vertex.getCurrentExecutionAttempt().getAttemptId()) .collect(Collectors.toList()); } public static ExecutionState getExecutionState( DefaultScheduler scheduler, JobVertexID jvid, int subtask) { final ExecutionJobVertex ejv = getJobVertex(scheduler, jvid); return ejv.getTaskVertices()[subtask].getCurrentExecutionAttempt().getState(); } public static void failExecution(DefaultScheduler scheduler, JobVertexID jvid, int subtask) { final ExecutionAttemptID attemptID = getAttemptId(scheduler, jvid, subtask); scheduler.updateTaskExecutionState( new TaskExecutionState( attemptID, ExecutionState.FAILED, new Exception("test task failure"))); } public static void canceledExecution( DefaultScheduler scheduler, JobVertexID jvid, int subtask) { final ExecutionAttemptID attemptID = getAttemptId(scheduler, jvid, subtask); scheduler.updateTaskExecutionState( new TaskExecutionState( attemptID, ExecutionState.CANCELED, new Exception("test task failure"))); } public static void setExecutionToState( ExecutionState executionState, DefaultScheduler scheduler, JobVertexID jvid, int subtask) { final ExecutionAttemptID attemptID = getAttemptId(scheduler, jvid, subtask); scheduler.updateTaskExecutionState(new TaskExecutionState(attemptID, executionState)); } public static void setAllExecutionsToRunning(final SchedulerNG scheduler) { getAllCurrentExecutionAttempts(scheduler) .forEach( (attemptId) -> { scheduler.updateTaskExecutionState( new TaskExecutionState(attemptId, ExecutionState.INITIALIZING)); scheduler.updateTaskExecutionState( new TaskExecutionState(attemptId, ExecutionState.RUNNING)); }); } public static void setAllExecutionsToCancelled(final DefaultScheduler scheduler) { for (final ExecutionAttemptID attemptId : getAllCurrentExecutionAttempts(scheduler)) { final boolean setToRunning = scheduler.updateTaskExecutionState( new TaskExecutionState(attemptId, ExecutionState.CANCELED)); assertThat(setToRunning).as("could not switch task to RUNNING").isTrue(); } } public static void acknowledgePendingCheckpoint( final DefaultScheduler scheduler, final long checkpointId) throws CheckpointException { final CheckpointCoordinator checkpointCoordinator = getCheckpointCoordinator(scheduler); final JobID jid = scheduler.getJobId(); for (ExecutionAttemptID attemptId : getAllCurrentExecutionAttempts(scheduler)) { final AcknowledgeCheckpoint acknowledgeCheckpoint = new AcknowledgeCheckpoint(jid, attemptId, checkpointId); checkpointCoordinator.receiveAcknowledgeMessage( acknowledgeCheckpoint, "Unknown location"); } } public static void acknowledgePendingCheckpoint( final SchedulerNG scheduler, final int checkpointId, final Map<OperatorID, OperatorSubtaskState> subtaskStateMap) { getAllCurrentExecutionAttempts(scheduler) .forEach( (executionAttemptID) -> { scheduler.acknowledgeCheckpoint( scheduler.requestJob().getJobId(), executionAttemptID, checkpointId, new CheckpointMetrics(), new TaskStateSnapshot(subtaskStateMap)); }); } public static CompletableFuture<CompletedCheckpoint> triggerCheckpoint( DefaultScheduler scheduler) throws Exception { final CheckpointCoordinator checkpointCoordinator = getCheckpointCoordinator(scheduler); return checkpointCoordinator.triggerCheckpoint(false); } public static void acknowledgeCurrentCheckpoint(DefaultScheduler scheduler) { final CheckpointCoordinator checkpointCoordinator = getCheckpointCoordinator(scheduler); assertThat(checkpointCoordinator.getNumberOfPendingCheckpoints()) .as("Coordinator has not ") .isOne(); final PendingCheckpoint pc = checkpointCoordinator.getPendingCheckpoints().values().iterator().next(); // because of races against the async thread in the coordinator, we need to wait here until // the // coordinator state is acknowledged. This can be removed once the CheckpointCoordinator is // executes all actions in the Scheduler's main thread executor. while (pc.getNumberOfNonAcknowledgedOperatorCoordinators() > 0) { try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); fail("interrupted"); } } getAllCurrentExecutionAttempts(scheduler) .forEach( (attemptId) -> scheduler.acknowledgeCheckpoint( pc.getJobId(), attemptId, pc.getCheckpointID(), new CheckpointMetrics(), null)); } @SuppressWarnings("deprecation") public static CheckpointCoordinator getCheckpointCoordinator(SchedulerBase scheduler) { return scheduler.getCheckpointCoordinator(); } public static void waitForJobStatusRunning(final SchedulerNG scheduler) throws Exception { waitUntilCondition( () -> scheduler.requestJobStatus() == JobStatus.RUNNING, RETRY_INTERVAL_MILLIS, RETRY_ATTEMPTS); } public static void waitForCheckpointInProgress(final SchedulerNG scheduler) throws Exception { waitUntilCondition( () -> scheduler .requestCheckpointStats() .getCounts() .getNumberOfInProgressCheckpoints() > 0, RETRY_INTERVAL_MILLIS, RETRY_ATTEMPTS); } public static void waitForCompletedCheckpoint(final SchedulerNG scheduler) throws Exception { waitUntilCondition( () -> scheduler .requestCheckpointStats() .getCounts() .getNumberOfCompletedCheckpoints() > 0, RETRY_INTERVAL_MILLIS, RETRY_ATTEMPTS); } private static ExecutionJobVertex getJobVertex( DefaultScheduler scheduler, JobVertexID jobVertexId) { final ExecutionVertexID id = new ExecutionVertexID(jobVertexId, 0); return scheduler.getExecutionVertex(id).getJobVertex(); } public static ExecutionAttemptID getAttemptId( DefaultScheduler scheduler, JobVertexID jvid, int subtask) { final ExecutionJobVertex ejv = getJobVertex(scheduler, jvid); assert ejv != null; return ejv.getTaskVertices()[subtask].getCurrentExecutionAttempt().getAttemptId(); } // ------------------------------------------------------------------------ public static SlotSharingExecutionSlotAllocatorFactory newSlotSharingExecutionSlotAllocatorFactory() { return newSlotSharingExecutionSlotAllocatorFactory( TestingPhysicalSlotProvider.createWithInfiniteSlotCreation()); } public static SlotSharingExecutionSlotAllocatorFactory newSlotSharingExecutionSlotAllocatorFactory(PhysicalSlotProvider physicalSlotProvider) { return newSlotSharingExecutionSlotAllocatorFactory(physicalSlotProvider, DEFAULT_TIMEOUT); } public static SlotSharingExecutionSlotAllocatorFactory newSlotSharingExecutionSlotAllocatorFactory( PhysicalSlotProvider physicalSlotProvider, Duration allocationTimeout) { return new SlotSharingExecutionSlotAllocatorFactory( physicalSlotProvider, true, new TestingPhysicalSlotRequestBulkChecker(), allocationTimeout, new LocalInputPreferredSlotSharingStrategy.Factory()); } public static SchedulerBase createSchedulerAndDeploy( boolean isAdaptive, JobID jobId, JobVertex producer, JobVertex[] consumers, DistributionPattern distributionPattern, BlobWriter blobWriter, ComponentMainThreadExecutor mainThreadExecutor, ScheduledExecutorService ioExecutor, JobMasterPartitionTracker partitionTracker, ScheduledExecutorService scheduledExecutor, Configuration jobMasterConfiguration) throws Exception { final List<JobVertex> vertices = new ArrayList<>(Collections.singletonList(producer)); IntermediateDataSetID dataSetId = new IntermediateDataSetID(); for (JobVertex consumer : consumers) { connectNewDataSetAsInput( consumer, producer, distributionPattern, ResultPartitionType.BLOCKING, dataSetId, false); vertices.add(consumer); } final SchedulerBase scheduler = createScheduler( isAdaptive, jobId, vertices, blobWriter, mainThreadExecutor, ioExecutor, partitionTracker, scheduledExecutor, jobMasterConfiguration); final ExecutionGraph executionGraph = scheduler.getExecutionGraph(); final TestingLogicalSlotBuilder slotBuilder = new TestingLogicalSlotBuilder(); runUnsafe( () -> { initializeExecutionJobVertex(producer.getID(), executionGraph, isAdaptive); deployTasks(executionGraph, producer.getID(), slotBuilder); }, mainThreadExecutor); waitForTaskDeploymentDescriptorsCreation( Objects.requireNonNull(executionGraph.getJobVertex(producer.getID())) .getTaskVertices()); // Transition upstream vertices into FINISHED runUnsafe(() -> finishJobVertex(executionGraph, producer.getID()), mainThreadExecutor); // Deploy downstream sink vertices for (JobVertex consumer : consumers) { runUnsafe( () -> { initializeExecutionJobVertex(consumer.getID(), executionGraph, isAdaptive); deployTasks(executionGraph, consumer.getID(), slotBuilder); }, mainThreadExecutor); waitForTaskDeploymentDescriptorsCreation( Objects.requireNonNull(executionGraph.getJobVertex(consumer.getID())) .getTaskVertices()); } return scheduler; } private static void initializeExecutionJobVertex( JobVertexID jobVertex, ExecutionGraph executionGraph, final boolean adaptiveSchedulerEnabled) { if (!adaptiveSchedulerEnabled) { // This method call only needed for adaptive scheduler, no-op otherwise. return; } try { executionGraph.initializeJobVertex( executionGraph.getJobVertex(jobVertex), System.currentTimeMillis()); executionGraph.notifyNewlyInitializedJobVertices( Collections.singletonList(executionGraph.getJobVertex(jobVertex))); } catch (JobException exception) { throw new RuntimeException(exception); } } private static DefaultScheduler createScheduler( boolean isAdaptive, JobID jobId, List<JobVertex> jobVertices, BlobWriter blobWriter, ComponentMainThreadExecutor mainThreadExecutor, ScheduledExecutorService ioExecutor, JobMasterPartitionTracker partitionTracker, ScheduledExecutorService scheduledExecutor, Configuration jobMasterConfiguration) throws Exception { final JobGraph jobGraph = JobGraphBuilder.newBatchJobGraphBuilder() .setJobId(jobId) .addJobVertices(jobVertices) .build(); final DefaultSchedulerBuilder builder = new DefaultSchedulerBuilder(jobGraph, mainThreadExecutor, scheduledExecutor) .setRestartBackoffTimeStrategy(new TestRestartBackoffTimeStrategy(true, 0)) .setBlobWriter(blobWriter) .setIoExecutor(ioExecutor) .setPartitionTracker(partitionTracker) .setJobMasterConfiguration(jobMasterConfiguration); return isAdaptive ? builder.buildAdaptiveBatchJobScheduler() : builder.build(); } private static void deployTasks( ExecutionGraph executionGraph, JobVertexID jobVertexID, TestingLogicalSlotBuilder slotBuilder) throws JobException, ExecutionException, InterruptedException { for (ExecutionVertex vertex : Objects.requireNonNull(executionGraph.getJobVertex(jobVertexID)) .getTaskVertices()) { LogicalSlot slot = slotBuilder.createTestingLogicalSlot(); Execution execution = vertex.getCurrentExecutionAttempt(); execution.registerProducedPartitions(slot.getTaskManagerLocation()).get(); execution.transitionState(ExecutionState.SCHEDULED); vertex.tryAssignResource(slot); vertex.deploy(); } } public static TaskExecutionState createFinishedTaskExecutionState( ExecutionAttemptID attemptId, Map<IntermediateResultPartitionID, ResultPartitionBytes> resultPartitionBytes) { return new TaskExecutionState( attemptId, ExecutionState.FINISHED, null, null, new IOMetrics(0, 0, 0, 0, 0, 0, 0, resultPartitionBytes)); } public static TaskExecutionState createFinishedTaskExecutionState( ExecutionAttemptID attemptId) { return createFinishedTaskExecutionState(attemptId, Collections.emptyMap()); } public static TaskExecutionState createFailedTaskExecutionState( ExecutionAttemptID attemptId, Throwable failureCause) { return new TaskExecutionState(attemptId, ExecutionState.FAILED, failureCause); } public static TaskExecutionState createFailedTaskExecutionState(ExecutionAttemptID attemptId) { return createFailedTaskExecutionState(attemptId, new Exception("Expected failure cause")); } public static TaskExecutionState createCanceledTaskExecutionState( ExecutionAttemptID attemptId) { return new TaskExecutionState(attemptId, ExecutionState.CANCELED); } private static void runUnsafe( final RunnableWithException callback, final ComponentMainThreadExecutor executor) { try { CompletableFuture.runAsync( () -> { try { callback.run(); } catch (Throwable e) { throw new RuntimeException( "Exception shouldn't happen here.", e); } }, executor) .join(); } catch (Exception e) { throw new RuntimeException("Exception shouldn't happen here.", e); } } }
SchedulerTestingUtils
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/ft/RestClientFallbackTest.java
{ "start": 831, "end": 1375 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(TestEndpoint.class, Client.class, MyFallback.class) .addAsResource(new StringAsset(setUrlForClass(Client.class)), "application.properties")); @Inject @RestClient Client client; @Test public void testFallbackWasUsed() { assertEquals("pong", client.ping()); } @Path("/test") public static
RestClientFallbackTest
java
apache__dubbo
dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/filter/support/MetricsConsumerFilter.java
{ "start": 1377, "end": 2020 }
class ____ extends MetricsFilter implements ClusterFilter, BaseFilter.Listener { public MetricsConsumerFilter() {} @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { return super.invoke(invoker, invocation, false); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { super.onResponse(appResponse, invoker, invocation, false); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { super.onError(t, invoker, invocation, false); } }
MetricsConsumerFilter
java
alibaba__druid
core/src/main/java/com/alibaba/druid/util/FnvHash.java
{ "start": 688, "end": 9480 }
class ____ { public static final long BASIC = 0xcbf29ce484222325L; public static final long PRIME = 0x100000001b3L; public static long fnv1a_64(String input) { if (input == null) { return 0; } long hash = BASIC; for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); hash ^= c; hash *= PRIME; } return hash; } public static long fnv1a_64(StringBuilder input) { if (input == null) { return 0; } long hash = BASIC; for (int i = 0; i < input.length(); ++i) { char c = input.charAt(i); hash ^= c; hash *= PRIME; } return hash; } public static long fnv1a_64(String input, int offset, int end) { if (input == null) { return 0; } if (input.length() < end) { end = input.length(); } long hash = BASIC; for (int i = offset; i < end; ++i) { char c = input.charAt(i); hash ^= c; hash *= PRIME; } return hash; } public static long fnv1a_64(byte[] input, int offset, int end) { if (input == null) { return 0; } if (input.length < end) { end = input.length; } long hash = BASIC; for (int i = offset; i < end; ++i) { byte c = input[i]; hash ^= c; hash *= PRIME; } return hash; } public static long fnv1a_64(char[] chars) { if (chars == null) { return 0; } long hash = BASIC; for (int i = 0; i < chars.length; ++i) { char c = chars[i]; hash ^= c; hash *= PRIME; } return hash; } /** * lower and normalized and fnv_1a_64 * * @param name the string to calculate the hash code for * @return the 64-bit hash code of the string */ public static long hashCode64(String name) { if (name == null) { return 0; } boolean quote = false; int len = name.length(); if (len > 2) { char c0 = name.charAt(0); char c1 = name.charAt(len - 1); if ((c0 == '`' && c1 == '`') || (c0 == '"' && c1 == '"') || (c0 == '\'' && c1 == '\'') || (c0 == '[' && c1 == ']')) { quote = true; } } if (quote) { return FnvHash.hashCode64(name, 1, len - 1); } else { return FnvHash.hashCode64(name, 0, len); } } public static long fnv1a_64_lower(String key) { long hashCode = BASIC; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } return hashCode; } public static long fnv1a_64_lower(StringBuilder key) { long hashCode = BASIC; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } return hashCode; } public static long fnv1a_64_lower(long basic, StringBuilder key) { long hashCode = basic; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } return hashCode; } public static long hashCode64(String key, int offset, int end) { long hashCode = BASIC; for (int i = offset; i < end; ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } return hashCode; } public static long hashCode64(long basic, String name) { if (name == null) { return basic; } boolean quote = false; int len = name.length(); if (len > 2) { char c0 = name.charAt(0); char c1 = name.charAt(len - 1); if ((c0 == '`' && c1 == '`') || (c0 == '"' && c1 == '"') || (c0 == '\'' && c1 == '\'') || (c0 == '[' && c1 == ']')) { quote = true; } } if (quote) { int offset = 1; int end = len - 1; for (int i = end - 1; i >= 0; --i) { char ch = name.charAt(i); if (ch == ' ') { end--; } else { break; } } return FnvHash.hashCode64(basic, name, offset, end); } else { return FnvHash.hashCode64(basic, name, 0, len); } } public static long hashCode64(long basic, String key, int offset, int end) { long hashCode = basic; for (int i = offset; i < end; ++i) { char ch = key.charAt(i); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } return hashCode; } public static long fnv_32_lower(String key) { long hashCode = 0x811c9dc5; for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); if (ch == '_' || ch == '-') { continue; } if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= 0x01000193; } return hashCode; } public static long[] fnv1a_64_lower(String[] strings, boolean sort) { long[] hashCodes = new long[strings.length]; for (int i = 0; i < strings.length; i++) { hashCodes[i] = fnv1a_64_lower(strings[i]); } if (sort) { Arrays.sort(hashCodes); } return hashCodes; } /** * normalized and lower and fnv1a_64_hash * * @param owner the owner string to include in the hash code calculation (can be null) * @param name the name string to include in the hash code calculation (can be null) * @return the 64-bit hash code calculated from the owner and name strings */ public static long hashCode64(String owner, String name) { long hashCode = BASIC; if (owner != null) { String item = owner; boolean quote = false; int len = item.length(); if (len > 2) { char c0 = item.charAt(0); char c1 = item.charAt(len - 1); if ((c0 == '`' && c1 == '`') || (c0 == '"' && c1 == '"') || (c0 == '\'' && c1 == '\'') || (c0 == '[' && c1 == ']')) { quote = true; } } int start = quote ? 1 : 0; int end = quote ? len - 1 : len; for (int j = start; j < end; ++j) { char ch = item.charAt(j); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } hashCode ^= '.'; hashCode *= PRIME; } if (name != null) { String item = name; boolean quote = false; int len = item.length(); if (len > 2) { char c0 = item.charAt(0); char c1 = item.charAt(len - 1); if ((c0 == '`' && c1 == '`') || (c0 == '"' && c1 == '"') || (c0 == '\'' && c1 == '\'') || (c0 == '[' && c1 == ']')) { quote = true; } } int start = quote ? 1 : 0; int end = quote ? len - 1 : len; for (int j = start; j < end; ++j) { char ch = item.charAt(j); if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; hashCode *= PRIME; } } return hashCode; } public
FnvHash
java
spring-projects__spring-framework
spring-core-test/src/main/java/org/springframework/core/test/tools/DynamicClassLoader.java
{ "start": 6344, "end": 6754 }
class ____ extends URLConnection { private final Supplier<byte[]> bytesSupplier; protected ResourceFileConnection(URL url, Supplier<byte[]> bytesSupplier) { super(url); this.bytesSupplier = bytesSupplier; } @Override public void connect() { } @Override public InputStream getInputStream() { return new ByteArrayInputStream(this.bytesSupplier.get()); } } }
ResourceFileConnection
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/JoinedInheritanceCircularBiDirectionalFetchTest.java
{ "start": 3136, "end": 3463 }
class ____ extends Animal { @OneToMany( mappedBy = "cat", cascade = CascadeType.PERSIST ) private List<Leg> legs = new LinkedList<>(); public List<Leg> getLegs() { return this.legs; } public void addToLegs(Leg person) { legs.add( person ); person.cat = this; } } @Entity( name = "Leg" ) public static
Cat
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/AbstractShowOperation.java
{ "start": 1421, "end": 3693 }
class ____ implements ShowOperation { protected final @Nullable String catalogName; protected final @Nullable String preposition; protected final @Nullable ShowLikeOperator likeOp; public AbstractShowOperation( @Nullable String catalogName, @Nullable String preposition, @Nullable ShowLikeOperator likeOp) { this.catalogName = catalogName; this.preposition = preposition; this.likeOp = likeOp; } protected abstract Collection<String> retrieveDataForTableResult(Context ctx); protected abstract String getOperationName(); protected abstract String getColumnName(); @Override public TableResultInternal execute(Context ctx) { final Collection<String> views = retrieveDataForTableResult(ctx); final String[] rows = views.stream() .filter(row -> ShowLikeOperator.likeFilter(row, likeOp)) .sorted() .toArray(String[]::new); return buildStringArrayResult(getColumnName(), rows); } @Override public String asSummaryString() { StringBuilder builder = new StringBuilder().append(getOperationName()); if (preposition != null) { builder.append(" ").append(getPrepositionSummaryString()); } if (likeOp != null) { builder.append(" ").append(likeOp); } return builder.toString(); } protected String getPrepositionSummaryString() { return String.format("%s %s", preposition, catalogName); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AbstractShowOperation that = (AbstractShowOperation) o; return Objects.equals(catalogName, that.catalogName) && Objects.equals(preposition, that.preposition) && Objects.equals(likeOp, that.likeOp); } @Override public int hashCode() { return Objects.hash(catalogName, preposition, likeOp); } @Override public String toString() { return asSummaryString(); } }
AbstractShowOperation
java
apache__dubbo
dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ArgumentBuilderTest.java
{ "start": 980, "end": 2176 }
class ____ { @Test void index() { ArgumentBuilder builder = ArgumentBuilder.newBuilder(); builder.index(1); Assertions.assertEquals(1, builder.build().getIndex()); } @Test void type() { ArgumentBuilder builder = ArgumentBuilder.newBuilder(); builder.type("int"); Assertions.assertEquals("int", builder.build().getType()); } @Test void callback() { ArgumentBuilder builder = ArgumentBuilder.newBuilder(); builder.callback(true); Assertions.assertTrue(builder.build().isCallback()); builder.callback(false); Assertions.assertFalse(builder.build().isCallback()); } @Test void build() { ArgumentBuilder builder = ArgumentBuilder.newBuilder(); builder.index(1).type("int").callback(true); ArgumentConfig argument1 = builder.build(); ArgumentConfig argument2 = builder.build(); Assertions.assertTrue(argument1.isCallback()); Assertions.assertEquals("int", argument1.getType()); Assertions.assertEquals(1, argument1.getIndex()); Assertions.assertNotSame(argument1, argument2); } }
ArgumentBuilderTest
java
apache__camel
components/camel-aws/camel-aws2-ec2/src/main/java/org/apache/camel/component/aws2/ec2/AWS2EC2Operations.java
{ "start": 856, "end": 1124 }
enum ____ { createAndRunInstances, startInstances, stopInstances, terminateInstances, describeInstances, describeInstancesStatus, rebootInstances, monitorInstances, unmonitorInstances, createTags, deleteTags }
AWS2EC2Operations
java
apache__maven
impl/maven-impl/src/main/java/org/apache/maven/impl/RequestTraceHelper.java
{ "start": 1628, "end": 6099 }
class ____ { /** * Represents a resolver trace containing both Maven and Resolver-specific trace information * @param session The current Maven session * @param context The trace context * @param trace The Resolver-specific trace * @param mvnTrace The Maven-specific trace */ public record ResolverTrace( Session session, String context, RequestTrace trace, org.apache.maven.api.services.RequestTrace mvnTrace) {} /** * Creates a new trace entry and updates the session's current trace * @param session The current Maven session * @param data The data object to associate with the trace * @return A new ResolverTrace containing both Maven and Resolver trace information */ public static ResolverTrace enter(Session session, Object data) { InternalSession iSession = InternalSession.from(session); org.apache.maven.api.services.RequestTrace trace = data instanceof Request<?> req && req.getTrace() != null ? req.getTrace() : new org.apache.maven.api.services.RequestTrace(iSession.getCurrentTrace(), data); iSession.setCurrentTrace(trace); return new ResolverTrace(session, trace.context(), toResolver(trace), trace); } /** * Restores the parent trace as the current trace in the session * @param trace The current resolver trace to exit from */ public static void exit(ResolverTrace trace) { InternalSession iSession = InternalSession.from(trace.session()); iSession.setCurrentTrace(trace.mvnTrace().parent()); } /** * Converts a Resolver trace to a Maven trace * @param context The context string for the new Maven trace * @param trace The Resolver trace to convert * @return A new Maven trace, or null if the input trace was null */ public static org.apache.maven.api.services.RequestTrace toMaven(String context, RequestTrace trace) { if (trace != null) { return new org.apache.maven.api.services.RequestTrace( context, toMaven(context, trace.getParent()), trace.getData()); } else { return null; } } /** * Converts a Maven trace to a Resolver trace * @param trace The Maven trace to convert * @return A new Resolver trace, or null if the input trace was null */ public static RequestTrace toResolver(org.apache.maven.api.services.RequestTrace trace) { if (trace != null) { return RequestTrace.newChild(toResolver(trace.parent()), trace.data()); } else { return null; } } /** * Creates a human-readable interpretation of a request trace * @param detailed If true, includes additional details such as dependency paths * @param requestTrace The trace to interpret * @return A string describing the trace context and relevant details */ public static String interpretTrace(boolean detailed, RequestTrace requestTrace) { while (requestTrace != null) { Object data = requestTrace.getData(); if (data instanceof DependencyRequest request) { return "dependency resolution for " + request; } else if (data instanceof CollectRequest request) { return "dependency collection for " + request; } else if (data instanceof CollectStepData stepData) { String msg = "dependency collection step for " + stepData.getContext(); if (detailed) { msg += ". Path to offending node from root:\n"; msg += stepData.getPath().stream() .map(n -> " -> " + n.toString()) .collect(Collectors.joining("\n")); msg += "\n => " + stepData.getNode(); } return msg; } else if (data instanceof ArtifactDescriptorRequest request) { return "artifact descriptor request for " + request.getArtifact(); } else if (data instanceof ArtifactRequest request) { return "artifact request for " + request.getArtifact(); } else if (data instanceof org.apache.maven.api.model.Plugin plugin) { return "plugin " + plugin.getId(); } requestTrace = requestTrace.getParent(); } return "n/a"; } }
RequestTraceHelper
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-jetty-ssl/src/main/java/smoketest/jetty/ssl/web/SampleController.java
{ "start": 806, "end": 910 }
class ____ { @GetMapping("/") public String helloWorld() { return "Hello World"; } }
SampleController
java
apache__camel
components/camel-mvel/src/generated/java/org/apache/camel/component/mvel/MvelComponentConfigurer.java
{ "start": 731, "end": 3356 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { MvelComponent target = (MvelComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "allowcontextmapall": case "allowContextMapAll": target.setAllowContextMapAll(property(camelContext, boolean.class, value)); return true; case "allowtemplatefromheader": case "allowTemplateFromHeader": target.setAllowTemplateFromHeader(property(camelContext, boolean.class, value)); return true; case "autowiredenabled": case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true; case "contentcache": case "contentCache": target.setContentCache(property(camelContext, boolean.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "allowcontextmapall": case "allowContextMapAll": return boolean.class; case "allowtemplatefromheader": case "allowTemplateFromHeader": return boolean.class; case "autowiredenabled": case "autowiredEnabled": return boolean.class; case "contentcache": case "contentCache": return boolean.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { MvelComponent target = (MvelComponent) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "allowcontextmapall": case "allowContextMapAll": return target.isAllowContextMapAll(); case "allowtemplatefromheader": case "allowTemplateFromHeader": return target.isAllowTemplateFromHeader(); case "autowiredenabled": case "autowiredEnabled": return target.isAutowiredEnabled(); case "contentcache": case "contentCache": return target.isContentCache(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); default: return null; } } }
MvelComponentConfigurer
java
spring-projects__spring-boot
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/ref/DefaultCleaner.java
{ "start": 877, "end": 1356 }
class ____ implements Cleaner { static final DefaultCleaner instance = new DefaultCleaner(); static BiConsumer<Object, Cleanable> tracker; private final java.lang.ref.Cleaner cleaner = java.lang.ref.Cleaner.create(); @Override public Cleanable register(Object obj, Runnable action) { Cleanable cleanable = (action != null) ? this.cleaner.register(obj, action) : null; if (tracker != null) { tracker.accept(obj, cleanable); } return cleanable; } }
DefaultCleaner
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/snapshots/mockstore/BlobStoreWrapper.java
{ "start": 801, "end": 1369 }
class ____ implements BlobStore { private final BlobStore delegate; public BlobStoreWrapper(BlobStore delegate) { this.delegate = delegate; } @Override public BlobContainer blobContainer(BlobPath path) { return delegate.blobContainer(path); } @Override public void close() throws IOException { delegate.close(); } @Override public Map<String, BlobStoreActionStats> stats() { return delegate.stats(); } public BlobStore delegate() { return delegate; } }
BlobStoreWrapper
java
quarkusio__quarkus
integration-tests/no-awt/src/main/java/io/quarkus/awt/it/GraphicsResource.java
{ "start": 712, "end": 3177 }
class ____ { private static final Logger LOG = Logger.getLogger(GraphicsResource.class); @Path("/graphics") @GET public Response graphics(@QueryParam("entrypoint") String entrypoint) throws IOException { if ("IIORegistry".equals(entrypoint)) { IIORegistry.getDefaultInstance() .getServiceProviders(ImageReaderSpi.class, true) .forEachRemaining(reader -> LOG.infof("Available image reader: %s", reader.getDescription(Locale.TAIWAN))); } else if ("GraphicsEnvironment".equals(entrypoint)) { final GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); for (Font f : ge.getAllFonts()) { LOG.info(f.getFamily()); } } else if ("Color".equals(entrypoint)) { final Color[] colors = new Color[] { Color.WHITE, Color.RED, Color.GREEN, Color.BLUE, Color.BLACK, new Color(190, 32, 40, 100), new Color(Color.HSBtoRGB(20, 200, 30)) }; for (Color c : colors) { LOG.infof("Color %s", c.toString()); } } else if ("BufferedImage".equals(entrypoint)) { final Graphics2D g = new BufferedImage(10, 10, BufferedImage.TYPE_3BYTE_BGR).createGraphics(); LOG.infof("Graphics2D: ", g.toString()); } else if ("Transformations".equals(entrypoint)) { final AffineTransform af = AffineTransform.getRotateInstance(Math.toRadians(5), 1, 1); LOG.infof("Transform: %s", af.toString()); } else if ("ConvolveOp".equals(entrypoint)) { final ConvolveOp cop = new ConvolveOp(new Kernel(1, 1, new float[] { 0f }), ConvolveOp.EDGE_NO_OP, null); LOG.infof("ConvolveOp: %s", cop.toString()); } else if ("Path2D".equals(entrypoint)) { final Path2D p = new Path2D.Double(); LOG.infof("Path2D: %s", p.toString()); } else if ("ImageReader".equals(entrypoint)) { final ImageReader p = ImageIO.getImageReadersByFormatName("JPEG").next(); LOG.infof("ImageReader: %s", p.toString()); } else if ("ImageWriter".equals(entrypoint)) { final ImageWriter p = ImageIO.getImageWritersByFormatName("GIF").next(); LOG.infof("ImageWriter: %s", p.toString()); } return Response.ok().build(); } }
GraphicsResource
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/GenericTypeSerializationTest.java
{ "start": 6179, "end": 6833 }
class ____<E, EE> { private final E first; private final EE second; GenericSpecificityWrapper0(E first, EE second) { this.first = first; this.second = second; } public E first() { return first; } public EE second() { return second; } @JsonCreator(mode = JsonCreator.Mode.DELEGATING) public static <F> GenericSpecificityWrapper0<?, F> fromJson(JsonGenericWrapper<Long, F> val) { return new GenericSpecificityWrapper0<>(val.first(), val.second()); } } public static final
GenericSpecificityWrapper0
java
spring-projects__spring-boot
cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/core/VersionCommand.java
{ "start": 1012, "end": 1294 }
class ____ extends AbstractCommand { public VersionCommand() { super("version", "Show the version"); } @Override public ExitStatus run(String... args) { Log.info("Spring CLI v" + getClass().getPackage().getImplementationVersion()); return ExitStatus.OK; } }
VersionCommand
java
quarkusio__quarkus
independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/runner/SerializedApplication.java
{ "start": 4484, "end": 14631 }
class ____ version"); } String mainClass = in.readUTF(); ResourceDirectoryTracker resourceDirectoryTracker = new ResourceDirectoryTracker(); Set<String> parentFirstPackages = new HashSet<>(); int numPaths = in.readUnsignedShort(); ClassLoadingResource[] allClassLoadingResources = new ClassLoadingResource[numPaths]; for (int pathCount = 0; pathCount < numPaths; pathCount++) { String path = in.readUTF(); boolean hasManifest = in.readBoolean(); ManifestInfo info = null; if (hasManifest) { info = new ManifestInfo(readNullableString(in), readNullableString(in), readNullableString(in), readNullableString(in), readNullableString(in), readNullableString(in)); } JarResource resource = new JarResource(info, appRoot.resolve(path)); allClassLoadingResources[pathCount] = resource; int numDirs = in.readUnsignedShort(); for (int i = 0; i < numDirs; ++i) { String dir = in.readUTF(); int j = dir.indexOf('/'); while (j >= 0) { resourceDirectoryTracker.addResourceDir(dir.substring(0, j), resource); j = dir.indexOf('/', j + 1); } resourceDirectoryTracker.addResourceDir(dir, resource); } } int packages = in.readUnsignedShort(); for (int i = 0; i < packages; ++i) { parentFirstPackages.add(in.readUTF()); } Set<String> nonExistentResources = new HashSet<>(); int nonExistentResourcesSize = in.readUnsignedShort(); for (int i = 0; i < nonExistentResourcesSize; i++) { nonExistentResources.add(in.readUTF()); } // this map is populated correctly because the JarResource entries are added to allClassLoadingResources // in the same order as the classpath was written during the writing of the index Map<String, ClassLoadingResource[]> directlyIndexedResourcesIndexMap = new HashMap<>(); int directlyIndexedSize = in.readUnsignedShort(); for (int i = 0; i < directlyIndexedSize; i++) { String resource = in.readUTF(); int indexesSize = in.readUnsignedShort(); ClassLoadingResource[] matchingResources = new ClassLoadingResource[indexesSize]; for (int j = 0; j < indexesSize; j++) { matchingResources[j] = allClassLoadingResources[in.readUnsignedShort()]; } directlyIndexedResourcesIndexMap.put(resource, matchingResources); } RunnerClassLoader runnerClassLoader = new RunnerClassLoader(ClassLoader.getSystemClassLoader(), resourceDirectoryTracker.getResult(), parentFirstPackages, nonExistentResources, FULLY_INDEXED_PATHS, directlyIndexedResourcesIndexMap); for (ClassLoadingResource classLoadingResource : allClassLoadingResources) { classLoadingResource.init(); } return new SerializedApplication(runnerClassLoader, mainClass); } } private static String readNullableString(DataInputStream in) throws IOException { if (in.readBoolean()) { return in.readUTF(); } return null; } /** * @return a List of all resources that exist in the paths that we desire to have fully indexed * (configured via {@code FULLY_INDEXED_PATHS}) */ private static List<String> writeJar(DataOutputStream out, Path jar) throws IOException { try (JarFile zip = new JarFile(jar.toFile())) { Manifest manifest = zip.getManifest(); if (manifest == null) { out.writeBoolean(false); } else { //write the manifest Attributes ma = manifest.getMainAttributes(); if (ma == null) { out.writeBoolean(false); } else { out.writeBoolean(true); writeNullableString(out, ma.getValue(Attributes.Name.SPECIFICATION_TITLE)); writeNullableString(out, ma.getValue(Attributes.Name.SPECIFICATION_VERSION)); writeNullableString(out, ma.getValue(Attributes.Name.SPECIFICATION_VENDOR)); writeNullableString(out, ma.getValue(Attributes.Name.IMPLEMENTATION_TITLE)); writeNullableString(out, ma.getValue(Attributes.Name.IMPLEMENTATION_VERSION)); writeNullableString(out, ma.getValue(Attributes.Name.IMPLEMENTATION_VENDOR)); } } Set<String> dirs = new LinkedHashSet<>(); Map<String, List<String>> fullyIndexedPaths = new LinkedHashMap<>(); Enumeration<? extends ZipEntry> entries = zip.entries(); boolean hasDefaultPackage = false; while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.getName().contains("/")) { hasDefaultPackage = true; if (!entry.getName().isEmpty() && FULLY_INDEXED_PATHS.contains("")) { fullyIndexedPaths.computeIfAbsent("", SerializedApplication::newFullyIndexedPathsValue) .add(entry.getName()); } } else if (!entry.isDirectory()) { //some jars don't have correct directory entries //so we look at the file paths instead //looking at you h2 final int index = entry.getName().lastIndexOf('/'); dirs.add(entry.getName().substring(0, index)); if (entry.getName().startsWith(META_INF_VERSIONS)) { //multi release jar //we add all packages here //they may not be relevant for some versions, but that is fine String part = entry.getName().substring(META_INF_VERSIONS.length()); int slash = part.indexOf("/"); if (slash != -1) { final int subIndex = part.lastIndexOf('/'); if (subIndex != slash) { dirs.add(part.substring(slash + 1, subIndex)); } } } for (int i = 0; i < FULLY_INDEXED_PATHS.size(); i++) { String path = FULLY_INDEXED_PATHS.get(i); if (path.isEmpty()) { continue; } if (entry.getName().startsWith(path)) { fullyIndexedPaths.computeIfAbsent(path, SerializedApplication::newFullyIndexedPathsValue) .add(entry.getName()); } } } } if (hasDefaultPackage) { dirs.add(""); } out.writeShort(dirs.size()); for (String i : dirs) { out.writeUTF(i); } List<String> result = new ArrayList<>(); for (List<String> values : fullyIndexedPaths.values()) { result.addAll(values); } return result; } } private static List<String> newFullyIndexedPathsValue(String ignored) { return new ArrayList<>(10); } private static void collectPackages(Path jar, Set<String> dirs) throws IOException { if (Files.isDirectory(jar)) { //this can only really happen when testing quarkus itself //but is included for completeness Files.walkFileTree(jar, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { dirs.add(jar.relativize(dir).toString()); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); } else { try (JarFile zip = new JarFile(jar.toFile())) { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { //some jars don't have correct directory entries //so we look at the file paths instead //looking at you h2 final int index = entry.getName().lastIndexOf('/'); if (index > 0) { dirs.add(entry.getName().substring(0, index)); } } } } } } private static void writeNullableString(DataOutputStream out, String string) throws IOException { if (string == null) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeUTF(string); } } /** * This
path
java
apache__dubbo
dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/DestinationRuleTest.java
{ "start": 1621, "end": 5068 }
class ____ { @Test void parserTest() { Yaml yaml = new Yaml(); DestinationRule destinationRule = yaml.loadAs( this.getClass().getClassLoader().getResourceAsStream("DestinationRuleTest.yaml"), DestinationRule.class); // apiVersion: service.dubbo.apache.org/v1alpha1 // kind: DestinationRule // metadata: { name: demo-route } // spec: // host: demo // subsets: // - labels: { env-sign: xxx,tag1: hello } // name: isolation // - labels: { env-sign: yyy } // name: testing-trunk // - labels: { env-sign: zzz } // name: testing assertEquals("service.dubbo.apache.org/v1alpha1", destinationRule.getApiVersion()); assertEquals(DESTINATION_RULE_KEY, destinationRule.getKind()); assertEquals("demo-route", destinationRule.getMetadata().get("name")); assertEquals("demo", destinationRule.getSpec().getHost()); assertEquals(3, destinationRule.getSpec().getSubsets().size()); assertEquals("isolation", destinationRule.getSpec().getSubsets().get(0).getName()); assertEquals( 2, destinationRule.getSpec().getSubsets().get(0).getLabels().size()); assertEquals( "xxx", destinationRule.getSpec().getSubsets().get(0).getLabels().get("env-sign")); assertEquals( "hello", destinationRule.getSpec().getSubsets().get(0).getLabels().get("tag1")); assertEquals( "testing-trunk", destinationRule.getSpec().getSubsets().get(1).getName()); assertEquals( 1, destinationRule.getSpec().getSubsets().get(1).getLabels().size()); assertEquals( "yyy", destinationRule.getSpec().getSubsets().get(1).getLabels().get("env-sign")); assertEquals("testing", destinationRule.getSpec().getSubsets().get(2).getName()); assertEquals( 1, destinationRule.getSpec().getSubsets().get(2).getLabels().size()); assertEquals( "zzz", destinationRule.getSpec().getSubsets().get(2).getLabels().get("env-sign")); assertEquals( SimpleLB.ROUND_ROBIN, destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getSimple()); assertEquals( null, destinationRule.getSpec().getTrafficPolicy().getLoadBalancer().getConsistentHash()); } @Test void parserMultiRuleTest() { Yaml yaml = new Yaml(); Yaml yaml2 = new Yaml(); Iterable objectIterable = yaml.loadAll(this.getClass().getClassLoader().getResourceAsStream("DestinationRuleTest2.yaml")); for (Object result : objectIterable) { Map resultMap = (Map) result; if (resultMap.get("kind").equals(DESTINATION_RULE_KEY)) { DestinationRule destinationRule = yaml2.loadAs(yaml2.dump(result), DestinationRule.class); assertNotNull(destinationRule); } else if (resultMap.get(KIND_KEY).equals(VIRTUAL_SERVICE_KEY)) { VirtualServiceRule virtualServiceRule = yaml2.loadAs(yaml2.dump(result), VirtualServiceRule.class); assertNotNull(virtualServiceRule); } } } }
DestinationRuleTest
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/TargetSource.java
{ "start": 1302, "end": 2815 }
interface ____ extends TargetClassAware { /** * Return the type of targets returned by this {@link TargetSource}. * <p>Can return {@code null}, although certain usages of a {@code TargetSource} * might just work with a predetermined target class. * @return the type of targets returned by this {@link TargetSource} */ @Override @Nullable Class<?> getTargetClass(); /** * Will all calls to {@link #getTarget()} return the same object? * <p>In that case, there will be no need to invoke {@link #releaseTarget(Object)}, * and the AOP framework can cache the return value of {@link #getTarget()}. * <p>The default implementation returns {@code false}. * @return {@code true} if the target is immutable * @see #getTarget */ default boolean isStatic() { return false; } /** * Return a target instance. Invoked immediately before the * AOP framework calls the "target" of an AOP method invocation. * @return the target object which contains the joinpoint, * or {@code null} if there is no actual target instance * @throws Exception if the target object can't be resolved */ @Nullable Object getTarget() throws Exception; /** * Release the given target object obtained from the * {@link #getTarget()} method, if any. * <p>The default implementation is empty. * @param target object obtained from a call to {@link #getTarget()} * @throws Exception if the object can't be released */ default void releaseTarget(Object target) throws Exception { } }
TargetSource
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/completable/CompletableLiftTest.java
{ "start": 916, "end": 1537 }
class ____ extends RxJavaTest { @Test public void callbackThrows() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { Completable.complete() .lift(new CompletableOperator() { @Override public CompletableObserver apply(CompletableObserver o) throws Exception { throw new TestException(); } }) .test(); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } }
CompletableLiftTest
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/tasks/StreamTaskTestHarness.java
{ "start": 21147, "end": 22805 }
class ____ extends Thread { private final SupplierWithException<? extends StreamTask<OUT, ?>, Exception> taskFactory; private volatile StreamTask<OUT, ?> task; private volatile Throwable error; TaskThread(SupplierWithException<? extends StreamTask<OUT, ?>, Exception> taskFactory) { super("Task Thread"); this.taskFactory = taskFactory; } @Override public void run() { try { task = taskFactory.get(); task.invoke(); shutdownIOManager(); shutdownMemoryManager(); } catch (Throwable throwable) { this.error = throwable; } finally { try { task.cleanUp(this.error); } catch (Exception cleanUpException) { if (this.error == null) { this.error = cleanUpException; } else { this.error.addSuppressed(cleanUpException); } } } } public Throwable getError() { return error; } } static TaskMetricGroup createTaskMetricGroup(Map<String, Metric> metrics) { return TaskManagerMetricGroup.createTaskManagerMetricGroup( new TestMetricRegistry(metrics), "localhost", ResourceID.generate()) .addJob(new JobID(), "jobName") .addTask(createExecutionAttemptId(), "test"); } /** The metric registry for storing the registered metrics to verify in tests. */ static
TaskThread
java
netty__netty
codec-native-quic/src/test/java/io/netty/handler/codec/quic/QuicCodecBuilderTest.java
{ "start": 2896, "end": 3633 }
class ____ extends QuicCodecBuilder<TestQuicCodecBuilder> { TestQuicCodecBuilder() { super(true); } TestQuicCodecBuilder(TestQuicCodecBuilder builder) { super(builder); } @Override public TestQuicCodecBuilder clone() { // no-op return null; } @Override protected ChannelHandler build( QuicheConfig config, Function<QuicChannel, ? extends QuicSslEngine> sslContextProvider, Executor sslTaskExecutor, int localConnIdLength, FlushStrategy flushStrategy) { // no-op return null; } } }
TestQuicCodecBuilder
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/BothBlockingAndNonBlockingOnMethodTest.java
{ "start": 561, "end": 1137 }
class ____ { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(Resource.class); } }).setExpectedException(DeploymentException.class); @Test public void test() { fail("Should never have been called"); } @Path("test") public static
BothBlockingAndNonBlockingOnMethodTest
java
redisson__redisson
redisson-quarkus/redisson-quarkus-16/runtime/src/main/java/io/quarkus/redisson/client/runtime/graal/CodecsSubstitutions.java
{ "start": 906, "end": 1192 }
class ____ { @Substitute private static EventLoopGroup createIOUringGroup(Config cfg) { throw new IllegalArgumentException("IOUring isn't compatible with native mode"); } } @TargetClass(className = "org.redisson.codec.JsonJacksonCodec") final
ServiceManagerSubstitute
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/LargeSorter.java
{ "start": 2991, "end": 3772 }
class ____ extends InputFormat<Text, Text> { /** * Generate the requested number of file splits, with the filename * set to the filename of the output file. */ public List<InputSplit> getSplits(JobContext job) throws IOException { List<InputSplit> result = new ArrayList<InputSplit>(); Path outDir = FileOutputFormat.getOutputPath(job); int numSplits = job.getConfiguration().getInt(MRJobConfig.NUM_MAPS, 1); for(int i=0; i < numSplits; ++i) { result.add(new FileSplit( new Path(outDir, "dummy-split-" + i), 0, 1, null)); } return result; } /** * Return a single record (filename, "") where the filename is taken from * the file split. */ static
RandomInputFormat
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/JSONReaderScannerTest_error2.java
{ "start": 176, "end": 810 }
class ____ extends TestCase { public void test_e() throws Exception { Exception error = null; try { StringBuilder buf = new StringBuilder(); buf.append("[{\"type\":\""); for (int i = 0; i < 8180; ++i) { buf.append('A'); } buf.append("\"}"); JSONReader reader = new JSONReader(new StringReader(buf.toString())); reader.readObject(); reader.close(); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public static
JSONReaderScannerTest_error2
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java
{ "start": 11488, "end": 11580 }
class ____ { } @SelectMethod(type = NoParameterTestCase.class, name = "testMethod")
SuiteA
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/Classes.java
{ "start": 751, "end": 947 }
class ____ { @Id @GeneratedValue(strategy=GenerationType.AUTO) Long id; @Embedded Edition<String> edition; } @Entity(name = "PopularBook") @Table(name="PopularBook") public static
Book
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/rank/utils/AppendOnlyTopNHelper.java
{ "start": 1844, "end": 7143 }
class ____ extends AbstractTopNFunction.AbstractTopNHelper { private static final Logger LOG = LoggerFactory.getLogger(AppendOnlyTopNHelper.class); // the kvSortedMap stores mapping from partition key to it's buffer private final Cache<RowData, TopNBuffer> kvSortedMap; private final long topNSize; public AppendOnlyTopNHelper(AbstractTopNFunction topNFunction, long cacheSize, long topNSize) { super(topNFunction); this.topNSize = topNSize; int lruCacheSize = Math.max(1, (int) (cacheSize / topNSize)); CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder(); if (ttlConfig.isEnabled()) { cacheBuilder.expireAfterWrite( ttlConfig.getTimeToLive().toMillis(), TimeUnit.MILLISECONDS); } kvSortedMap = cacheBuilder.maximumSize(lruCacheSize).build(); LOG.info("Top{} operator is using LRU caches key-size: {}", topNSize, lruCacheSize); } public void registerMetric() { registerMetric(kvSortedMap.size() * topNSize); } @Nullable public TopNBuffer getTopNBufferFromCache(RowData currentKey) { return kvSortedMap.getIfPresent(currentKey); } public void saveTopNBufferToCache(RowData currentKey, TopNBuffer topNBuffer) { kvSortedMap.put(currentKey, topNBuffer); } /** * The without-number-algorithm can't handle topN with offset, so use the with-number-algorithm * to handle offset. */ public void processElementWithRowNumber( TopNBuffer buffer, RowData sortKey, RowData input, long rankEnd, Collector<RowData> out) throws Exception { Iterator<Map.Entry<RowData, Collection<RowData>>> iterator = buffer.entrySet().iterator(); long currentRank = 0L; boolean findsSortKey = false; RowData currentRow = null; while (iterator.hasNext() && isInRankEnd(currentRank, rankEnd)) { Map.Entry<RowData, Collection<RowData>> entry = iterator.next(); Collection<RowData> records = entry.getValue(); // meet its own sort key if (!findsSortKey && entry.getKey().equals(sortKey)) { currentRank += records.size(); currentRow = input; findsSortKey = true; } else if (findsSortKey) { Iterator<RowData> recordsIter = records.iterator(); while (recordsIter.hasNext() && isInRankEnd(currentRank, rankEnd)) { RowData prevRow = recordsIter.next(); collectUpdateBefore(out, prevRow, currentRank, rankEnd); collectUpdateAfter(out, currentRow, currentRank, rankEnd); currentRow = prevRow; currentRank += 1; } } else { currentRank += records.size(); } } if (isInRankEnd(currentRank, rankEnd)) { // there is no enough elements in Top-N, emit INSERT message for the new record. collectInsert(out, currentRow, currentRank, rankEnd); } // remove the records associated to the sort key which is out of topN List<RowData> toDeleteSortKeys = new ArrayList<>(); while (iterator.hasNext()) { Map.Entry<RowData, Collection<RowData>> entry = iterator.next(); RowData key = entry.getKey(); removeFromState(key); toDeleteSortKeys.add(key); } for (RowData toDeleteKey : toDeleteSortKeys) { buffer.removeAll(toDeleteKey); } } public void processElementWithoutRowNumber( TopNBuffer buffer, RowData input, long rankEnd, Collector<RowData> out) throws Exception { // remove retired element if (buffer.getCurrentTopNum() > rankEnd) { Map.Entry<RowData, Collection<RowData>> lastEntry = buffer.lastEntry(); RowData lastKey = lastEntry.getKey(); Collection<RowData> lastList = lastEntry.getValue(); RowData lastElement = buffer.lastElement(); int size = lastList.size(); // remove last one if (size <= 1) { buffer.removeAll(lastKey); removeFromState(lastKey); } else { buffer.removeLast(); // last element has been removed from lastList, we have to copy a new collection // for lastList to avoid mutating state values, see CopyOnWriteStateMap, // otherwise, the result might be corrupt. // don't need to perform a deep copy, because RowData elements will not be updated updateState(lastKey, new ArrayList<>(lastList)); } if (size == 0 || input.equals(lastElement)) { return; } else { // lastElement shouldn't be null collectDelete(out, lastElement); } } // it first appears in the TopN, send INSERT message collectInsert(out, input); } protected abstract void removeFromState(RowData key) throws Exception; protected abstract void updateState(RowData key, List<RowData> value) throws Exception; }
AppendOnlyTopNHelper
java
spring-projects__spring-security
crypto/src/main/java/org/springframework/security/crypto/password/Md4PasswordEncoder.java
{ "start": 2898, "end": 5232 }
class ____ extends AbstractValidatingPasswordEncoder { private static final String PREFIX = "{"; private static final String SUFFIX = "}"; private StringKeyGenerator saltGenerator = new Base64StringKeyGenerator(); private boolean encodeHashAsBase64; public void setEncodeHashAsBase64(boolean encodeHashAsBase64) { this.encodeHashAsBase64 = encodeHashAsBase64; } /** * Encodes the rawPass using a MessageDigest. If a salt is specified it will be merged * with the password before encoding. * @param rawPassword The plain text password * @return Hex string of password digest (or base64 encoded string if * encodeHashAsBase64 is enabled. */ @Override public String encodeNonNullPassword(String rawPassword) { String salt = PREFIX + this.saltGenerator.generateKey() + SUFFIX; return digest(salt, rawPassword); } private String digest(String salt, CharSequence rawPassword) { if (rawPassword == null) { rawPassword = ""; } String saltedPassword = rawPassword + salt; byte[] saltedPasswordBytes = Utf8.encode(saltedPassword); Md4 md4 = new Md4(); md4.update(saltedPasswordBytes, 0, saltedPasswordBytes.length); byte[] digest = md4.digest(); String encoded = encodedNonNullPassword(digest); return salt + encoded; } private String encodedNonNullPassword(byte[] digest) { if (this.encodeHashAsBase64) { return Utf8.decode(Base64.getEncoder().encode(digest)); } return new String(Hex.encode(digest)); } /** * Takes a previously encoded password and compares it with a rawpassword after mixing * in the salt and encoding that value * @param rawPassword plain text password * @param encodedPassword previously encoded password * @return true or false */ @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { String salt = extractSalt(encodedPassword); String rawPasswordEncoded = digest(salt, rawPassword); return PasswordEncoderUtils.equals(encodedPassword.toString(), rawPasswordEncoded); } private String extractSalt(String prefixEncodedPassword) { int start = prefixEncodedPassword.indexOf(PREFIX); if (start != 0) { return ""; } int end = prefixEncodedPassword.indexOf(SUFFIX, start); if (end < 0) { return ""; } return prefixEncodedPassword.substring(start, end + 1); } }
Md4PasswordEncoder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/querycache/QueryCacheJoinFetchTest.java
{ "start": 3761, "end": 4579 }
class ____ { @Id @GeneratedValue private Long id; @NaturalId @Column(name = "`number`", unique = true) private String number; @ManyToOne private Person person; public Phone() { } public Phone(String number) { this.number = number; } public Long getId() { return id; } public String getNumber() { return number; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Phone phone = (Phone) o; return Objects.equals( number, phone.number ); } @Override public int hashCode() { return Objects.hash( number ); } } }
Phone
java
spring-projects__spring-framework
spring-messaging/src/test/java/org/springframework/messaging/converter/MappingJackson2MessageConverterTests.java
{ "start": 1593, "end": 10988 }
class ____ { @Test void defaultConstructor() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); assertThat(converter.getSupportedMimeTypes()).contains(new MimeType("application", "json")); assertThat(converter.getObjectMapper().getDeserializationConfig() .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); } @Test // SPR-12724 public void mimetypeParametrizedConstructor() { MimeType mimetype = new MimeType("application", "xml", StandardCharsets.UTF_8); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(mimetype); assertThat(converter.getSupportedMimeTypes()).contains(mimetype); assertThat(converter.getObjectMapper().getDeserializationConfig() .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); } @Test // SPR-12724 public void mimetypesParametrizedConstructor() { MimeType jsonMimetype = new MimeType("application", "json", StandardCharsets.UTF_8); MimeType xmlMimetype = new MimeType("application", "xml", StandardCharsets.UTF_8); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(jsonMimetype, xmlMimetype); assertThat(converter.getSupportedMimeTypes()).contains(jsonMimetype, xmlMimetype); assertThat(converter.getObjectMapper().getDeserializationConfig() .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse(); } @Test void fromMessage() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); String payload = "{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"]," + "\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}"; Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); MyBean actual = (MyBean) converter.fromMessage(message, MyBean.class); assertThat(actual.getString()).isEqualTo("Foo"); assertThat(actual.getNumber()).isEqualTo(42); assertThat(actual.getFraction()).isCloseTo(42F, within(0F)); assertThat(actual.getArray()).isEqualTo(new String[]{"Foo", "Bar"}); assertThat(actual.isBool()).isTrue(); assertThat(actual.getBytes()).isEqualTo(new byte[]{0x1, 0x2}); } @Test void fromMessageUntyped() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); String payload = "{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"]," + "\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}"; Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); @SuppressWarnings("unchecked") HashMap<String, Object> actual = (HashMap<String, Object>) converter.fromMessage(message, HashMap.class); assertThat(actual.get("string")).isEqualTo("Foo"); assertThat(actual.get("number")).isEqualTo(42); assertThat((Double) actual.get("fraction")).isCloseTo(42D, within(0D)); assertThat(actual.get("array")).isEqualTo(Arrays.asList("Foo", "Bar")); assertThat(actual.get("bool")).isEqualTo(Boolean.TRUE); assertThat(actual.get("bytes")).isEqualTo("AQI="); } @Test // gh-22386 public void fromMessageMatchingInstance() { MyBean myBean = new MyBean(); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); Message<?> message = MessageBuilder.withPayload(myBean).build(); assertThat(converter.fromMessage(message, MyBean.class)).isSameAs(myBean); } @Test void fromMessageInvalidJson() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); String payload = "FooBar"; Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); assertThatExceptionOfType(MessageConversionException.class).isThrownBy(() -> converter.fromMessage(message, MyBean.class)); } @Test void fromMessageValidJsonWithUnknownProperty() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); String payload = "{\"string\":\"string\",\"unknownProperty\":\"value\"}"; Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); MyBean myBean = (MyBean)converter.fromMessage(message, MyBean.class); assertThat(myBean.getString()).isEqualTo("string"); } @Test // SPR-16252 public void fromMessageToList() throws Exception { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); String payload = "[1, 2, 3, 4, 5, 6, 7, 8, 9]"; Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); Method method = getClass().getDeclaredMethod("handleList", List.class); MethodParameter param = new MethodParameter(method, 0); Object actual = converter.fromMessage(message, List.class, param); assertThat(actual).isNotNull(); assertThat(actual).isEqualTo(Arrays.asList(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L)); } @Test // SPR-16486 public void fromMessageToMessageWithPojo() throws Exception { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); String payload = "{\"string\":\"foo\"}"; Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build(); Method method = getClass().getDeclaredMethod("handleMessage", Message.class); MethodParameter param = new MethodParameter(method, 0); Object actual = converter.fromMessage(message, MyBean.class, param); assertThat(actual).isInstanceOf(MyBean.class); assertThat(((MyBean) actual).getString()).isEqualTo("foo"); } @Test void toMessage() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); MyBean payload = new MyBean(); payload.setString("Foo"); payload.setNumber(42); payload.setFraction(42F); payload.setArray(new String[]{"Foo", "Bar"}); payload.setBool(true); payload.setBytes(new byte[]{0x1, 0x2}); Message<?> message = converter.toMessage(payload, null); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); assertThat(actual).contains("\"string\":\"Foo\""); assertThat(actual).contains("\"number\":42"); assertThat(actual).contains("fraction\":42.0"); assertThat(actual).contains("\"array\":[\"Foo\",\"Bar\"]"); assertThat(actual).contains("\"bool\":true"); assertThat(actual).contains("\"bytes\":\"AQI=\""); assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)).as("Invalid content-type").isEqualTo(new MimeType("application", "json")); } @Test void toMessageUtf16() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); MimeType contentType = new MimeType("application", "json", StandardCharsets.UTF_16BE); Map<String, Object> map = new HashMap<>(); map.put(MessageHeaders.CONTENT_TYPE, contentType); MessageHeaders headers = new MessageHeaders(map); String payload = "H\u00e9llo W\u00f6rld"; Message<?> message = converter.toMessage(payload, headers); assertThat(new String((byte[]) message.getPayload(), StandardCharsets.UTF_16BE)).isEqualTo("\"" + payload + "\""); assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(contentType); } @Test void toMessageUtf16String() { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); converter.setSerializedPayloadClass(String.class); MimeType contentType = new MimeType("application", "json", StandardCharsets.UTF_16BE); Map<String, Object> map = new HashMap<>(); map.put(MessageHeaders.CONTENT_TYPE, contentType); MessageHeaders headers = new MessageHeaders(map); String payload = "H\u00e9llo W\u00f6rld"; Message<?> message = converter.toMessage(payload, headers); assertThat(message.getPayload()).isEqualTo("\"" + payload + "\""); assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(contentType); } @Test void toMessageJsonView() throws Exception { MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); Map<String, Object> map = new HashMap<>(); Method method = getClass().getDeclaredMethod("jsonViewResponse"); MethodParameter returnType = new MethodParameter(method, -1); Message<?> message = converter.toMessage(jsonViewResponse(), new MessageHeaders(map), returnType); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); assertThat(actual).contains("\"withView1\":\"with\""); assertThat(actual).contains("\"withView2\":\"with\""); assertThat(actual).doesNotContain("\"withoutView\":\"with\""); method = getClass().getDeclaredMethod("jsonViewPayload", JacksonViewBean.class); MethodParameter param = new MethodParameter(method, 0); JacksonViewBean back = (JacksonViewBean) converter.fromMessage(message, JacksonViewBean.class, param); assertThat(back.getWithView1()).isNull(); assertThat(back.getWithView2()).isEqualTo("with"); assertThat(back.getWithoutView()).isNull(); } @JsonView(MyJacksonView1.class) public JacksonViewBean jsonViewResponse() { JacksonViewBean bean = new JacksonViewBean(); bean.setWithView1("with"); bean.setWithView2("with"); bean.setWithoutView("with"); return bean; } public void jsonViewPayload(@JsonView(MyJacksonView2.class) JacksonViewBean payload) { } void handleList(List<Long> payload) { } void handleMessage(Message<MyBean> message) { } public static
MappingJackson2MessageConverterTests
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/targetclass/mixed/AroundInvokeOnTargetClassAndOutsideAndManySuperclassesWithOverridesTest.java
{ "start": 1476, "end": 1698 }
class ____ extends Alpha { @AroundInvoke Object specialIntercept(InvocationContext ctx) { return "this should not be called as the method is overridden in Charlie"; } } static
Bravo
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/IgniteIdGenEndpointBuilderFactory.java
{ "start": 7879, "end": 10390 }
interface ____ extends EndpointProducerBuilder { default IgniteIdGenEndpointBuilder basic() { return (IgniteIdGenEndpointBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedIgniteIdGenEndpointBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedIgniteIdGenEndpointBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } } public
AdvancedIgniteIdGenEndpointBuilder
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/XdsNameResolver.java
{ "start": 20265, "end": 24683 }
class ____ implements ClientInterceptor { @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) { CallOptions callOptionsForCluster = callOptions.withOption(CLUSTER_SELECTION_KEY, finalCluster) .withOption(XDS_CONFIG_CALL_OPTION_KEY, xdsConfig) .withOption(RPC_HASH_KEY, hash); if (routeAction.autoHostRewrite()) { callOptionsForCluster = callOptionsForCluster.withOption(AUTO_HOST_REWRITE_KEY, true); } return new SimpleForwardingClientCall<ReqT, RespT>( next.newCall(method, callOptionsForCluster)) { @Override public void start(Listener<RespT> listener, Metadata headers) { listener = new SimpleForwardingClientCallListener<RespT>(listener) { boolean committed; @Override public void onHeaders(Metadata headers) { committed = true; releaseCluster(finalCluster); delegate().onHeaders(headers); } @Override public void onClose(Status status, Metadata trailers) { if (!committed) { releaseCluster(finalCluster); } delegate().onClose(status, trailers); } }; delegate().start(listener, headers); } }; } } return Result.newBuilder() .setConfig(config) .setInterceptor(combineInterceptors( ImmutableList.of(new ClusterSelectionInterceptor(), filters))) .build(); } private boolean retainCluster(String cluster) { ClusterRefState clusterRefState = clusterRefs.get(cluster); if (clusterRefState == null) { return false; } AtomicInteger refCount = clusterRefState.refCount; int count; do { count = refCount.get(); if (count == 0) { return false; } } while (!refCount.compareAndSet(count, count + 1)); return true; } private void releaseCluster(final String cluster) { int count = clusterRefs.get(cluster).refCount.decrementAndGet(); if (count < 0) { throw new AssertionError(); } if (count == 0) { syncContext.execute(new Runnable() { @Override public void run() { if (clusterRefs.get(cluster).refCount.get() != 0) { throw new AssertionError(); } clusterRefs.remove(cluster).close(); if (resolveState.lastConfigOrStatus.hasValue()) { updateResolutionResult(resolveState.lastConfigOrStatus.getValue()); } else { resolveState.cleanUpRoutes(resolveState.lastConfigOrStatus.getStatus()); } } }); } } private long generateHash(List<HashPolicy> hashPolicies, Metadata headers) { Long hash = null; for (HashPolicy policy : hashPolicies) { Long newHash = null; if (policy.type() == HashPolicy.Type.HEADER) { String value = getHeaderValue(headers, policy.headerName()); if (value != null) { if (policy.regEx() != null && policy.regExSubstitution() != null) { value = policy.regEx().matcher(value).replaceAll(policy.regExSubstitution()); } newHash = hashFunc.hashAsciiString(value); } } else if (policy.type() == HashPolicy.Type.CHANNEL_ID) { newHash = hashFunc.hashLong(randomChannelId); } if (newHash != null ) { // Rotating the old value prevents duplicate hash rules from cancelling each other out // and preserves all of the entropy. long oldHash = hash != null ? ((hash << 1L) | (hash >> 63L)) : 0; hash = oldHash ^ newHash; } // If the policy is a terminal policy and a hash has been generated, ignore // the rest of the hash policies. if (policy.isTerminal() && hash != null) { break; } } return hash == null ? random.nextLong() : hash; } } static final
ClusterSelectionInterceptor
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/launcher/TestPlanTests.java
{ "start": 820, "end": 2831 }
class ____ { private final ConfigurationParameters configParams = mock(); private final EngineDescriptor engineDescriptor = new EngineDescriptor(UniqueId.forEngine("foo"), "Foo"); @Test void acceptsVisitorsInDepthFirstOrder() { var container = new TestDescriptorStub(engineDescriptor.getUniqueId().append("container", "bar"), "Bar"); var test1 = new TestDescriptorStub(container.getUniqueId().append("test", "bar"), "Bar"); container.addChild(test1); engineDescriptor.addChild(container); var engineDescriptor2 = new EngineDescriptor(UniqueId.forEngine("baz"), "Baz"); var test2 = new TestDescriptorStub(engineDescriptor2.getUniqueId().append("test", "baz1"), "Baz"); var test3 = new TestDescriptorStub(engineDescriptor2.getUniqueId().append("test", "baz2"), "Baz"); engineDescriptor2.addChild(test2); engineDescriptor2.addChild(test3); var testPlan = TestPlan.from(true, List.of(engineDescriptor, engineDescriptor2), configParams, dummyOutputDirectoryCreator()); var visitor = mock(TestPlan.Visitor.class); testPlan.accept(visitor); var inOrder = inOrder(visitor); inOrder.verify(visitor).preVisitContainer(TestIdentifier.from(engineDescriptor)); inOrder.verify(visitor).visit(TestIdentifier.from(engineDescriptor)); inOrder.verify(visitor).preVisitContainer(TestIdentifier.from(container)); inOrder.verify(visitor).visit(TestIdentifier.from(container)); inOrder.verify(visitor).visit(TestIdentifier.from(test1)); inOrder.verify(visitor).postVisitContainer(TestIdentifier.from(container)); inOrder.verify(visitor).postVisitContainer(TestIdentifier.from(engineDescriptor)); inOrder.verify(visitor).preVisitContainer(TestIdentifier.from(engineDescriptor2)); inOrder.verify(visitor).visit(TestIdentifier.from(engineDescriptor2)); inOrder.verify(visitor).visit(TestIdentifier.from(test2)); inOrder.verify(visitor).visit(TestIdentifier.from(test3)); inOrder.verify(visitor).postVisitContainer(TestIdentifier.from(engineDescriptor2)); } }
TestPlanTests
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/preprocessing/TargetMeanEncoding.java
{ "start": 1107, "end": 8287 }
class ____ implements LenientlyParsedPreProcessor, StrictlyParsedPreProcessor { public static final long SHALLOW_SIZE = RamUsageEstimator.shallowSizeOfInstance(TargetMeanEncoding.class); public static final ParseField NAME = new ParseField("target_mean_encoding"); public static final ParseField FIELD = new ParseField("field"); public static final ParseField FEATURE_NAME = new ParseField("feature_name"); public static final ParseField TARGET_MAP = new ParseField("target_map"); public static final ParseField DEFAULT_VALUE = new ParseField("default_value"); public static final ParseField CUSTOM = new ParseField("custom"); private static final ConstructingObjectParser<TargetMeanEncoding, PreProcessorParseContext> STRICT_PARSER = createParser(false); private static final ConstructingObjectParser<TargetMeanEncoding, PreProcessorParseContext> LENIENT_PARSER = createParser(true); @SuppressWarnings("unchecked") private static ConstructingObjectParser<TargetMeanEncoding, PreProcessorParseContext> createParser(boolean lenient) { ConstructingObjectParser<TargetMeanEncoding, PreProcessorParseContext> parser = new ConstructingObjectParser<>( NAME.getPreferredName(), lenient, (a, c) -> new TargetMeanEncoding( (String) a[0], (String) a[1], (Map<String, Double>) a[2], (Double) a[3], a[4] == null ? c.isCustomByDefault() : (Boolean) a[4] ) ); parser.declareString(ConstructingObjectParser.constructorArg(), FIELD); parser.declareString(ConstructingObjectParser.constructorArg(), FEATURE_NAME); parser.declareObject( ConstructingObjectParser.constructorArg(), (p, c) -> p.map(HashMap::new, XContentParser::doubleValue), TARGET_MAP ); parser.declareDouble(ConstructingObjectParser.constructorArg(), DEFAULT_VALUE); parser.declareBoolean(ConstructingObjectParser.optionalConstructorArg(), CUSTOM); return parser; } public static TargetMeanEncoding fromXContentStrict(XContentParser parser, PreProcessorParseContext context) { return STRICT_PARSER.apply(parser, context == null ? PreProcessorParseContext.DEFAULT : context); } public static TargetMeanEncoding fromXContentLenient(XContentParser parser, PreProcessorParseContext context) { return LENIENT_PARSER.apply(parser, context == null ? PreProcessorParseContext.DEFAULT : context); } private final String field; private final String featureName; private final Map<String, Double> meanMap; private final double defaultValue; private final boolean custom; public TargetMeanEncoding(String field, String featureName, Map<String, Double> meanMap, Double defaultValue, Boolean custom) { this.field = ExceptionsHelper.requireNonNull(field, FIELD); this.featureName = ExceptionsHelper.requireNonNull(featureName, FEATURE_NAME); this.meanMap = Collections.unmodifiableMap(ExceptionsHelper.requireNonNull(meanMap, TARGET_MAP)); this.defaultValue = ExceptionsHelper.requireNonNull(defaultValue, DEFAULT_VALUE); this.custom = custom == null ? false : custom; } public TargetMeanEncoding(StreamInput in) throws IOException { this.field = in.readString(); this.featureName = in.readString(); this.meanMap = in.readImmutableMap(StreamInput::readDouble); this.defaultValue = in.readDouble(); this.custom = in.readBoolean(); } /** * @return Field name on which to target mean encode */ public String getField() { return field; } /** * @return Map of Value: targetMean for the target mean encoding */ public Map<String, Double> getMeanMap() { return meanMap; } /** * @return The default value to set when a previously unobserved value is seen */ public Double getDefaultValue() { return defaultValue; } /** * @return The feature name for the encoded value */ public String getFeatureName() { return featureName; } @Override public Map<String, String> reverseLookup() { return Collections.singletonMap(featureName, field); } @Override public boolean isCustom() { return custom; } @Override public String getOutputFieldType(String outputField) { return NumberFieldMapper.NumberType.DOUBLE.typeName(); } @Override public String getName() { return NAME.getPreferredName(); } @Override public List<String> inputFields() { return Collections.singletonList(field); } @Override public List<String> outputFields() { return Collections.singletonList(featureName); } @Override public void process(Map<String, Object> fields) { Object value = fields.get(field); if (value == null) { return; } fields.put(featureName, meanMap.getOrDefault(value.toString(), defaultValue)); } @Override public String getWriteableName() { return NAME.getPreferredName(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(field); out.writeString(featureName); out.writeMap(meanMap, StreamOutput::writeDouble); out.writeDouble(defaultValue); out.writeBoolean(custom); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(FIELD.getPreferredName(), field); builder.field(FEATURE_NAME.getPreferredName(), featureName); builder.field(TARGET_MAP.getPreferredName(), meanMap); builder.field(DEFAULT_VALUE.getPreferredName(), defaultValue); builder.field(CUSTOM.getPreferredName(), custom); builder.endObject(); return builder; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TargetMeanEncoding that = (TargetMeanEncoding) o; return Objects.equals(field, that.field) && Objects.equals(featureName, that.featureName) && Objects.equals(meanMap, that.meanMap) && Objects.equals(defaultValue, that.defaultValue) && Objects.equals(custom, that.custom); } @Override public int hashCode() { return Objects.hash(field, featureName, meanMap, defaultValue, custom); } @Override public long ramBytesUsed() { long size = SHALLOW_SIZE; size += RamUsageEstimator.sizeOf(field); size += RamUsageEstimator.sizeOf(featureName); // defSize:0 indicates that there is not a defined size. Finding the shallowSize of Double gives the best estimate size += RamUsageEstimator.sizeOfMap(meanMap, 0); return size; } @Override public String toString() { return Strings.toString(this); } }
TargetMeanEncoding
java
spring-projects__spring-framework
spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DefaultDatabaseClient.java
{ "start": 20011, "end": 20639 }
class ____ extends AtomicBoolean { private static final long serialVersionUID = -8994138383301201380L; final transient Connection connection; final transient Function<Connection, Publisher<Void>> closeFunction; ConnectionCloseHolder(Connection connection, Function<Connection, Publisher<Void>> closeFunction) { this.connection = connection; this.closeFunction = closeFunction; } Mono<Void> close() { return Mono.defer(() -> { if (compareAndSet(false, true)) { return Mono.from(this.closeFunction.apply(this.connection)); } return Mono.empty(); }); } } static
ConnectionCloseHolder
java
grpc__grpc-java
binder/src/test/java/io/grpc/binder/internal/SimplePromiseTest.java
{ "start": 1263, "end": 4584 }
class ____ { private static final String FULFILLED_VALUE = "a fulfilled value"; @Mock private Listener<String> mockListener1; @Mock private Listener<String> mockListener2; @Rule public final MockitoRule mocks = MockitoJUnit.rule(); private SimplePromise<String> promise = new SimplePromise<>(); @Before public void setUp() { } @Test public void get_beforeFulfilled_throws() { IllegalStateException e = assertThrows(IllegalStateException.class, () -> promise.get()); assertThat(e).hasMessageThat().isEqualTo("Not yet set!"); } @Test public void get_afterFulfilled_returnsValue() { promise.set(FULFILLED_VALUE); assertThat(promise.get()).isEqualTo(FULFILLED_VALUE); } @Test public void set_withNull_throws() { assertThrows(NullPointerException.class, () -> promise.set(null)); } @Test public void set_calledTwice_throws() { promise.set(FULFILLED_VALUE); IllegalStateException e = assertThrows(IllegalStateException.class, () -> promise.set("another value")); assertThat(e).hasMessageThat().isEqualTo("Already set!"); } @Test public void runWhenSet_beforeFulfill_listenerIsNotifiedUponSet() { promise.runWhenSet(mockListener1); // Should not have been called yet. verify(mockListener1, never()).notify(FULFILLED_VALUE); promise.set(FULFILLED_VALUE); // Now it should be called. verify(mockListener1, times(1)).notify(FULFILLED_VALUE); } @Test public void runWhenSet_afterSet_listenerIsNotifiedImmediately() { promise.set(FULFILLED_VALUE); promise.runWhenSet(mockListener1); // Should have been called immediately. verify(mockListener1, times(1)).notify(FULFILLED_VALUE); } @Test public void multipleListeners_addedBeforeSet_allNotifiedInOrder() { promise.runWhenSet(mockListener1); promise.runWhenSet(mockListener2); promise.set(FULFILLED_VALUE); InOrder inOrder = inOrder(mockListener1, mockListener2); inOrder.verify(mockListener1).notify(FULFILLED_VALUE); inOrder.verify(mockListener2).notify(FULFILLED_VALUE); } @Test public void listenerThrows_duringSet_propagatesException() { // A listener that will throw when notified. Listener<String> throwingListener = (value) -> { throw new UnsupportedOperationException("Listener failed"); }; promise.runWhenSet(throwingListener); // Fulfilling the promise should now throw the exception from the listener. UnsupportedOperationException e = assertThrows(UnsupportedOperationException.class, () -> promise.set(FULFILLED_VALUE)); assertThat(e).hasMessageThat().isEqualTo("Listener failed"); } @Test public void listenerThrows_whenAddedAfterSet_propagatesException() { promise.set(FULFILLED_VALUE); // A listener that will throw when notified. Listener<String> throwingListener = (value) -> { throw new UnsupportedOperationException("Listener failed"); }; // Running the listener should throw immediately because the promise is already fulfilled. UnsupportedOperationException e = assertThrows( UnsupportedOperationException.class, () -> promise.runWhenSet(throwingListener)); assertThat(e).hasMessageThat().isEqualTo("Listener failed"); } }
SimplePromiseTest
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/common/notifications/LevelTests.java
{ "start": 409, "end": 1668 }
class ____ extends ESTestCase { public void testFromString() { assertThat(Level.fromString("info"), equalTo(Level.INFO)); assertThat(Level.fromString("INFO"), equalTo(Level.INFO)); assertThat(Level.fromString("warning"), equalTo(Level.WARNING)); assertThat(Level.fromString("WARNING"), equalTo(Level.WARNING)); assertThat(Level.fromString("error"), equalTo(Level.ERROR)); assertThat(Level.fromString("ERROR"), equalTo(Level.ERROR)); } public void testToString() { assertThat(Level.INFO.toString(), equalTo("info")); assertThat(Level.WARNING.toString(), equalTo("warning")); assertThat(Level.ERROR.toString(), equalTo("error")); } public void testValidOrdinals() { assertThat(Level.INFO.ordinal(), equalTo(0)); assertThat(Level.WARNING.ordinal(), equalTo(1)); assertThat(Level.ERROR.ordinal(), equalTo(2)); } public void testLog4JLevel() { assertThat(Level.INFO.log4jLevel(), equalTo(org.apache.logging.log4j.Level.INFO)); assertThat(Level.WARNING.log4jLevel(), equalTo(org.apache.logging.log4j.Level.WARN)); assertThat(Level.ERROR.log4jLevel(), equalTo(org.apache.logging.log4j.Level.ERROR)); } }
LevelTests
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/selection/twosteperror/ErroneousMapperMM.java
{ "start": 286, "end": 868 }
interface ____ { ErroneousMapperMM INSTANCE = Mappers.getMapper( ErroneousMapperMM.class ); Target map( Source s ); default TargetType methodY1(TypeInTheMiddleA s) { return new TargetType( s.test ); } default TypeInTheMiddleA methodX1(SourceType s) { return new TypeInTheMiddleA( s.t1 ); } default TargetType methodY2(TypeInTheMiddleB s) { return new TargetType( s.test ); } default TypeInTheMiddleB methodX2(SourceType s) { return new TypeInTheMiddleB( s.t1 ); } // CHECKSTYLE:OFF
ErroneousMapperMM
java
apache__kafka
trogdor/src/main/java/org/apache/kafka/trogdor/coordinator/CoordinatorClient.java
{ "start": 3424, "end": 21925 }
class ____ { private Logger log = LoggerFactory.getLogger(CoordinatorClient.class); private int maxTries = 1; private String target = null; public Builder() { } public Builder log(Logger log) { this.log = log; return this; } public Builder maxTries(int maxTries) { this.maxTries = maxTries; return this; } public Builder target(String target) { this.target = target; return this; } public Builder target(String host, int port) { this.target = String.format("%s:%d", host, port); return this; } public CoordinatorClient build() { if (target == null) { throw new RuntimeException("You must specify a target."); } return new CoordinatorClient(log, maxTries, target); } } private CoordinatorClient(Logger log, int maxTries, String target) { this.log = log; this.maxTries = maxTries; this.target = target; } public int maxTries() { return maxTries; } private String url(String suffix) { return String.format("http://%s%s", target, suffix); } public CoordinatorStatusResponse status() throws Exception { HttpResponse<CoordinatorStatusResponse> resp = JsonRestServer.httpRequest(url("/coordinator/status"), "GET", null, new TypeReference<CoordinatorStatusResponse>() { }, maxTries); return resp.body(); } public UptimeResponse uptime() throws Exception { HttpResponse<UptimeResponse> resp = JsonRestServer.httpRequest(url("/coordinator/uptime"), "GET", null, new TypeReference<UptimeResponse>() { }, maxTries); return resp.body(); } public void createTask(CreateTaskRequest request) throws Exception { HttpResponse<Empty> resp = JsonRestServer.httpRequest(log, url("/coordinator/task/create"), "POST", request, new TypeReference<Empty>() { }, maxTries); resp.body(); } public void stopTask(StopTaskRequest request) throws Exception { HttpResponse<Empty> resp = JsonRestServer.httpRequest(log, url("/coordinator/task/stop"), "PUT", request, new TypeReference<Empty>() { }, maxTries); resp.body(); } public void destroyTask(DestroyTaskRequest request) throws Exception { UriBuilder uriBuilder = UriBuilder.fromPath(url("/coordinator/tasks")); uriBuilder.queryParam("taskId", request.id()); HttpResponse<Empty> resp = JsonRestServer.httpRequest(log, uriBuilder.build().toString(), "DELETE", null, new TypeReference<Empty>() { }, maxTries); resp.body(); } public TasksResponse tasks(TasksRequest request) throws Exception { UriBuilder uriBuilder = UriBuilder.fromPath(url("/coordinator/tasks")); uriBuilder.queryParam("taskId", request.taskIds().toArray(new Object[0])); uriBuilder.queryParam("firstStartMs", request.firstStartMs()); uriBuilder.queryParam("lastStartMs", request.lastStartMs()); uriBuilder.queryParam("firstEndMs", request.firstEndMs()); uriBuilder.queryParam("lastEndMs", request.lastEndMs()); if (request.state().isPresent()) { uriBuilder.queryParam("state", request.state().get().toString()); } HttpResponse<TasksResponse> resp = JsonRestServer.httpRequest(log, uriBuilder.build().toString(), "GET", null, new TypeReference<TasksResponse>() { }, maxTries); return resp.body(); } public TaskState task(TaskRequest request) throws Exception { String uri = UriBuilder.fromPath(url("/coordinator/tasks/{taskId}")).build(request.taskId()).toString(); HttpResponse<TaskState> resp = JsonRestServer.httpRequest(log, uri, "GET", null, new TypeReference<TaskState>() { }, maxTries); return resp.body(); } public void shutdown() throws Exception { HttpResponse<Empty> resp = JsonRestServer.httpRequest(log, url("/coordinator/shutdown"), "PUT", null, new TypeReference<Empty>() { }, maxTries); resp.body(); } private static void addTargetArgument(ArgumentParser parser) { parser.addArgument("--target", "-t") .action(store()) .required(true) .type(String.class) .dest("target") .metavar("TARGET") .help("A colon-separated host and port pair. For example, example.com:8889"); } private static void addJsonArgument(ArgumentParser parser) { parser.addArgument("--json") .action(storeTrue()) .dest("json") .metavar("JSON") .help("Show the full response as JSON."); } public static void main(String[] args) throws Exception { ArgumentParser rootParser = ArgumentParsers .newArgumentParser("trogdor-coordinator-client") .description("The Trogdor coordinator client."); Subparsers subParsers = rootParser.addSubparsers(). dest("command"); Subparser uptimeParser = subParsers.addParser("uptime") .help("Get the coordinator uptime."); addTargetArgument(uptimeParser); addJsonArgument(uptimeParser); Subparser statusParser = subParsers.addParser("status") .help("Get the coordinator status."); addTargetArgument(statusParser); addJsonArgument(statusParser); Subparser showTaskParser = subParsers.addParser("showTask") .help("Show a coordinator task."); addTargetArgument(showTaskParser); addJsonArgument(showTaskParser); showTaskParser.addArgument("--id", "-i") .action(store()) .required(true) .type(String.class) .dest("taskId") .metavar("TASK_ID") .help("The task ID to show."); showTaskParser.addArgument("--verbose", "-v") .action(storeTrue()) .dest("verbose") .metavar("VERBOSE") .help("Print out everything."); showTaskParser.addArgument("--show-status", "-S") .action(storeTrue()) .dest("showStatus") .metavar("SHOW_STATUS") .help("Show the task status."); Subparser showTasksParser = subParsers.addParser("showTasks") .help("Show many coordinator tasks. By default, all tasks are shown, but " + "command-line options can be specified as filters."); addTargetArgument(showTasksParser); addJsonArgument(showTasksParser); MutuallyExclusiveGroup idGroup = showTasksParser.addMutuallyExclusiveGroup(); idGroup.addArgument("--id", "-i") .action(append()) .type(String.class) .dest("taskIds") .metavar("TASK_IDS") .help("Show only this task ID. This option may be specified multiple times."); idGroup.addArgument("--id-pattern") .action(store()) .type(String.class) .dest("taskIdPattern") .metavar("TASK_ID_PATTERN") .help("Only display tasks which match the given ID pattern."); showTasksParser.addArgument("--state", "-s") .type(TaskStateType.class) .dest("taskStateType") .metavar("TASK_STATE_TYPE") .help("Show only tasks in this state."); Subparser createTaskParser = subParsers.addParser("createTask") .help("Create a new task."); addTargetArgument(createTaskParser); createTaskParser.addArgument("--id", "-i") .action(store()) .required(true) .type(String.class) .dest("taskId") .metavar("TASK_ID") .help("The task ID to create."); createTaskParser.addArgument("--spec", "-s") .action(store()) .required(true) .type(String.class) .dest("taskSpec") .metavar("TASK_SPEC") .help("The task spec to create, or a path to a file containing the task spec."); Subparser stopTaskParser = subParsers.addParser("stopTask") .help("Stop a task."); addTargetArgument(stopTaskParser); stopTaskParser.addArgument("--id", "-i") .action(store()) .required(true) .type(String.class) .dest("taskId") .metavar("TASK_ID") .help("The task ID to create."); Subparser destroyTaskParser = subParsers.addParser("destroyTask") .help("Destroy a task."); addTargetArgument(destroyTaskParser); destroyTaskParser.addArgument("--id", "-i") .action(store()) .required(true) .type(String.class) .dest("taskId") .metavar("TASK_ID") .help("The task ID to destroy."); Subparser shutdownParser = subParsers.addParser("shutdown") .help("Shut down the coordinator."); addTargetArgument(shutdownParser); Namespace res = rootParser.parseArgsOrFail(args); String target = res.getString("target"); CoordinatorClient client = new Builder(). maxTries(3). target(target). build(); ZoneOffset localOffset = OffsetDateTime.now().getOffset(); switch (res.getString("command")) { case "uptime": { UptimeResponse uptime = client.uptime(); if (res.getBoolean("json")) { System.out.println(JsonUtil.toJsonString(uptime)); } else { System.out.printf("Coordinator is running at %s.%n", target); System.out.printf("\tStart time: %s%n", dateString(uptime.serverStartMs(), localOffset)); System.out.printf("\tCurrent server time: %s%n", dateString(uptime.nowMs(), localOffset)); System.out.printf("\tUptime: %s%n", durationString(uptime.nowMs() - uptime.serverStartMs())); } break; } case "status": { CoordinatorStatusResponse response = client.status(); if (res.getBoolean("json")) { System.out.println(JsonUtil.toJsonString(response)); } else { System.out.printf("Coordinator is running at %s.%n", target); System.out.printf("\tStart time: %s%n", dateString(response.serverStartMs(), localOffset)); } break; } case "showTask": { String taskId = res.getString("taskId"); TaskRequest req = new TaskRequest(taskId); TaskState taskState = null; try { taskState = client.task(req); } catch (NotFoundException e) { System.out.printf("Task %s was not found.%n", taskId); Exit.exit(1); } if (res.getBoolean("json")) { System.out.println(JsonUtil.toJsonString(taskState)); } else { System.out.printf("Task %s of type %s is %s. %s%n", taskId, taskState.spec().getClass().getCanonicalName(), taskState.stateType(), prettyPrintTaskInfo(taskState, localOffset)); if (taskState instanceof TaskDone taskDone) { if ((taskDone.error() != null) && (!taskDone.error().isEmpty())) { System.out.printf("Error: %s%n", taskDone.error()); } } if (res.getBoolean("verbose")) { System.out.printf("Spec: %s%n%n", JsonUtil.toPrettyJsonString(taskState.spec())); } if (res.getBoolean("verbose") || res.getBoolean("showStatus")) { System.out.printf("Status: %s%n%n", JsonUtil.toPrettyJsonString(taskState.status())); } } break; } case "showTasks": { TaskStateType taskStateType = res.get("taskStateType"); List<String> taskIds = new ArrayList<>(); Pattern taskIdPattern = null; if (res.getList("taskIds") != null) { for (Object taskId : res.getList("taskIds")) { taskIds.add((String) taskId); } } else if (res.getString("taskIdPattern") != null) { try { taskIdPattern = Pattern.compile(res.getString("taskIdPattern")); } catch (PatternSyntaxException e) { System.out.println("Invalid task ID regular expression " + res.getString("taskIdPattern")); e.printStackTrace(); Exit.exit(1); } } TasksRequest req = new TasksRequest(taskIds, 0, 0, 0, 0, Optional.ofNullable(taskStateType)); TasksResponse response = client.tasks(req); if (taskIdPattern != null) { TreeMap<String, TaskState> filteredTasks = new TreeMap<>(); for (Map.Entry<String, TaskState> entry : response.tasks().entrySet()) { if (taskIdPattern.matcher(entry.getKey()).matches()) { filteredTasks.put(entry.getKey(), entry.getValue()); } } response = new TasksResponse(filteredTasks); } if (res.getBoolean("json")) { System.out.println(JsonUtil.toJsonString(response)); } else { System.out.println(prettyPrintTasksResponse(response, localOffset)); } if (response.tasks().isEmpty()) { Exit.exit(1); } break; } case "createTask": { String taskId = res.getString("taskId"); TaskSpec taskSpec = JsonUtil. objectFromCommandLineArgument(res.getString("taskSpec"), TaskSpec.class); CreateTaskRequest req = new CreateTaskRequest(taskId, taskSpec); try { client.createTask(req); System.out.printf("Sent CreateTaskRequest for task %s.%n", req.id()); } catch (RequestConflictException rce) { System.out.printf("CreateTaskRequest for task %s got a 409 status code - " + "a task with the same ID but a different specification already exists.%nException: %s%n", req.id(), rce.getMessage()); Exit.exit(1); } break; } case "stopTask": { String taskId = res.getString("taskId"); StopTaskRequest req = new StopTaskRequest(taskId); client.stopTask(req); System.out.printf("Sent StopTaskRequest for task %s.%n", taskId); break; } case "destroyTask": { String taskId = res.getString("taskId"); DestroyTaskRequest req = new DestroyTaskRequest(taskId); client.destroyTask(req); System.out.printf("Sent DestroyTaskRequest for task %s.%n", taskId); break; } case "shutdown": { client.shutdown(); System.out.println("Sent ShutdownRequest."); break; } default: { System.out.println("You must choose an action. Type --help for help."); Exit.exit(1); } } } static String prettyPrintTasksResponse(TasksResponse response, ZoneOffset zoneOffset) { if (response.tasks().isEmpty()) { return "No matching tasks found."; } List<List<String>> lines = new ArrayList<>(); lines.add(List.of("ID", "TYPE", "STATE", "INFO")); for (Map.Entry<String, TaskState> entry : response.tasks().entrySet()) { String taskId = entry.getKey(); TaskState taskState = entry.getValue(); List<String> cols = new ArrayList<>(); cols.add(taskId); cols.add(taskState.spec().getClass().getCanonicalName()); cols.add(taskState.stateType().toString()); cols.add(prettyPrintTaskInfo(taskState, zoneOffset)); lines.add(cols); } return StringFormatter.prettyPrintGrid(lines); } static String prettyPrintTaskInfo(TaskState taskState, ZoneOffset zoneOffset) { if (taskState instanceof TaskPending) { return "Will start at " + dateString(taskState.spec().startMs(), zoneOffset); } else if (taskState instanceof TaskRunning runState) { return "Started " + dateString(runState.startedMs(), zoneOffset) + "; will stop after " + durationString(taskState.spec().durationMs()); } else if (taskState instanceof TaskStopping stoppingState) { return "Started " + dateString(stoppingState.startedMs(), zoneOffset); } else if (taskState instanceof TaskDone doneState) { String status; if (doneState.error() == null || doneState.error().isEmpty()) { if (doneState.cancelled()) { status = "CANCELLED"; } else { status = "FINISHED"; } } else { status = "FAILED"; } return String.format("%s at %s after %s", status, dateString(doneState.doneMs(), zoneOffset), durationString(doneState.doneMs() - doneState.startedMs())); } else { throw new RuntimeException("Unknown task state type " + taskState.stateType()); } } }
Builder
java
alibaba__nacos
naming/src/main/java/com/alibaba/nacos/naming/paramcheck/NamingInstanceListHttpParamExtractor.java
{ "start": 1070, "end": 2098 }
class ____ extends AbstractHttpParamExtractor { @Override public List<ParamInfo> extractParam(HttpServletRequest request) { ParamInfo paramInfo = new ParamInfo(); String serviceName = request.getParameter("serviceName"); String groupName = request.getParameter("groupName"); String groupServiceName = serviceName; if (StringUtils.isNotBlank(groupServiceName) && groupServiceName.contains(Constants.SERVICE_INFO_SPLITER)) { String[] splits = groupServiceName.split(Constants.SERVICE_INFO_SPLITER, 2); groupName = splits[0]; serviceName = splits[1]; } paramInfo.setServiceName(serviceName); paramInfo.setGroup(groupName); paramInfo.setNamespaceId(request.getParameter("namespaceId")); paramInfo.setClusters(request.getParameter("clusters")); ArrayList<ParamInfo> paramInfos = new ArrayList<>(); paramInfos.add(paramInfo); return paramInfos; } }
NamingInstanceListHttpParamExtractor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/object/ConvertedClassAttributeTest.java
{ "start": 3006, "end": 3352 }
class ____ implements AttributeConverter<Status, Integer> { @Override public Integer convertToDatabaseColumn(Status attribute) { return attribute == null ? null : attribute.getValue(); } @Override public Status convertToEntityAttribute(Integer dbData) { return dbData == null ? null : Status.from( dbData ); } } }
StatusConverter
java
spring-projects__spring-framework
spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterUtilsTests.java
{ "start": 15745, "end": 16988 }
class ____ { final Map<String, Object> headers = new HashMap<>(); public Foo() { this.headers.put("id", 1); } public Map<String, Object> getHeaders() { return this.headers; } } Foo foo = new Foo(); SqlParameterSource paramSource = new BeanPropertySqlParameterSource(foo); Object[] params = NamedParameterUtils.buildValueArray(parsedSql, paramSource, null); assertThat(params[0]).isInstanceOfSatisfying(SqlParameterValue.class, sqlParameterValue -> assertThat(sqlParameterValue.getValue()).isEqualTo(foo.getHeaders().get("id"))); String sqlToUse = NamedParameterUtils.substituteNamedParameters(parsedSql, paramSource); assertThat(sqlToUse).isEqualTo("insert into foos (id) values (?)"); } @Test // gh-31944 void parseSqlStatementWithBackticks() { String sql = "select * from `tb&user` where id = :id"; ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(sql); assertThat(parsedSql.getParameterNames()).containsExactly("id"); assertThat(substituteNamedParameters(parsedSql)).isEqualTo("select * from `tb&user` where id = ?"); } private static String substituteNamedParameters(ParsedSql parsedSql) { return NamedParameterUtils.substituteNamedParameters(parsedSql, null); } }
Foo
java
google__auto
factory/src/it/functional/src/main/java/com/google/auto/factory/GuiceModule.java
{ "start": 673, "end": 1058 }
class ____ extends AbstractModule { @Override protected void configure() { bind(Dependency.class).to(DependencyImpl.class); bind(Dependency.class).annotatedWith(Qualifier.class).to(QualifiedDependencyImpl.class); bind(Integer.class).toInstance(1); bind(Integer.class).annotatedWith(Qualifier.class).toInstance(2); bind(Number.class).toInstance(3); } }
GuiceModule
java
alibaba__nacos
naming/src/test/java/com/alibaba/nacos/naming/controllers/ServiceControllerTest.java
{ "start": 1931, "end": 7153 }
class ____ extends BaseTest { @InjectMocks private ServiceController serviceController; @Mock private ServiceOperatorV2Impl serviceOperatorV2; @Mock private SubscribeManager subscribeManager; private SmartSubscriber subscriber; private volatile Class<? extends Event> eventReceivedClass; @BeforeEach public void before() { super.before(); subscriber = new SmartSubscriber() { @Override public List<Class<? extends Event>> subscribeTypes() { List<Class<? extends Event>> result = new LinkedList<>(); result.add(UpdateServiceTraceEvent.class); return result; } @Override public void onEvent(Event event) { eventReceivedClass = event.getClass(); } }; NotifyCenter.registerSubscriber(subscriber); } @AfterEach void tearDown() throws Exception { NotifyCenter.deregisterSubscriber(subscriber); NotifyCenter.deregisterPublisher(UpdateServiceTraceEvent.class); eventReceivedClass = null; } @Test void testList() throws Exception { Mockito.when(serviceOperatorV2.listService(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(Collections.singletonList("DEFAULT_GROUP@@providers:com.alibaba.nacos.controller.test:1")); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.addParameter("pageNo", "1"); servletRequest.addParameter("pageSize", "10"); ObjectNode objectNode = serviceController.list(servletRequest); assertEquals(1, objectNode.get("count").asInt()); } @Test void testCreate() { try { String res = serviceController.create(TEST_NAMESPACE, TEST_SERVICE_NAME, 0, "", ""); assertEquals("ok", res); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test void testRemove() { try { String res = serviceController.remove(TEST_NAMESPACE, TEST_SERVICE_NAME); assertEquals("ok", res); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test void testDetail() { try { ObjectNode result = Mockito.mock(ObjectNode.class); Mockito.when(serviceOperatorV2.queryService(Mockito.anyString(), Mockito.anyString())).thenReturn(result); ObjectNode objectNode = serviceController.detail(TEST_NAMESPACE, TEST_SERVICE_NAME); assertEquals(result, objectNode); } catch (NacosException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test void testUpdate() throws Exception { MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.addParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME); servletRequest.addParameter("protectThreshold", "0.01"); try { String res = serviceController.update(servletRequest); assertEquals("ok", res); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } TimeUnit.MILLISECONDS.sleep(1200L); assertEquals(UpdateServiceTraceEvent.class, eventReceivedClass); } @Test void testSearchService() { try { Mockito.when(serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString())) .thenReturn(Collections.singletonList("result")); ObjectNode objectNode = serviceController.searchService(TEST_NAMESPACE, ""); assertEquals(1, objectNode.get("count").asInt()); } catch (NacosException e) { e.printStackTrace(); fail(e.getMessage()); } try { Mockito.when(serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString())) .thenReturn(Arrays.asList("re1", "re2")); Mockito.when(serviceOperatorV2.listAllNamespace()).thenReturn(Arrays.asList("re1", "re2")); ObjectNode objectNode = serviceController.searchService(null, ""); assertEquals(4, objectNode.get("count").asInt()); } catch (NacosException e) { e.printStackTrace(); fail(e.getMessage()); } } @Test void testSubscribers() { Mockito.when(subscribeManager.getSubscribers(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean())) .thenReturn(Collections.singletonList(Mockito.mock(Subscriber.class))); MockHttpServletRequest servletRequest = new MockHttpServletRequest(); servletRequest.addParameter(CommonParams.SERVICE_NAME, TEST_SERVICE_NAME); ObjectNode objectNode = serviceController.subscribers(servletRequest); assertEquals(1, objectNode.get("count").asInt()); } }
ServiceControllerTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/entrypoint/ClusterConfigurationParserFactory.java
{ "start": 1399, "end": 2215 }
class ____ implements ParserResultFactory<ClusterConfiguration> { public static Options options() { final Options options = new Options(); options.addOption(CONFIG_DIR_OPTION); options.addOption(DYNAMIC_PROPERTY_OPTION); return options; } @Override public Options getOptions() { return options(); } @Override public ClusterConfiguration createResult(@Nonnull CommandLine commandLine) { final String configDir = commandLine.getOptionValue(CONFIG_DIR_OPTION.getOpt()); final Properties dynamicProperties = commandLine.getOptionProperties(DYNAMIC_PROPERTY_OPTION.getOpt()); return new ClusterConfiguration(configDir, dynamicProperties, commandLine.getArgs()); } }
ClusterConfigurationParserFactory
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/MulticastParallelAllTimeoutAwareTest.java
{ "start": 1333, "end": 2905 }
class ____ extends ContextTestSupport { private volatile Exchange receivedExchange; private volatile int receivedIndex; private volatile int receivedTotal; private volatile long receivedTimeout; @Test public void testMulticastParallelAllTimeoutAware() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); // ABC will timeout so we only get our canned response mock.expectedBodiesReceived("AllTimeout"); template.sendBody("direct:start", "Hello"); assertMockEndpointsSatisfied(); assertNotNull(receivedExchange); // Just make sure the MyAggregationStrategy is called for all the // exchange assertEquals(2, receivedIndex); assertEquals(3, receivedTotal); assertEquals(500, receivedTimeout); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").multicast(new MyAggregationStrategy()).parallelProcessing().timeout(500) .to("direct:a", "direct:b", "direct:c") // use end to indicate end of multicast route .end().to("mock:result"); from("direct:a").delay(1000).setBody(constant("A")); from("direct:b").delay(2000).setBody(constant("B")); from("direct:c").delay(1500).setBody(constant("C")); } }; } private
MulticastParallelAllTimeoutAwareTest
java
elastic__elasticsearch
x-pack/plugin/old-lucene-versions/src/main/java/org/elasticsearch/xpack/lucene/bwc/codecs/lucene70/fst/FST.java
{ "start": 5714, "end": 12279 }
class ____<T> { // *** Arc fields. private int label; private T output; private long target; private byte flags; private T nextFinalOutput; private long nextArc; private byte nodeFlags; // *** Fields for arcs belonging to a node with fixed length arcs. // So only valid when bytesPerArc != 0. // nodeFlags == ARCS_FOR_BINARY_SEARCH || nodeFlags == ARCS_FOR_DIRECT_ADDRESSING. private int bytesPerArc; private long posArcsStart; private int arcIdx; private int numArcs; // *** Fields for a direct addressing node. nodeFlags == ARCS_FOR_DIRECT_ADDRESSING. /** * Start position in the {@link BytesReader} of the presence bits for a direct addressing * node, aka the bit-table */ private long bitTableStart; /** First label of a direct addressing node. */ private int firstLabel; /** * Index of the current label of a direct addressing node. While {@link #arcIdx} is the current * index in the label range, {@link #presenceIndex} is its corresponding index in the list of * actually present labels. It is equal to the number of bits set before the bit at {@link * #arcIdx} in the bit-table. This field is a cache to avoid to count bits set repeatedly when * iterating the next arcs. */ private int presenceIndex; /** Returns this */ public Arc<T> copyFrom(Arc<T> other) { label = other.label(); target = other.target(); flags = other.flags(); output = other.output(); nextFinalOutput = other.nextFinalOutput(); nextArc = other.nextArc(); nodeFlags = other.nodeFlags(); bytesPerArc = other.bytesPerArc(); // Fields for arcs belonging to a node with fixed length arcs. // We could avoid copying them if bytesPerArc() == 0 (this was the case with previous code, // and the current code // still supports that), but it may actually help external uses of FST to have consistent arc // state, and debugging // is easier. posArcsStart = other.posArcsStart(); arcIdx = other.arcIdx(); numArcs = other.numArcs(); bitTableStart = other.bitTableStart; firstLabel = other.firstLabel(); presenceIndex = other.presenceIndex; return this; } boolean flag(int flag) { return FST.flag(flags, flag); } public boolean isLast() { return flag(BIT_LAST_ARC); } public boolean isFinal() { return flag(BIT_FINAL_ARC); } @Override public String toString() { StringBuilder b = new StringBuilder(); b.append(" target=").append(target()); b.append(" label=0x").append(Integer.toHexString(label())); if (flag(BIT_FINAL_ARC)) { b.append(" final"); } if (flag(BIT_LAST_ARC)) { b.append(" last"); } if (flag(BIT_TARGET_NEXT)) { b.append(" targetNext"); } if (flag(BIT_STOP_NODE)) { b.append(" stop"); } if (flag(BIT_ARC_HAS_OUTPUT)) { b.append(" output=").append(output()); } if (flag(BIT_ARC_HAS_FINAL_OUTPUT)) { b.append(" nextFinalOutput=").append(nextFinalOutput()); } if (bytesPerArc() != 0) { b.append(" arcArray(idx=") .append(arcIdx()) .append(" of ") .append(numArcs()) .append(")") .append("(") .append(nodeFlags() == ARCS_FOR_DIRECT_ADDRESSING ? "da" : "bs") .append(")"); } return b.toString(); } public int label() { return label; } public T output() { return output; } /** Ord/address to target node. */ public long target() { return target; } public byte flags() { return flags; } public T nextFinalOutput() { return nextFinalOutput; } /** * Address (into the byte[]) of the next arc - only for list of variable length arc. Or * ord/address to the next node if label == {@link #END_LABEL}. */ long nextArc() { return nextArc; } /** Where we are in the array; only valid if bytesPerArc != 0. */ public int arcIdx() { return arcIdx; } /** * Node header flags. Only meaningful to check if the value is either {@link * #ARCS_FOR_BINARY_SEARCH} or {@link #ARCS_FOR_DIRECT_ADDRESSING} (other value when bytesPerArc * == 0). */ public byte nodeFlags() { return nodeFlags; } /** Where the first arc in the array starts; only valid if bytesPerArc != 0 */ public long posArcsStart() { return posArcsStart; } /** * Non-zero if this arc is part of a node with fixed length arcs, which means all arcs for the * node are encoded with a fixed number of bytes so that we binary search or direct address. We * do when there are enough arcs leaving one node. It wastes some bytes but gives faster * lookups. */ public int bytesPerArc() { return bytesPerArc; } /** * How many arcs; only valid if bytesPerArc != 0 (fixed length arcs). For a node designed for * binary search this is the array size. For a node designed for direct addressing, this is the * label range. */ public int numArcs() { return numArcs; } /** * First label of a direct addressing node. Only valid if nodeFlags == {@link * #ARCS_FOR_DIRECT_ADDRESSING}. */ int firstLabel() { return firstLabel; } /** * Helper methods to read the bit-table of a direct addressing node. Only valid for {@link Arc} * with {@link Arc#nodeFlags()} == {@code ARCS_FOR_DIRECT_ADDRESSING}. */ static
Arc
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/comparables/Comparables_isBetween_Test.java
{ "start": 1446, "end": 7120 }
class ____ extends ComparablesBaseTest { @Test void succeeds_if_actual_is_between_start_and_end() { assertThat(BigInteger.ONE).isBetween(BigInteger.ZERO, BigInteger.TEN); } @Test void succeeds_if_actual_is_equal_to_start() { comparables.assertIsBetween(someInfo(), 8, 8, 10, true, true); } @Test void succeeds_if_actual_is_equal_to_end() { comparables.assertIsBetween(someInfo(), 10, 8, 10, true, true); } @Test void fails_if_actual_is_less_than_start() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> comparables.assertIsBetween(someInfo(), 6, 8, 10, true, true)) .withMessage("%nExpecting actual:%n 6%nto be between:%n [8, 10]%n".formatted()); } @Test void fails_if_actual_is_greater_than_end() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> comparables.assertIsBetween(someInfo(), 12, 8, 10, true, true)) .withMessage("%nExpecting actual:%n 12%nto be between:%n [8, 10]%n".formatted()); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> comparables.assertIsBetween(someInfo(), null, 8, 10, true, true)) .withMessage(actualIsNull()); } @Test void should_fail_if_start_is_null() { assertThatNullPointerException().isThrownBy(() -> comparables.assertIsBetween(someInfo(), 8, null, 10, true, true)) .withMessage("The start range to compare actual with should not be null"); } @Test void should_fail_if_end_is_null() { assertThatNullPointerException().isThrownBy(() -> comparables.assertIsBetween(someInfo(), 8, 10, null, true, true)) .withMessage("The end range to compare actual with should not be null"); } @Test void should_fail_if_end_is_less_than_start() { assertThatIllegalArgumentException().isThrownBy(() -> comparables.assertIsBetween(someInfo(), 8, 10, 8, true, true)) .withMessage("The end value <8> must not be less than the start value <10>!"); } @Test void succeeds_if_end_is_equal_to_start() { comparables.assertIsBetween(someInfo(), 8, 8, 8, true, true); comparables.assertIsBetween(someInfo(), BigDecimal.TEN, BigDecimal.TEN, BigDecimal.TEN, true, true); comparables.assertIsBetween(someInfo(), BigDecimal.TEN, new BigDecimal("10.000"), new BigDecimal("10.000"), true, true); comparables.assertIsBetween(someInfo(), BigDecimal.TEN, new BigDecimal("10.000"), new BigDecimal("10.0"), true, true); comparables.assertIsBetween(someInfo(), BigDecimal.TEN, new BigDecimal("10.00"), new BigDecimal("10.0000"), true, true); } // ------------------------------------------------------------------------------------------------------------------ // tests using a custom comparison strategy // ------------------------------------------------------------------------------------------------------------------ @Test void succeeds_if_actual_is_between_start_and_end_according_to_custom_comparison_strategy() { comparablesWithCustomComparisonStrategy.assertIsBetween(someInfo(), -7, 6, 8, true, true); } @Test void fails_if_actual_is_is_greater_than_end_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> comparablesWithCustomComparisonStrategy.assertIsBetween(someInfo(), -12, 8, 10, true, true)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeBetween(-12, 8, 10, true, true, customComparisonStrategy)); } @Test void fails_if_actual_is_is_less_than_start_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> comparablesWithCustomComparisonStrategy.assertIsBetween(someInfo(), 6, -8, 10, true, true)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldBeBetween(6, -8, 10, true, true, customComparisonStrategy)); } @Test void fails_if_end_is_less_than_start_according_to_custom_comparison_strategy() { assertThatIllegalArgumentException().isThrownBy(() -> comparablesWithCustomComparisonStrategy.assertIsBetween(someInfo(), 8, -10, 8, true, true)) .withMessage("The end value <8> must not be less than the start value <-10> (using AbsValueComparator)!"); } }
Comparables_isBetween_Test
java
apache__camel
components/camel-pqc/src/main/java/org/apache/camel/component/pqc/PQCConfiguration.java
{ "start": 1191, "end": 6600 }
class ____ implements Cloneable { @UriPath(description = "Logical name") @Metadata(required = true) private String label; @UriParam @Metadata(label = "advanced", autowired = true) private KeyPair keyPair; @UriParam @Metadata(required = true) private PQCOperations operation; @UriParam @Metadata(label = "advanced", autowired = true) private Signature signer; @UriParam(enums = "MLDSA,SLHDSA,LMS,HSS,XMSS,XMSSMT,DILITHIUM,FALCON,PICNIC,SNOVA,MAYO,SPHINCSPLUS") @Metadata(label = "advanced") private String signatureAlgorithm; @UriParam @Metadata(label = "advanced", autowired = true) private KeyGenerator keyGenerator; @UriParam(enums = "MLKEM,BIKE,HQC,CMCE,SABER,FRODO,NTRU,NTRULPRime,SNTRUPrime,KYBER") @Metadata(label = "advanced") private String keyEncapsulationAlgorithm; @UriParam(enums = "AES,ARIA,RC2,RC5,CAMELLIA,CAST5,CAST6,CHACHA7539,DSTU7624,GOST28147,GOST3412_2015,GRAIN128,HC128,HC256,SALSA20,SEED,SM4,DESEDE") @Metadata(label = "advanced") private String symmetricKeyAlgorithm; @UriParam @Metadata(label = "advanced", defaultValue = "128") private int symmetricKeyLength = 128; @UriParam @Metadata(label = "advanced", defaultValue = "false") private boolean storeExtractedSecretKeyAsHeader = false; @UriParam @Metadata(label = "advanced", autowired = true) private KeyStore keyStore; @UriParam @Metadata(label = "advanced") private String keyPairAlias; @UriParam @Metadata(label = "advanced", secret = true) private String keyStorePassword; public PQCOperations getOperation() { return operation; } /** * The operation to perform */ public void setOperation(PQCOperations operation) { this.operation = operation; } public KeyPair getKeyPair() { return keyPair; } /** * The KeyPair to be used */ public void setKeyPair(KeyPair keyPair) { this.keyPair = keyPair; } public Signature getSigner() { return signer; } /** * The Signer to be used */ public void setSigner(Signature signer) { this.signer = signer; } public String getSignatureAlgorithm() { return signatureAlgorithm; } /** * In case there is no signer, we specify an algorithm to build the KeyPair or the Signer */ public void setSignatureAlgorithm(String signatureAlgorithm) { this.signatureAlgorithm = signatureAlgorithm; } public KeyGenerator getKeyGenerator() { return keyGenerator; } /** * The Key Generator to be used in encapsulation and extraction */ public void setKeyGenerator(KeyGenerator keyGenerator) { this.keyGenerator = keyGenerator; } public String getKeyEncapsulationAlgorithm() { return keyEncapsulationAlgorithm; } /** * In case there is no keyGenerator, we specify an algorithm to build the KeyGenerator */ public void setKeyEncapsulationAlgorithm(String keyEncapsulationAlgorithm) { this.keyEncapsulationAlgorithm = keyEncapsulationAlgorithm; } public String getSymmetricKeyAlgorithm() { return symmetricKeyAlgorithm; } /** * In case we are using KEM operations, we need a Symmetric algorithm to be defined for the flow to work. */ public void setSymmetricKeyAlgorithm(String symmetricKeyAlgorithm) { this.symmetricKeyAlgorithm = symmetricKeyAlgorithm; } public int getSymmetricKeyLength() { return symmetricKeyLength; } /** * The required length of the symmetric key used */ public void setSymmetricKeyLength(int symmetricKeyLength) { this.symmetricKeyLength = symmetricKeyLength; } public boolean isStoreExtractedSecretKeyAsHeader() { return storeExtractedSecretKeyAsHeader; } /** * In the context of extractSecretKeyFromEncapsulation operation, this option define if we want to have the key set * as header */ public void setStoreExtractedSecretKeyAsHeader(boolean storeExtractedSecretKeyAsHeader) { this.storeExtractedSecretKeyAsHeader = storeExtractedSecretKeyAsHeader; } public KeyStore getKeyStore() { return keyStore; } /** * A KeyStore where we could get Cryptographic material */ public void setKeyStore(KeyStore keyStore) { this.keyStore = keyStore; } public String getKeyStorePassword() { return keyStorePassword; } /** * The KeyStore password to use in combination with KeyStore Parameter */ public void setKeyStorePassword(String keyStorePassword) { this.keyStorePassword = keyStorePassword; } public String getKeyPairAlias() { return keyPairAlias; } /** * A KeyPair alias to use in combination with KeyStore parameter */ public void setKeyPairAlias(String keyPairAlias) { this.keyPairAlias = keyPairAlias; } // ************************************************* // // ************************************************* public PQCConfiguration copy() { try { return (PQCConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } }
PQCConfiguration
java
elastic__elasticsearch
x-pack/plugin/sql/jdbc/src/main/java/org/elasticsearch/xpack/sql/jdbc/JdbcResultSetMetaData.java
{ "start": 518, "end": 4211 }
class ____ implements ResultSetMetaData, JdbcWrapper { private final JdbcResultSet rs; private final List<JdbcColumnInfo> columns; JdbcResultSetMetaData(JdbcResultSet rs, List<JdbcColumnInfo> columns) { this.rs = rs; this.columns = columns; } @Override public int getColumnCount() throws SQLException { checkOpen(); return columns.size(); } @Override public boolean isAutoIncrement(int column) throws SQLException { column(column); return false; } @Override public boolean isCaseSensitive(int column) throws SQLException { column(column); return true; } @Override public boolean isSearchable(int column) throws SQLException { column(column); return true; } @Override public boolean isCurrency(int column) throws SQLException { column(column); return false; } @Override public int isNullable(int column) throws SQLException { column(column); return columnNullableUnknown; } @Override public boolean isSigned(int column) throws SQLException { return TypeUtils.isSigned(column(column).type); } @Override public int getColumnDisplaySize(int column) throws SQLException { return column(column).displaySize(); } @Override public String getColumnLabel(int column) throws SQLException { JdbcColumnInfo info = column(column); return EMPTY.equals(info.label) ? info.name : info.label; } @Override public String getColumnName(int column) throws SQLException { return column(column).name; } @Override public String getSchemaName(int column) throws SQLException { return column(column).schema; } @Override public int getPrecision(int column) throws SQLException { column(column); return 0; } @Override public int getScale(int column) throws SQLException { return column(column).displaySize(); } @Override public String getTableName(int column) throws SQLException { return column(column).table; } @Override public String getCatalogName(int column) throws SQLException { return column(column).catalog; } @Override public int getColumnType(int column) throws SQLException { return column(column).type.getVendorTypeNumber(); } @Override public String getColumnTypeName(int column) throws SQLException { return column(column).type.getName(); } @Override public boolean isReadOnly(int column) throws SQLException { column(column); return true; } @Override public boolean isWritable(int column) throws SQLException { column(column); return false; } @Override public boolean isDefinitelyWritable(int column) throws SQLException { column(column); return false; } @Override public String getColumnClassName(int column) throws SQLException { return TypeUtils.classOf(column(column).type).getName(); } private void checkOpen() throws SQLException { if (rs != null) { rs.checkOpen(); } } private JdbcColumnInfo column(int column) throws SQLException { checkOpen(); if (column < 1 || column > columns.size()) { throw new SQLException("Invalid column index [" + column + "]"); } return columns.get(column - 1); } @Override public String toString() { return format(Locale.ROOT, "%s(%s)", getClass().getSimpleName(), columns); } }
JdbcResultSetMetaData
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_haveAtMost_Test.java
{ "start": 1077, "end": 1553 }
class ____ extends ObjectArrayAssertBaseTest { private Condition<Object> condition; @BeforeEach void before() { condition = new TestCondition<>(); } @Override protected ObjectArrayAssert<Object> invoke_api_method() { return assertions.haveAtMost(2, condition); } @Override protected void verify_internal_effects() { verify(arrays).assertHaveAtMost(getInfo(assertions), getActual(assertions), 2, condition); } }
ObjectArrayAssert_haveAtMost_Test