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
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/fs/slive/PathFinder.java
{ "start": 1096, "end": 3359 }
enum ____ { FILE, DIRECTORY } private static final String DIR_PREFIX = "sl_dir_"; private static final String FILE_PREFIX = "sl_file_"; private Path basePath; private ConfigExtractor config; private Random rnd; PathFinder(ConfigExtractor cfg, Random rnd) { this.basePath = cfg.getDataPath(); this.config = cfg; this.rnd = rnd; } /** * This function uses a simple recursive algorithm to generate a path name * using the current id % limitPerDir and using current id / limitPerDir to * form the rest of the tree segments * * @param curId * the current id to use for determining the current directory id % * per directory limit and then used for determining the next segment * of the path to use, if <= zero this will return the base path * @param limitPerDir * the per directory file limit used in modulo and division * operations to calculate the file name and path tree * @param type * directory or file enumeration * @return Path */ private Path getPath(int curId, int limitPerDir, Type type) { if (curId <= 0) { return basePath; } String name = ""; switch (type) { case FILE: name = FILE_PREFIX + new Integer(curId % limitPerDir).toString(); break; case DIRECTORY: name = DIR_PREFIX + new Integer(curId % limitPerDir).toString(); break; } Path base = getPath((curId / limitPerDir), limitPerDir, Type.DIRECTORY); return new Path(base, name); } /** * Gets a file path using the given configuration provided total files and * files per directory * * @return path */ Path getFile() { int fileLimit = config.getTotalFiles(); int dirLimit = config.getDirSize(); int startPoint = 1 + rnd.nextInt(fileLimit); return getPath(startPoint, dirLimit, Type.FILE); } /** * Gets a directory path using the given configuration provided total files * and files per directory * * @return path */ Path getDirectory() { int fileLimit = config.getTotalFiles(); int dirLimit = config.getDirSize(); int startPoint = rnd.nextInt(fileLimit); return getPath(startPoint, dirLimit, Type.DIRECTORY); } }
Type
java
apache__flink
flink-filesystems/flink-hadoop-fs/src/test/java/org/apache/flink/runtime/fs/hdfs/HadoopConfigLoadingTest.java
{ "start": 1491, "end": 10062 }
class ____ { private static final String IN_CP_CONFIG_KEY = "cp_conf_key"; private static final String IN_CP_CONFIG_VALUE = "oompf!"; @Test void loadFromClasspathByDefault() { org.apache.hadoop.conf.Configuration hadoopConf = HadoopUtils.getHadoopConfiguration(new Configuration()); assertThat(hadoopConf.get(IN_CP_CONFIG_KEY, null)).isEqualTo(IN_CP_CONFIG_VALUE); } @Test void loadFromEnvVariables(@TempDir File hadoopConfDir, @TempDir File hadoopHome) throws Exception { final String k1 = "where?"; final String v1 = "I'm on a boat"; final String k2 = "when?"; final String v2 = "midnight"; final String k3 = "why?"; final String v3 = "what do you think?"; final String k4 = "which way?"; final String v4 = "south, always south..."; final String k5 = "how long?"; final String v5 = "an eternity"; final String k6 = "for real?"; final String v6 = "quite so..."; final File hadoopHomeConf = new File(hadoopHome, "conf"); final File hadoopHomeEtc = new File(hadoopHome, "etc/hadoop"); assertThat(hadoopHomeConf.mkdirs()).isTrue(); assertThat(hadoopHomeEtc.mkdirs()).isTrue(); final File file1 = new File(hadoopConfDir, "core-site.xml"); final File file2 = new File(hadoopConfDir, "hdfs-site.xml"); final File file3 = new File(hadoopHomeConf, "core-site.xml"); final File file4 = new File(hadoopHomeConf, "hdfs-site.xml"); final File file5 = new File(hadoopHomeEtc, "core-site.xml"); final File file6 = new File(hadoopHomeEtc, "hdfs-site.xml"); printConfig(file1, k1, v1); printConfig(file2, k2, v2); printConfig(file3, k3, v3); printConfig(file4, k4, v4); printConfig(file5, k5, v5); printConfig(file6, k6, v6); final org.apache.hadoop.conf.Configuration hadoopConf; final Map<String, String> originalEnv = System.getenv(); final Map<String, String> newEnv = new HashMap<>(originalEnv); newEnv.put("HADOOP_CONF_DIR", hadoopConfDir.getAbsolutePath()); newEnv.put("HADOOP_HOME", hadoopHome.getAbsolutePath()); try { CommonTestUtils.setEnv(newEnv); hadoopConf = HadoopUtils.getHadoopConfiguration(new Configuration()); } finally { CommonTestUtils.setEnv(originalEnv); } // contains extra entries assertThat(hadoopConf.get(k1, null)).isEqualTo(v1); assertThat(hadoopConf.get(k2, null)).isEqualTo(v2); assertThat(hadoopConf.get(k3, null)).isEqualTo(v3); assertThat(hadoopConf.get(k4, null)).isEqualTo(v4); assertThat(hadoopConf.get(k5, null)).isEqualTo(v5); assertThat(hadoopConf.get(k6, null)).isEqualTo(v6); // also contains classpath defaults assertThat(hadoopConf.get(IN_CP_CONFIG_KEY, null)).isEqualTo(IN_CP_CONFIG_VALUE); } @Test void loadOverlappingConfig( @TempDir File hadoopConfDir, @TempDir File hadoopConfEntryDir, @TempDir File legacyConfDir, @TempDir File hadoopHome) throws Exception { final String k1 = "key1"; final String k2 = "key2"; final String k3 = "key3"; final String k4 = "key4"; final String k5 = "key5"; final String v1 = "from HADOOP_CONF_DIR"; final String v2 = "from HADOOP_HOME/etc/hadoop"; final String v3 = "from HADOOP_HOME/etc/hadoop"; final String v4 = "from HADOOP_HOME/etc/hadoop"; final String v5 = "from HADOOP_HOME/conf"; final File hadoopHomeConf = new File(hadoopHome, "conf"); final File hadoopHomeEtc = new File(hadoopHome, "etc/hadoop"); assertThat(hadoopHomeConf.mkdirs()).isTrue(); assertThat(hadoopHomeEtc.mkdirs()).isTrue(); final File file1 = new File(hadoopConfDir, "core-site.xml"); final File file2 = new File(hadoopConfEntryDir, "core-site.xml"); final File file3 = new File(legacyConfDir, "core-site.xml"); final File file4 = new File(hadoopHomeEtc, "core-site.xml"); final File file5 = new File(hadoopHomeConf, "core-site.xml"); printConfig(file1, k1, v1); Map<String, String> properties2 = new HashMap<>(); properties2.put(k1, v2); properties2.put(k2, v2); printConfigs(file2, properties2); Map<String, String> properties3 = new HashMap<>(); properties3.put(k1, v3); properties3.put(k2, v3); properties3.put(k3, v3); printConfigs(file3, properties3); Map<String, String> properties4 = new HashMap<>(); properties4.put(k1, v4); properties4.put(k2, v4); properties4.put(k3, v4); properties4.put(k4, v4); printConfigs(file4, properties4); Map<String, String> properties5 = new HashMap<>(); properties5.put(k1, v5); properties5.put(k2, v5); properties5.put(k3, v5); properties5.put(k4, v5); properties5.put(k5, v5); printConfigs(file5, properties5); final Configuration cfg = new Configuration(); final org.apache.hadoop.conf.Configuration hadoopConf; final Map<String, String> originalEnv = System.getenv(); final Map<String, String> newEnv = new HashMap<>(originalEnv); newEnv.put("HADOOP_CONF_DIR", hadoopConfDir.getAbsolutePath()); newEnv.put("HADOOP_HOME", hadoopHome.getAbsolutePath()); try { CommonTestUtils.setEnv(newEnv); hadoopConf = HadoopUtils.getHadoopConfiguration(cfg); } finally { CommonTestUtils.setEnv(originalEnv); } // contains extra entries assertThat(hadoopConf.get(k1, null)).isEqualTo(v1); assertThat(hadoopConf.get(k2, null)).isEqualTo(v2); assertThat(hadoopConf.get(k3, null)).isEqualTo(v3); assertThat(hadoopConf.get(k4, null)).isEqualTo(v4); assertThat(hadoopConf.get(k5, null)).isEqualTo(v5); // also contains classpath defaults assertThat(hadoopConf.get(IN_CP_CONFIG_KEY, null)).isEqualTo(IN_CP_CONFIG_VALUE); } @Test void loadFromFlinkConfEntry() throws Exception { final String prefix = "flink.hadoop."; final String k1 = "brooklyn"; final String v1 = "nets"; final String k2 = "miami"; final String v2 = "heat"; final String k3 = "philadelphia"; final String v3 = "76ers"; final String k4 = "golden.state"; final String v4 = "warriors"; final String k5 = "oklahoma.city"; final String v5 = "thunders"; final Configuration cfg = new Configuration(); cfg.setString(prefix + k1, v1); cfg.setString(prefix + k2, v2); cfg.setString(prefix + k3, v3); cfg.setString(prefix + k4, v4); cfg.setString(k5, v5); org.apache.hadoop.conf.Configuration hadoopConf = HadoopUtils.getHadoopConfiguration(cfg); // contains extra entries assertThat(hadoopConf.get(k1, null)).isEqualTo(v1); assertThat(hadoopConf.get(k2, null)).isEqualTo(v2); assertThat(hadoopConf.get(k3, null)).isEqualTo(v3); assertThat(hadoopConf.get(k4, null)).isEqualTo(v4); assertThat(hadoopConf.get(k5)).isNull(); // also contains classpath defaults assertThat(hadoopConf.get(IN_CP_CONFIG_KEY, null)).isEqualTo(IN_CP_CONFIG_VALUE); } private static void printConfig(File file, String key, String value) throws IOException { Map<String, String> map = new HashMap<>(1); map.put(key, value); printConfigs(file, map); } private static void printConfigs(File file, Map<String, String> properties) throws IOException { try (PrintStream out = new PrintStream(new FileOutputStream(file))) { out.println("<?xml version=\"1.0\"?>"); out.println("<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>"); out.println("<configuration>"); for (Map.Entry<String, String> entry : properties.entrySet()) { out.println("\t<property>"); out.println("\t\t<name>" + entry.getKey() + "</name>"); out.println("\t\t<value>" + entry.getValue() + "</value>"); out.println("\t</property>"); } out.println("</configuration>"); } } }
HadoopConfigLoadingTest
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestYARNRunner.java
{ "start": 6654, "end": 7174 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(TestYARNRunner.class); private static final RecordFactory recordFactory = RecordFactoryProvider.getRecordFactory(null); // prefix before <LOG_DIR>/profile.out private static final String PROFILE_PARAMS = MRJobConfig.DEFAULT_TASK_PROFILE_PARAMS.substring(0, MRJobConfig.DEFAULT_TASK_PROFILE_PARAMS.lastIndexOf("%")); private static final String CUSTOM_RESOURCE_NAME = "a-custom-resource"; private static
TestYARNRunner
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/convert/support/CharacterToNumberFactory.java
{ "start": 1427, "end": 1678 }
class ____ implements ConverterFactory<Character, Number> { @Override public <T extends Number> Converter<Character, T> getConverter(Class<T> targetType) { return new CharacterToNumber<>(targetType); } private static final
CharacterToNumberFactory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/criteria/CountQueryTests.java
{ "start": 14722, "end": 14916 }
class ____ { private String description; public BaseAttribs() { } public BaseAttribs(String description) { this.description = description; } } @MappedSuperclass static
BaseAttribs
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/StatisticsCollector.java
{ "start": 5223, "end": 5765 }
class ____ { final String name; private Map<TimeWindow, TimeStat> timeStats; private Stat(String name, Map<TimeWindow, TimeStat> timeStats) { this.name = name; this.timeStats = timeStats; } public synchronized void inc(int incr) { for (TimeStat ts : timeStats.values()) { ts.inc(incr); } } public synchronized void inc() { inc(1); } public synchronized Map<TimeWindow, TimeStat> getValues() { return Collections.unmodifiableMap(timeStats); } static
Stat
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/SplitterOnPrepareTest.java
{ "start": 1167, "end": 2075 }
class ____ extends ContextTestSupport { @Test public void testSplitterOnPrepare() throws Exception { getMockEndpoint("mock:a").expectedMessageCount(2); getMockEndpoint("mock:a").allMessages().body(String.class).isEqualTo("1 Tony the Tiger"); List<Animal> animals = new ArrayList<>(); animals.add(new Animal(1, "Tiger")); animals.add(new Animal(1, "Tiger")); template.sendBody("direct:start", animals); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").split(body()).onPrepare(new FixNamePrepare()).to("direct:a"); from("direct:a").process(new ProcessorA()).to("mock:a"); } }; } public static
SplitterOnPrepareTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/JobFailureMetricReporter.java
{ "start": 1222, "end": 3360 }
class ____ { public static final String FAILURE_LABEL_ATTRIBUTE_PREFIX = "failureLabel."; private final MetricGroup metricGroup; public JobFailureMetricReporter(MetricGroup metricGroup) { this.metricGroup = Preconditions.checkNotNull(metricGroup); } public void reportJobFailure( FailureHandlingResult failureHandlingResult, Map<String, String> failureLabels) { reportJobFailure( failureHandlingResult.getTimestamp(), failureHandlingResult.canRestart(), failureHandlingResult.isGlobalFailure(), failureLabels); } public void reportJobFailure( FailureResult failureHandlingResult, Map<String, String> failureLabels) { reportJobFailure( System.currentTimeMillis(), failureHandlingResult.canRestart(), null, failureLabels); } private void reportJobFailure( long timestamp, Boolean canRestart, Boolean isGlobal, Map<String, String> failureLabels) { EventBuilder eventBuilder = Events.JobFailureEvent.builder(JobFailureMetricReporter.class) .setObservedTsMillis(timestamp) .setSeverity("INFO"); if (canRestart != null) { eventBuilder.setAttribute("canRestart", String.valueOf(canRestart)); } if (isGlobal != null) { eventBuilder.setAttribute("isGlobalFailure", String.valueOf(isGlobal)); } // Add all failure labels for (Map.Entry<String, String> entry : failureLabels.entrySet()) { String value = entry.getValue(); // Add artificial value instead of null/empty string if (value == null) { value = "<null>"; } else if (value.isEmpty()) { value = "<empty>"; } eventBuilder.setAttribute(FAILURE_LABEL_ATTRIBUTE_PREFIX + entry.getKey(), value); } metricGroup.addEvent(eventBuilder); } }
JobFailureMetricReporter
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/RepositoryTransformersExtension.java
{ "start": 1209, "end": 5959 }
class ____ { private static final String CREDENTIALS_MARKER = "{spring.mavenCredentials}"; private static final String REPOSITORIES_MARKER = "{spring.mavenRepositories}"; private static final String PLUGIN_REPOSITORIES_MARKER = "{spring.mavenPluginRepositories}"; private final Project project; @Inject public RepositoryTransformersExtension(Project project) { this.project = project; } public Transformer<String, String> ant() { return this::transformAnt; } private String transformAnt(String line) { if (line.contains(REPOSITORIES_MARKER)) { return transform(line, (repository, indent) -> { String name = repository.getName(); URI url = repository.getUrl(); return "%s<ibiblio name=\"%s\" m2compatible=\"true\" root=\"%s\" />".formatted(indent, name, url); }); } if (line.contains(CREDENTIALS_MARKER)) { Map<String, MavenCredential> hostCredentials = new LinkedHashMap<>(); getSpringRepositories().forEach((repository) -> { if (repository.getName().startsWith("spring-commercial-")) { String host = repository.getUrl().getHost(); hostCredentials.put(host, new MavenCredential("${env.COMMERCIAL_REPO_USERNAME}", "${env.COMMERCIAL_REPO_PASSWORD")); } }); return transform(line, hostCredentials.entrySet(), (entry, indent) -> "%s<credentials host=\"%s\" realm=\"Artifactory Realm\" username=\"%s\" passwd=\"%s\" />%n" .formatted(indent, entry.getKey(), entry.getValue().username(), entry.getValue().password())); } return line; } public Transformer<String, String> mavenSettings() { return this::transformMavenSettings; } private String transformMavenSettings(String line) { if (line.contains(REPOSITORIES_MARKER)) { return transformMavenRepositories(line, false); } if (line.contains(PLUGIN_REPOSITORIES_MARKER)) { return transformMavenRepositories(line, true); } return line; } private String transformMavenRepositories(String line, boolean pluginRepository) { return transform(line, (repository, indent) -> mavenRepositoryXml(indent, repository, pluginRepository)); } private String mavenRepositoryXml(String indent, MavenArtifactRepository repository, boolean pluginRepository) { String rootTag = pluginRepository ? "pluginRepository" : "repository"; boolean snapshots = repository.getName().endsWith("-snapshot"); StringBuilder xml = new StringBuilder(); xml.append("%s<%s>%n".formatted(indent, rootTag)); xml.append("%s\t<id>%s</id>%n".formatted(indent, repository.getName())); xml.append("%s\t<url>%s</url>%n".formatted(indent, repository.getUrl())); xml.append("%s\t<releases>%n".formatted(indent)); xml.append("%s\t\t<enabled>%s</enabled>%n".formatted(indent, !snapshots)); xml.append("%s\t</releases>%n".formatted(indent)); xml.append("%s\t<snapshots>%n".formatted(indent)); xml.append("%s\t\t<enabled>%s</enabled>%n".formatted(indent, snapshots)); xml.append("%s\t</snapshots>%n".formatted(indent)); xml.append("%s</%s>".formatted(indent, rootTag)); return xml.toString(); } private String transform(String line, BiFunction<MavenArtifactRepository, String, String> generator) { return transform(line, getSpringRepositories(), generator); } private <T> String transform(String line, Iterable<T> iterable, BiFunction<T, String, String> generator) { StringBuilder result = new StringBuilder(); String indent = getIndent(line); iterable.forEach((item) -> { String fragment = generator.apply(item, indent); if (fragment != null) { result.append(!result.isEmpty() ? "\n" : ""); result.append(fragment); } }); return result.toString(); } private List<MavenArtifactRepository> getSpringRepositories() { List<MavenArtifactRepository> springRepositories = new ArrayList<>(this.project.getRepositories() .withType(MavenArtifactRepository.class) .stream() .filter(this::isSpringRepository) .toList()); Function<MavenArtifactRepository, Boolean> bySnapshots = (repository) -> repository.getName() .contains("snapshot"); Function<MavenArtifactRepository, String> byName = MavenArtifactRepository::getName; Collections.sort(springRepositories, Comparator.comparing(bySnapshots).thenComparing(byName)); return springRepositories; } private boolean isSpringRepository(MavenArtifactRepository repository) { return (repository.getName().startsWith("spring-")); } private String getIndent(String line) { return line.substring(0, line.length() - line.stripLeading().length()); } static void apply(Project project) { project.getExtensions().create("springRepositoryTransformers", RepositoryTransformersExtension.class, project); } record MavenCredential(String username, String password) { } }
RepositoryTransformersExtension
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/impl/SnapshotDiffReportGenerator.java
{ "start": 1303, "end": 1534 }
class ____ to end users the difference between two snapshots of * the same directory, or the difference between a snapshot of the directory and * its current state. Instead of capturing all the details of the diff, this *
represents
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/language/simple/MyAttachmentMessage.java
{ "start": 936, "end": 1266 }
class ____ extends DefaultMessage { public MyAttachmentMessage(Exchange exchange) { super(exchange); } public boolean hasAttachments() { return true; } public String toString() { return "MyAttachmentMessage"; } public int size() { return 42; } }
MyAttachmentMessage
java
spring-projects__spring-boot
documentation/spring-boot-actuator-docs/src/test/java/org/springframework/boot/actuate/docs/AbstractEndpointDocumentationTests.java
{ "start": 5999, "end": 6524 }
class ____ { @Bean static BeanPostProcessor endpointJsonMapperBeanPostProcessor() { return new BeanPostProcessor() { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof EndpointJsonMapper) { return (EndpointJsonMapper) () -> ((EndpointJsonMapper) bean).get() .rebuild() .enable(SerializationFeature.INDENT_OUTPUT) .build(); } return bean; } }; } } }
BaseDocumentationConfiguration
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsPushDownTableSample.java
{ "start": 970, "end": 1044 }
interface ____ * push down SAMPLE. * * @since 3.3.0 */ @Evolving public
to
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/settings/LocallyMountedSecrets.java
{ "start": 9990, "end": 10566 }
class ____ only be used node-locally, to represent the local secrets on a particular * node. Thus, the transport version should always be {@link TransportVersion#current()} */ public static LocalFileSecrets readFrom(StreamInput in) throws IOException { assert in.getTransportVersion() == TransportVersion.current(); return new LocalFileSecrets(in.readMap(StreamInput::readByteArray), ReservedStateVersion.readFrom(in)); } /** * Write LocalFileSecrets to stream output * * <p>This
should
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/OrphanedFormatStringTest.java
{ "start": 1787, "end": 2548 }
class ____ extends Exception { FormatException(String f, Object... xs) { super(String.format(f, xs)); } } void f() { String s = "%s"; new FormatException("%s"); System.err.printf("%s"); } void appendToStringBuilder(StringBuilder b) { b.append("%s"); } } """) .doTest(); } @Test public void formatMethod() { testHelper .addSourceLines( "Test.java", "import com.google.errorprone.annotations.FormatMethod;", "import com.google.errorprone.annotations.FormatString;", "
FormatException
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/FromPartialAggregatorFunction.java
{ "start": 782, "end": 3771 }
class ____ implements AggregatorFunction { private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of( new IntermediateStateDesc("partial", ElementType.COMPOSITE, "partial_agg") ); public static List<IntermediateStateDesc> intermediateStateDesc() { return INTERMEDIATE_STATE_DESC; } private final DriverContext driverContext; private final GroupingAggregatorFunction groupingAggregator; private final int inputChannel; private boolean receivedInput = false; public FromPartialAggregatorFunction(DriverContext driverContext, GroupingAggregatorFunction groupingAggregator, int inputChannel) { this.driverContext = driverContext; this.groupingAggregator = groupingAggregator; this.inputChannel = inputChannel; } @Override public void addRawInput(Page page, BooleanVector mask) { if (mask.isConstant() == false || mask.getBoolean(0) == false) { throw new IllegalStateException("can't mask partial"); } addIntermediateInput(page); } @Override public void addIntermediateInput(Page page) { try (IntVector groupIds = driverContext.blockFactory().newConstantIntVector(0, page.getPositionCount())) { if (page.getPositionCount() > 0) { receivedInput = true; } final CompositeBlock inputBlock = page.getBlock(inputChannel); groupingAggregator.addIntermediateInput(0, groupIds, inputBlock.asPage()); } } private IntVector outputPositions() { return driverContext.blockFactory().newConstantIntVector(0, receivedInput ? 1 : 0); } @Override public void evaluateIntermediate(Block[] blocks, int offset, DriverContext driverContext) { final Block[] partialBlocks = new Block[groupingAggregator.intermediateBlockCount()]; boolean success = false; try (IntVector selected = outputPositions()) { groupingAggregator.evaluateIntermediate(partialBlocks, 0, selected); blocks[offset] = new CompositeBlock(partialBlocks); success = true; } finally { if (success == false) { Releasables.close(partialBlocks); } } } @Override public void evaluateFinal(Block[] blocks, int offset, DriverContext driverContext) { try (IntVector selected = outputPositions()) { groupingAggregator.evaluateFinal(blocks, offset, selected, new GroupingAggregatorEvaluationContext(driverContext)); } } @Override public int intermediateBlockCount() { return INTERMEDIATE_STATE_DESC.size(); } @Override public void close() { Releasables.close(groupingAggregator); } @Override public String toString() { return getClass().getSimpleName() + "[" + "channel=" + inputChannel + ",delegate=" + groupingAggregator + "]"; } }
FromPartialAggregatorFunction
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/sql/autodiscovery/User.java
{ "start": 423, "end": 1008 }
class ____ { private Long id; private String name; private Set<Membership> memberships; public User() { } public User(String name) { this.name = name; } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany( mappedBy = "member" ) public Set<Membership> getMemberships() { return memberships; } public void setMemberships(Set<Membership> memberships) { this.memberships = memberships; } }
User
java
apache__maven
compat/maven-model-builder/src/main/java/org/apache/maven/model/building/DefaultModelBuildingEvent.java
{ "start": 1057, "end": 1723 }
class ____ implements ModelBuildingEvent { private final Model model; private final ModelBuildingRequest request; private final ModelProblemCollector problems; DefaultModelBuildingEvent(Model model, ModelBuildingRequest request, ModelProblemCollector problems) { this.model = model; this.request = request; this.problems = problems; } @Override public Model getModel() { return model; } @Override public ModelBuildingRequest getRequest() { return request; } @Override public ModelProblemCollector getProblems() { return problems; } }
DefaultModelBuildingEvent
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/placement/csmappingrule/MappingRuleMatchers.java
{ "start": 4893, "end": 6085 }
class ____ implements MappingRuleMatcher { /** * The list of matchers to be checked during evaluation. */ private MappingRuleMatcher[] matchers; /** * Constructor. * @param matchers List of matchers to be checked during evaluation */ AndMatcher(MappingRuleMatcher...matchers) { this.matchers = matchers; } /** * This match method will go through all the provided matchers and call * their match method, if all match we return true. * @param variables The variable context, which contains all the variables * @return true if all matchers match */ @Override public boolean match(VariableContext variables) { for (MappingRuleMatcher matcher : matchers) { if (!matcher.match(variables)) { return false; } } return true; } @Override public String toString() { return "AndMatcher{" + "matchers=" + Arrays.toString(matchers) + '}'; } } /** * OrMatcher is a basic boolean matcher which takes multiple other * matcher as its arguments, and on match it checks if any of them are true. */ public static
AndMatcher
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/aggregate/IrateTests.java
{ "start": 1215, "end": 7027 }
class ____ extends AbstractAggregationTestCase { public IrateTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) { this.testCase = testCaseSupplier.get(); } @ParametersFactory public static Iterable<Object[]> parameters() { var suppliers = new ArrayList<TestCaseSupplier>(); var valuesSuppliers = List.of( MultiRowTestCaseSupplier.longCases(1, 1000, 0, 1000_000_000, true), MultiRowTestCaseSupplier.intCases(1, 1000, 0, 1000_000_000, true), MultiRowTestCaseSupplier.doubleCases(1, 1000, 0, 1000_000_000, true) ); for (List<TestCaseSupplier.TypedDataSupplier> valuesSupplier : valuesSuppliers) { for (TestCaseSupplier.TypedDataSupplier fieldSupplier : valuesSupplier) { TestCaseSupplier testCaseSupplier = makeSupplier(fieldSupplier); suppliers.add(testCaseSupplier); } } return parameterSuppliersFromTypedDataWithDefaultChecks(suppliers); } @Override protected Expression build(Source source, List<Expression> args) { return new Irate(source, args.get(0), args.get(1)); } @Override public void testAggregate() { assumeTrue("time-series aggregation doesn't support ungrouped", false); } @Override public void testAggregateToString() { assumeTrue("time-series aggregation doesn't support ungrouped", false); } @Override public void testAggregateIntermediate() { assumeTrue("time-series aggregation doesn't support ungrouped", false); } private static DataType counterType(DataType type) { return switch (type) { case DOUBLE -> DataType.COUNTER_DOUBLE; case LONG -> DataType.COUNTER_LONG; case INTEGER -> DataType.COUNTER_INTEGER; default -> throw new AssertionError("unknown type for counter: " + type); }; } @SuppressWarnings("unchecked") private static TestCaseSupplier makeSupplier(TestCaseSupplier.TypedDataSupplier fieldSupplier) { DataType type = counterType(fieldSupplier.type()); return new TestCaseSupplier(fieldSupplier.name(), List.of(type, DataType.DATETIME, DataType.INTEGER, DataType.LONG), () -> { TestCaseSupplier.TypedData fieldTypedData = fieldSupplier.get(); List<Object> dataRows = fieldTypedData.multiRowData(); if (randomBoolean()) { List<Object> withNulls = new ArrayList<>(dataRows.size()); for (Object dataRow : dataRows) { if (randomBoolean()) { withNulls.add(null); } else { withNulls.add(dataRow); } } dataRows = withNulls; } fieldTypedData = TestCaseSupplier.TypedData.multiRow(dataRows, type, fieldTypedData.name()); List<Long> timestamps = new ArrayList<>(); List<Integer> slices = new ArrayList<>(); List<Long> maxTimestamps = new ArrayList<>(); long lastTimestamp = randomLongBetween(0, 1_000_000); for (int row = 0; row < dataRows.size(); row++) { lastTimestamp += randomLongBetween(1, 10_000); timestamps.add(lastTimestamp); slices.add(0); maxTimestamps.add(Long.MAX_VALUE); } TestCaseSupplier.TypedData timestampsField = TestCaseSupplier.TypedData.multiRow( timestamps.reversed(), DataType.DATETIME, "timestamps" ); TestCaseSupplier.TypedData sliceIndexType = TestCaseSupplier.TypedData.multiRow(slices, DataType.INTEGER, "_slice_index"); TestCaseSupplier.TypedData nextTimestampType = TestCaseSupplier.TypedData.multiRow( maxTimestamps, DataType.LONG, "_max_timestamp" ); List<Object> nonNullDataRows = dataRows.stream().filter(Objects::nonNull).toList(); Matcher<?> matcher; if (nonNullDataRows.size() < 2) { matcher = Matchers.nullValue(); } else { var lastValue = ((Number) nonNullDataRows.getFirst()).doubleValue(); var secondLastValue = ((Number) nonNullDataRows.get(1)).doubleValue(); var increase = lastValue >= secondLastValue ? lastValue - secondLastValue : lastValue; var largestTimestamp = timestamps.get(0); var secondLargestTimestamp = timestamps.get(1); var smallestTimestamp = timestamps.getLast(); matcher = Matchers.allOf( Matchers.greaterThanOrEqualTo(increase / (largestTimestamp - smallestTimestamp) * 1000 * 0.9), Matchers.lessThanOrEqualTo( increase / (largestTimestamp - secondLargestTimestamp) * (largestTimestamp - smallestTimestamp) * 1000 ) ); } return new TestCaseSupplier.TestCase( List.of(fieldTypedData, timestampsField, sliceIndexType, nextTimestampType), standardAggregatorName("Irate", fieldTypedData.type()), DataType.DOUBLE, matcher ); }); } public static List<DocsV3Support.Param> signatureTypes(List<DocsV3Support.Param> params) { assertThat(params, hasSize(4)); assertThat(params.get(1).dataType(), equalTo(DataType.DATETIME)); assertThat(params.get(2).dataType(), equalTo(DataType.INTEGER)); assertThat(params.get(3).dataType(), equalTo(DataType.LONG)); return List.of(params.get(0)); } }
IrateTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/action/shard/ShardStateAction.java
{ "start": 23243, "end": 28193 }
class ____ extends AbstractTransportRequest { final ShardId shardId; final String allocationId; final long primaryTerm; final String message; @Nullable final Exception failure; final boolean markAsStale; FailedShardEntry(StreamInput in) throws IOException { super(in); shardId = new ShardId(in); allocationId = in.readString(); primaryTerm = in.readVLong(); message = in.readString(); failure = in.readException(); markAsStale = in.readBoolean(); } public FailedShardEntry( ShardId shardId, String allocationId, long primaryTerm, String message, @Nullable Exception failure, boolean markAsStale ) { this.shardId = shardId; this.allocationId = allocationId; this.primaryTerm = primaryTerm; this.message = message; this.failure = failure; this.markAsStale = markAsStale; } public ShardId getShardId() { return shardId; } public String getAllocationId() { return allocationId; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); shardId.writeTo(out); out.writeString(allocationId); out.writeVLong(primaryTerm); out.writeString(message); out.writeException(failure); out.writeBoolean(markAsStale); } @Override public String toString() { return toString(true); } public String toStringNoFailureStackTrace() { return toString(false); } private String toString(boolean includeStackTrace) { return Strings.format( "FailedShardEntry{shardId [%s], allocationId [%s], primary term [%d], message [%s], markAsStale [%b], failure [%s]}", shardId, allocationId, primaryTerm, message, markAsStale, failure == null ? null : (includeStackTrace ? ExceptionsHelper.stackTrace(failure) : failure.getMessage()) ); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FailedShardEntry that = (FailedShardEntry) o; // Exclude message and exception from equals and hashCode return Objects.equals(this.shardId, that.shardId) && Objects.equals(this.allocationId, that.allocationId) && primaryTerm == that.primaryTerm && markAsStale == that.markAsStale; } @Override public int hashCode() { return Objects.hash(shardId, allocationId, primaryTerm, markAsStale); } } public record FailedShardUpdateTask(FailedShardEntry entry, ActionListener<Void> listener) implements ClusterStateTaskListener { public void onSuccess() { listener.onResponse(null); } @Override public void onFailure(Exception e) { logger.log( isPublishFailureException(e) ? DEBUG : ERROR, () -> format("%s unexpected failure while failing shard [%s]", entry.shardId, entry), e ); listener.onFailure(e); } } public void shardStarted( final ShardRouting shardRouting, final long primaryTerm, final String message, final ShardLongFieldRange timestampRange, final ShardLongFieldRange eventIngestedRange, final ActionListener<Void> listener ) { shardStarted(shardRouting, primaryTerm, message, timestampRange, eventIngestedRange, listener, clusterService.state()); } public void shardStarted( final ShardRouting shardRouting, final long primaryTerm, final String message, final ShardLongFieldRange timestampRange, final ShardLongFieldRange eventIngestedRange, final ActionListener<Void> listener, final ClusterState currentState ) { remoteShardStateUpdateDeduplicator.executeOnce( new StartedShardEntry( shardRouting.shardId(), shardRouting.allocationId().getId(), primaryTerm, message, timestampRange, eventIngestedRange ), listener, (req, l) -> sendShardAction(SHARD_STARTED_ACTION_NAME, currentState, req, l) ); } // TODO: Make this a TransportMasterNodeAction and remove duplication of master failover retrying from upstream code private static
FailedShardEntry
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/YodaConditionTest.java
{ "start": 9325, "end": 9502 }
class ____ { public boolean foo(int x) { return Build.VERSION.SDK_INT < x; } } """) .doTest(); } }
Test
java
mockito__mockito
mockito-core/src/testFixtures/java/org/mockitoutil/SafeJUnitRule.java
{ "start": 3562, "end": 3749 }
interface ____ { void doAssert(Throwable t); } /** * Thrown when user expects the tested rule to throw an exception but no exception was thrown */
FailureAssert
java
google__error-prone
check_api/src/main/java/com/google/errorprone/util/MoreAnnotations.java
{ "start": 8267, "end": 10211 }
class ____ extends SimpleAnnotationValueVisitor8<TypeMirror, Void> { @Override public TypeMirror visitType(TypeMirror t, Void unused) { return t; } } return Optional.ofNullable(a.accept(new Visitor(), null)); } /** Converts the given annotation value to one or more strings. */ public static Stream<String> asStrings(AnnotationValue v) { return MoreObjects.firstNonNull( v.accept( new SimpleAnnotationValueVisitor8<Stream<String>, Void>() { @Override public Stream<String> visitString(String s, Void unused) { return Stream.of(s); } @Override public Stream<String> visitArray(List<? extends AnnotationValue> list, Void unused) { return list.stream().flatMap(a -> a.accept(this, null)).filter(x -> x != null); } }, null), Stream.empty()); } /** Converts the given annotation value to one or more annotations. */ public static Stream<AnnotationMirror> asAnnotations(AnnotationValue v) { return v.accept( new SimpleAnnotationValueVisitor8<Stream<AnnotationMirror>, Void>(Stream.empty()) { @Override public Stream<AnnotationMirror> visitAnnotation(AnnotationMirror av, Void unused) { return Stream.of(av); } @Override public Stream<AnnotationMirror> visitArray( List<? extends AnnotationValue> list, Void unused) { return list.stream().flatMap(a -> a.accept(this, null)); } }, null); } /** Converts the given annotation value to one or more types. */ public static Stream<TypeMirror> asTypes(AnnotationValue v) { return asArray(v, MoreAnnotations::asTypeValue); } private static <T> Stream<T> asArray( AnnotationValue v, Function<AnnotationValue, Optional<T>> mapper) {
Visitor
java
quarkusio__quarkus
independent-projects/tools/codestarts/src/main/java/io/quarkus/devtools/codestarts/core/strategy/ForbiddenCodestartFileStrategyHandler.java
{ "start": 292, "end": 814 }
class ____ implements CodestartFileStrategyHandler { @Override public String name() { return "forbidden"; } @Override public void process(Path targetDirectory, String relativePath, List<TargetFile> codestartFiles, Map<String, Object> data) throws IOException { if (codestartFiles.size() > 0) { throw new CodestartStructureException("This file is forbidden in the output-strategy definition: " + relativePath); } } }
ForbiddenCodestartFileStrategyHandler
java
apache__camel
components/camel-paho-mqtt5/src/test/java/org/apache/camel/component/paho/mqtt5/integration/PahoMqtt5ComponentMqtt5IT.java
{ "start": 1903, "end": 8635 }
class ____ extends PahoMqtt5ITSupport { @EndpointInject("mock:test") MockEndpoint mock; @EndpointInject("mock:testCustomizedPaho") MockEndpoint testCustomizedPahoMock; @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { PahoMqtt5Component customizedPaho = new PahoMqtt5Component(); context.addComponent("customizedPaho", customizedPaho); from("direct:test").to("paho-mqtt5:queue?brokerUrl=tcp://localhost:" + mqttPort); from("paho-mqtt5:queue?brokerUrl=tcp://localhost:" + mqttPort).to("mock:test"); from("direct:test2").to("paho-mqtt5:queue?brokerUrl=tcp://localhost:" + mqttPort); from("paho-mqtt5:persistenceTest?persistence=FILE&brokerUrl=tcp://localhost:" + mqttPort) .to("mock:persistenceTest"); from("direct:testCustomizedPaho").to("customizedPaho:testCustomizedPaho?brokerUrl=tcp://localhost:" + mqttPort); from("paho-mqtt5:testCustomizedPaho?brokerUrl=tcp://localhost:" + mqttPort).to("mock:testCustomizedPaho"); } }; } // Tests @Test public void checkOptions() { String uri = "paho-mqtt5:/test/topic" + "?clientId=sampleClient" + "&brokerUrl=tcp://localhost:" + mqttPort + "&qos=2" + "&persistence=file"; PahoMqtt5Endpoint endpoint = getMandatoryEndpoint(uri, PahoMqtt5Endpoint.class); // Then assertEquals("/test/topic", endpoint.getTopic()); assertEquals("sampleClient", endpoint.getConfiguration().getClientId()); assertEquals("tcp://localhost:" + mqttPort, endpoint.getConfiguration().getBrokerUrl()); assertEquals(2, endpoint.getConfiguration().getQos()); Assertions.assertEquals(PahoMqtt5Persistence.FILE, endpoint.getConfiguration().getPersistence()); } @Test public void checkUserNameOnly() { String uri = "paho-mqtt5:/test/topic?brokerUrl=tcp://localhost:" + mqttPort + "&userName=test"; PahoMqtt5Endpoint endpoint = getMandatoryEndpoint(uri, PahoMqtt5Endpoint.class); assertEquals("test", endpoint.getConfiguration().getUserName()); } @Test public void checkUserNameAndPassword() { String uri = "paho-mqtt5:/test/topic?brokerUrl=tcp://localhost:" + mqttPort + "&userName=test&password=testpass"; PahoMqtt5Endpoint endpoint = getMandatoryEndpoint(uri, PahoMqtt5Endpoint.class); assertEquals("test", endpoint.getConfiguration().getUserName()); assertEquals("testpass", endpoint.getConfiguration().getPassword()); } @Test public void shouldReadMessageFromMqtt() throws InterruptedException { // Given String msg = "msg"; mock.expectedBodiesReceived(msg); // When template.sendBody("direct:test", msg); // Then mock.assertIsSatisfied(); } @Test public void shouldSendAndReadMessagePropertiesFromMqtt() throws InterruptedException { // Given String msg = "msg"; MqttProperties publishedMqttProperties = createMqttProperties( "text/plain", "some-response-topic", List.of(new UserProperty("key1", "value1"), new UserProperty("key2", "value2"))); mock.expectedBodiesReceived(msg); // When template.sendBodyAndHeader("direct:test", msg, CAMEL_PAHO_MSG_PROPERTIES, publishedMqttProperties); // Then mock.assertIsSatisfied(); MqttProperties receivedMqttProperties = mock.getExchanges().get(0).getIn().getHeader(CAMEL_PAHO_MSG_PROPERTIES, MqttProperties.class); assertEquals(receivedMqttProperties.getContentType(), publishedMqttProperties.getContentType()); assertEquals(receivedMqttProperties.getResponseTopic(), publishedMqttProperties.getResponseTopic()); assertEquals(receivedMqttProperties.getUserProperties(), publishedMqttProperties.getUserProperties()); } @Test public void shouldNotReadMessageFromUnregisteredTopic() throws InterruptedException { // Given mock.expectedMessageCount(0); // When template.sendBody("paho-mqtt5:someRandomQueue?brokerUrl=tcp://localhost:" + mqttPort, "msg"); // Then mock.assertIsSatisfied(); } @Test public void shouldKeepDefaultMessageInHeader() throws InterruptedException { // Given final String msg = "msg"; mock.expectedBodiesReceived(msg); // When template.sendBody("direct:test", msg); // Then mock.assertIsSatisfied(); Exchange exchange = mock.getExchanges().get(0); String payload = new String((byte[]) exchange.getIn().getBody(), StandardCharsets.UTF_8); assertEquals("queue", exchange.getIn().getHeader(PahoMqtt5Constants.MQTT_TOPIC)); assertEquals(msg, payload); } @Test public void shouldKeepOriginalMessageInHeader() throws InterruptedException { // Given final String msg = "msg"; mock.expectedBodiesReceived(msg); // When template.sendBody("direct:test2", msg); // Then mock.assertIsSatisfied(); Exchange exchange = mock.getExchanges().get(0); MqttMessage message = exchange.getIn(PahoMqtt5Message.class).getMqttMessage(); assertNotNull(message); assertEquals(msg, new String(message.getPayload())); } @Test public void shouldReadMessageFromCustomizedComponent() throws InterruptedException { // Given String msg = "msg"; testCustomizedPahoMock.expectedBodiesReceived(msg); // When template.sendBody("direct:testCustomizedPaho", msg); // Then testCustomizedPahoMock.assertIsSatisfied(); } @Test public void shouldNotSendMessageAuthIsNotValid() throws InterruptedException { // Given mock.expectedMessageCount(0); // When template.sendBody("paho-mqtt5:someRandomQueue?brokerUrl=tcp://localhost:" + mqttPort + "&userName=test&password=test", "msg"); // Then mock.assertIsSatisfied(); } private MqttProperties createMqttProperties(String contentType, String responseTopic, List<UserProperty> userProperties) { MqttProperties properties = new MqttProperties(); properties.setContentType(contentType); properties.setResponseTopic(responseTopic); properties.setUserProperties(userProperties); return properties; } }
PahoMqtt5ComponentMqtt5IT
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerQueueHelpers.java
{ "start": 1091, "end": 11623 }
class ____ { public static final String DEFAULT_PATH = CapacitySchedulerConfiguration.ROOT + ".default"; public static final String A_PATH = CapacitySchedulerConfiguration.ROOT + ".a"; public static final String B_PATH = CapacitySchedulerConfiguration.ROOT + ".b"; public static final String A_CHILD_PATH = A_PATH + ".a"; public static final String A1_PATH = A_PATH + ".a1"; public static final String A2_PATH = A_PATH + ".a2"; public static final String A3_PATH = A_PATH + ".a3"; public static final String B1_PATH = B_PATH + ".b1"; public static final String B2_PATH = B_PATH + ".b2"; public static final String B3_PATH = B_PATH + ".b3"; public static final String A1_B1_PATH = A1_PATH + ".b1"; public static final QueuePath ROOT = new QueuePath(CapacitySchedulerConfiguration.ROOT); public static final QueuePath DEFAULT = new QueuePath(DEFAULT_PATH); public static final QueuePath A = new QueuePath(A_PATH); public static final QueuePath A_CHILD = new QueuePath(A_CHILD_PATH); public static final QueuePath A1 = new QueuePath(A1_PATH); public static final QueuePath A2 = new QueuePath(A2_PATH); public static final QueuePath A3 = new QueuePath(A3_PATH); public static final QueuePath B = new QueuePath(B_PATH); public static final QueuePath B1 = new QueuePath(B1_PATH); public static final QueuePath B2 = new QueuePath(B2_PATH); public static final QueuePath B3 = new QueuePath(B3_PATH); public static final QueuePath A1_B1 = new QueuePath(A1_B1_PATH); public static final float A_CAPACITY = 10.5f; public static final float B_CAPACITY = 89.5f; public static final String P1_PATH = CapacitySchedulerConfiguration.ROOT + ".p1"; public static final String P2_PATH = CapacitySchedulerConfiguration.ROOT + ".p2"; public static final String X1_PATH = P1_PATH + ".x1"; public static final String X2_PATH = P1_PATH + ".x2"; public static final String Y1_PATH = P2_PATH + ".y1"; public static final String Y2_PATH = P2_PATH + ".y2"; public static final QueuePath P1 = new QueuePath(P1_PATH); public static final QueuePath P2 = new QueuePath(P2_PATH); public static final QueuePath X1 = new QueuePath(X1_PATH); public static final QueuePath X2 = new QueuePath(X2_PATH); public static final QueuePath Y1 = new QueuePath(Y1_PATH); public static final QueuePath Y2 = new QueuePath(Y2_PATH); public static final float A1_CAPACITY = 30; public static final float A2_CAPACITY = 70; public static final float B1_CAPACITY = 79.2f; public static final float B2_CAPACITY = 0.8f; public static final float B3_CAPACITY = 20; private CapacitySchedulerQueueHelpers() { throw new IllegalStateException("Utility class"); } /** * @param conf, to be modified * @return * root * / \ * a b * / \ / | \ * a1 a2 b1 b2 b3 * */ public static CapacitySchedulerConfiguration setupQueueConfiguration( CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(ROOT, new String[]{"a", "b"}); conf.setCapacity(A, A_CAPACITY); conf.setCapacity(B, B_CAPACITY); // Define 2nd-level queues conf.setQueues(A, new String[]{"a1", "a2"}); conf.setCapacity(A1, A1_CAPACITY); conf.setUserLimitFactor(A1, 100.0f); conf.setCapacity(A2, A2_CAPACITY); conf.setUserLimitFactor(A2, 100.0f); conf.setQueues(B, new String[]{"b1", "b2", "b3"}); conf.setCapacity(B1, B1_CAPACITY); conf.setUserLimitFactor(B1, 100.0f); conf.setCapacity(B2, B2_CAPACITY); conf.setUserLimitFactor(B2, 100.0f); conf.setCapacity(B3, B3_CAPACITY); conf.setUserLimitFactor(B3, 100.0f); return conf; } public static CapacitySchedulerConfiguration setupAdditionalQueues( CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(ROOT, new String[]{"a", "b"}); conf.setCapacity(A, A_CAPACITY); conf.setCapacity(B, B_CAPACITY); // Define 2nd-level queues conf.setQueues(A, new String[]{"a1", "a2", "a3"}); conf.setCapacity(A1, 30.0f); conf.setUserLimitFactor(A1, 100.0f); conf.setCapacity(A2, 30.0f); conf.setUserLimitFactor(A2, 100.0f); conf.setCapacity(A3, 40.0f); conf.setUserLimitFactor(A3, 100.0f); conf.setQueues(B, new String[]{"b1", "b2", "b3"}); conf.setCapacity(B1, B1_CAPACITY); conf.setUserLimitFactor(B1, 100.0f); conf.setCapacity(B2, B2_CAPACITY); conf.setUserLimitFactor(B2, 100.0f); conf.setCapacity(B3, B3_CAPACITY); conf.setUserLimitFactor(B3, 100.0f); return conf; } /** * @param conf, to be modified * @return CS configuration which has deleted all children of queue(b) * root * / \ * a b * / \ * a1 a2 */ public static CapacitySchedulerConfiguration setupQueueConfAmbiguousQueue( CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(ROOT, new String[]{"a", "b"}); conf.setCapacity(A, A_CAPACITY); conf.setCapacity(B, B_CAPACITY); // Define 2nd-level queues conf.setQueues(A, new String[]{"a", "a1"}); conf.setCapacity(A_CHILD, A1_CAPACITY); conf.setUserLimitFactor(A1, 100.0f); conf.setCapacity(A1, A2_CAPACITY); conf.setUserLimitFactor(A2, 100.0f); return conf; } /** * @param conf, to be modified * @return CS configuration which has deleted all childred of queue(b) * root * / \ * a b * / \ * a1 a2 */ public static CapacitySchedulerConfiguration setupQueueConfWithoutChildrenOfB( CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(ROOT, new String[]{"a", "b"}); conf.setCapacity(A, A_CAPACITY); conf.setCapacity(B, B_CAPACITY); // Define 2nd-level queues conf.setQueues(A, new String[]{"a1", "a2"}); conf.setCapacity(A1, A1_CAPACITY); conf.setUserLimitFactor(A1, 100.0f); conf.setCapacity(A2, A2_CAPACITY); conf.setUserLimitFactor(A2, 100.0f); return conf; } /** * @param conf, to be modified * @return CS configuration which has deleted a queue(b1) * root * / \ * a b * / \ | \ * a1 a2 b2 b3 */ public static CapacitySchedulerConfiguration setupQueueConfigurationWithoutB1( CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(ROOT, new String[]{"a", "b"}); conf.setCapacity(A, A_CAPACITY); conf.setCapacity(B, B_CAPACITY); // Define 2nd-level queues conf.setQueues(A, new String[]{"a1", "a2"}); conf.setCapacity(A1, A1_CAPACITY); conf.setUserLimitFactor(A1, 100.0f); conf.setCapacity(A2, A2_CAPACITY); conf.setUserLimitFactor(A2, 100.0f); conf.setQueues(B, new String[]{"b2", "b3"}); conf.setCapacity(B2, B2_CAPACITY + B1_CAPACITY); //as B1 is deleted conf.setUserLimitFactor(B2, 100.0f); conf.setCapacity(B3, B3_CAPACITY); conf.setUserLimitFactor(B3, 100.0f); return conf; } /** * @param conf, to be modified * @return CS configuration which has converted b1 to parent queue * root * / \ * a b * / \ / | \ * a1 a2 b1 b2 b3 * | * b11 */ public static CapacitySchedulerConfiguration setupQueueConfigurationWithB1AsParentQueue( CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(ROOT, new String[]{"a", "b"}); conf.setCapacity(A, A_CAPACITY); conf.setCapacity(B, B_CAPACITY); // Define 2nd-level queues conf.setQueues(A, new String[]{"a1", "a2"}); conf.setCapacity(A1, A1_CAPACITY); conf.setUserLimitFactor(A1, 100.0f); conf.setCapacity(A2, A2_CAPACITY); conf.setUserLimitFactor(A2, 100.0f); conf.setQueues(B, new String[]{"b1", "b2", "b3"}); conf.setCapacity(B1, B1_CAPACITY); conf.setUserLimitFactor(B1, 100.0f); conf.setCapacity(B2, B2_CAPACITY); conf.setUserLimitFactor(B2, 100.0f); conf.setCapacity(B3, B3_CAPACITY); conf.setUserLimitFactor(B3, 100.0f); // Set childQueue for B1 conf.setQueues(B1, new String[]{"b11"}); final String b11Path = B1 + ".b11"; final QueuePath b11 = new QueuePath(b11Path); conf.setCapacity(b11, 100.0f); conf.setUserLimitFactor(b11, 100.0f); return conf; } /** * @param conf, to be modified * @return CS configuration which has deleted a Parent queue(b) */ public static CapacitySchedulerConfiguration setupQueueConfigurationWithoutB( CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(ROOT, new String[]{"a"}); conf.setCapacity(A, A_CAPACITY + B_CAPACITY); // Define 2nd-level queues conf.setQueues(A, new String[]{"a1", "a2"}); conf.setCapacity(A1, A1_CAPACITY); conf.setUserLimitFactor(A1, 100.0f); conf.setCapacity(A2, A2_CAPACITY); conf.setUserLimitFactor(A2, 100.0f); return conf; } public static CapacitySchedulerConfiguration setupBlockedQueueConfiguration( CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(ROOT, new String[]{"a", "b"}); conf.setCapacity(A, 80f); conf.setCapacity(B, 20f); conf.setUserLimitFactor(A, 100); conf.setUserLimitFactor(B, 100); conf.setMaximumCapacity(A, 100); conf.setMaximumCapacity(B, 100); return conf; } public static CapacitySchedulerConfiguration setupOtherBlockedQueueConfiguration( CapacitySchedulerConfiguration conf) { // Define top-level queues conf.setQueues(ROOT, new String[]{"p1", "p2"}); conf.setCapacity(P1, 50f); conf.setMaximumCapacity(P1, 50f); conf.setCapacity(P2, 50f); conf.setMaximumCapacity(P2, 100f); // Define 2nd-level queues conf.setQueues(P1, new String[]{"x1", "x2"}); conf.setCapacity(X1, 80f); conf.setMaximumCapacity(X1, 100f); conf.setUserLimitFactor(X1, 2f); conf.setCapacity(X2, 20f); conf.setMaximumCapacity(X2, 100f); conf.setUserLimitFactor(X2, 2f); conf.setQueues(P2, new String[]{"y1", "y2"}); conf.setCapacity(Y1, 80f); conf.setUserLimitFactor(Y1, 2f); conf.setCapacity(Y2, 20f); conf.setUserLimitFactor(Y2, 2f); return conf; } public static
CapacitySchedulerQueueHelpers
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/desktop/TransientTest.java
{ "start": 1720, "end": 4895 }
class ____ implements Serializable { private static final long serialVersionUID = -1L; private String a = "hello"; @JsonIgnore private transient String b = "world"; @JsonProperty("cat") private String c = "jackson"; @JsonProperty("dog") private transient String d = "databind"; public String getA() { return a; } public String getB() { return b; } public String getC() { return c; } public String getD() { return d; } } /* /********************************************************** /* Unit tests /********************************************************** */ private final ObjectMapper MAPPER = newJsonMapper(); // for [databind#296] @Test public void testTransientFieldHandling() throws Exception { // default handling: remove transient field but do not propagate assertEquals(a2q("{'x':42,'value':3}"), MAPPER.writeValueAsString(new ClassyTransient())); assertEquals(a2q("{'a':1}"), MAPPER.writeValueAsString(new SimplePrunableTransient())); // but may change that ObjectMapper m = jsonMapperBuilder() .enable(MapperFeature.PROPAGATE_TRANSIENT_MARKER) .build(); assertEquals(a2q("{'x':42}"), m.writeValueAsString(new ClassyTransient())); } // for [databind#857] @Test public void testBeanTransient() throws Exception { assertEquals(a2q("{'y':4}"), MAPPER.writeValueAsString(new BeanTransient())); } // for [databind#1184] @Test public void testOverridingTransient() throws Exception { assertEquals(a2q("{'tValue':38}"), MAPPER.writeValueAsString(new OverridableTransient(38))); } // for [databind#3682]: SHOULD prune `transient` Field, not pull in @Test public void testTransientToPrune() throws Exception { try { TransientToPrune result = MAPPER.readerFor(TransientToPrune.class) .with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .readValue("{\"a\":3}"); fail("Should not pass, got: "+result); } catch (UnrecognizedPropertyException e) { verifyException(e, "Unrecognized", "\"a\""); } } @Test public void testJsonIgnoreSerialization() throws Exception { Obj3948 obj1 = new Obj3948(); String json = MAPPER.writeValueAsString(obj1); assertEquals(a2q("{'a':'hello','cat':'jackson','dog':'databind'}"), json); } @Test public void testJsonIgnoreSerializationTransient() throws Exception { final ObjectMapper mapperTransient = jsonMapperBuilder() .configure(MapperFeature.PROPAGATE_TRANSIENT_MARKER, true) .build(); Obj3948 obj1 = new Obj3948(); String json = mapperTransient.writeValueAsString(obj1); assertEquals(a2q("{'a':'hello','cat':'jackson','dog':'databind'}"), json); } }
Obj3948
java
apache__avro
lang/java/trevni/avro/src/main/java/org/apache/trevni/avro/mapreduce/AvroTrevniKeyValueRecordReader.java
{ "start": 1463, "end": 2446 }
class ____<K, V> extends AvroTrevniRecordReaderBase<AvroKey<K>, AvroValue<V>, GenericRecord> { /** The current key the reader is on. */ private final AvroKey<K> mCurrentKey = new AvroKey<>(); /** The current value the reader is on. */ private final AvroValue<V> mCurrentValue = new AvroValue<>(); /** {@inheritDoc} */ @Override public AvroKey<K> getCurrentKey() throws IOException, InterruptedException { return mCurrentKey; } /** {@inheritDoc} */ @Override public AvroValue<V> getCurrentValue() throws IOException, InterruptedException { return mCurrentValue; } /** {@inheritDoc} */ @Override public boolean nextKeyValue() throws IOException, InterruptedException { boolean hasNext = super.nextKeyValue(); AvroKeyValue<K, V> avroKeyValue = new AvroKeyValue<>(getCurrentRecord()); mCurrentKey.datum(avroKeyValue.getKey()); mCurrentValue.datum(avroKeyValue.getValue()); return hasNext; } }
AvroTrevniKeyValueRecordReader
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/conditional/ClampMax.java
{ "start": 1774, "end": 8080 }
class ____ extends EsqlScalarFunction { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "ClampMax", ClampMax::new); private DataType resolvedType; @FunctionInfo( returnType = { "double", "integer", "long", "unsigned_long", "double", "keyword", "ip", "boolean", "date", "version" }, description = "Returns clamps the values of all input samples clamped to have an upper limit of max.", examples = @Example(file = "k8s-timeseries-clamp", tag = "clamp-max") ) public ClampMax( Source source, @Param( name = "field", type = { "double", "integer", "long", "unsigned_long", "double", "keyword", "ip", "boolean", "date", "version" }, description = "field to clamp." ) Expression field, @Param( name = "max", type = { "double", "integer", "long", "unsigned_long", "double", "keyword", "ip", "boolean", "date", "version" }, description = "The max value to clamp data into." ) Expression max ) { super(source, List.of(field, max)); } private ClampMax(StreamInput in) throws IOException { this(Source.readFrom((PlanStreamInput) in), in.readNamedWriteable(Expression.class), in.readNamedWriteable(Expression.class)); } @Override public void writeTo(StreamOutput out) throws IOException { source().writeTo(out); out.writeNamedWriteable(children().get(0)); out.writeNamedWriteable(children().get(1)); } @Override public String getWriteableName() { return ENTRY.name; } @Override public DataType dataType() { if (resolvedType == null && resolveType().resolved() == false) { throw new EsqlIllegalArgumentException("Unable to resolve data type for clamp_max"); } return resolvedType; } @Override protected TypeResolution resolveType() { if (childrenResolved() == false) { return new TypeResolution("Unresolved children"); } var field = children().get(0); var max = children().get(1); var fieldDataType = field.dataType().noText(); TypeResolution resolution = TypeResolutions.isType( field, t -> t.isNumeric() || t == DataType.BOOLEAN || t.isDate() || DataType.isString(t) || t == DataType.IP || t == DataType.VERSION, sourceText(), TypeResolutions.ParamOrdinal.FIRST, fieldDataType.typeName() ); if (resolution.unresolved()) { return resolution; } if (fieldDataType == NULL) { return new TypeResolution("'field' must not be null in clamp()"); } resolution = TypeResolutions.isType( max, t -> t.isNumeric() ? fieldDataType.isNumeric() : t.noText() == fieldDataType.noText(), sourceText(), TypeResolutions.ParamOrdinal.SECOND, fieldDataType.typeName() ); if (resolution.unresolved()) { return resolution; } if (fieldDataType.isNumeric() == false) { resolvedType = fieldDataType; } else if (fieldDataType.estimatedSize() == max.dataType().estimatedSize()) { // When the types are equally wide, prefer rational numbers resolvedType = fieldDataType.isRationalNumber() ? fieldDataType : max.dataType(); } else { // Otherwise, prefer the wider type resolvedType = fieldDataType.estimatedSize() > max.dataType().estimatedSize() ? fieldDataType : max.dataType(); } return TypeResolution.TYPE_RESOLVED; } @Override public Expression replaceChildren(List<Expression> newChildren) { return new ClampMax(source(), newChildren.get(0), newChildren.get(1)); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, ClampMax::new, children().get(0), children().get(1)); } @Override public boolean foldable() { return Expressions.foldable(children()); } @Override public ExpressionEvaluator.Factory toEvaluator(ToEvaluator toEvaluator) { var outputType = PlannerUtils.toElementType(dataType()); var fieldEval = PlannerUtils.toElementType(children().getFirst().dataType()) != outputType ? Cast.cast(source(), children().getFirst().dataType(), dataType(), toEvaluator.apply(children().get(0))) : toEvaluator.apply(children().getFirst()); var maxEval = PlannerUtils.toElementType(children().get(1).dataType()) != outputType ? Cast.cast(source(), children().get(1).dataType(), dataType(), toEvaluator.apply(children().get(1))) : toEvaluator.apply(children().get(1)); return switch (outputType) { case BOOLEAN -> new ClampMaxBooleanEvaluator.Factory(source(), fieldEval, maxEval); case DOUBLE -> new ClampMaxDoubleEvaluator.Factory(source(), fieldEval, maxEval); case INT -> new ClampMaxIntegerEvaluator.Factory(source(), fieldEval, maxEval); case LONG -> new ClampMaxLongEvaluator.Factory(source(), fieldEval, maxEval); case BYTES_REF -> new ClampMaxBytesRefEvaluator.Factory(source(), fieldEval, maxEval); default -> throw EsqlIllegalArgumentException.illegalDataType(dataType()); }; } @Evaluator(extraName = "Boolean") static boolean process(boolean field, boolean max) { if (max == false) { return false; } else { return field; } } @Evaluator(extraName = "BytesRef") static BytesRef process(BytesRef field, BytesRef max) { if (field.compareTo(max) > 0) { return max; } else { return field; } } @Evaluator(extraName = "Integer") static int process(int field, int max) { return Math.min(field, max); } @Evaluator(extraName = "Long") static long process(long field, long max) { return Math.min(field, max); } @Evaluator(extraName = "Double") static double process(double field, double max) { return Math.min(field, max); } }
ClampMax
java
google__auto
common/src/test/java/com/google/auto/common/BasicAnnotationProcessorTest.java
{ "start": 2954, "end": 3042 }
interface ____ {} /** * Rejects elements unless the
TypeParameterRequiresGeneratedCode
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/function/server/LocaleContextResolverIntegrationTests.java
{ "start": 1536, "end": 2705 }
class ____ extends AbstractRouterFunctionIntegrationTests { private final WebClient webClient = WebClient.create(); @Override protected RouterFunction<?> routerFunction() { return RouterFunctions.route(RequestPredicates.path("/"), this::render); } Mono<RenderingResponse> render(ServerRequest request) { return RenderingResponse.create("foo").build(); } @Override protected HandlerStrategies handlerStrategies() { return HandlerStrategies.builder() .viewResolver(new DummyViewResolver()) .localeContextResolver(new FixedLocaleContextResolver(Locale.GERMANY)) .build(); } @ParameterizedHttpServerTest void fixedLocale(HttpServer httpServer) throws Exception { startServer(httpServer); Mono<ResponseEntity<Void>> result = webClient .get() .uri("http://localhost:" + this.port + "/") .retrieve().toBodilessEntity(); StepVerifier .create(result) .consumeNextWith(entity -> { assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(entity.getHeaders().getContentLanguage()).isEqualTo(Locale.GERMANY); }) .verifyComplete(); } private static
LocaleContextResolverIntegrationTests
java
apache__flink
flink-clients/src/main/java/org/apache/flink/client/deployment/application/FromClasspathEntryClassInformationProvider.java
{ "start": 2370, "end": 2763 }
class ____ passed."); Preconditions.checkNotNull(classpath, "No classpath passed."); return new FromClasspathEntryClassInformationProvider(jobClassName); } /** * Creates a {@code FromClasspathEntryClassInformationProvider} looking for the entry class * providing the main method on the passed classpath. * * @param classpath The classpath the job
name
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/normalizer/ShortCircuitingRenormalizer.java
{ "start": 4768, "end": 8662 }
interface ____ new InterruptedException("Normalization cancelled"); } } } while (latch != null || taskToWaitFor != null); } @Override public void shutdown() throws InterruptedException { scoresUpdater.shutdown(); // We have to wait until idle to avoid a raft of exceptions as other parts of the // system are stopped after this method returns. However, shutting down the // scoresUpdater first means it won't do all pending work; it will stop as soon // as it can without causing further errors. waitUntilIdle(); } private synchronized AugmentedQuantiles getLatestAugmentedQuantilesAndClear() { AugmentedQuantiles latest = latestQuantilesHolder; latestQuantilesHolder = null; return latest; } private synchronized boolean tryStartWork() { if (latestQuantilesHolder == null) { return false; } // Don't start a thread if another normalization thread is still working. The existing thread will // do this normalization when it finishes its current one. This means we serialise normalizations // without hogging threads or queuing up many large quantiles documents. if (semaphore.tryAcquire()) { try { latestTask = executorService.submit(this::doRenormalizations); } catch (RejectedExecutionException e) { latestQuantilesHolder.getLatch().countDown(); latestQuantilesHolder = null; latestTask = null; semaphore.release(); logger.warn("[{}] Normalization discarded as threadpool is shutting down", jobId); return false; } return true; } return false; } private synchronized boolean tryFinishWork() { // Synchronized because we cannot tolerate new work being added in between the null check and releasing the semaphore if (latestQuantilesHolder != null) { return false; } semaphore.release(); latestTask = null; return true; } private void doRenormalizations() { do { AugmentedQuantiles latestAugmentedQuantiles = getLatestAugmentedQuantilesAndClear(); assert latestAugmentedQuantiles != null; if (latestAugmentedQuantiles != null) { // TODO: remove this if the assert doesn't trip in CI over the next year or so latestAugmentedQuantiles.runSetupStep(); Quantiles latestQuantiles = latestAugmentedQuantiles.getQuantiles(); CountDownLatch latch = latestAugmentedQuantiles.getLatch(); try { scoresUpdater.update( latestQuantiles.getQuantileState(), latestQuantiles.getTimestamp().getTime(), latestAugmentedQuantiles.getWindowExtensionMs() ); } catch (Exception e) { logger.error("[" + jobId + "] Normalization failed", e); } finally { latch.countDown(); } } else { logger.warn("[{}] request to normalize null quantiles", jobId); } // Loop if more work has become available while we were working, because the // tasks originally submitted to do that work will have exited early. } while (tryFinishWork() == false); } /** * Grouping of a {@linkplain Quantiles} object with its corresponding {@linkplain CountDownLatch} object. * Also stores the earliest timestamp that any set of discarded quantiles held, to allow the normalization * window to be extended if multiple normalization requests are combined. */ private
throw
java
google__guice
core/test/com/google/inject/RestrictedBindingSourceTest.java
{ "start": 6015, "end": 6316 }
class ____ implements RoutingTable { @Inject RoutingTableImpl() {} @Override public int getNextHopIpAddress(int destinationIpAddress) { return destinationIpAddress + 2; } } @Test public void untargettedBindingAllowedWithPermit() { @NetworkLibrary
RoutingTableImpl
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java
{ "start": 27794, "end": 27994 }
class ____ { @Autowired String autowiredName; @Bean TestBean testBean() { TestBean testBean = new TestBean(); testBean.name = autowiredName; return testBean; } } static
AutowiredConfig
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/configuration/plugins/PluginLoaderTest.java
{ "start": 7756, "end": 7807 }
class ____ implements Bar {} static
BarChildPlugin
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_259.java
{ "start": 842, "end": 1246 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "SELECT rank() OVER (ROWS BETWEEN CURRENT ROW AND 'foo' FOLLOWING)"; SQLSelectStatement stmt = (SQLSelectStatement) SQLUtils.parseSingleStatement(sql, DbType.mysql); assertEquals("SELECT rank() OVER ( ROWS BETWEEN CURRENT ROW AND 'foo' FOLLOWING)", stmt.toString()); } }
MySqlSelectTest_259
java
spring-projects__spring-boot
module/spring-boot-jackson2/src/test/java/org/springframework/boot/jackson2/autoconfigure/Jackson2AutoConfigurationTests.java
{ "start": 26710, "end": 26993 }
class ____ { @JsonFormat(pattern = "yyyyMMdd") private @Nullable Date birthDate; @Nullable Date getBirthDate() { return this.birthDate; } void setBirthDate(@Nullable Date birthDate) { this.birthDate = birthDate; } } @JsonMixin(type = Person.class) static
Person
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/catalog/CatalogLanguage.java
{ "start": 1262, "end": 2278 }
class ____ extends CatalogBaseCommand { public CatalogLanguage(CamelJBangMain main) { super(main); } @Override List<Row> collectRows() { List<Row> rows = new ArrayList<>(); for (String name : catalog.findLanguageNames()) { LanguageModel model = catalog.languageModel(name); if (model != null) { Row row = new Row(); row.name = model.getName(); row.title = model.getTitle(); row.level = model.getSupportLevel().name(); row.since = fixQuarkusSince(model.getFirstVersionShort()); row.description = model.getDescription(); row.label = model.getLabel() != null ? model.getLabel() : ""; row.deprecated = model.isDeprecated(); row.nativeSupported = model.isNativeSupported(); row.gav = getGAV(model); rows.add(row); } } return rows; } }
CatalogLanguage
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/DeserializerFactoryTest.java
{ "start": 442, "end": 699 }
class ____ extends ObjectMapper { public DeserializationContextExt deserializationContext() { return _deserializationContext(); } } private final AccessibleMapper MAPPER = new AccessibleMapper(); static
AccessibleMapper
java
spring-projects__spring-framework
spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java
{ "start": 3223, "end": 3311 }
interface ____ { @Transactional void doInTransaction(); } static
ITransactionalBean
java
netty__netty
codec-http3/src/test/java/io/netty/handler/codec/http3/Http3FrameToHttpObjectCodecTest.java
{ "start": 4136, "end": 29180 }
class ____ { @Test public void testUpgradeEmptyFullResponse() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); assertTrue(ch.writeOutbound(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK))); Http3HeadersFrame headersFrame = ch.readOutbound(); assertThat(headersFrame.headers().status().toString(), is("200")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void encode100ContinueAsHttp2HeadersFrameThatIsNotEndStream() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); assertTrue(ch.writeOutbound(new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE))); Http3HeadersFrame headersFrame = ch.readOutbound(); assertThat(headersFrame.headers().status().toString(), is("100")); assertFalse(ch.isOutputShutdown()); assertThat(ch.readOutbound(), is(nullValue())); assertFalse(ch.finish()); } @Test public void encodeNonFullHttpResponse100ContinueIsRejected() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); assertThrows(EncoderException.class, () -> ch.writeOutbound(new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE))); ch.finishAndReleaseAll(); } @Test public void testUpgradeNonEmptyFullResponse() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); assertTrue(ch.writeOutbound(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, hello))); Http3HeadersFrame headersFrame = ch.readOutbound(); assertThat(headersFrame.headers().status().toString(), is("200")); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world")); } finally { dataFrame.release(); } assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testUpgradeEmptyFullResponseWithTrailers() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders trailers = response.trailingHeaders(); trailers.set("key", "value"); assertTrue(ch.writeOutbound(response)); Http3HeadersFrame headersFrame = ch.readOutbound(); assertThat(headersFrame.headers().status().toString(), is("200")); Http3HeadersFrame trailersFrame = ch.readOutbound(); assertThat(trailersFrame.headers().get("key").toString(), is("value")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testUpgradeNonEmptyFullResponseWithTrailers() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, hello); HttpHeaders trailers = response.trailingHeaders(); trailers.set("key", "value"); assertTrue(ch.writeOutbound(response)); Http3HeadersFrame headersFrame = ch.readOutbound(); assertThat(headersFrame.headers().status().toString(), is("200")); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world")); } finally { dataFrame.release(); } Http3HeadersFrame trailersFrame = ch.readOutbound(); assertThat(trailersFrame.headers().get("key").toString(), is("value")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testUpgradeHeaders() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); assertTrue(ch.writeOutbound(response)); Http3HeadersFrame headersFrame = ch.readOutbound(); assertThat(headersFrame.headers().status().toString(), is("200")); assertFalse(ch.isOutputShutdown()); assertThat(ch.readOutbound(), is(nullValue())); assertFalse(ch.finish()); } @Test public void testUpgradeChunk() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); HttpContent content = new DefaultHttpContent(hello); assertTrue(ch.writeOutbound(content)); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world")); assertFalse(ch.isOutputShutdown()); } finally { dataFrame.release(); } assertThat(ch.readOutbound(), is(nullValue())); assertFalse(ch.finish()); } @Test public void testUpgradeEmptyEnd() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); ch.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT); assertTrue(ch.isOutputShutdown()); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().readableBytes(), is(0)); } finally { dataFrame.release(); } assertFalse(ch.finish()); } @Test public void testUpgradeDataEnd() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); LastHttpContent end = new DefaultLastHttpContent(hello, true); assertTrue(ch.writeOutbound(end)); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world")); } finally { dataFrame.release(); } assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testUpgradeDataEndWithTrailers() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); LastHttpContent trailers = new DefaultLastHttpContent(hello, true); HttpHeaders headers = trailers.trailingHeaders(); headers.set("key", "value"); assertTrue(ch.writeOutbound(trailers)); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world")); } finally { dataFrame.release(); } Http3HeadersFrame headerFrame = ch.readOutbound(); assertThat(headerFrame.headers().get("key").toString(), is("value")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testDowngradeHeaders() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); Http3Headers headers = new DefaultHttp3Headers(); headers.path("/"); headers.method("GET"); assertTrue(ch.writeInbound(new DefaultHttp3HeadersFrame(headers))); HttpRequest request = ch.readInbound(); assertThat(request.uri(), is("/")); assertThat(request.method(), is(HttpMethod.GET)); assertThat(request.protocolVersion(), is(HttpVersion.HTTP_1_1)); assertFalse(request instanceof FullHttpRequest); assertTrue(HttpUtil.isTransferEncodingChunked(request)); assertThat(ch.readInbound(), is(nullValue())); assertFalse(ch.finish()); } @Test public void testDowngradeHeadersWithContentLength() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); Http3Headers headers = new DefaultHttp3Headers(); headers.path("/"); headers.method("GET"); headers.setInt("content-length", 0); assertTrue(ch.writeInbound(new DefaultHttp3HeadersFrame(headers))); HttpRequest request = ch.readInbound(); assertThat(request.uri(), is("/")); assertThat(request.method(), is(HttpMethod.GET)); assertThat(request.protocolVersion(), is(HttpVersion.HTTP_1_1)); assertFalse(request instanceof FullHttpRequest); assertFalse(HttpUtil.isTransferEncodingChunked(request)); assertThat(ch.readInbound(), is(nullValue())); assertFalse(ch.finish()); } @Test public void testDowngradeTrailers() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); Http3Headers headers = new DefaultHttp3Headers(); headers.set("key", "value"); assertTrue(ch.writeInboundWithFin(new DefaultHttp3HeadersFrame(headers))); LastHttpContent trailers = ch.readInbound(); try { assertThat(trailers.content().readableBytes(), is(0)); assertThat(trailers.trailingHeaders().get("key"), is("value")); assertFalse(trailers instanceof FullHttpRequest); } finally { trailers.release(); } assertThat(ch.readInbound(), is(nullValue())); assertFalse(ch.finish()); } @Test public void testDowngradeData() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); assertTrue(ch.writeInbound(new DefaultHttp3DataFrame(hello))); HttpContent content = ch.readInbound(); try { assertThat(content.content().toString(CharsetUtil.UTF_8), is("hello world")); assertFalse(content instanceof LastHttpContent); } finally { content.release(); } assertThat(ch.readInbound(), is(nullValue())); assertFalse(ch.finish()); } @Test public void testDowngradeEndData() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(true)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); assertTrue(ch.writeInboundWithFin(new DefaultHttp3DataFrame(hello))); HttpContent content = ch.readInbound(); try { assertThat(content.content().toString(CharsetUtil.UTF_8), is("hello world")); } finally { content.release(); } LastHttpContent last = ch.readInbound(); try { assertFalse(last.content().isReadable()); assertTrue(last.trailingHeaders().isEmpty()); } finally { last.release(); } assertThat(ch.readInbound(), is(nullValue())); assertFalse(ch.finish()); } // client-specific tests @Test public void testEncodeEmptyFullRequest() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); assertTrue(ch.writeOutbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/world"))); Http3HeadersFrame headersFrame = ch.readOutbound(); Http3Headers headers = headersFrame.headers(); assertThat(headers.scheme().toString(), is("https")); assertThat(headers.method().toString(), is("GET")); assertThat(headers.path().toString(), is("/hello/world")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testEncodeNonEmptyFullRequest() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); assertTrue(ch.writeOutbound(new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.PUT, "/hello/world", hello))); Http3HeadersFrame headersFrame = ch.readOutbound(); Http3Headers headers = headersFrame.headers(); assertThat(headers.scheme().toString(), is("https")); assertThat(headers.method().toString(), is("PUT")); assertThat(headers.path().toString(), is("/hello/world")); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world")); } finally { dataFrame.release(); } assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testEncodeEmptyFullRequestWithTrailers() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); FullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.PUT, "/hello/world"); HttpHeaders trailers = request.trailingHeaders(); trailers.set("key", "value"); assertTrue(ch.writeOutbound(request)); Http3HeadersFrame headersFrame = ch.readOutbound(); Http3Headers headers = headersFrame.headers(); assertThat(headers.scheme().toString(), is("https")); assertThat(headers.method().toString(), is("PUT")); assertThat(headers.path().toString(), is("/hello/world")); Http3HeadersFrame trailersFrame = ch.readOutbound(); assertThat(trailersFrame.headers().get("key").toString(), is("value")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testEncodeNonEmptyFullRequestWithTrailers() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); FullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.PUT, "/hello/world", hello); HttpHeaders trailers = request.trailingHeaders(); trailers.set("key", "value"); assertTrue(ch.writeOutbound(request)); Http3HeadersFrame headersFrame = ch.readOutbound(); Http3Headers headers = headersFrame.headers(); assertThat(headers.scheme().toString(), is("https")); assertThat(headers.method().toString(), is("PUT")); assertThat(headers.path().toString(), is("/hello/world")); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world")); } finally { dataFrame.release(); } Http3HeadersFrame trailersFrame = ch.readOutbound(); assertThat(trailersFrame.headers().get("key").toString(), is("value")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testEncodeRequestHeaders() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/world"); assertTrue(ch.writeOutbound(request)); Http3HeadersFrame headersFrame = ch.readOutbound(); Http3Headers headers = headersFrame.headers(); assertThat(headers.scheme().toString(), is("https")); assertThat(headers.method().toString(), is("GET")); assertThat(headers.path().toString(), is("/hello/world")); assertFalse(ch.isOutputShutdown()); assertThat(ch.readOutbound(), is(nullValue())); assertFalse(ch.finish()); } @Test public void testEncodeChunkAsClient() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); HttpContent content = new DefaultHttpContent(hello); assertTrue(ch.writeOutbound(content)); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world")); } finally { dataFrame.release(); } assertFalse(ch.isOutputShutdown()); assertThat(ch.readOutbound(), is(nullValue())); assertFalse(ch.finish()); } @Test public void testEncodeEmptyEndAsClient() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ch.writeOutbound(LastHttpContent.EMPTY_LAST_CONTENT); assertTrue(ch.isOutputShutdown()); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().readableBytes(), is(0)); } finally { dataFrame.release(); } assertFalse(ch.finish()); } @Test public void testEncodeDataEndAsClient() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); LastHttpContent end = new DefaultLastHttpContent(hello, true); assertTrue(ch.writeOutbound(end)); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world")); } finally { dataFrame.release(); } assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testEncodeTrailersAsClient() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); LastHttpContent trailers = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER, true); HttpHeaders headers = trailers.trailingHeaders(); headers.set("key", "value"); assertTrue(ch.writeOutbound(trailers)); Http3HeadersFrame headerFrame = ch.readOutbound(); assertThat(headerFrame.headers().get("key").toString(), is("value")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testEncodeDataEndWithTrailersAsClient() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ByteBuf hello = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8); LastHttpContent trailers = new DefaultLastHttpContent(hello, true); HttpHeaders headers = trailers.trailingHeaders(); headers.set("key", "value"); assertTrue(ch.writeOutbound(trailers)); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().toString(CharsetUtil.UTF_8), is("hello world")); } finally { dataFrame.release(); } Http3HeadersFrame headerFrame = ch.readOutbound(); assertThat(headerFrame.headers().get("key").toString(), is("value")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testEncodeFullPromiseCompletes() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ChannelFuture writeFuture = ch.writeOneOutbound(new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/world")); ch.flushOutbound(); assertTrue(writeFuture.isSuccess()); Http3HeadersFrame headersFrame = ch.readOutbound(); Http3Headers headers = headersFrame.headers(); assertThat(headers.scheme().toString(), is("https")); assertThat(headers.method().toString(), is("GET")); assertThat(headers.path().toString(), is("/hello/world")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } @Test public void testEncodeEmptyLastPromiseCompletes() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ChannelFuture f1 = ch.writeOneOutbound(new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/world")); ChannelFuture f2 = ch.writeOneOutbound(new DefaultLastHttpContent()); ch.flushOutbound(); assertTrue(f1.isSuccess()); assertTrue(f2.isSuccess()); Http3HeadersFrame headersFrame = ch.readOutbound(); Http3Headers headers = headersFrame.headers(); assertThat(headers.scheme().toString(), is("https")); assertThat(headers.method().toString(), is("GET")); assertThat(headers.path().toString(), is("/hello/world")); assertTrue(ch.isOutputShutdown()); Http3DataFrame dataFrame = ch.readOutbound(); try { assertThat(dataFrame.content().readableBytes(), is(0)); } finally { dataFrame.release(); } assertFalse(ch.finish()); } @Test public void testEncodeMultiplePromiseCompletes() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ChannelFuture f1 = ch.writeOneOutbound(new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/world")); ChannelFuture f2 = ch.writeOneOutbound(new DefaultLastHttpContent( Unpooled.wrappedBuffer("foo".getBytes(StandardCharsets.UTF_8)))); ch.flushOutbound(); assertTrue(f1.isSuccess()); assertTrue(f2.isSuccess()); Http3HeadersFrame headersFrame = ch.readOutbound(); Http3Headers headers = headersFrame.headers(); assertThat(headers.scheme().toString(), is("https")); assertThat(headers.method().toString(), is("GET")); assertThat(headers.path().toString(), is("/hello/world")); assertTrue(ch.isOutputShutdown()); Http3DataFrame dataFrame = ch.readOutbound(); assertEquals("foo", dataFrame.content().toString(StandardCharsets.UTF_8)); assertFalse(ch.finish()); } @Test public void testEncodeTrailersCompletes() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ChannelFuture f1 = ch.writeOneOutbound(new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, "/hello/world")); LastHttpContent last = new DefaultLastHttpContent( Unpooled.wrappedBuffer("foo".getBytes(StandardCharsets.UTF_8))); last.trailingHeaders().add("foo", "bar"); ChannelFuture f2 = ch.writeOneOutbound(last); ch.flushOutbound(); assertTrue(f1.isSuccess()); assertTrue(f2.isSuccess()); Http3HeadersFrame headersFrame = ch.readOutbound(); Http3Headers headers = headersFrame.headers(); assertThat(headers.scheme().toString(), is("https")); assertThat(headers.method().toString(), is("GET")); assertThat(headers.path().toString(), is("/hello/world")); assertTrue(ch.isOutputShutdown()); Http3DataFrame dataFrame = ch.readOutbound(); assertEquals("foo", dataFrame.content().toString(StandardCharsets.UTF_8)); Http3HeadersFrame trailingHeadersFrame = ch.readOutbound(); assertEquals("bar", trailingHeadersFrame.headers().get("foo").toString()); assertFalse(ch.finish()); } @Test public void testEncodeVoidPromise() { EmbeddedQuicStreamChannel ch = new EmbeddedQuicStreamChannel(new Http3FrameToHttpObjectCodec(false)); ch.writeOneOutbound(new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "/hello/world", Unpooled.wrappedBuffer(new byte[1])), ch.voidPromise()); ch.flushOutbound(); Http3HeadersFrame headersFrame = ch.readOutbound(); Http3Headers headers = headersFrame.headers(); Http3DataFrame data = ch.readOutbound(); data.release(); assertThat(headers.scheme().toString(), is("https")); assertThat(headers.method().toString(), is("POST")); assertThat(headers.path().toString(), is("/hello/world")); assertTrue(ch.isOutputShutdown()); assertFalse(ch.finish()); } private static final
Http3FrameToHttpObjectCodecTest
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/method/MethodSecurityBeanDefinitionParserTests.java
{ "start": 18767, "end": 19206 }
class ____ implements PermissionEvaluator { @Override public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) { return "grant".equals(targetDomainObject); } @Override public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) { throw new UnsupportedOperationException(); } } static
MyPermissionEvaluator
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/onetomany/OneToManyHqlMemberOfQueryTest.java
{ "start": 1523, "end": 6303 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { Person person1 = new Person( "John Doe" ); person1.setNickName( "JD" ); person1.setAddress( "Earth" ); person1.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) .toInstant( ZoneOffset.UTC ) ) ); person1.getAddresses().put( AddressType.HOME, "Home address" ); person1.getAddresses().put( AddressType.OFFICE, "Office address" ); session.persist( person1 ); Person person2 = new Person( "Mrs. John Doe" ); person2.setAddress( "Earth" ); person2.setCreatedOn( Timestamp.from( LocalDateTime.of( 2000, 1, 2, 12, 0, 0 ) .toInstant( ZoneOffset.UTC ) ) ); session.persist( person2 ); Person person3 = new Person( "Dr_ John Doe" ); session.persist( person3 ); Phone phone1 = new Phone( "123-456-7890" ); phone1.setId( 1L ); person1.addPhone( phone1 ); phone1.getRepairTimestamps().add( Timestamp.from( LocalDateTime.of( 2005, 1, 1, 12, 0, 0 ) .toInstant( ZoneOffset.UTC ) ) ); phone1.getRepairTimestamps().add( Timestamp.from( LocalDateTime.of( 2006, 1, 1, 12, 0, 0 ) .toInstant( ZoneOffset.UTC ) ) ); Call call11 = new Call(); call11.setDuration( 12 ); call11.setTimestamp( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 0, 0, 0 ) .toInstant( ZoneOffset.UTC ) ) ); Call call12 = new Call(); call12.setDuration( 33 ); call12.setTimestamp( Timestamp.from( LocalDateTime.of( 2000, 1, 1, 1, 0, 0 ) .toInstant( ZoneOffset.UTC ) ) ); phone1.addCall( call11 ); phone1.addCall( call12 ); Phone phone2 = new Phone( "098-765-4321" ); phone2.setId( 2L ); Phone phone3 = new Phone( "098-765-4320" ); phone3.setId( 3L ); person2.addPhone( phone2 ); person2.addPhone( phone3 ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testMemberOf(SessionFactoryScope scope) { scope.inTransaction( session -> { Call call = session.createQuery( "select c from Call c", Call.class ).getResultList().get( 0 ); Phone phone = call.getPhone(); List<Person> people = session.createQuery( "select p " + "from Person p " + "where :phone member of p.phones", Person.class ) .setParameter( "phone", phone ) .getResultList(); assertEquals( 1, people.size() ); } ); } @Test public void testNegatedMemberOf(SessionFactoryScope scope) { scope.inTransaction( session -> { Call call = session.createQuery( "select c from Call c", Call.class ).getResultList().get( 0 ); Phone phone = call.getPhone(); List<Person> people = session.createQuery( "select p " + "from Person p " + "where :phone not member of p.phones", Person.class ) .setParameter( "phone", phone ) .getResultList(); assertEquals( 2, people.size() ); } ); } @Test public void testMember(SessionFactoryScope scope) { scope.inTransaction( session -> { Call call = session.createQuery( "select c from Call c", Call.class ).getResultList().get( 0 ); Phone phone = call.getPhone(); List<Person> people = session.createQuery( "select p " + "from Person p " + "where :phone member p.phones", Person.class ) .setParameter( "phone", phone ) .getResultList(); assertEquals( 1, people.size() ); } ); } @Test public void testNegatedMember(SessionFactoryScope scope) { scope.inTransaction( session -> { Call call = session.createQuery( "select c from Call c", Call.class ).getResultList().get( 0 ); Phone phone = call.getPhone(); List<Person> people = session.createQuery( "select p " + "from Person p " + "where :phone not member p.phones", Person.class ) .setParameter( "phone", phone ) .getResultList(); assertEquals( 2, people.size() ); } ); } @Test public void testMemberOf2(SessionFactoryScope scope) { scope.inTransaction( session -> { Call call = session.createQuery( "select c from Call c", Call.class ).getResultList().get( 0 ); List<Person> people = session.createQuery( "select p " + "from Person p " + "join p.phones phone " + "where :call member of phone.calls", Person.class ) .setParameter( "call", call ) .getResultList(); assertEquals( 1, people.size() ); } ); } @Entity(name = "Person") public static
OneToManyHqlMemberOfQueryTest
java
grpc__grpc-java
opentelemetry/src/main/java/io/grpc/opentelemetry/OpenTelemetryTracingModule.java
{ "start": 7168, "end": 8751 }
class ____ extends ClientStreamTracer { private final Span span; private final Span parentSpan; volatile int seqNo; boolean isPendingStream; ClientTracer(Span span, Span parentSpan) { this.span = checkNotNull(span, "span"); this.parentSpan = checkNotNull(parentSpan, "parent span"); } @Override public void streamCreated(Attributes transportAtts, Metadata headers) { contextPropagators.getTextMapPropagator().inject(Context.current().with(span), headers, metadataSetter); if (isPendingStream) { span.addEvent("Delayed LB pick complete"); } } @Override public void createPendingStream() { isPendingStream = true; } @Override public void outboundMessageSent( int seqNo, long optionalWireSize, long optionalUncompressedSize) { recordOutboundMessageSentEvent(span, seqNo, optionalWireSize, optionalUncompressedSize); } @Override public void inboundMessageRead( int seqNo, long optionalWireSize, long optionalUncompressedSize) { if (optionalWireSize != optionalUncompressedSize) { recordInboundCompressedMessage(span, seqNo, optionalWireSize); } } @Override public void inboundMessage(int seqNo) { this.seqNo = seqNo; } @Override public void inboundUncompressedSize(long bytes) { recordInboundMessageSize(parentSpan, seqNo, bytes); } @Override public void streamClosed(io.grpc.Status status) { endSpanWithStatus(span, status); } } private final
ClientTracer
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ImapComponentBuilderFactory.java
{ "start": 1829, "end": 35048 }
interface ____ extends ComponentBuilder<MailComponent> { /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default ImapComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Whether the consumer should close the folder after polling. Setting * this option to false and having disconnect=false as well, then the * consumer keeps the folder open between polls. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer * * @param closeFolder the value to set * @return the dsl builder */ default ImapComponentBuilder closeFolder(boolean closeFolder) { doSetProperty("closeFolder", closeFolder); return this; } /** * After processing a mail message, it can be copied to a mail folder * with the given name. You can override this configuration value with a * header with the key copyTo, allowing you to copy messages to folder * names configured at runtime. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: consumer * * @param copyTo the value to set * @return the dsl builder */ default ImapComponentBuilder copyTo(java.lang.String copyTo) { doSetProperty("copyTo", copyTo); return this; } /** * If set to true, the MimeUtility.decodeText method will be used to * decode the filename. This is similar to setting JVM system property * mail.mime.encodefilename. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param decodeFilename the value to set * @return the dsl builder */ default ImapComponentBuilder decodeFilename(boolean decodeFilename) { doSetProperty("decodeFilename", decodeFilename); return this; } /** * Deletes the messages after they have been processed. This is done by * setting the DELETED flag on the mail message. If false, the SEEN flag * is set instead. You can override this configuration option by setting * a header with the key delete to determine if the mail should be * deleted or not. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param delete the value to set * @return the dsl builder */ default ImapComponentBuilder delete(boolean delete) { doSetProperty("delete", delete); return this; } /** * Whether the consumer should disconnect after polling. If enabled, * this forces Camel to connect on each poll. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param disconnect the value to set * @return the dsl builder */ default ImapComponentBuilder disconnect(boolean disconnect) { doSetProperty("disconnect", disconnect); return this; } /** * If the mail consumer cannot retrieve a given mail message, then this * option allows handling the caused exception by the consumer's error * handler. By enabling the bridge error handler on the consumer, then * the Camel routing error handler can handle the exception instead. The * default behavior would be the consumer throws an exception and no * mails from the batch would be able to be routed by Camel. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param handleFailedMessage the value to set * @return the dsl builder */ default ImapComponentBuilder handleFailedMessage(boolean handleFailedMessage) { doSetProperty("handleFailedMessage", handleFailedMessage); return this; } /** * This option enables transparent MIME decoding and unfolding for mail * headers. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param mimeDecodeHeaders the value to set * @return the dsl builder */ default ImapComponentBuilder mimeDecodeHeaders(boolean mimeDecodeHeaders) { doSetProperty("mimeDecodeHeaders", mimeDecodeHeaders); return this; } /** * After processing a mail message, it can be moved to a mail folder * with the given name. You can override this configuration value with a * header with the key moveTo, allowing you to move messages to folder * names configured at runtime. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: consumer * * @param moveTo the value to set * @return the dsl builder */ default ImapComponentBuilder moveTo(java.lang.String moveTo) { doSetProperty("moveTo", moveTo); return this; } /** * Will mark the jakarta.mail.Message as peeked before processing the * mail message. This applies to IMAPMessage messages types only. By * using peek, the mail will not be eagerly marked as SEEN on the mail * server, which allows us to roll back the mail message if there is a * processing error in Camel. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer * * @param peek the value to set * @return the dsl builder */ default ImapComponentBuilder peek(boolean peek) { doSetProperty("peek", peek); return this; } /** * If the mail consumer cannot retrieve a given mail message, then this * option allows skipping the message and move on to retrieve the next * mail message. The default behavior would be the consumer throws an * exception and no mails from the batch would be able to be routed by * Camel. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param skipFailedMessage the value to set * @return the dsl builder */ default ImapComponentBuilder skipFailedMessage(boolean skipFailedMessage) { doSetProperty("skipFailedMessage", skipFailedMessage); return this; } /** * Whether to limit by unseen mails only. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer * * @param unseen the value to set * @return the dsl builder */ default ImapComponentBuilder unseen(boolean unseen) { doSetProperty("unseen", unseen); return this; } /** * Whether to fail processing the mail if the mail message contains * attachments with duplicate file names. If set to false, then the * duplicate attachment is skipped and a WARN is logged. If set to true, * then an exception is thrown failing to process the mail message. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer (advanced) * * @param failOnDuplicateFileAttachment the value to set * @return the dsl builder */ default ImapComponentBuilder failOnDuplicateFileAttachment(boolean failOnDuplicateFileAttachment) { doSetProperty("failOnDuplicateFileAttachment", failOnDuplicateFileAttachment); return this; } /** * Sets the maximum number of messages to consume during a poll. This * can be used to avoid overloading a mail server, if a mailbox folder * contains a lot of messages. The default value of -1 means no fetch * size and all messages will be consumed. Setting the value to 0 is a * special corner case, where Camel will not consume any messages at * all. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: -1 * Group: consumer (advanced) * * @param fetchSize the value to set * @return the dsl builder */ default ImapComponentBuilder fetchSize(int fetchSize) { doSetProperty("fetchSize", fetchSize); return this; } /** * The folder to poll. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: INBOX * Group: consumer (advanced) * * @param folderName the value to set * @return the dsl builder */ default ImapComponentBuilder folderName(java.lang.String folderName) { doSetProperty("folderName", folderName); return this; } /** * Set this to 'uuid' to set a UUID for the filename of the attachment * if no filename was set. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: consumer (advanced) * * @param generateMissingAttachmentNames the value to set * @return the dsl builder */ default ImapComponentBuilder generateMissingAttachmentNames(java.lang.String generateMissingAttachmentNames) { doSetProperty("generateMissingAttachmentNames", generateMissingAttachmentNames); return this; } /** * Set the strategy to handle duplicate filenames of attachments never: * attachments that have a filename which is already present in the * attachments will be ignored unless failOnDuplicateFileAttachment is * set to true. uuidPrefix: this will prefix the duplicate attachment * filenames each with an uuid and underscore * (uuid_filename.fileextension). uuidSuffix: this will suffix the * duplicate attachment filenames each with an underscore and uuid * (filename_uuid.fileextension). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: consumer (advanced) * * @param handleDuplicateAttachmentNames the value to set * @return the dsl builder */ default ImapComponentBuilder handleDuplicateAttachmentNames(java.lang.String handleDuplicateAttachmentNames) { doSetProperty("handleDuplicateAttachmentNames", handleDuplicateAttachmentNames); return this; } /** * Specifies whether Camel should map the received mail message to Camel * body/headers/attachments. If set to true, the body of the mail * message is mapped to the body of the Camel IN message, the mail * headers are mapped to IN headers, and the attachments to Camel IN * attachment message. If this option is set to false, then the IN * message contains a raw jakarta.mail.Message. You can retrieve this * raw message by calling * exchange.getIn().getBody(jakarta.mail.Message.class). * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: consumer (advanced) * * @param mapMailMessage the value to set * @return the dsl builder */ default ImapComponentBuilder mapMailMessage(boolean mapMailMessage) { doSetProperty("mapMailMessage", mapMailMessage); return this; } /** * Sets the BCC email address. Separate multiple email addresses with * comma. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param bcc the value to set * @return the dsl builder */ default ImapComponentBuilder bcc(java.lang.String bcc) { doSetProperty("bcc", bcc); return this; } /** * Sets the CC email address. Separate multiple email addresses with * comma. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param cc the value to set * @return the dsl builder */ default ImapComponentBuilder cc(java.lang.String cc) { doSetProperty("cc", cc); return this; } /** * The from email address. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: camel@localhost * Group: producer * * @param from the value to set * @return the dsl builder */ default ImapComponentBuilder from(java.lang.String from) { doSetProperty("from", from); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default ImapComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * The Reply-To recipients (the receivers of the response mail). * Separate multiple email addresses with a comma. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param replyTo the value to set * @return the dsl builder */ default ImapComponentBuilder replyTo(java.lang.String replyTo) { doSetProperty("replyTo", replyTo); return this; } /** * The Subject of the message being sent. Note: Setting the subject in * the header takes precedence over this option. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param subject the value to set * @return the dsl builder */ default ImapComponentBuilder subject(java.lang.String subject) { doSetProperty("subject", subject); return this; } /** * Sets the destination email address. Separate multiple email addresses * with comma. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param to the value to set * @return the dsl builder */ default ImapComponentBuilder to(java.lang.String to) { doSetProperty("to", to); return this; } /** * To use a custom org.apache.camel.component.mail.JavaMailSender for * sending emails. * * The option is a: * &lt;code&gt;org.apache.camel.component.mail.JavaMailSender&lt;/code&gt; type. * * Group: producer (advanced) * * @param javaMailSender the value to set * @return the dsl builder */ default ImapComponentBuilder javaMailSender(org.apache.camel.component.mail.JavaMailSender javaMailSender) { doSetProperty("javaMailSender", javaMailSender); return this; } /** * Sets additional java mail properties, that will append/override any * default properties that are set based on all the other options. This * is useful if you need to add some special options but want to keep * the others as is. This is a multi-value option with prefix: mail. * * The option is a: &lt;code&gt;java.util.Properties&lt;/code&gt; type. * * Group: advanced * * @param additionalJavaMailProperties the value to set * @return the dsl builder */ default ImapComponentBuilder additionalJavaMailProperties(java.util.Properties additionalJavaMailProperties) { doSetProperty("additionalJavaMailProperties", additionalJavaMailProperties); return this; } /** * Specifies the key to an IN message header that contains an * alternative email body. For example, if you send emails in text/html * format and want to provide an alternative mail body for non-HTML * email clients, set the alternative mail body with this key as a * header. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: CamelMailAlternativeBody * Group: advanced * * @param alternativeBodyHeader the value to set * @return the dsl builder */ default ImapComponentBuilder alternativeBodyHeader(java.lang.String alternativeBodyHeader) { doSetProperty("alternativeBodyHeader", alternativeBodyHeader); return this; } /** * To use a custom AttachmentsContentTransferEncodingResolver to resolve * what content-type-encoding to use for attachments. * * The option is a: * &lt;code&gt;org.apache.camel.component.mail.AttachmentsContentTransferEncodingResolver&lt;/code&gt; type. * * Group: advanced * * @param attachmentsContentTransferEncodingResolver the value to set * @return the dsl builder */ default ImapComponentBuilder attachmentsContentTransferEncodingResolver(org.apache.camel.component.mail.AttachmentsContentTransferEncodingResolver attachmentsContentTransferEncodingResolver) { doSetProperty("attachmentsContentTransferEncodingResolver", attachmentsContentTransferEncodingResolver); return this; } /** * The authenticator for login. If set then the password and username * are ignored. It can be used for tokens which can expire and therefore * must be read dynamically. * * The option is a: * &lt;code&gt;org.apache.camel.component.mail.MailAuthenticator&lt;/code&gt; type. * * Group: advanced * * @param authenticator the value to set * @return the dsl builder */ default ImapComponentBuilder authenticator(org.apache.camel.component.mail.MailAuthenticator authenticator) { doSetProperty("authenticator", authenticator); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default ImapComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * Sets the Mail configuration. * * The option is a: * &lt;code&gt;org.apache.camel.component.mail.MailConfiguration&lt;/code&gt; type. * * Group: advanced * * @param configuration the value to set * @return the dsl builder */ default ImapComponentBuilder configuration(org.apache.camel.component.mail.MailConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * The connection timeout in milliseconds. * * The option is a: &lt;code&gt;int&lt;/code&gt; type. * * Default: 30000 * Group: advanced * * @param connectionTimeout the value to set * @return the dsl builder */ default ImapComponentBuilder connectionTimeout(int connectionTimeout) { doSetProperty("connectionTimeout", connectionTimeout); return this; } /** * The mail message content type. Use text/html for HTML mails. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: text/plain * Group: advanced * * @param contentType the value to set * @return the dsl builder */ default ImapComponentBuilder contentType(java.lang.String contentType) { doSetProperty("contentType", contentType); return this; } /** * Resolver to determine Content-Type for file attachments. * * The option is a: * &lt;code&gt;org.apache.camel.component.mail.ContentTypeResolver&lt;/code&gt; type. * * Group: advanced * * @param contentTypeResolver the value to set * @return the dsl builder */ default ImapComponentBuilder contentTypeResolver(org.apache.camel.component.mail.ContentTypeResolver contentTypeResolver) { doSetProperty("contentTypeResolver", contentTypeResolver); return this; } /** * Enable debug mode on the underlying mail framework. The SUN Mail * framework logs the debug messages to System.out by default. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param debugMode the value to set * @return the dsl builder */ default ImapComponentBuilder debugMode(boolean debugMode) { doSetProperty("debugMode", debugMode); return this; } /** * Option to let Camel ignore unsupported charset in the local JVM when * sending mails. If the charset is unsupported, then charset=XXX (where * XXX represents the unsupported charset) is removed from the * content-type, and it relies on the platform default instead. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param ignoreUnsupportedCharset the value to set * @return the dsl builder */ default ImapComponentBuilder ignoreUnsupportedCharset(boolean ignoreUnsupportedCharset) { doSetProperty("ignoreUnsupportedCharset", ignoreUnsupportedCharset); return this; } /** * Option to let Camel ignore unsupported charset in the local JVM when * sending mails. If the charset is unsupported, then charset=XXX (where * XXX represents the unsupported charset) is removed from the * content-type, and it relies on the platform default instead. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param ignoreUriScheme the value to set * @return the dsl builder */ default ImapComponentBuilder ignoreUriScheme(boolean ignoreUriScheme) { doSetProperty("ignoreUriScheme", ignoreUriScheme); return this; } /** * Sets the java mail options. Will clear any default properties and * only use the properties provided for this method. * * The option is a: &lt;code&gt;java.util.Properties&lt;/code&gt; type. * * Group: advanced * * @param javaMailProperties the value to set * @return the dsl builder */ default ImapComponentBuilder javaMailProperties(java.util.Properties javaMailProperties) { doSetProperty("javaMailProperties", javaMailProperties); return this; } /** * Specifies the mail session that camel should use for all mail * interactions. Useful in scenarios where mail sessions are created and * managed by some other resource, such as a JavaEE container. When * using a custom mail session, then the hostname and port from the mail * session will be used (if configured on the session). * * The option is a: &lt;code&gt;jakarta.mail.Session&lt;/code&gt; type. * * Group: advanced * * @param session the value to set * @return the dsl builder */ default ImapComponentBuilder session(jakarta.mail.Session session) { doSetProperty("session", session); return this; } /** * Whether to use disposition inline or attachment. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: advanced * * @param useInlineAttachments the value to set * @return the dsl builder */ default ImapComponentBuilder useInlineAttachments(boolean useInlineAttachments) { doSetProperty("useInlineAttachments", useInlineAttachments); return this; } /** * To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter * header to and from Camel message. * * The option is a: * &lt;code&gt;org.apache.camel.spi.HeaderFilterStrategy&lt;/code&gt; * type. * * Group: filter * * @param headerFilterStrategy the value to set * @return the dsl builder */ default ImapComponentBuilder headerFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy headerFilterStrategy) { doSetProperty("headerFilterStrategy", headerFilterStrategy); return this; } /** * Used for enabling or disabling all consumer based health checks from * this component. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: health * * @param healthCheckConsumerEnabled the value to set * @return the dsl builder */ default ImapComponentBuilder healthCheckConsumerEnabled(boolean healthCheckConsumerEnabled) { doSetProperty("healthCheckConsumerEnabled", healthCheckConsumerEnabled); return this; } /** * Used for enabling or disabling all producer based health checks from * this component. Notice: Camel has by default disabled all producer * based health-checks. You can turn on producer checks globally by * setting camel.health.producersEnabled=true. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: health * * @param healthCheckProducerEnabled the value to set * @return the dsl builder */ default ImapComponentBuilder healthCheckProducerEnabled(boolean healthCheckProducerEnabled) { doSetProperty("healthCheckProducerEnabled", healthCheckProducerEnabled); return this; } /** * The password for login. See also setAuthenticator(MailAuthenticator). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param password the value to set * @return the dsl builder */ default ImapComponentBuilder password(java.lang.String password) { doSetProperty("password", password); return this; } /** * To configure security using SSLContextParameters. * * The option is a: * &lt;code&gt;org.apache.camel.support.jsse.SSLContextParameters&lt;/code&gt; type. * * Group: security * * @param sslContextParameters the value to set * @return the dsl builder */ default ImapComponentBuilder sslContextParameters(org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) { doSetProperty("sslContextParameters", sslContextParameters); return this; } /** * Enable usage of global SSL context parameters. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useGlobalSslContextParameters the value to set * @return the dsl builder */ default ImapComponentBuilder useGlobalSslContextParameters(boolean useGlobalSslContextParameters) { doSetProperty("useGlobalSslContextParameters", useGlobalSslContextParameters); return this; } /** * The username for login. See also setAuthenticator(MailAuthenticator). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param username the value to set * @return the dsl builder */ default ImapComponentBuilder username(java.lang.String username) { doSetProperty("username", username); return this; } }
ImapComponentBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/SubQuerySelectCaseWhenTest.java
{ "start": 1724, "end": 1906 }
class ____ { @Id @GeneratedValue private Long id; private String name; public TestEntity() { } public TestEntity(String name) { this.name = name; } } }
TestEntity
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/compression/PerMessageDeflateDecoder.java
{ "start": 1273, "end": 3733 }
class ____ extends DeflateDecoder { private boolean compressing; /** * Constructor * * @param noContext true to disable context takeover. * @param maxAllocation * maximum size of the decompression buffer. Must be &gt;= 0. If zero, maximum size is not limited. */ PerMessageDeflateDecoder(boolean noContext, int maxAllocation) { super(noContext, WebSocketExtensionFilter.NEVER_SKIP, maxAllocation); } /** * Constructor * * @param noContext true to disable context takeover. * @param extensionDecoderFilter extension decoder for per message deflate decoder. * @param maxAllocation * maximum size of the decompression buffer. Must be &gt;= 0. If zero, maximum size is not limited. */ PerMessageDeflateDecoder(boolean noContext, WebSocketExtensionFilter extensionDecoderFilter, int maxAllocation) { super(noContext, extensionDecoderFilter, maxAllocation); } @Override public boolean acceptInboundMessage(Object msg) throws Exception { if (!super.acceptInboundMessage(msg)) { return false; } WebSocketFrame wsFrame = (WebSocketFrame) msg; if (extensionDecoderFilter().mustSkip(wsFrame)) { if (compressing) { throw new IllegalStateException("Cannot skip per message deflate decoder, compression in progress"); } return false; } return ((wsFrame instanceof TextWebSocketFrame || wsFrame instanceof BinaryWebSocketFrame) && (wsFrame.rsv() & WebSocketExtension.RSV1) > 0) || (wsFrame instanceof ContinuationWebSocketFrame && compressing); } @Override protected int newRsv(WebSocketFrame msg) { return (msg.rsv() & WebSocketExtension.RSV1) > 0? msg.rsv() ^ WebSocketExtension.RSV1 : msg.rsv(); } @Override protected boolean appendFrameTail(WebSocketFrame msg) { return msg.isFinalFragment(); } @Override protected void decode(ChannelHandlerContext ctx, WebSocketFrame msg, List<Object> out) throws Exception { super.decode(ctx, msg, out); if (msg.isFinalFragment()) { compressing = false; } else if (msg instanceof TextWebSocketFrame || msg instanceof BinaryWebSocketFrame) { compressing = true; } } }
PerMessageDeflateDecoder
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/histogram/InternalVariableWidthHistogram.java
{ "start": 2038, "end": 7180 }
class ____ { public double min; public double max; public BucketBounds(double min, double max) { assert min <= max; this.min = min; this.max = max; } public BucketBounds(StreamInput in) throws IOException { this(in.readDouble(), in.readDouble()); } public void writeTo(StreamOutput out) throws IOException { out.writeDouble(min); out.writeDouble(max); } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; BucketBounds that = (BucketBounds) obj; return min == that.min && max == that.max; } @Override public int hashCode() { return Objects.hash(getClass(), min, max); } } private final BucketBounds bounds; private final double centroid; public Bucket(double centroid, BucketBounds bounds, long docCount, DocValueFormat format, InternalAggregations aggregations) { super(docCount, aggregations, format); this.centroid = centroid; this.bounds = bounds; } /** * Read from a stream. */ public static Bucket readFrom(StreamInput in, DocValueFormat format) throws IOException { final double centroid = in.readDouble(); final long docCount = in.readVLong(); final BucketBounds bounds = new BucketBounds(in); final InternalAggregations aggregations = InternalAggregations.readFrom(in); return new Bucket(centroid, bounds, docCount, format, aggregations); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeDouble(centroid); out.writeVLong(docCount); bounds.writeTo(out); aggregations.writeTo(out); } @Override public boolean equals(Object obj) { if (obj == null || obj.getClass() != InternalVariableWidthHistogram.Bucket.class) { return false; } InternalVariableWidthHistogram.Bucket that = (InternalVariableWidthHistogram.Bucket) obj; return centroid == that.centroid && bounds.equals(that.bounds) && docCount == that.docCount && Objects.equals(aggregations, that.aggregations); } @Override public int hashCode() { return Objects.hash(getClass(), centroid, bounds, docCount, aggregations); } @Override public String getKeyAsString() { return format.format(centroid).toString(); } /** * Buckets are compared using their centroids. But, in the final XContent returned by the aggregation, * we want the bucket's key to be its min. Otherwise, it would look like the distances between centroids * are buckets, which is incorrect. */ @Override public Object getKey() { return centroid; } public double min() { return bounds.min; } public double max() { return bounds.max; } public double centroid() { return centroid; } private void bucketToXContent(XContentBuilder builder, Params params) throws IOException { String keyAsString = format.format((double) getKey()).toString(); builder.startObject(); builder.field(CommonFields.MIN.getPreferredName(), min()); if (format != DocValueFormat.RAW) { builder.field(CommonFields.MIN_AS_STRING.getPreferredName(), format.format(min())); } builder.field(CommonFields.KEY.getPreferredName(), getKey()); if (format != DocValueFormat.RAW) { builder.field(CommonFields.KEY_AS_STRING.getPreferredName(), keyAsString); } builder.field(CommonFields.MAX.getPreferredName(), max()); if (format != DocValueFormat.RAW) { builder.field(CommonFields.MAX_AS_STRING.getPreferredName(), format.format(max())); } builder.field(CommonFields.DOC_COUNT.getPreferredName(), docCount); aggregations.toXContentInternal(builder, params); builder.endObject(); } @Override public int compareKey(InternalVariableWidthHistogram.Bucket other) { return Double.compare(centroid, other.centroid); // Use centroid for bucket ordering } Bucket finalizeSampling(SamplingContext samplingContext) { return new Bucket( centroid, bounds, samplingContext.scaleUp(docCount), format, InternalAggregations.finalizeSampling(aggregations, samplingContext) ); } } static
BucketBounds
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/date/MonthNameTests.java
{ "start": 1639, "end": 7844 }
class ____ extends AbstractConfigurationFunctionTestCase { public MonthNameTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) { this.testCase = testCaseSupplier.get(); } @Override protected Expression buildWithConfiguration(Source source, List<Expression> args, Configuration configuration) { return new MonthName(source, args.get(0), configuration); } @ParametersFactory public static Iterable<Object[]> parameters() { List<TestCaseSupplier> suppliers = new ArrayList<>(); suppliers.addAll(generateTest("1994-01-19T00:00:00.00Z", "January", "Z", "en")); suppliers.addAll(generateTest("1995-02-20T23:59:59.99Z", "February", "Z", "en")); suppliers.addAll(generateTest("1996-03-21T23:12:32.12Z", "March", "Z", "en")); suppliers.addAll(generateTest("1997-04-22T07:39:01.28Z", "April", "Z", "en")); suppliers.addAll(generateTest("1998-05-23T10:25:33.38Z", "May", "Z", "en")); suppliers.addAll(generateTest("1999-06-24T22:55:33.82Z", "June", "Z", "en")); suppliers.addAll(generateTest("2000-07-25T01:01:29.49Z", "July", "Z", "en")); suppliers.addAll(generateTest("2001-08-25T01:01:29.49Z", "August", "Z", "en")); suppliers.addAll(generateTest("2002-09-25T01:01:29.49Z", "September", "Z", "en")); suppliers.addAll(generateTest("2003-10-25T01:01:29.49Z", "October", "Z", "en")); suppliers.addAll(generateTest("2004-11-25T01:01:29.49Z", "November", "Z", "en")); suppliers.addAll(generateTest("2005-12-25T01:01:29.49Z", "December", "Z", "en")); // Other timezones and locales suppliers.addAll(generateTest("2019-03-31T22:00:00.00Z", "April", "+05:00", "en")); suppliers.addAll(generateTest("2019-03-01T00:00:00.00Z", "February", "America/New_York", "en")); suppliers.addAll(generateTest("2019-03-11T00:00:00.00Z", "marzo", "Z", "es")); suppliers.addAll(generateTest("2019-03-01T00:00:00.00Z", "febrero", "America/New_York", "es")); suppliers.add( new TestCaseSupplier( "Null", List.of(DataType.DATETIME), () -> new TestCaseSupplier.TestCase( List.of(new TestCaseSupplier.TypedData(null, DataType.DATETIME, "date")), Matchers.startsWith("MonthNameMillisEvaluator[val=Attribute[channel=0], zoneId="), DataType.KEYWORD, equalTo(null) ) ) ); return parameterSuppliersFromTypedDataWithDefaultChecks(true, suppliers); } private static List<TestCaseSupplier> generateTest(String dateTime, String expectedMonthName, String zoneIdString, String localeTag) { ZoneId zoneId = ZoneId.of(zoneIdString); Locale locale = Locale.forLanguageTag(localeTag); return List.of( new TestCaseSupplier( expectedMonthName, List.of(DataType.DATETIME), () -> new TestCaseSupplier.TestCase( List.of(new TestCaseSupplier.TypedData(toMillis(dateTime), DataType.DATETIME, "date")), Matchers.startsWith("MonthNameMillisEvaluator[val=Attribute[channel=0], zoneId=" + zoneId + ", locale=" + locale + "]"), DataType.KEYWORD, matchesBytesRef(expectedMonthName) ).withConfiguration(TestCaseSupplier.TEST_SOURCE, configurationForTimezoneAndLocale(zoneId, locale)) ), new TestCaseSupplier( expectedMonthName, List.of(DataType.DATE_NANOS), () -> new TestCaseSupplier.TestCase( List.of(new TestCaseSupplier.TypedData(toNanos(dateTime), DataType.DATE_NANOS, "date")), Matchers.is("MonthNameNanosEvaluator[val=Attribute[channel=0], zoneId=" + zoneId + ", locale=" + locale + "]"), DataType.KEYWORD, matchesBytesRef(expectedMonthName) ).withConfiguration(TestCaseSupplier.TEST_SOURCE, configurationForTimezoneAndLocale(zoneId, locale)) ) ); } private static long toMillis(String timestamp) { return Instant.parse(timestamp).toEpochMilli(); } private static long toNanos(String timestamp) { return DateUtils.toLong(Instant.parse(timestamp)); } public void testRandomLocale() { long randomMillis = randomMillisUpToYear9999(); Configuration cfg = configWithZoneAndLocale(randomZone(), randomLocale(random())); String expected = Instant.ofEpochMilli(randomMillis).atZone(cfg.zoneId()).getMonth().getDisplayName(TextStyle.FULL, cfg.locale()); MonthName func = new MonthName(Source.EMPTY, new Literal(Source.EMPTY, randomMillis, DataType.DATETIME), cfg); assertThat(BytesRefs.toBytesRef(expected), equalTo(func.fold(FoldContext.small()))); } public void testFixedLocaleAndTime() { long randomMillis = toMillis("1996-03-21T00:00:00.00Z"); Configuration cfg = configWithZoneAndLocale(ZoneId.of("America/Sao_Paulo"), Locale.of("pt", "br")); String expected = "março"; MonthName func = new MonthName(Source.EMPTY, new Literal(Source.EMPTY, randomMillis, DataType.DATETIME), cfg); assertThat(BytesRefs.toBytesRef(expected), equalTo(func.fold(FoldContext.small()))); } private Configuration configWithZoneAndLocale(ZoneId zone, Locale locale) { return new Configuration( zone, locale, null, null, QueryPragmas.EMPTY, AnalyzerSettings.QUERY_RESULT_TRUNCATION_MAX_SIZE.getDefault(Settings.EMPTY), AnalyzerSettings.QUERY_RESULT_TRUNCATION_DEFAULT_SIZE.getDefault(Settings.EMPTY), "", false, Map.of(), System.nanoTime(), randomBoolean(), AnalyzerSettings.QUERY_TIMESERIES_RESULT_TRUNCATION_MAX_SIZE.getDefault(Settings.EMPTY), AnalyzerSettings.QUERY_TIMESERIES_RESULT_TRUNCATION_DEFAULT_SIZE.getDefault(Settings.EMPTY), null ); } }
MonthNameTests
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractToOneMapper.java
{ "start": 891, "end": 1062 }
class ____ property mappers that manage to-one relation. * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) * @author Chris Cranford */ public abstract
for
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/transaction/manager/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java
{ "start": 2583, "end": 2815 }
class ____ { @Bean PlatformTransactionManager txManager1() { return new CallCountingTransactionManager(); } @Bean PlatformTransactionManager txManager2() { return new CallCountingTransactionManager(); } } }
Config
java
netty__netty
transport-classes-io_uring/src/main/java/io/netty/channel/uring/Iov.java
{ "start": 867, "end": 2090 }
class ____ { private Iov() { } static void set(ByteBuffer buffer, long bufferAddress, int length) { int position = buffer.position(); if (Native.SIZEOF_SIZE_T == 4) { buffer.putInt(position + Native.IOVEC_OFFSETOF_IOV_BASE, (int) bufferAddress); buffer.putInt(position + Native.IOVEC_OFFSETOF_IOV_LEN, length); } else { assert Native.SIZEOF_SIZE_T == 8; buffer.putLong(position + Native.IOVEC_OFFSETOF_IOV_BASE, bufferAddress); buffer.putLong(position + Native.IOVEC_OFFSETOF_IOV_LEN, length); } } static long getBufferAddress(ByteBuffer iov) { if (Native.SIZEOF_SIZE_T == 4) { return iov.getInt(iov.position() + Native.IOVEC_OFFSETOF_IOV_BASE); } assert Native.SIZEOF_SIZE_T == 8; return iov.getLong(iov.position() + Native.IOVEC_OFFSETOF_IOV_BASE); } static int getBufferLength(ByteBuffer iov) { if (Native.SIZEOF_SIZE_T == 4) { return iov.getInt(iov.position() + Native.IOVEC_OFFSETOF_IOV_LEN); } assert Native.SIZEOF_SIZE_T == 8; return (int) iov.getLong(iov.position() + Native.IOVEC_OFFSETOF_IOV_LEN); } }
Iov
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/dangling/list/NodeListDanglingIndicesResponse.java
{ "start": 1003, "end": 1751 }
class ____ extends BaseNodeResponse { private final List<DanglingIndexInfo> indexMetaData; public List<DanglingIndexInfo> getDanglingIndices() { return this.indexMetaData; } public NodeListDanglingIndicesResponse(DiscoveryNode node, List<DanglingIndexInfo> indexMetaData) { super(node); this.indexMetaData = indexMetaData; } protected NodeListDanglingIndicesResponse(StreamInput in) throws IOException { super(in); this.indexMetaData = in.readCollectionAsList(DanglingIndexInfo::new); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeCollection(this.indexMetaData); } }
NodeListDanglingIndicesResponse
java
google__dagger
javatests/dagger/internal/codegen/DependencyCycleValidationTest.java
{ "start": 17676, "end": 18004 }
interface ____ {", " Child build();", " }", "}"); Source grandchild = CompilerTests.javaSource( "test.Grandchild", "package test;", "", "import dagger.Subcomponent;", "", "@Subcomponent", "
Builder
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/schedulers/TrampolineSchedulerInternalTest.java
{ "start": 1277, "end": 6849 }
class ____ extends RxJavaTest { @Test @SuppressUndeliverable public void scheduleDirectInterrupt() { Thread.currentThread().interrupt(); final int[] calls = { 0 }; assertSame(EmptyDisposable.INSTANCE, Schedulers.trampoline().scheduleDirect(new Runnable() { @Override public void run() { calls[0]++; } }, 1, TimeUnit.SECONDS)); assertTrue(Thread.interrupted()); assertEquals(0, calls[0]); } @Test public void dispose() { Worker w = Schedulers.trampoline().createWorker(); assertFalse(w.isDisposed()); w.dispose(); assertTrue(w.isDisposed()); assertEquals(EmptyDisposable.INSTANCE, w.schedule(Functions.EMPTY_RUNNABLE)); } @Test public void reentrantScheduleDispose() { final Worker w = Schedulers.trampoline().createWorker(); try { final int[] calls = { 0, 0 }; w.schedule(new Runnable() { @Override public void run() { calls[0]++; w.schedule(new Runnable() { @Override public void run() { calls[1]++; } }) .dispose(); } }); assertEquals(1, calls[0]); assertEquals(0, calls[1]); } finally { w.dispose(); } } @Test public void reentrantScheduleShutdown() { final Worker w = Schedulers.trampoline().createWorker(); try { final int[] calls = { 0, 0 }; w.schedule(new Runnable() { @Override public void run() { calls[0]++; w.schedule(new Runnable() { @Override public void run() { calls[1]++; } }, 1, TimeUnit.MILLISECONDS); w.dispose(); } }); assertEquals(1, calls[0]); assertEquals(0, calls[1]); } finally { w.dispose(); } } @Test public void reentrantScheduleShutdown2() { final Worker w = Schedulers.trampoline().createWorker(); try { final int[] calls = { 0, 0 }; w.schedule(new Runnable() { @Override public void run() { calls[0]++; w.dispose(); assertSame(EmptyDisposable.INSTANCE, w.schedule(new Runnable() { @Override public void run() { calls[1]++; } }, 1, TimeUnit.MILLISECONDS)); } }); assertEquals(1, calls[0]); assertEquals(0, calls[1]); } finally { w.dispose(); } } @Test @SuppressUndeliverable public void reentrantScheduleInterrupt() { final Worker w = Schedulers.trampoline().createWorker(); try { final int[] calls = { 0 }; Thread.currentThread().interrupt(); w.schedule(new Runnable() { @Override public void run() { calls[0]++; } }, 1, TimeUnit.DAYS); assertTrue(Thread.interrupted()); assertEquals(0, calls[0]); } finally { w.dispose(); } } @Test public void sleepingRunnableDisposedOnRun() { TrampolineWorker w = new TrampolineWorker(); Runnable r = mock(Runnable.class); SleepingRunnable run = new SleepingRunnable(r, w, 0); w.dispose(); run.run(); verify(r, never()).run(); } @Test public void sleepingRunnableNoDelayRun() { TrampolineWorker w = new TrampolineWorker(); Runnable r = mock(Runnable.class); SleepingRunnable run = new SleepingRunnable(r, w, 0); run.run(); verify(r).run(); } @Test public void sleepingRunnableDisposedOnDelayedRun() { final TrampolineWorker w = new TrampolineWorker(); Runnable r = mock(Runnable.class); SleepingRunnable run = new SleepingRunnable(r, w, System.currentTimeMillis() + 200); Schedulers.single().scheduleDirect(new Runnable() { @Override public void run() { w.dispose(); } }, 100, TimeUnit.MILLISECONDS); run.run(); verify(r, never()).run(); } @Test public void submitAndDisposeNextTask() { Scheduler.Worker w = Schedulers.trampoline().createWorker(); for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { Runnable run = mock(Runnable.class); AtomicInteger sync = new AtomicInteger(2); w.schedule(() -> { Disposable d = w.schedule(run); Schedulers.single().scheduleDirect(() -> { if (sync.decrementAndGet() != 0) { while (sync.get() != 0) { } } d.dispose(); }); if (sync.decrementAndGet() != 0) { while (sync.get() != 0) { } } }); } } }
TrampolineSchedulerInternalTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/BlockReportTestBase.java
{ "start": 32997, "end": 34295 }
class ____ implements FilenameFilter { private String nameToAccept = ""; private boolean all = false; public MyFileFilter(String nameToAccept, boolean all) { if (nameToAccept == null) throw new IllegalArgumentException("Argument isn't suppose to be null"); this.nameToAccept = nameToAccept; this.all = all; } @Override public boolean accept(File file, String s) { if (all) return s != null && s.startsWith(nameToAccept); else return s != null && s.equals(nameToAccept); } } private static void initLoggers() { DFSTestUtil.setNameNodeLogLevel(Level.TRACE); GenericTestUtils.setLogLevel(DataNode.LOG, Level.TRACE); GenericTestUtils.setLogLevel(BlockReportTestBase.LOG, Level.DEBUG); } private Block findBlock(Path path, long size) throws IOException { Block ret; List<LocatedBlock> lbs = cluster.getNameNodeRpc() .getBlockLocations(path.toString(), FILE_START, size).getLocatedBlocks(); LocatedBlock lb = lbs.get(lbs.size() - 1); // Get block from the first DN ret = cluster.getDataNodes().get(DN_N0). data.getStoredBlock(lb.getBlock() .getBlockPoolId(), lb.getBlock().getBlockId()); return ret; } private
MyFileFilter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/enums/Person.java
{ "start": 158, "end": 1014 }
class ____ { private long id; private Gender gender; private HairColor hairColor; private HairColor originalHairColor; public static Person person(Gender gender, HairColor hairColor) { Person person = new Person(); person.setGender( gender ); person.setHairColor( hairColor ); return person; } public long getId() { return id; } public void setId(long id) { this.id = id; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public HairColor getHairColor() { return hairColor; } public void setHairColor(HairColor hairColor) { this.hairColor = hairColor; } public HairColor getOriginalHairColor() { return originalHairColor; } public void setOriginalHairColor(HairColor originalHairColor) { this.originalHairColor = originalHairColor; } }
Person
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/bean/injectionpoints/BeanInjectionPointsTest.java
{ "start": 8852, "end": 9068 }
class ____ extends AnnotationLiteral<MyQualifier1> implements MyQualifier1 { static final Literal INSTANCE = new Literal(); } } @Qualifier @Retention(RetentionPolicy.RUNTIME) @
Literal
java
google__dagger
javatests/dagger/functional/jakarta/JakartaProviderTest.java
{ "start": 1296, "end": 1344 }
class ____ { @Scope public @
JakartaProviderTest
java
netty__netty
transport/src/main/java/io/netty/channel/socket/ChannelOutputShutdownEvent.java
{ "start": 992, "end": 1175 }
class ____ { public static final ChannelOutputShutdownEvent INSTANCE = new ChannelOutputShutdownEvent(); private ChannelOutputShutdownEvent() { } }
ChannelOutputShutdownEvent
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/direct/DirectNoMultipleConsumersTest.java
{ "start": 1096, "end": 1746 }
class ____ extends TestSupport { @Test public void testNoMultipleConsumersTest() throws Exception { CamelContext container = new DefaultCamelContext(false); container.disableJMX(); container.addRoutes(new RouteBuilder() { public void configure() { from("direct:in").to("mock:result"); from("direct:in").to("mock:result"); } }); Assertions.assertThrows(FailedToStartRouteException.class, () -> container.start(), "Should have thrown an FailedToStartRouteException"); container.stop(); } }
DirectNoMultipleConsumersTest
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/FluxTakeTest.java
{ "start": 1566, "end": 22244 }
class ____ { @Test public void sourceNull() { assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> { new FluxTake<>(null, 1); }); } @Test public void numberIsInvalid() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { Flux.never() .take(-1, false); }); } @Test public void numberIsInvalidFused() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { Flux.just(1) .take(-1, false); }); } @Test public void normal() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 10) .take(5, false) .subscribe(ts); ts.assertValues(1, 2, 3, 4, 5) .assertComplete() .assertNoError(); } @Test public void normalBackpressured() { AssertSubscriber<Integer> ts = AssertSubscriber.create(0); Flux.range(1, 10) .take(5, false) .subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertNoError(); ts.request(2); ts.assertValues(1, 2) .assertNotComplete() .assertNoError(); ts.request(10); ts.assertValues(1, 2, 3, 4, 5) .assertComplete() .assertNoError(); } @Test public void takeZero() { AssertSubscriber<Integer> ts = AssertSubscriber.create(0); Flux.range(1, 10) .take(0, false) .subscribe(ts); ts.assertNoValues() .assertComplete() .assertNoError(); } @Test public void takeNever() { StepVerifier.create( Flux.never().take(1, false)) .expectSubscription() .expectNoEvent(Duration.ofSeconds(1)) .thenCancel() .verify(); } @Test public void takeNeverZero() { PublisherProbe<Object> probe = PublisherProbe.of(Flux.never()); StepVerifier.create(probe.flux().take(0, false)) .expectSubscription() .expectComplete() .verify(Duration.ofSeconds(1)); probe.assertWasCancelled(); } @Test public void takeOverflowAttempt() { Publisher<Integer> p = s -> { s.onSubscribe(Operators.emptySubscription()); s.onNext(1); s.onNext(2); s.onNext(3); }; StepVerifier.create(Flux.from(p).take(2, false)) .expectNext(1, 2) .expectComplete() .verifyThenAssertThat() .hasDroppedExactly(3); } @Test public void aFluxCanBeLimited(){ StepVerifier.create(Flux.just("test", "test2", "test3") .take(2, false) ) .expectNext("test", "test2") .verifyComplete(); } @Test public void takeBackpressured() { StepVerifier.create(Flux.from(s -> { s.onSubscribe(new Subscription() { @Override public void request(long n) { for(int i = 0 ; i < n; i ++) { s.onNext("test"); } } boolean extraNext = true; @Override public void cancel() { if(extraNext){ extraNext = false; s.onNext("test"); } } }); }) .take(3, false), 0) .thenAwait() .thenRequest(2) .expectNext("test", "test") .thenRequest(1) .expectNext("test") .verifyComplete(); } @Test public void takeFusedBackpressured() { Sinks.Many<String> up = Sinks.many().unicast().onBackpressureBuffer(); StepVerifier.create(up.asFlux() .take(3, false), 0) .expectFusion() .then(() -> up.emitNext("test", FAIL_FAST)) .then(() -> up.emitNext("test2", FAIL_FAST)) .thenRequest(2) .expectNext("test", "test2") .then(() -> up.emitNext("test3", FAIL_FAST)) .then(() -> up.emitNext("test4", FAIL_FAST)) .thenRequest(1) .expectNext("test3") .thenRequest(1) .verifyComplete(); } @Test public void takeFusedBackpressuredCancelled() { Sinks.Many<String> up = Sinks.many().unicast().onBackpressureBuffer(); StepVerifier.create(up.asFlux() .take(3, false).doOnSubscribe(s -> { assertThat(((Fuseable.QueueSubscription)s).size()).isEqualTo(0); }), 0) .expectFusion() .then(() -> up.emitNext("test", FAIL_FAST)) .then(() -> up.emitNext("test", FAIL_FAST)) .then(() -> up.emitNext("test", FAIL_FAST)) .thenRequest(2) .expectNext("test", "test") .thenCancel() .verify(); } @Test public void takeBackpressuredConditional() { StepVerifier.create(Flux.from(s -> { s.onSubscribe(new Subscription() { @Override public void request(long n) { for(int i = 0 ; i < n; i ++) { s.onNext("test"); } } boolean extraNext = true; @Override public void cancel() { if(extraNext){ extraNext = false; s.onNext("test"); } } }); }) .take(3, false) .filter("test"::equals), 0) .thenAwait() .thenRequest(2) .expectNext("test", "test") .thenRequest(1) .expectNext("test") .verifyComplete(); } @Test @SuppressWarnings("unchecked") public void takeBackpressuredSourceConditional() { StepVerifier.create(Flux.from(_s -> { Fuseable.ConditionalSubscriber s = (Fuseable.ConditionalSubscriber)_s; s.onSubscribe(new Subscription() { @Override public void request(long n) { for(int i = 0 ; i < n; i ++) { s.tryOnNext("test"); } } boolean extraNext = true; @Override public void cancel() { if(extraNext){ extraNext = false; s.tryOnNext("test"); } } }); }) .take(3, false) .filter("test"::equals), 0) .thenAwait() .thenRequest(2) .expectNext("test", "test") .thenRequest(1) .expectNext("test") .verifyComplete(); } @Test void propagatesUnboundedDemand() { AtomicLong requested = new AtomicLong(); Flux.range(1, 100) .hide() .doOnRequest(requested::set) .take(5, false) .as(f -> StepVerifier.create(f, 40)) .expectNextCount(5) .verifyComplete(); assertThat(requested).hasValue(Long.MAX_VALUE); } @Test public void failNextIfTerminatedTake() { Hooks.onNextDropped(t -> assertThat(t).isEqualTo(1)); StepVerifier.create(Flux.from(s -> { s.onSubscribe(Operators.emptySubscription()); s.onComplete(); s.onNext(1); }) .take(2, false)) .verifyComplete(); Hooks.resetOnNextDropped(); } @Test public void failNextIfTerminatedTakeFused() { TestPublisher<Integer> up = TestPublisher.createNoncompliant(TestPublisher.Violation.CLEANUP_ON_TERMINATE); Hooks.onNextDropped(t -> assertThat(t).isEqualTo(1)); StepVerifier.create(up.flux().take(2, false)) .then(up::complete) .then(() -> up.next(1)) .verifyComplete(); Hooks.resetOnNextDropped(); } @Test public void failNextIfTerminatedTakeConditional() { Hooks.onNextDropped(t -> assertThat(t).isEqualTo(1)); StepVerifier.create(Flux.from(s -> { s.onSubscribe(Operators.emptySubscription()); s.onComplete(); s.onNext(1); }) .take(2, false) .filter("test2"::equals)) .verifyComplete(); Hooks.resetOnNextDropped(); } @Test // fixme when we have a fuseable testPublisher or an improved hide operator @SuppressWarnings("unchecked") public void failNextIfTerminatedTakeSourceConditional() { Hooks.onNextDropped(t -> assertThat(t).isEqualTo(1)); StepVerifier.create(Flux.from(s -> { s.onSubscribe(Operators.emptySubscription()); s.onComplete(); ((Fuseable.ConditionalSubscriber)s).tryOnNext(1); }) .take(2, false) .filter("test2"::equals)) .verifyComplete(); Hooks.resetOnNextDropped(); } @Test public void take() { StepVerifier.create(Flux.just("test", "test2", "test3") .hide() .take(2, false)) .expectNext("test", "test2") .verifyComplete(); } @Test public void takeCancel() { StepVerifier.create(Flux.just("test", "test2", "test3") .hide() .take(3, false), 2) .expectNext("test", "test2") .thenCancel() .verify(); } @Test public void takeFused() { StepVerifier.create(Flux.just("test", "test2", "test3") .take(2, false)) .expectNext("test", "test2") .verifyComplete(); } @Test public void takeFusedSync() { StepVerifier.create(Flux.just("test", "test2", "test3") .take(2, false)) .expectFusion(Fuseable.SYNC) .expectNext("test", "test2") .verifyComplete(); } @Test public void takeFusedAsync() { Sinks.Many<String> up = Sinks.many().unicast().onBackpressureBuffer(); StepVerifier.create(up.asFlux() .take(2, false)) .expectFusion(Fuseable.ASYNC) .then(() -> { up.emitNext("test", FAIL_FAST); up.emitNext("test2", FAIL_FAST); }) .expectNext("test", "test2") .verifyComplete(); } @Test public void takeFusedCancel() { StepVerifier.create(Flux.just("test", "test2", "test3") .take(3, false), 2) .expectNext("test", "test2") .thenCancel() .verify(); } @Test public void takeConditional() { StepVerifier.create(Flux.just("test", "test2", "test3") .hide() .take(2, false) .filter("test2"::equals)) .expectNext("test2") .verifyComplete(); } @Test public void takeConditionalCancel() { StepVerifier.create(Flux.just("test", "test2", "test3") .hide() .take(3, false) .filter("test2"::equals), 2) .thenCancel() .verify(); } @Test public void takeConditionalFused() { StepVerifier.create(Flux.just("test", "test2", "test3") .take(2, false) .filter("test2"::equals)) .expectNext("test2") .verifyComplete(); } @Test public void takeConditionalFusedCancel() { StepVerifier.create(Flux.just("test", "test2", "test3") .take(3, false) .filter("test2"::equals), 2) .expectNext("test2") .thenCancel() .verify(); } @SuppressWarnings("unchecked") void assertTrackableBeforeOnSubscribe(InnerOperator t){ assertThat(t.scan(Scannable.Attr.TERMINATED)).isFalse(); } void assertTrackableAfterOnSubscribe(InnerOperator t){ assertThat(t.scan(Scannable.Attr.TERMINATED)).isFalse(); } void assertTrackableAfterOnComplete(InnerOperator t){ assertThat(t.scan(Scannable.Attr.TERMINATED)).isTrue(); } @Test @SuppressWarnings("unchecked") public void failDoubleError() { Hooks.onErrorDropped(e -> assertThat(e).hasMessage("test2")); StepVerifier.create(Flux.from(s -> { assertTrackableBeforeOnSubscribe((InnerOperator)s); s.onSubscribe(Operators.emptySubscription()); assertTrackableAfterOnSubscribe((InnerOperator)s); s.onError(new Exception("test")); assertTrackableAfterOnComplete((InnerOperator)s); s.onError(new Exception("test2")); }) .take(2, false)) .verifyErrorMessage("test"); } @Test @SuppressWarnings("unchecked") public void failConditionalDoubleError() { Hooks.onErrorDropped(e -> assertThat(e).hasMessage("test2")); StepVerifier.create(Flux.from(s -> { assertTrackableBeforeOnSubscribe((InnerOperator)s); s.onSubscribe(Operators.emptySubscription()); assertTrackableAfterOnSubscribe((InnerOperator)s); s.onError(new Exception("test")); assertTrackableAfterOnComplete((InnerOperator)s); s.onError(new Exception("test2")); }) .take(2, false).filter(d -> true)) .verifyErrorMessage("test"); } @Test @SuppressWarnings("unchecked") public void failFusedDoubleError() { Sinks.Many<Integer> up = Sinks.many().unicast().onBackpressureBuffer(); Hooks.onErrorDropped(e -> assertThat(e).hasMessage("test2")); StepVerifier.create(up.asFlux() .take(2, false)) .consumeSubscriptionWith(s -> { assertTrackableBeforeOnSubscribe((InnerOperator)s); }) .then(() -> { InnerOperator processorDownstream = (InnerOperator) Scannable.from(up).scan(Scannable.Attr.ACTUAL); assertTrackableAfterOnSubscribe(processorDownstream); processorDownstream.onError(new Exception("test")); assertTrackableAfterOnComplete(processorDownstream); processorDownstream.onError(new Exception("test2")); }) .verifyErrorMessage("test"); } @Test public void ignoreFusedDoubleComplete() { Sinks.Many<Integer> up = Sinks.many().unicast().onBackpressureBuffer(); StepVerifier.create(up.asFlux() .take(2, false).filter(d -> true)) .consumeSubscriptionWith(s -> { assertTrackableAfterOnSubscribe((InnerOperator)s); }) .then(() -> { InnerOperator processorDownstream = (InnerOperator) Scannable.from(up).scan(Scannable.Attr.ACTUAL); assertTrackableAfterOnSubscribe(processorDownstream); processorDownstream.onComplete(); assertTrackableAfterOnComplete(processorDownstream); processorDownstream.onComplete(); }) .verifyComplete(); } @Test public void ignoreDoubleComplete() { StepVerifier.create(Flux.from(s -> { s.onSubscribe(Operators.emptySubscription()); s.onComplete(); s.onComplete(); }) .take(2, false)) .verifyComplete(); } @Test public void assertPrefetch() { assertThat(Flux.just("test", "test2", "test3") .hide() .take(2, false) .getPrefetch()).isEqualTo(Integer.MAX_VALUE); } @Test public void ignoreDoubleOnSubscribe() { StepVerifier.create(Flux.from(s -> { s.onSubscribe(Operators.emptySubscription()); s.onSubscribe(Operators.emptySubscription()); s.onComplete(); }) .take(2, false)) .verifyComplete(); } @Test public void ignoreConditionalDoubleOnSubscribe() { StepVerifier.create(Flux.from(s -> { s.onSubscribe(Operators.emptySubscription()); s.onSubscribe(Operators.emptySubscription()); s.onComplete(); }) .take(2, false) .filter(d -> true)) .verifyComplete(); } @Test public void takeZeroCancelsWhenNoRequest() { TestPublisher<Integer> ts = TestPublisher.create(); StepVerifier.create(ts.flux() .take(0, false), 0) .thenAwait() .verifyComplete(); ts.assertWasNotRequested(); ts.assertWasCancelled(); } @Test public void takeZeroIgnoresRequestAndCancels() { TestPublisher<Integer> ts = TestPublisher.create(); StepVerifier.create(ts.flux() .take(0, false), 3) .thenAwait() .verifyComplete(); ts.assertWasNotRequested(); ts.assertWasCancelled(); } @Test public void takeConditionalZeroCancelsWhenNoRequest() { TestPublisher<Integer> ts = TestPublisher.create(); StepVerifier.create(ts.flux() .take(0, false) .filter(d -> true), 0) .thenAwait() .verifyComplete(); ts.assertWasNotRequested(); ts.assertWasCancelled(); } @Test public void takeConditionalZeroIgnoresRequestAndCancels() { TestPublisher<Integer> ts = TestPublisher.create(); StepVerifier.create(ts.flux() .take(0, false) .filter(d -> true), 3) .thenAwait() .verifyComplete(); ts.assertWasNotRequested(); ts.assertWasCancelled(); } @Test public void scanOperator(){ Flux<Integer> parent = Flux.just(1); FluxTake<Integer> test = new FluxTake<>(parent, 3); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); } @Test public void scanFuseableOperator(){ Flux<Integer> parent = Flux.just(1); FluxTakeFuseable<Integer> test = new FluxTakeFuseable<>(parent, 3); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); } @Test public void scanSubscriber() { CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null); FluxTake.TakeSubscriber<Integer> test = new FluxTake.TakeSubscriber<>(actual, 5); Subscription parent = Operators.emptySubscription(); test.onSubscribe(parent); Assertions.assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent); Assertions.assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual); Assertions.assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); test.onComplete(); Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue(); } @Test public void scanConditionalSubscriber() { @SuppressWarnings("unchecked") Fuseable.ConditionalSubscriber<Integer> actual = Mockito.mock(MockUtils.TestScannableConditionalSubscriber.class); FluxTake.TakeConditionalSubscriber<Integer> test = new FluxTake.TakeConditionalSubscriber<>(actual, 5); Subscription parent = Operators.emptySubscription(); test.onSubscribe(parent); Assertions.assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent); Assertions.assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual); Assertions.assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); test.onComplete(); Assertions.assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue(); } @Test public void scanFuseableSubscriber() { CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null); FluxTake.TakeFuseableSubscriber<Integer> test = new FluxTake.TakeFuseableSubscriber<>(actual, 10); Subscription parent = Operators.emptySubscription(); test.onSubscribe(parent); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent); assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); test.onError(new IllegalStateException("boom")); assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue(); } @Test @Tag("slow") public void onSubscribeRaceRequestingShouldBeConsistentForTakeFuseableTest() throws InterruptedException { for (int i = 0; i < 5; i++) { int take = 3000; RaceSubscriber<Integer> actual = new RaceSubscriber<>(take); Flux.range(0, Integer.MAX_VALUE) .take(take, false) .subscribe(actual); actual.await(5, TimeUnit.SECONDS); } } @Test @Tag("slow") public void onSubscribeRaceRequestingShouldBeConsistentForTakeConditionalTest() throws InterruptedException { for (int i = 0; i < 5; i++) { int take = 3000; RaceSubscriber<Integer> actual = new RaceSubscriber<>(take); Flux.range(0, Integer.MAX_VALUE) .take(take, false) .filter(e -> true) .subscribe(actual); actual.await(5, TimeUnit.SECONDS); } } @Test @Tag("slow") public void onSubscribeRaceRequestingShouldBeConsistentForTakeTest() throws InterruptedException { for (int i = 0; i < 5; i++) { int take = 3000; RaceSubscriber<Integer> actual = new RaceSubscriber<>(take); Flux.range(0, Integer.MAX_VALUE) .hide() .take(take, false) .subscribe(actual); actual.await(5, TimeUnit.SECONDS); } } static final
FluxTakeTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/floatarray/FloatArrayAssert_hasSizeLessThanOrEqualTo_Test.java
{ "start": 803, "end": 1172 }
class ____ extends FloatArrayAssertBaseTest { @Override protected FloatArrayAssert invoke_api_method() { return assertions.hasSizeLessThanOrEqualTo(6); } @Override protected void verify_internal_effects() { verify(arrays).assertHasSizeLessThanOrEqualTo(getInfo(assertions), getActual(assertions), 6); } }
FloatArrayAssert_hasSizeLessThanOrEqualTo_Test
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/superbuilder/InheritedAbstractCar.java
{ "start": 200, "end": 670 }
class ____ extends AbstractVehicle { private final String manufacturer; protected InheritedAbstractCar(InheritedAbstractCarBuilder<?, ?> b) { super( b ); this.manufacturer = b.manufacturer; } public static InheritedAbstractCarBuilder<?, ?> builder() { return new InheritedAbstractCarBuilderImpl(); } public String getManufacturer() { return this.manufacturer; } public abstract static
InheritedAbstractCar
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/readonly/ReadOnlyUserDefinedTest.java
{ "start": 2211, "end": 2644 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @org.hibernate.annotations.JavaType( value = MyTypeJavaType.class ) private MyType myType; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public MyType getMyType() { return myType; } public void setMyType(MyType myType) { this.myType = myType; } } public static
MyEntity
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/fieldcaps/FieldCapabilities.java
{ "start": 17931, "end": 25202 }
class ____ { private final String name; private final String type; private boolean isMetadataField; private int searchableIndices = 0; private int aggregatableIndices = 0; private int dimensionIndices = 0; private TimeSeriesParams.MetricType metricType; private boolean hasConflictMetricType; private final List<IndexCaps> indicesList; private final Map<String, Set<String>> meta; private int totalIndices; Builder(String name, String type) { this.name = name; this.type = type; this.metricType = null; this.hasConflictMetricType = false; this.indicesList = new ArrayList<>(); this.meta = new HashMap<>(); } private boolean assertIndicesSorted(String[] indices) { for (int i = 1; i < indices.length; i++) { assert indices[i - 1].compareTo(indices[i]) < 0 : "indices [" + Arrays.toString(indices) + "] aren't sorted"; } if (indicesList.isEmpty() == false) { final IndexCaps lastCaps = indicesList.get(indicesList.size() - 1); final String lastIndex = lastCaps.indices[lastCaps.indices.length - 1]; assert lastIndex.compareTo(indices[0]) < 0 : "indices aren't sorted; previous [" + lastIndex + "], current [" + indices[0] + "]"; } return true; } /** * Collect the field capabilities for an index. */ void add( String[] indices, boolean isMetadataField, boolean search, boolean agg, boolean isDimension, TimeSeriesParams.MetricType metricType, Map<String, String> meta ) { assert assertIndicesSorted(indices); totalIndices += indices.length; if (search) { searchableIndices += indices.length; } if (agg) { aggregatableIndices += indices.length; } if (isDimension) { dimensionIndices += indices.length; } this.isMetadataField |= isMetadataField; // If we have discrepancy in metric types or in some indices this field is not marked as a metric field - we will // treat is a non-metric field and report this discrepancy in metricConflictsIndices if (indicesList.isEmpty()) { this.metricType = metricType; } else if (this.metricType != metricType) { hasConflictMetricType = true; this.metricType = null; } indicesList.add(new IndexCaps(indices, search, agg, isDimension, metricType)); for (Map.Entry<String, String> entry : meta.entrySet()) { this.meta.computeIfAbsent(entry.getKey(), key -> new HashSet<>()).add(entry.getValue()); } } void getIndices(Set<String> into) { for (int i = 0; i < indicesList.size(); i++) { IndexCaps indexCaps = indicesList.get(i); for (String element : indexCaps.indices) { into.add(element); } } } private String[] filterIndices(int length, Predicate<IndexCaps> pred) { int index = 0; final String[] dst = new String[length]; for (IndexCaps indexCaps : indicesList) { if (pred.test(indexCaps)) { System.arraycopy(indexCaps.indices, 0, dst, index, indexCaps.indices.length); index += indexCaps.indices.length; } } assert index == length : index + "!=" + length; return dst; } FieldCapabilities build(boolean withIndices) { final String[] indices = withIndices ? filterIndices(totalIndices, Predicates.always()) : null; // Iff this field is searchable in some indices AND non-searchable in others // we record the list of non-searchable indices final boolean isSearchable = searchableIndices == totalIndices; final String[] nonSearchableIndices; if (isSearchable || searchableIndices == 0) { nonSearchableIndices = null; } else { nonSearchableIndices = filterIndices(totalIndices - searchableIndices, ic -> ic.isSearchable == false); } // Iff this field is aggregatable in some indices AND non-aggregatable in others // we keep the list of non-aggregatable indices final boolean isAggregatable = aggregatableIndices == totalIndices; final String[] nonAggregatableIndices; if (isAggregatable || aggregatableIndices == 0) { nonAggregatableIndices = null; } else { nonAggregatableIndices = filterIndices(totalIndices - aggregatableIndices, ic -> ic.isAggregatable == false); } // Collect all indices that have dimension == false if this field is marked as a dimension in at least one index final boolean isDimension = dimensionIndices == totalIndices; final String[] nonDimensionIndices; if (isDimension || dimensionIndices == 0) { nonDimensionIndices = null; } else { nonDimensionIndices = filterIndices(totalIndices - dimensionIndices, ic -> ic.isDimension == false); } final String[] metricConflictsIndices; if (hasConflictMetricType) { // Collect all indices that have this field. If it is marked differently in different indices, we cannot really // make a decisions which index is "right" and which index is "wrong" so collecting all indices where this field // is present is probably the only sensible thing to do here metricConflictsIndices = Objects.requireNonNullElseGet(indices, () -> filterIndices(totalIndices, Predicates.always())); } else { metricConflictsIndices = null; } final Function<Map.Entry<String, Set<String>>, Set<String>> entryValueFunction = Map.Entry::getValue; Map<String, Set<String>> immutableMeta = meta.entrySet() .stream() .collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, entryValueFunction.andThen(Set::copyOf))); return new FieldCapabilities( name, type, isMetadataField, isSearchable, isAggregatable, isDimension, metricType, indices, nonSearchableIndices, nonAggregatableIndices, nonDimensionIndices, metricConflictsIndices, immutableMeta ); } } private record IndexCaps( String[] indices, boolean isSearchable, boolean isAggregatable, boolean isDimension, TimeSeriesParams.MetricType metricType ) {} }
Builder
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ObjectMapperTestAccess.java
{ "start": 47, "end": 195 }
class ____ by tests to access state of {@link ObjectMapper} that is * only accessible from the same package * * @since 3.0 */ public abstract
needed
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/geo/GeoJsonSerializationTests.java
{ "start": 2097, "end": 5489 }
class ____ implements ToXContentObject { private final Geometry geometry; GeometryWrapper(Geometry geometry) { this.geometry = geometry; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return GeoJson.toXContent(geometry, builder, params); } public static GeometryWrapper fromXContent(XContentParser parser) throws IOException { parser.nextToken(); return new GeometryWrapper(GeoJson.fromXContent(GeographyValidator.instance(true), false, true, parser)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GeometryWrapper that = (GeometryWrapper) o; return Objects.equals(geometry, that.geometry); } @Override public int hashCode() { return Objects.hash(geometry); } } private void xContentTest(Supplier<Geometry> instanceSupplier) throws IOException { AbstractXContentTestCase.xContentTester( this::createParser, () -> new GeometryWrapper(instanceSupplier.get()), (geometryWrapper, xContentBuilder) -> { geometryWrapper.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS); }, GeometryWrapper::fromXContent ).supportsUnknownFields(true).test(); } public void testPoint() throws IOException { xContentTest(() -> randomPoint(randomBoolean())); } public void testMultiPoint() throws IOException { xContentTest(() -> randomMultiPoint(randomBoolean())); } public void testLineString() throws IOException { xContentTest(() -> randomLine(randomBoolean())); } public void testMultiLineString() throws IOException { xContentTest(() -> randomMultiLine(randomBoolean())); } public void testPolygon() throws IOException { xContentTest(() -> randomPolygon(randomBoolean())); } public void testMultiPolygon() throws IOException { xContentTest(() -> randomMultiPolygon(randomBoolean())); } public void testEnvelope() throws IOException { xContentTest(GeometryTestUtils::randomRectangle); } public void testGeometryCollection() throws IOException { xContentTest(() -> randomGeometryCollection(randomBoolean())); } public void testCircle() throws IOException { xContentTest(() -> randomCircle(randomBoolean())); } public void testToMap() throws IOException { for (int i = 0; i < 10; i++) { Geometry geometry = GeometryTestUtils.randomGeometry(randomBoolean()); XContentBuilder builder = XContentFactory.jsonBuilder(); GeoJson.toXContent(geometry, builder, ToXContent.EMPTY_PARAMS); StreamInput input = BytesReference.bytes(builder).streamInput(); try ( XContentParser parser = XContentType.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, input) ) { Map<String, Object> map = GeoJson.toMap(geometry); assertThat(parser.map(), equalTo(map)); } } } }
GeometryWrapper
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/DynamicNodeGenerationTests.java
{ "start": 22845, "end": 24949 }
class ____ { private static final List<DynamicTest> list = Arrays.asList( dynamicTest("succeedingTest", () -> assertTrue(true, "succeeding")), dynamicTest("failingTest", () -> fail("failing"))); private static final AtomicBoolean exceptionThrowingStreamClosed = new AtomicBoolean(false); @TestFactory Collection<DynamicTest> dynamicCollection() { return list; } @TestFactory Stream<DynamicTest> dynamicStream() { return list.stream(); } @TestFactory Iterator<DynamicTest> dynamicIterator() { return list.iterator(); } @TestFactory Iterable<DynamicTest> dynamicIterable() { return this::dynamicIterator; } @TestFactory Iterable<DynamicNode> dynamicContainerWithIterable() { return Set.of(dynamicContainer("box", list)); } @TestFactory Iterable<DynamicNode> nestedDynamicContainers() { return Set.of(dynamicContainer("gift wrap", Set.of(dynamicContainer("box", list)))); } @TestFactory Stream<DynamicNode> twoNestedContainersWithTwoTestsEach() { return Stream.of( // dynamicContainer("a", Set.of(dynamicContainer("a1", list))), // dynamicContainer("b", Set.of(dynamicContainer("b1", list))) // ); } @TestFactory Iterable<DynamicNode> dynamicContainerWithExceptionThrowingStream() { // @formatter:off return Set.of(dynamicContainer("box", IntStream.rangeClosed(0, 100) .mapToObj(list::get) .onClose(() -> exceptionThrowingStreamClosed.set(true)))); // @formatter:on } @TestFactory Iterable<DynamicNode> dynamicContainerWithNullChildren() { return Set.of(dynamicContainer("box", singleton(null))); } @TestFactory DynamicNode singleContainer() { return dynamicContainer("box", list); } @TestFactory DynamicNode singleTest() { return dynamicTest("succeedingTest", () -> assertTrue(true)); } @TestFactory Stream<DynamicNode> threeTests() { return Stream.of( // dynamicTest("one", () -> assertTrue(true)), // dynamicTest("two", () -> assertTrue(true)), // dynamicTest("three", () -> assertTrue(true)) // ); } } }
MyDynamicTestCase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/sequences/entities/Bunny.java
{ "start": 680, "end": 1234 }
class ____ implements Serializable { @Id @GeneratedValue(generator = "java5_uuid") @GenericGenerator(name = "java5_uuid", type = org.hibernate.orm.test.annotations.id.UUIDGenerator.class) @Column(name = "id", precision = 128) private BigInteger id; @OneToMany(mappedBy = "bunny", cascade = CascadeType.PERSIST) Set<PointyTooth> teeth; @OneToMany(mappedBy = "bunny", cascade = CascadeType.PERSIST) Set<TwinkleToes> toes; public void setTeeth(Set<PointyTooth> teeth) { this.teeth = teeth; } public BigInteger getId() { return id; } }
Bunny
java
dropwizard__dropwizard
dropwizard-core/src/main/java/io/dropwizard/core/server/AbstractServerFactory.java
{ "start": 8713, "end": 23621 }
class ____ implements ServerFactory { private static final Logger LOGGER = LoggerFactory.getLogger(ServerFactory.class); @Valid @Nullable private RequestLogFactory<?> requestLog; @Valid @NotNull private GzipHandlerFactory gzip = new GzipHandlerFactory(); @Valid @NotNull private ResponseMeteredLevel responseMeteredLevel = COARSE; @Nullable private String metricPrefix = null; @Min(4) private int maxThreads = 1024; @Min(1) private int minThreads = 8; @MinDuration(1) private Duration idleThreadTimeout = Duration.minutes(1); @Min(1) @Nullable private Integer nofileSoftLimit; @Min(1) @Nullable private Integer nofileHardLimit; @Nullable private Integer gid; @Nullable private Integer uid; @Nullable private String user; @Nullable private String group; @Nullable private String umask; @Nullable private Boolean startsAsRoot; private Boolean registerDefaultExceptionMappers = Boolean.TRUE; private Boolean detailedJsonProcessingExceptionMapper = Boolean.FALSE; private Duration shutdownGracePeriod = Duration.seconds(30); @NotNull private Set<String> allowedMethods = AllowedMethodsFilter.DEFAULT_ALLOWED_METHODS; private Optional<String> jerseyRootPath = Optional.empty(); private boolean enableThreadNameFilter = true; private boolean dumpAfterStart = false; private boolean dumpBeforeStop = false; private boolean enableVirtualThreads = false; @JsonIgnore @ValidationMethod(message = "must have a smaller minThreads than maxThreads") public boolean isThreadPoolSizedCorrectly() { return minThreads <= maxThreads; } @JsonProperty("requestLog") public synchronized RequestLogFactory<?> getRequestLogFactory() { if (requestLog == null) { // Lazy init to avoid a hard dependency to logback requestLog = new LogbackAccessRequestLogFactory(); } return requestLog; } @JsonProperty("requestLog") public synchronized void setRequestLogFactory(RequestLogFactory<?> requestLog) { this.requestLog = requestLog; } @JsonProperty("gzip") public GzipHandlerFactory getGzipFilterFactory() { return gzip; } @JsonProperty("gzip") public void setGzipFilterFactory(GzipHandlerFactory gzip) { this.gzip = gzip; } @JsonProperty("responseMeteredLevel") public ResponseMeteredLevel getResponseMeteredLevel() { return responseMeteredLevel; } @JsonProperty("metricPrefix") @Nullable public String getMetricPrefix() { return metricPrefix; } @JsonProperty public int getMaxThreads() { return maxThreads; } @JsonProperty public void setMaxThreads(int count) { this.maxThreads = count; } @JsonProperty public int getMinThreads() { return minThreads; } @JsonProperty public void setMinThreads(int count) { this.minThreads = count; } @JsonProperty public Duration getIdleThreadTimeout() { return idleThreadTimeout; } @JsonProperty public void setIdleThreadTimeout(Duration idleThreadTimeout) { this.idleThreadTimeout = idleThreadTimeout; } @JsonProperty @Nullable public Integer getNofileSoftLimit() { return nofileSoftLimit; } @JsonProperty public void setNofileSoftLimit(Integer nofileSoftLimit) { this.nofileSoftLimit = nofileSoftLimit; } @JsonProperty @Nullable public Integer getNofileHardLimit() { return nofileHardLimit; } @JsonProperty public void setNofileHardLimit(Integer nofileHardLimit) { this.nofileHardLimit = nofileHardLimit; } @JsonProperty @Nullable public Integer getGid() { return gid; } @JsonProperty public void setGid(Integer gid) { this.gid = gid; } @JsonProperty @Nullable public Integer getUid() { return uid; } @JsonProperty public void setUid(Integer uid) { this.uid = uid; } @JsonProperty @Nullable public String getUser() { return user; } @JsonProperty public void setUser(String user) { this.user = user; } @JsonProperty @Nullable public String getGroup() { return group; } @JsonProperty public void setGroup(String group) { this.group = group; } @JsonProperty @Nullable public String getUmask() { return umask; } @JsonProperty public void setUmask(String umask) { this.umask = umask; } @JsonProperty @Nullable public Boolean getStartsAsRoot() { return startsAsRoot; } @JsonProperty public void setStartsAsRoot(Boolean startsAsRoot) { this.startsAsRoot = startsAsRoot; } public Boolean getRegisterDefaultExceptionMappers() { return registerDefaultExceptionMappers; } @JsonProperty public void setRegisterDefaultExceptionMappers(Boolean registerDefaultExceptionMappers) { this.registerDefaultExceptionMappers = registerDefaultExceptionMappers; } public Boolean getDetailedJsonProcessingExceptionMapper() { return detailedJsonProcessingExceptionMapper; } @JsonProperty public void setDetailedJsonProcessingExceptionMapper(Boolean detailedJsonProcessingExceptionMapper) { this.detailedJsonProcessingExceptionMapper = detailedJsonProcessingExceptionMapper; } @JsonProperty public Duration getShutdownGracePeriod() { return shutdownGracePeriod; } @JsonProperty public void setShutdownGracePeriod(Duration shutdownGracePeriod) { this.shutdownGracePeriod = shutdownGracePeriod; } @JsonProperty public Set<String> getAllowedMethods() { return allowedMethods; } @JsonProperty public void setAllowedMethods(Set<String> allowedMethods) { this.allowedMethods = allowedMethods; } @JsonProperty("rootPath") public Optional<String> getJerseyRootPath() { return jerseyRootPath; } @JsonProperty("rootPath") public void setJerseyRootPath(String jerseyRootPath) { this.jerseyRootPath = Optional.ofNullable(jerseyRootPath); } @JsonProperty public boolean getEnableThreadNameFilter() { return enableThreadNameFilter; } @JsonProperty public void setEnableThreadNameFilter(boolean enableThreadNameFilter) { this.enableThreadNameFilter = enableThreadNameFilter; } /** * @since 2.0 */ @JsonProperty public boolean getDumpAfterStart() { return dumpAfterStart; } /** * @since 2.0 */ @JsonProperty public void setDumpAfterStart(boolean dumpAfterStart) { this.dumpAfterStart = dumpAfterStart; } /** * @since 2.0 */ @JsonProperty public boolean getDumpBeforeStop() { return dumpBeforeStop; } /** * @since 2.0 */ @JsonProperty public void setDumpBeforeStop(boolean dumpBeforeStop) { this.dumpBeforeStop = dumpBeforeStop; } @JsonProperty public boolean isEnableVirtualThreads() { return enableVirtualThreads; } @JsonProperty public void setEnableVirtualThreads(boolean enableVirtualThreads) { this.enableVirtualThreads = enableVirtualThreads; } protected Handler createAdminServlet(Server server, MutableServletContextHandler handler, MetricRegistry metrics, HealthCheckRegistry healthChecks, AdminEnvironment admin) { configureSessionsAndSecurity(handler, server); handler.setServer(server); handler.getServletContext().setAttribute(MetricsServlet.METRICS_REGISTRY, metrics); handler.getServletContext().setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY, healthChecks); handler.getServletContext().setAttribute(AdminServlet.HEALTHCHECK_ENABLED_PARAM_KEY, admin.isHealthCheckServletEnabled()); handler.addServlet(AdminServlet.class, "/*"); final String allowedMethodsParam = String.join(",", allowedMethods); handler.addFilter(AllowedMethodsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)) .setInitParameter(AllowedMethodsFilter.ALLOWED_METHODS_PARAM, allowedMethodsParam); return handler; } private void configureSessionsAndSecurity(MutableServletContextHandler handler, Server server) { handler.setServer(server); if (handler.isSecurityEnabled()) { handler.getSecurityHandler().setServer(server); } if (handler.isSessionsEnabled()) { handler.getSessionHandler().setServer(server); } } protected Handler createAppServlet(Server server, JerseyEnvironment jersey, ObjectMapper objectMapper, Validator validator, MutableServletContextHandler handler, @Nullable Servlet jerseyContainer, MetricRegistry metricRegistry) { configureSessionsAndSecurity(handler, server); final String allowedMethodsParam = String.join(",", allowedMethods); handler.addFilter(AllowedMethodsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)) .setInitParameter(AllowedMethodsFilter.ALLOWED_METHODS_PARAM, allowedMethodsParam); handler.addFilter(ZipExceptionHandlingServletFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); if (enableThreadNameFilter) { handler.addFilter(ThreadNameFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); } if (jerseyContainer != null) { jerseyRootPath.ifPresent(jersey::setUrlPattern); jersey.register(new JacksonFeature(objectMapper)); jersey.register(new HibernateValidationBinder(validator)); if (registerDefaultExceptionMappers == null || registerDefaultExceptionMappers) { jersey.register(new ExceptionMapperBinder(detailedJsonProcessingExceptionMapper)); } handler.addServlet(new ServletHolder("jersey", jerseyContainer), jersey.getUrlPattern()); } @SuppressWarnings("NullAway") final InstrumentedEE10Handler instrumented = new InstrumentedEE10Handler(metricRegistry, metricPrefix, responseMeteredLevel); instrumented.setServer(server); instrumented.setHandler(handler); return instrumented; } protected ThreadPool createThreadPool(MetricRegistry metricRegistry) { final BlockingQueue<Runnable> queue = new BlockingArrayQueue<>(minThreads, maxThreads); final InstrumentedQueuedThreadPool threadPool = new InstrumentedQueuedThreadPool(metricRegistry, maxThreads, minThreads, (int) idleThreadTimeout.toMilliseconds(), queue); if (enableVirtualThreads) { threadPool.setVirtualThreadsExecutor(new VirtualThreadPool(maxThreads)); } threadPool.setName("dw"); return threadPool; } protected Server buildServer(LifecycleEnvironment lifecycle, ThreadPool threadPool) { final Server server = new Server(threadPool); server.addEventListener(buildSetUIDListener()); lifecycle.attach(server); final ErrorHandler errorHandler = new ErrorHandler(); errorHandler.setShowStacks(false); server.setErrorHandler(errorHandler); server.setStopAtShutdown(true); server.setStopTimeout(shutdownGracePeriod.toMilliseconds()); server.setDumpAfterStart(dumpAfterStart); server.setDumpBeforeStop(dumpBeforeStop); return server; } protected SetUIDListener buildSetUIDListener() { final SetUIDListener listener = new SetUIDListener(); if (startsAsRoot != null) { listener.setStartServerAsPrivileged(startsAsRoot); } if (gid != null) { listener.setGid(gid); } if (uid != null) { listener.setUid(uid); } if (user != null) { listener.setUsername(user); } if (group != null) { listener.setGroupname(group); } if (nofileHardLimit != null || nofileSoftLimit != null) { final RLimit rlimit = new RLimit(); if (nofileHardLimit != null) { rlimit.setHard(nofileHardLimit); } if (nofileSoftLimit != null) { rlimit.setSoft(nofileSoftLimit); } listener.setRLimitNoFiles(rlimit); } if (umask != null) { listener.setUmaskOctal(umask); } return listener; } protected void addRequestLog(Server server, String name, MutableServletContextHandler servletContextHandler) { if (getRequestLogFactory().isEnabled()) { RequestLog log = getRequestLogFactory().build(name); if (log instanceof LogbackAccessRequestLog) { servletContextHandler.insertHandler(new LogbackAccessRequestLogAwareHandler()); } server.setRequestLog(log); } } protected Handler addGracefulHandler(Handler handler) { final GracefulHandler gracefulHandler = new GracefulHandler(); gracefulHandler.setHandler(handler); return gracefulHandler; } protected Handler buildGzipHandler(Handler handler) { return gzip.isEnabled() ? gzip.build(handler) : handler; } @SuppressWarnings("Slf4jFormatShouldBeConst") protected void printBanner(String name) { String msg = "Starting " + name; try (final InputStream resourceStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("banner.txt")) { if (resourceStream != null) { try (final InputStreamReader inputStreamReader = new InputStreamReader(resourceStream); final BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { final String banner = bufferedReader .lines() .collect(Collectors.joining(System.lineSeparator())); msg = String.format("Starting %s%n%s", name, banner); } } } catch (IllegalArgumentException | IOException ignored) { } LOGGER.info(msg); } }
AbstractServerFactory
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/health/node/FetchHealthInfoCacheAction.java
{ "start": 1705, "end": 2151 }
class ____ extends HealthNodeRequest { public Request() {} public Request(StreamInput in) throws IOException { super(in); } @Override public ActionRequestValidationException validate() { return null; } @Override public String getDescription() { return "Fetching health information from the health node."; } } public static
Request
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/dataview/PerWindowStateDataViewStore.java
{ "start": 1891, "end": 4773 }
class ____ implements StateDataViewStore { private static final String NULL_STATE_POSTFIX = "_null_state"; private final KeyedStateBackend<?> keyedStateBackend; private final TypeSerializer<?> windowSerializer; private final RuntimeContext ctx; public PerWindowStateDataViewStore( KeyedStateBackend<?> keyedStateBackend, TypeSerializer<?> windowSerializer, RuntimeContext runtimeContext) { this.keyedStateBackend = keyedStateBackend; this.windowSerializer = windowSerializer; this.ctx = runtimeContext; } @Override public <N, EK, EV> StateMapView<N, EK, EV> getStateMapView( String stateName, boolean supportNullKey, TypeSerializer<EK> keySerializer, TypeSerializer<EV> valueSerializer) throws Exception { final MapStateDescriptor<EK, EV> mapStateDescriptor = new MapStateDescriptor<>(stateName, keySerializer, valueSerializer); final MapState<EK, EV> mapState = keyedStateBackend.getOrCreateKeyedState(windowSerializer, mapStateDescriptor); // explict cast to internal state final InternalMapState<?, N, EK, EV> internalMapState = (InternalMapState<?, N, EK, EV>) mapState; if (supportNullKey) { final ValueStateDescriptor<EV> nullStateDescriptor = new ValueStateDescriptor<>(stateName + NULL_STATE_POSTFIX, valueSerializer); final ValueState<EV> nullState = keyedStateBackend.getOrCreateKeyedState(windowSerializer, nullStateDescriptor); // explict cast to internal state final InternalValueState<?, N, EV> internalNullState = (InternalValueState<?, N, EV>) nullState; return new StateMapView.NamespacedStateMapViewWithKeysNullable<>( internalMapState, internalNullState); } else { return new StateMapView.NamespacedStateMapViewWithKeysNotNull<>(internalMapState); } } @Override public <N, EE> StateListView<N, EE> getStateListView( String stateName, TypeSerializer<EE> elementSerializer) throws Exception { final ListStateDescriptor<EE> listStateDescriptor = new ListStateDescriptor<>(stateName, elementSerializer); final ListState<EE> listState = keyedStateBackend.getOrCreateKeyedState(windowSerializer, listStateDescriptor); // explict cast to internal state final InternalListState<?, N, EE> internalListState = (InternalListState<?, N, EE>) listState; return new StateListView.NamespacedStateListView<>(internalListState); } @Override public RuntimeContext getRuntimeContext() { return ctx; } }
PerWindowStateDataViewStore
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/client/HdfsClientConfigKeys.java
{ "start": 14563, "end": 17307 }
interface ____ { String DFS_NAMENODE_BACKUP_ADDRESS_KEY = "dfs.namenode.backup.address"; String DFS_NAMENODE_BACKUP_HTTP_ADDRESS_KEY = "dfs.namenode.backup.http-address"; String DFS_DATANODE_BALANCE_BANDWIDTHPERSEC_KEY = "dfs.datanode.balance.bandwidthPerSec"; //Following keys have no defaults String DFS_DATANODE_DATA_DIR_KEY = "dfs.datanode.data.dir"; String DFS_NAMENODE_MAX_OBJECTS_KEY = "dfs.namenode.max.objects"; String DFS_NAMENODE_NAME_DIR_KEY = "dfs.namenode.name.dir"; String DFS_NAMENODE_NAME_DIR_RESTORE_KEY = "dfs.namenode.name.dir.restore"; String DFS_NAMENODE_EDITS_DIR_KEY = "dfs.namenode.edits.dir"; String DFS_NAMENODE_SAFEMODE_EXTENSION_KEY = "dfs.namenode.safemode.extension"; String DFS_NAMENODE_SAFEMODE_THRESHOLD_PCT_KEY = "dfs.namenode.safemode.threshold-pct"; String DFS_NAMENODE_SECONDARY_HTTP_ADDRESS_KEY = "dfs.namenode.secondary.http-address"; String DFS_NAMENODE_CHECKPOINT_DIR_KEY = "dfs.namenode.checkpoint.dir"; String DFS_NAMENODE_CHECKPOINT_EDITS_DIR_KEY = "dfs.namenode.checkpoint.edits.dir"; String DFS_NAMENODE_CHECKPOINT_PERIOD_KEY = "dfs.namenode.checkpoint.period"; String DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY = "dfs.namenode.heartbeat.recheck-interval"; String DFS_CLIENT_HTTPS_KEYSTORE_RESOURCE_KEY = "dfs.client.https.keystore.resource"; String DFS_CLIENT_HTTPS_NEED_AUTH_KEY = "dfs.client.https.need-auth"; String DFS_DATANODE_HOST_NAME_KEY = "dfs.datanode.hostname"; String DFS_METRICS_SESSION_ID_KEY = "dfs.metrics.session-id"; String DFS_NAMENODE_ACCESSTIME_PRECISION_KEY = "dfs.namenode.accesstime.precision"; String DFS_NAMENODE_REDUNDANCY_CONSIDERLOAD_KEY = "dfs.namenode.redundancy.considerLoad"; String DFS_NAMENODE_REDUNDANCY_CONSIDERLOAD_FACTOR = "dfs.namenode.redundancy.considerLoad.factor"; String DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_KEY = "dfs.namenode.redundancy.interval.seconds"; String DFS_NAMENODE_REPLICATION_MIN_KEY = "dfs.namenode.replication.min"; String DFS_NAMENODE_RECONSTRUCTION_PENDING_TIMEOUT_SEC_KEY = "dfs.namenode.reconstruction.pending.timeout-sec"; String DFS_NAMENODE_REPLICATION_MAX_STREAMS_KEY = "dfs.namenode.replication.max-streams"; String DFS_PERMISSIONS_ENABLED_KEY = "dfs.permissions.enabled"; String DFS_PERMISSIONS_SUPERUSERGROUP_KEY = "dfs.permissions.superusergroup"; String DFS_DATANODE_MAX_RECEIVER_THREADS_KEY = "dfs.datanode.max.transfer.threads"; String DFS_NAMESERVICE_ID = "dfs.nameservice.id"; } /** dfs.client.retry configuration properties */
DeprecatedKeys
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/ssl/AliasKeyManagerFactory.java
{ "start": 3349, "end": 4888 }
class ____ extends X509ExtendedKeyManager { private final X509ExtendedKeyManager delegate; private final String alias; private AliasX509ExtendedKeyManager(X509ExtendedKeyManager keyManager, String alias) { this.delegate = keyManager; this.alias = alias; } @Override public String chooseEngineClientAlias(String[] strings, Principal[] principals, SSLEngine sslEngine) { return this.delegate.chooseEngineClientAlias(strings, principals, sslEngine); } @Override public String chooseEngineServerAlias(String s, Principal[] principals, SSLEngine sslEngine) { return this.alias; } @Override public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { return this.delegate.chooseClientAlias(keyType, issuers, socket); } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { return this.delegate.chooseServerAlias(keyType, issuers, socket); } @Override public X509Certificate[] getCertificateChain(String alias) { return this.delegate.getCertificateChain(alias); } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { return this.delegate.getClientAliases(keyType, issuers); } @Override public PrivateKey getPrivateKey(String alias) { return this.delegate.getPrivateKey(alias); } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { return this.delegate.getServerAliases(keyType, issuers); } } }
AliasX509ExtendedKeyManager
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/openshiftai/rerank/OpenShiftAiRerankServiceSettings.java
{ "start": 1085, "end": 3932 }
class ____ extends OpenShiftAiServiceSettings { public static final String NAME = "openshift_ai_rerank_service_settings"; /** * Creates a new instance of OpenShiftAiRerankServiceSettings from a map of settings. * * @param map the map containing the service settings * @param context the context for parsing configuration settings * @return a new instance of OpenShiftAiRerankServiceSettings * @throws ValidationException if required fields are missing or invalid */ public static OpenShiftAiRerankServiceSettings fromMap(Map<String, Object> map, ConfigurationParseContext context) { return fromMap( map, context, commonServiceSettings -> new OpenShiftAiRerankServiceSettings( commonServiceSettings.model(), commonServiceSettings.uri(), commonServiceSettings.rateLimitSettings() ) ); } /** * Constructs a new OpenShiftAiRerankServiceSettings from a StreamInput. * * @param in the StreamInput to read from * @throws IOException if an I/O error occurs during reading */ public OpenShiftAiRerankServiceSettings(StreamInput in) throws IOException { super(in); } /** * Constructs a new OpenShiftAiRerankServiceSettings with the specified model ID, URI, and rate limit settings. * * @param modelId the ID of the model * @param uri the URI of the service * @param rateLimitSettings the rate limit settings for the service */ public OpenShiftAiRerankServiceSettings(@Nullable String modelId, URI uri, @Nullable RateLimitSettings rateLimitSettings) { super(modelId, uri, rateLimitSettings); } /** * Constructs a new OpenShiftAiRerankServiceSettings with the specified model ID and URL. * The rate limit settings will be set to the default value. * * @param modelId the ID of the model * @param url the URL of the service */ public OpenShiftAiRerankServiceSettings(@Nullable String modelId, String url, @Nullable RateLimitSettings rateLimitSettings) { this(modelId, createUri(url), rateLimitSettings); } @Override public String getWriteableName() { return NAME; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OpenShiftAiRerankServiceSettings that = (OpenShiftAiRerankServiceSettings) o; return Objects.equals(modelId, that.modelId) && Objects.equals(uri, that.uri) && Objects.equals(rateLimitSettings, that.rateLimitSettings); } @Override public int hashCode() { return Objects.hash(modelId, uri, rateLimitSettings); } }
OpenShiftAiRerankServiceSettings
java
bumptech__glide
benchmark/src/androidTest/java/com/bumptech/glide/benchmark/data/DataOpener.java
{ "start": 618, "end": 968 }
class ____ implements DataOpener<InputStream> { @Override public InputStream acquire(@RawRes int resourceId) { return ApplicationProvider.getApplicationContext().getResources().openRawResource(resourceId); } @Override public void close(InputStream data) throws IOException { data.close(); } } final
StreamOpener
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/vans/VansObject.java
{ "start": 253, "end": 424 }
class ____ implements Serializable { public String uuid; public String type; public ArrayList<VansObjectChildren> children; public float[] matrix; }
VansObject
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/context/properties/CheckAggregatedSpringConfigurationMetadata.java
{ "start": 1470, "end": 3115 }
class ____ extends DefaultTask { private FileCollection configurationPropertyMetadata; @OutputFile public abstract RegularFileProperty getReportLocation(); @InputFiles @PathSensitive(PathSensitivity.RELATIVE) public FileCollection getConfigurationPropertyMetadata() { return this.configurationPropertyMetadata; } public void setConfigurationPropertyMetadata(FileCollection configurationPropertyMetadata) { this.configurationPropertyMetadata = configurationPropertyMetadata; } @TaskAction void check() throws IOException { Report report = createReport(); File reportFile = getReportLocation().get().getAsFile(); Files.write(reportFile.toPath(), report, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); if (report.hasProblems()) { throw new VerificationException( "Problems found in aggregated Spring configuration metadata. See " + reportFile + " for details."); } } private Report createReport() { ConfigurationProperties configurationProperties = ConfigurationProperties .fromFiles(this.configurationPropertyMetadata); Set<String> propertyNames = configurationProperties.stream() .map(ConfigurationProperty::getName) .collect(Collectors.toSet()); List<ConfigurationProperty> missingReplacement = configurationProperties.stream() .filter(ConfigurationProperty::isDeprecated) .filter((deprecated) -> { String replacement = deprecated.getDeprecation().replacement(); return replacement != null && !propertyNames.contains(replacement); }) .toList(); return new Report(missingReplacement); } private static final
CheckAggregatedSpringConfigurationMetadata
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/internal/ContextIndexSearcher.java
{ "start": 24183, "end": 25059 }
class ____ implements ExitableDirectoryReader.QueryCancellation { private final List<Runnable> runnables = new ArrayList<>(); private void add(Runnable action) { Objects.requireNonNull(action, "cancellation runnable should not be null"); assert runnables.contains(action) == false : "Cancellation runnable already added"; runnables.add(action); } private void remove(Runnable action) { runnables.remove(action); } @Override public void checkCancelled() { for (Runnable timeout : runnables) { timeout.run(); } } @Override public boolean isEnabled() { return runnables.isEmpty() == false; } public void clear() { runnables.clear(); } } }
MutableQueryTimeout
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/ClassUtils.java
{ "start": 64885, "end": 65982 }
class ____ {@code cls} or {@code cls} if {@code cls} is not a primitive. {@code null} if null input. * @since 2.1 */ public static Class<?> primitiveToWrapper(final Class<?> cls) { return cls != null && cls.isPrimitive() ? PRIMITIVE_WRAPPER_MAP.get(cls) : cls; } /** * Converts an array of {@link Object} in to an array of {@link Class} objects. If any of these objects is null, a null element will be inserted into the * array. * * <p> * This method returns {@code null} for a {@code null} input array. * </p> * * @param array an {@link Object} array. * @return a {@link Class} array, {@code null} if null array input. * @since 2.4 */ public static Class<?>[] toClass(final Object... array) { if (array == null) { return null; } if (array.length == 0) { return ArrayUtils.EMPTY_CLASS_ARRAY; } return ArrayUtils.setAll(new Class[array.length], i -> array[i] == null ? null : array[i].getClass()); } /** * Converts and cleans up a
for
java
netty__netty
handler/src/main/java/io/netty/handler/ssl/ResumableX509ExtendedTrustManager.java
{ "start": 1472, "end": 2157 }
interface ____ {@link TrustManager} implementations an opportunity to restore any * values they would normally add during the TLS handshake, before the handshake completion is signalled * to the application. * <p> * When a session is resumed, the {@link SslHandler} will call the relevant {@code resume*} method, * before completing the handshake promise and sending the {@link SslHandshakeCompletionEvent#SUCCESS} * event down the pipeline. * <p> * A trust manager that does not add values to the handshake session in its {@code check*} methods, * will typically not have any need to implement this interface. * <p> * <strong>Note:</strong> The implementing trust manager
gives
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/checkpointing/StreamCheckpointNotifierITCase.java
{ "start": 11884, "end": 11991 }
interface ____ stores all the checkpoint ids it has seen in a static * list. */ private static
it
java
apache__rocketmq
common/src/main/java/org/apache/rocketmq/common/attribute/TopicMessageType.java
{ "start": 997, "end": 2479 }
enum ____ { UNSPECIFIED("UNSPECIFIED"), NORMAL("NORMAL"), FIFO("FIFO"), DELAY("DELAY"), TRANSACTION("TRANSACTION"), MIXED("MIXED"); private final String value; TopicMessageType(String value) { this.value = value; } public static Set<String> topicMessageTypeSet() { return Sets.newHashSet(UNSPECIFIED.value, NORMAL.value, FIFO.value, DELAY.value, TRANSACTION.value, MIXED.value); } public String getValue() { return value; } public static TopicMessageType parseFromMessageProperty(Map<String, String> messageProperty) { String isTrans = messageProperty.get(MessageConst.PROPERTY_TRANSACTION_PREPARED); String isTransValue = "true"; if (isTransValue.equals(isTrans)) { return TopicMessageType.TRANSACTION; } else if (messageProperty.get(MessageConst.PROPERTY_DELAY_TIME_LEVEL) != null || messageProperty.get(MessageConst.PROPERTY_TIMER_DELIVER_MS) != null || messageProperty.get(MessageConst.PROPERTY_TIMER_DELAY_SEC) != null || messageProperty.get(MessageConst.PROPERTY_TIMER_DELAY_MS) != null) { return TopicMessageType.DELAY; } else if (messageProperty.get(MessageConst.PROPERTY_SHARDING_KEY) != null) { return TopicMessageType.FIFO; } return TopicMessageType.NORMAL; } public String getMetricsValue() { return value.toLowerCase(); } }
TopicMessageType
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/datatransfer/PacketHeader.java
{ "start": 2270, "end": 7096 }
class ____ { private static final int MAX_PROTO_SIZE = PacketHeaderProto.newBuilder() .setOffsetInBlock(0) .setSeqno(0) .setLastPacketInBlock(false) .setDataLen(0) .setSyncBlock(false) .build().getSerializedSize(); public static final int PKT_LENGTHS_LEN = Ints.BYTES + Shorts.BYTES; public static final int PKT_MAX_HEADER_LEN = PKT_LENGTHS_LEN + MAX_PROTO_SIZE; private int packetLen; private PacketHeaderProto proto; public PacketHeader() { } public PacketHeader(int packetLen, long offsetInBlock, long seqno, boolean lastPacketInBlock, int dataLen, boolean syncBlock) { this.packetLen = packetLen; Preconditions.checkArgument(packetLen >= Ints.BYTES, "packet len %s should always be at least 4 bytes", packetLen); PacketHeaderProto.Builder builder = PacketHeaderProto.newBuilder() .setOffsetInBlock(offsetInBlock) .setSeqno(seqno) .setLastPacketInBlock(lastPacketInBlock) .setDataLen(dataLen); if (syncBlock) { // Only set syncBlock if it is specified. // This is wire-incompatible with Hadoop 2.0.0-alpha due to HDFS-3721 // because it changes the length of the packet header, and BlockReceiver // in that version did not support variable-length headers. builder.setSyncBlock(true); } proto = builder.build(); } public int getDataLen() { return proto.getDataLen(); } public boolean isLastPacketInBlock() { return proto.getLastPacketInBlock(); } public long getSeqno() { return proto.getSeqno(); } public long getOffsetInBlock() { return proto.getOffsetInBlock(); } public int getPacketLen() { return packetLen; } public boolean getSyncBlock() { return proto.getSyncBlock(); } @Override public String toString() { return "PacketHeader with packetLen=" + packetLen + " header data: " + proto.toString(); } public void setFieldsFromData( int packetLen, byte[] headerData) throws InvalidProtocolBufferException { this.packetLen = packetLen; proto = PacketHeaderProto.parseFrom(headerData); } public void readFields(ByteBuffer buf) throws IOException { packetLen = buf.getInt(); short protoLen = buf.getShort(); byte[] data = new byte[protoLen]; buf.get(data); proto = PacketHeaderProto.parseFrom(data); } public void readFields(DataInputStream in) throws IOException { this.packetLen = in.readInt(); short protoLen = in.readShort(); byte[] data = new byte[protoLen]; in.readFully(data); proto = PacketHeaderProto.parseFrom(data); } /** * @return the number of bytes necessary to write out this header, * including the length-prefixing of the payload and header */ public int getSerializedSize() { return PKT_LENGTHS_LEN + proto.getSerializedSize(); } /** * Write the header into the buffer. * This requires that PKT_HEADER_LEN bytes are available. */ public void putInBuffer(final ByteBuffer buf) { assert proto.getSerializedSize() <= MAX_PROTO_SIZE : "Expected " + (MAX_PROTO_SIZE) + " got: " + proto.getSerializedSize(); try { buf.putInt(packetLen); buf.putShort((short) proto.getSerializedSize()); proto.writeTo(new ByteBufferOutputStream(buf)); } catch (IOException e) { throw new RuntimeException(e); } } public void write(DataOutputStream out) throws IOException { assert proto.getSerializedSize() <= MAX_PROTO_SIZE : "Expected " + (MAX_PROTO_SIZE) + " got: " + proto.getSerializedSize(); out.writeInt(packetLen); out.writeShort(proto.getSerializedSize()); proto.writeTo(out); } public byte[] getBytes() { ByteBuffer buf = ByteBuffer.allocate(getSerializedSize()); putInBuffer(buf); return buf.array(); } /** * Perform a sanity check on the packet, returning true if it is sane. * @param lastSeqNo the previous sequence number received - we expect the * current sequence number to be larger by 1. */ public boolean sanityCheck(long lastSeqNo) { // We should only have a non-positive data length for the last packet if (proto.getDataLen() <= 0 && !proto.getLastPacketInBlock()) return false; // The last packet should not contain data if (proto.getLastPacketInBlock() && proto.getDataLen() != 0) return false; // Seqnos should always increase by 1 with each packet received return proto.getSeqno() == lastSeqNo + 1; } @Override public boolean equals(Object o) { if (!(o instanceof PacketHeader)) return false; PacketHeader other = (PacketHeader)o; return this.proto.equals(other.proto); } @Override public int hashCode() { return (int)proto.getSeqno(); } }
PacketHeader
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1576/java8/Issue1576Mapper.java
{ "start": 280, "end": 420 }
interface ____ { Issue1576Mapper INSTANCE = Mappers.getMapper( Issue1576Mapper.class ); Target map( Source source ); }
Issue1576Mapper
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/lib/input/TestMultipleInputs.java
{ "start": 6876, "end": 7146 }
class ____ extends Mapper<Text, Text, Text, Text> { // receives "a", "b", "c" as keys @Override public void map(Text key, Text value, Context ctx) throws IOException, InterruptedException { ctx.write(key, blah); } } static
KeyValueMapClass
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/convert/value/ConvertibleMultiValues.java
{ "start": 1358, "end": 7585 }
interface ____<V> extends ConvertibleValues<List<V>> { /** * Get all the values for the given name without applying conversion. * * @param name The header name * @return All the values */ List<V> getAll(CharSequence name); /** * Get a value without applying any conversion. * * @param name The name of the value * @return The raw value or null * @see #getFirst(CharSequence) */ @Nullable V get(CharSequence name); /** * @return Whether these values are empty */ @Override default boolean isEmpty() { return this == ConvertibleMultiValuesMap.EMPTY || names().isEmpty(); } /** * Performs the given action for each header. Note that in the case * where multiple values exist for the same header then the consumer will be invoked * multiple times for the same key. * * @param action The action to be performed for each entry * @throws NullPointerException if the specified action is null * @since 1.0 */ default void forEachValue(BiConsumer<String, V> action) { Objects.requireNonNull(action, "Consumer cannot be null"); Collection<String> names = names(); for (String headerName : names) { Collection<V> values = getAll(headerName); for (V value : values) { action.accept(headerName, value); } } } @Override default void forEach(BiConsumer<String, List<V>> action) { Objects.requireNonNull(action, "Consumer cannot be null"); Collection<String> names = names(); for (String headerName : names) { List<V> values = getAll(headerName); action.accept(headerName, values); } } @Override default Iterator<Map.Entry<String, List<V>>> iterator() { Iterator<String> headerNames = names().iterator(); return new Iterator<>() { @Override public boolean hasNext() { return headerNames.hasNext(); } @Override public Map.Entry<String, List<V>> next() { if (!hasNext()) { throw new NoSuchElementException(); } String name = headerNames.next(); return new Map.Entry<>() { @Override public String getKey() { return name; } @Override public List<V> getValue() { return getAll(name); } @Override public List<V> setValue(List<V> value) { throw new UnsupportedOperationException("Not mutable"); } }; } }; } /** * Get the first value of the given header. * * @param name The header name * @return The first value or null if it is present */ default Optional<V> getFirst(CharSequence name) { Optional<Class<?>> type = GenericTypeUtils.resolveInterfaceTypeArgument(getClass(), ConvertibleMultiValues.class); return (Optional<V>) getFirst(name, type.orElse(Object.class)); } /** * Find a header and convert it to the given type. * * @param name The name of the header * @param requiredType The required type * @param <T> The generic type * @return If the header is presented and can be converted an optional of the value otherwise {@link Optional#empty()} */ default <T> Optional<T> getFirst(CharSequence name, Class<T> requiredType) { return getFirst(name, Argument.of(requiredType)); } /** * Find a header and convert it to the given type. * * @param name The name of the header * @param requiredType The required type * @param <T> The generic type * @return If the header is presented and can be converted an optional of the value otherwise {@link Optional#empty()} */ default <T> Optional<T> getFirst(CharSequence name, Argument<T> requiredType) { V v = get(name); if (v != null) { return ConversionService.SHARED.convert(v, ConversionContext.of(requiredType)); } return Optional.empty(); } /** * Find a header and convert it to the given type. * * @param name The name of the header * @param conversionContext The conversion context * @param <T> The generic type * @return If the header is presented and can be converted an optional of the value otherwise {@link Optional#empty()} */ default <T> Optional<T> getFirst(CharSequence name, ArgumentConversionContext<T> conversionContext) { V v = get(name); if (v != null) { return ConversionService.SHARED.convert(v, conversionContext); } return Optional.empty(); } /** * Find a header and convert it to the given type. * * @param name The name of the header * @param requiredType The required type * @param defaultValue The default value * @param <T> The generic type * @return The first value of the default supplied value if it is present */ default <T> T getFirst(CharSequence name, Class<T> requiredType, T defaultValue) { return getFirst(name, requiredType).orElse(defaultValue); } /** * Creates a new {@link io.micronaut.core.value.OptionalValues} for the given type and values. * * @param values A map of values * @param <T> The target generic type * @return The values */ static <T> ConvertibleMultiValues<T> of(Map<CharSequence, List<T>> values) { return new ConvertibleMultiValuesMap<>(values); } /** * An empty {@link ConvertibleValues}. * * @param <V> The generic type * @return The empty {@link ConvertibleValues} */ @SuppressWarnings("unchecked") static <V> ConvertibleMultiValues<V> empty() { return ConvertibleMultiValuesMap.EMPTY; } }
ConvertibleMultiValues
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/test/PosixPermissionsResetter.java
{ "start": 845, "end": 1674 }
class ____ implements AutoCloseable { private final PosixFileAttributeView attributeView; private final Set<PosixFilePermission> permissions; public PosixPermissionsResetter(Path path) throws IOException { attributeView = Files.getFileAttributeView(path, PosixFileAttributeView.class); Assert.assertNotNull(attributeView); permissions = attributeView.readAttributes().permissions(); } @Override public void close() throws IOException { attributeView.setPermissions(permissions); } public void setPermissions(Set<PosixFilePermission> newPermissions) throws IOException { attributeView.setPermissions(newPermissions); } public Set<PosixFilePermission> getCopyPermissions() { return EnumSet.copyOf(permissions); } }
PosixPermissionsResetter
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/bzip2/BZip2Constants.java
{ "start": 1047, "end": 1155 }
class ____ both the compress and decompress classes. Holds common arrays, * and static data. * <p> * This
for
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/operators/StreamTaskTimerITCase.java
{ "start": 2382, "end": 5816 }
class ____ { private StreamTaskTestHarness<?> testHarness; private ProcessingTimeService timeService; @BeforeEach void setup() throws Exception { testHarness = startTestHarness(); StreamTask<?, ?> task = testHarness.getTask(); timeService = task.getProcessingTimeServiceFactory() .createProcessingTimeService( task.getMailboxExecutorFactory() .createExecutor( testHarness.getStreamConfig().getChainIndex())); } @AfterEach void teardown() throws Exception { stopTestHarness(testHarness, 4000L); } @Test void testOpenCloseAndTimestamps() throws InterruptedException { // Wait for StreamTask#invoke spawn the timeService threads for the throughput calculation. while (StreamTask.TRIGGER_THREAD_GROUP.activeCount() != 1) { Thread.sleep(1); } // The timeout would happen if spawning the thread failed. } @Test void testErrorReporting() throws Exception { AtomicReference<Throwable> errorRef = new AtomicReference<>(); OneShotLatch latch = new OneShotLatch(); testHarness .getEnvironment() .setExternalExceptionHandler( ex -> { errorRef.set(ex); latch.trigger(); }); ProcessingTimeCallback callback = timestamp -> { throw new Exception("Exception in Timer"); }; timeService.registerTimer(System.currentTimeMillis(), callback); latch.await(); assertThat(errorRef.get()).isInstanceOf(Exception.class); } @Test void checkScheduledTimestamps() throws Exception { ValidatingProcessingTimeCallback.numInSequence = 0; long currentTimeMillis = System.currentTimeMillis(); ArrayList<ValidatingProcessingTimeCallback> timeCallbacks = new ArrayList<>(); /* It is not possible to test registering timer for currentTimeMillis or value slightly greater than currentTimeMillis because if the during registerTimer the internal currentTime is equal to this value then according to current logic the time will be increased for 1ms while `currentTimeMillis - 200` is always transform to 0, so it can lead to reordering. See comment in {@link ProcessingTimeServiceUtil#getRecordProcessingTimeDelay(long, long)}. */ timeCallbacks.add(new ValidatingProcessingTimeCallback(currentTimeMillis - 1, 0)); timeCallbacks.add(new ValidatingProcessingTimeCallback(currentTimeMillis - 200, 1)); timeCallbacks.add(new ValidatingProcessingTimeCallback(currentTimeMillis + 100, 2)); timeCallbacks.add(new ValidatingProcessingTimeCallback(currentTimeMillis + 200, 3)); for (ValidatingProcessingTimeCallback timeCallback : timeCallbacks) { timeService.registerTimer(timeCallback.expectedTimestamp, timeCallback); } for (ValidatingProcessingTimeCallback timeCallback : timeCallbacks) { timeCallback.assertExpectedValues(); } assertThat(ValidatingProcessingTimeCallback.numInSequence).isEqualTo(4); } private static
StreamTaskTimerITCase
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java
{ "start": 20081, "end": 20415 }
class ____ { @RequestMapping("/lat/{latitude}/long/{longitude}") void testLatLong(@PathVariable Double latitude, @PathVariable Double longitude, Writer writer) throws IOException { writer.write("latitude-" + latitude + "-longitude-" + longitude); } } @Controller @RequestMapping("hotels") public static
DoubleController
java
apache__camel
components/camel-aws/camel-aws2-s3/src/test/java/org/apache/camel/component/aws2/s3/integration/S3SimpleEncryptedUploadOperationIT.java
{ "start": 1416, "end": 3765 }
class ____ extends Aws2S3Base { @EndpointInject private ProducerTemplate template; @EndpointInject("mock:result") private MockEndpoint result; @EndpointInject("mock:resultGet") private MockEndpoint resultGet; @Test public void sendIn() throws Exception { result.expectedMessageCount(1); resultGet.expectedMessageCount(1); template.send("direct:putObject", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(AWS2S3Constants.KEY, "camel.txt"); exchange.getIn().setBody("Camel rocks!"); } }); template.request("direct:listObjects", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(AWS2S3Constants.BUCKET_NAME, name.get()); exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.listObjects); } }); Exchange c = template.request("direct:getObject", new Processor() { @Override public void process(Exchange exchange) { exchange.getIn().setHeader(AWS2S3Constants.KEY, "camel.txt"); exchange.getIn().setHeader(AWS2S3Constants.S3_OPERATION, AWS2S3Operations.getObject); } }); List<S3Object> resp = result.getExchanges().get(0).getMessage().getBody(List.class); assertEquals(1, resp.size()); assertEquals("camel.txt", resp.get(0).key()); assertEquals("Camel rocks!", c.getIn().getBody(String.class)); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() { String key = createKmsKey(); return new RouteBuilder() { @Override public void configure() { String awsEndpoint = "aws2-s3://" + name.get() + "?autoCreateBucket=true&useAwsKMS=true&awsKMSKeyId=" + key; from("direct:putObject").to(awsEndpoint); from("direct:listObjects").to(awsEndpoint).to("mock:result"); from("direct:getObject").to("aws2-s3://" + name.get() + "?autoCreateBucket=true").to("mock:resultGet"); } }; } }
S3SimpleEncryptedUploadOperationIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/CriteriaWithWhereClauseAndColumnDefinitionTest.java
{ "start": 2681, "end": 3518 }
class ____ { private int submissionid; private Task task; private Integer peerReviewParticipation; @ManyToOne @JoinColumn(name = "taskid", nullable = false) public Task getTask() { return task; } public void setTask(Task task) { this.task = task; } @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int getSubmissionid() { return submissionid; } public void setSubmissionid(int submissionid) { this.submissionid = submissionid; } @Column(columnDefinition = "TINYINT") public Integer getPeerReviewParticipation() { return peerReviewParticipation; } public void setPeerReviewParticipation(Integer peerReviewParticipation) { this.peerReviewParticipation = peerReviewParticipation; } } @Entity(name = "task") @Table(name = "TASK_TABLE") public static
Submission
java
apache__camel
components/camel-knative/camel-knative-http/src/test/java/org/apache/camel/component/knative/http/KnativeHttpsServer.java
{ "start": 1145, "end": 2920 }
class ____ extends KnativeHttpServer { public KnativeHttpsServer(CamelContext context) { super(context, "localhost", AvailablePortFinder.getNextAvailable(), "/", null); } public KnativeHttpsServer(CamelContext context, int port) { super(context, "localhost", port, "/", null); } public KnativeHttpsServer(CamelContext context, int port, Handler<RoutingContext> handler) { super(context, "localhost", port, "/", handler); } public KnativeHttpsServer(CamelContext context, Handler<RoutingContext> handler) { super(context, "localhost", AvailablePortFinder.getNextAvailable(), "/", handler); } public KnativeHttpsServer(CamelContext context, String host, int port, String path) { super(context, host, port, path, null); } public KnativeHttpsServer(CamelContext context, String host, String path) { super(context, host, AvailablePortFinder.getNextAvailable(), path, null); } public KnativeHttpsServer(CamelContext context, String host, String path, Handler<RoutingContext> handler) { super(context, host, AvailablePortFinder.getNextAvailable(), path, handler); } @Override protected HttpServerOptions getServerOptions() { return new HttpServerOptions() .setSsl(true) .setKeyCertOptions( new PemKeyCertOptions() .setKeyPath("keystore/server.pem") .setCertPath("keystore/server.crt")) .setTrustOptions( new JksOptions() .setPath("keystore/truststore.jks") .setPassword("secr3t") ); } }
KnativeHttpsServer
java
spring-projects__spring-boot
module/spring-boot-r2dbc/src/main/java/org/springframework/boot/r2dbc/autoconfigure/ConnectionFactoryConfigurations.java
{ "start": 6698, "end": 6723 }
class ____. */ static
path
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/JobProfile.java
{ "start": 1552, "end": 5354 }
class ____ implements Writable { static { // register a ctor WritableFactories.setFactory (JobProfile.class, new WritableFactory() { public Writable newInstance() { return new JobProfile(); } }); } String user; final JobID jobid; String jobFile; String url; String name; String queueName; /** * Construct an empty {@link JobProfile}. */ public JobProfile() { jobid = new JobID(); } /** * Construct a {@link JobProfile} the userid, jobid, * job config-file, job-details url and job name. * * @param user userid of the person who submitted the job. * @param jobid id of the job. * @param jobFile job configuration file. * @param url link to the web-ui for details of the job. * @param name user-specified job name. */ public JobProfile(String user, org.apache.hadoop.mapreduce.JobID jobid, String jobFile, String url, String name) { this(user, jobid, jobFile, url, name, JobConf.DEFAULT_QUEUE_NAME); } /** * Construct a {@link JobProfile} the userid, jobid, * job config-file, job-details url and job name. * * @param user userid of the person who submitted the job. * @param jobid id of the job. * @param jobFile job configuration file. * @param url link to the web-ui for details of the job. * @param name user-specified job name. * @param queueName name of the queue to which the job is submitted */ public JobProfile(String user, org.apache.hadoop.mapreduce.JobID jobid, String jobFile, String url, String name, String queueName) { this.user = user; this.jobid = JobID.downgrade(jobid); this.jobFile = jobFile; this.url = url; this.name = name; this.queueName = queueName; } /** * @deprecated use JobProfile(String, JobID, String, String, String) instead */ @Deprecated public JobProfile(String user, String jobid, String jobFile, String url, String name) { this(user, JobID.forName(jobid), jobFile, url, name); } /** * Get the user id. */ public String getUser() { return user; } /** * Get the job id. */ public JobID getJobID() { return jobid; } /** * @deprecated use getJobID() instead */ @Deprecated public String getJobId() { return jobid.toString(); } /** * Get the configuration file for the job. */ public String getJobFile() { return jobFile; } /** * Get the link to the web-ui for details of the job. */ public URL getURL() { try { return new URL(url); } catch (IOException ie) { return null; } } /** * Get the user-specified job name. */ public String getJobName() { return name; } /** * Get the name of the queue to which the job is submitted. * @return name of the queue. */ public String getQueueName() { return queueName; } /////////////////////////////////////// // Writable /////////////////////////////////////// public void write(DataOutput out) throws IOException { jobid.write(out); Text.writeString(out, jobFile); Text.writeString(out, url); Text.writeString(out, user); Text.writeString(out, name); Text.writeString(out, queueName); } public void readFields(DataInput in) throws IOException { jobid.readFields(in); this.jobFile = StringInterner.weakIntern(Text.readString(in)); this.url = StringInterner.weakIntern(Text.readString(in)); this.user = StringInterner.weakIntern(Text.readString(in)); this.name = StringInterner.weakIntern(Text.readString(in)); this.queueName = StringInterner.weakIntern(Text.readString(in)); } }
JobProfile
java
spring-projects__spring-boot
module/spring-boot-r2dbc/src/main/java/org/springframework/boot/r2dbc/testcontainers/OracleFreeR2dbcContainerConnectionDetailsFactory.java
{ "start": 1410, "end": 1987 }
class ____ extends ContainerConnectionDetailsFactory<OracleContainer, R2dbcConnectionDetails> { OracleFreeR2dbcContainerConnectionDetailsFactory() { super(ANY_CONNECTION_NAME, "io.r2dbc.spi.ConnectionFactoryOptions"); } @Override public R2dbcConnectionDetails getContainerConnectionDetails(ContainerConnectionSource<OracleContainer> source) { return new R2dbcDatabaseContainerConnectionDetails(source); } /** * {@link R2dbcConnectionDetails} backed by a {@link ContainerConnectionSource}. */ private static final
OracleFreeR2dbcContainerConnectionDetailsFactory