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__kafka
streams/src/test/java/org/apache/kafka/streams/kstream/internals/KTableKTableRightJoinTest.java
{ "start": 1609, "end": 3191 }
class ____ { private final Properties props = StreamsTestUtils.getStreamsConfig(Serdes.String(), Serdes.String()); @Test public void shouldLogAndMeterSkippedRecordsDueToNullLeftKeyWithBuiltInMetricsVersionLatest() { final StreamsBuilder builder = new StreamsBuilder(); @SuppressWarnings("unchecked") final Processor<String, Change<String>, String, Change<Object>> join = new KTableKTableRightJoin<>( (KTableImpl<String, String, String>) builder.table("left", Consumed.with(Serdes.String(), Serdes.String())), (KTableImpl<String, String, String>) builder.table("right", Consumed.with(Serdes.String(), Serdes.String())), null ).get(); props.setProperty(StreamsConfig.BUILT_IN_METRICS_VERSION_CONFIG, StreamsConfig.METRICS_LATEST); final MockProcessorContext<String, Change<Object>> context = new MockProcessorContext<>(props); context.setRecordMetadata("left", -1, -2); join.init(context); try (final LogCaptureAppender appender = LogCaptureAppender.createAndRegister(KTableKTableRightJoin.class)) { join.process(new Record<>(null, new Change<>("new", "old"), 0)); assertThat( appender.getEvents().stream() .filter(e -> e.getLevel().equals("WARN")) .map(Event::getMessage) .collect(Collectors.toList()), hasItem("Skipping record due to null key. topic=[left] partition=[-1] offset=[-2]") ); } } }
KTableKTableRightJoinTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/support/DirtiesContextTestExecutionListenerTests.java
{ "start": 16914, "end": 17057 }
class ____ { void test() { } } @DirtiesContext(classMode = BEFORE_CLASS) static
DirtiesContextDeclaredViaMetaAnnotationAfterEachTestMethod
java
google__guava
guava/src/com/google/common/collect/EnumMultiset.java
{ "start": 6851, "end": 8851 }
class ____<T> implements Iterator<T> { int index = 0; int toRemove = -1; abstract T output(int index); @Override public boolean hasNext() { for (; index < enumConstants.length; index++) { if (counts[index] > 0) { return true; } } return false; } @Override public T next() { if (!hasNext()) { throw new NoSuchElementException(); } T result = output(index); toRemove = index; index++; return result; } @Override public void remove() { checkRemove(toRemove >= 0); if (counts[toRemove] > 0) { distinctElements--; size -= counts[toRemove]; counts[toRemove] = 0; } toRemove = -1; } } @Override Iterator<E> elementIterator() { return new Itr<E>() { @Override E output(int index) { return enumConstants[index]; } }; } @Override Iterator<Entry<E>> entryIterator() { return new Itr<Entry<E>>() { @Override Entry<E> output(int index) { return new Multisets.AbstractEntry<E>() { @Override public E getElement() { return enumConstants[index]; } @Override public int getCount() { return counts[index]; } }; } }; } @Override public void forEachEntry(ObjIntConsumer<? super E> action) { checkNotNull(action); for (int i = 0; i < enumConstants.length; i++) { if (counts[i] > 0) { action.accept(enumConstants[i], counts[i]); } } } @Override public Iterator<E> iterator() { return Multisets.iteratorImpl(this); } @GwtIncompatible // java.io.ObjectOutputStream private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(type); Serialization.writeMultiset(this, stream); } /** * @serialData the {@code Class<E>} for the
Itr
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/policies/exceptions/FederationPolicyInitializationException.java
{ "start": 983, "end": 1245 }
class ____ extends FederationPolicyException { public FederationPolicyInitializationException(String message) { super(message); } public FederationPolicyInitializationException(Throwable j) { super(j); } }
FederationPolicyInitializationException
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/ExecEdge.java
{ "start": 6788, "end": 7455 }
enum ____ { /** Any type of shuffle is OK when passing through this edge. */ ANY, /** Records are shuffled by hash when passing through this edge. */ HASH, /** Full records are provided for each parallelism of the target node. */ BROADCAST, /** Records are shuffled to one node, the parallelism of the target node must be 1. */ SINGLETON, /** Records are shuffled in same parallelism (the shuffle behavior is function call). */ FORWARD } } /** Records are shuffled by hash when passing through this edge. */ public static
Type
java
apache__camel
components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpUtils.java
{ "start": 1129, "end": 6697 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(FtpUtils.class); private FtpUtils() { } public static String extractDirNameFromAbsolutePath(String path) { // default is unix so try with '/' // otherwise force File.separator if (path.endsWith("/") || path.endsWith("\\")) { path = path.substring(0, path.length() - 1); } return FileUtil.stripPath(path); } /** * Compacts a path by stacking it and reducing <tt>..</tt>, and uses OS specific file separators (eg * {@link java.io.File#separator}). * <p/> * <b>Important: </b> This implementation works for the camel-ftp component for various FTP clients and FTP servers * using different platforms and whatnot. This implementation has been working for many Camel releases, and is * included here to restore patch compatibility with the Camel releases. */ public static String compactPath(String path) { if (path == null) { return null; } // only normalize if contains a path separator if (path.indexOf(File.separator) == -1) { return path; } // preserve ending slash if given in input path boolean endsWithSlash = path.endsWith("/") || path.endsWith("\\"); // preserve starting slash if given in input path boolean startsWithSlash = path.startsWith("/") || path.startsWith("\\"); Deque<String> stack = new ArrayDeque<>(); String separatorRegex = File.separator; if (FileUtil.isWindows()) { separatorRegex = "\\\\"; } String[] parts = path.split(separatorRegex); for (String part : parts) { if (part.equals("..") && !stack.isEmpty() && !"..".equals(stack.peek())) { // only pop if there is a previous path, which is not a ".." // path either stack.pop(); } else if (part.equals(".") || part.isEmpty()) { // do nothing because we don't want a path like foo/./bar or // foo//bar } else { stack.push(part); } } // build path based on stack StringBuilder sb = new StringBuilder(256); if (startsWithSlash) { sb.append(File.separator); } // now we build back using FIFO so need to use descending for (Iterator<String> it = stack.descendingIterator(); it.hasNext();) { sb.append(it.next()); if (it.hasNext()) { sb.append(File.separator); } } if (endsWithSlash && !stack.isEmpty()) { sb.append(File.separator); } // there has been problems with double slashes, // so avoid this by removing any 2nd slash if (sb.length() >= 2) { boolean firstSlash = sb.charAt(0) == '/' || sb.charAt(0) == '\\'; boolean secondSlash = sb.charAt(1) == '/' || sb.charAt(1) == '\\'; if (firstSlash && secondSlash) { // remove 2nd clash sb = sb.replace(1, 2, ""); } } return sb.toString(); } /** * Checks whether directory used in ftp/ftps/sftp endpoint URI is relative. Absolute path will be converted to * relative path and a WARN will be printed. * * @see <a href="http://camel.apache.org/ftp2.html">FTP/SFTP/FTPS Component</a> */ public static void ensureRelativeFtpDirectory(Component ftpComponent, RemoteFileConfiguration configuration) { if (FileUtil.hasLeadingSeparator(configuration.getDirectoryName())) { String relativePath = FileUtil.stripLeadingSeparator(configuration.getDirectoryName()); LOG.warn("{} doesn't support absolute paths, \"{}\" will be converted to \"{}\". " + "After Camel 2.16, absolute paths will be invalid.", ftpComponent.getClass().getSimpleName(), configuration.getDirectoryName(), relativePath); configuration.setDirectory(relativePath); configuration.setDirectoryName(relativePath); } } public static String absoluteFilePath(FtpConfiguration configuration, String absolutePath, String name) { boolean absolute = FileUtil.hasLeadingSeparator(absolutePath); // create a pseudo absolute name String dir = FileUtil.stripTrailingSeparator(absolutePath); String fileName = name; if (configuration.isHandleDirectoryParserAbsoluteResult()) { fileName = FtpUtils.extractDirNameFromAbsolutePath(name); } String absoluteFileName = FileUtil.stripLeadingSeparator(dir + "/" + fileName); // if absolute start with a leading separator otherwise let it be // relative if (absolute) { absoluteFileName = "/" + absoluteFileName; } return absoluteFileName; } public static String absoluteFilePath(String absolutePath, String name) { boolean absolute = FileUtil.hasLeadingSeparator(absolutePath); // create a pseudo absolute name String dir = FileUtil.stripTrailingSeparator(absolutePath); String absoluteFileName = FileUtil.stripLeadingSeparator(dir + "/" + name); // if absolute start with a leading separator otherwise let it be // relative if (absolute) { absoluteFileName = "/" + absoluteFileName; } return absoluteFileName; } }
FtpUtils
java
elastic__elasticsearch
x-pack/plugin/transform/qa/single-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/transform/integration/TransformDestIndexIT.java
{ "start": 1092, "end": 15664 }
class ____ extends TransformRestTestCase { private static boolean indicesCreated = false; // preserve indices in order to reuse source indices in several test cases @Override protected boolean preserveIndicesUponCompletion() { return true; } @Before public void createIndexes() throws IOException { // it's not possible to run it as @BeforeClass as clients aren't initialized then, so we need this little hack if (indicesCreated) { return; } createReviewsIndex(); indicesCreated = true; } public void testTransformDestIndexMetadata() throws Exception { long testStarted = System.currentTimeMillis(); String transformId = "test_meta"; createPivotReviewsTransform(transformId, "pivot_reviews", null); startAndWaitForTransform(transformId, "pivot_reviews"); Response mappingResponse = client().performRequest(new Request("GET", "pivot_reviews/_mapping")); Map<?, ?> mappingAsMap = entityAsMap(mappingResponse); assertEquals( TransformConfigVersion.CURRENT.toString(), XContentMapValues.extractValue("pivot_reviews.mappings._meta._transform.version.created", mappingAsMap) ); assertTrue( (Long) XContentMapValues.extractValue("pivot_reviews.mappings._meta._transform.creation_date_in_millis", mappingAsMap) < System .currentTimeMillis() ); assertTrue( (Long) XContentMapValues.extractValue( "pivot_reviews.mappings._meta._transform.creation_date_in_millis", mappingAsMap ) > testStarted ); assertEquals(transformId, XContentMapValues.extractValue("pivot_reviews.mappings._meta._transform.transform", mappingAsMap)); assertEquals("transform", XContentMapValues.extractValue("pivot_reviews.mappings._meta.created_by", mappingAsMap)); Response aliasesResponse = client().performRequest(new Request("GET", "pivot_reviews/_alias")); Map<?, ?> aliasesAsMap = entityAsMap(aliasesResponse); assertEquals(Map.of(), XContentMapValues.extractValue("pivot_reviews.aliases", aliasesAsMap)); } public void testTransformDestIndexAliases() throws Exception { String transformId = "test_aliases"; String destIndex1 = transformId + ".1"; String destIndex2 = transformId + ".2"; String destAliasAll = transformId + ".all"; String destAliasLatest = transformId + ".latest"; List<DestAlias> destAliases = List.of(new DestAlias(destAliasAll, false), new DestAlias(destAliasLatest, true)); // Create the transform createPivotReviewsTransform(transformId, destIndex1, null, null, destAliases, null, null, null, REVIEWS_INDEX_NAME); startAndWaitForTransform(transformId, destIndex1); // Verify that both aliases are configured on the dest index assertAliases(destIndex1, destAliasAll, destAliasLatest); // Verify that the search results are the same, regardless whether we use index or alias assertHitsAreTheSame(destIndex1, destAliasAll, destAliasLatest); // Stop the transform so that the transform task is properly removed before calling DELETE. // TODO: Remove this step once the underlying issue (race condition is fixed). stopTransform(transformId, false); // Delete the transform deleteTransform(transformId); assertAliases(destIndex1, destAliasAll, destAliasLatest); // Create the transform again (this time with a different destination index) createPivotReviewsTransform(transformId, destIndex2, null, null, destAliases, null, null, null, REVIEWS_INDEX_NAME); startAndWaitForTransform(transformId, destIndex2); // Verify that destAliasLatest no longer points at destIndex1 but it now points at destIndex2 assertAliases(destIndex1, destAliasAll); assertAliases(destIndex2, destAliasAll, destAliasLatest); } public void testUnattendedTransformDestIndexCreatedDuringUpdate_NoDeferValidation() throws Exception { testUnattendedTransformDestIndexCreatedDuringUpdate(false); } public void testUnattendedTransformDestIndexCreatedDuringUpdate_DeferValidation() throws Exception { testUnattendedTransformDestIndexCreatedDuringUpdate(true); } private void testUnattendedTransformDestIndexCreatedDuringUpdate(boolean deferValidation) throws Exception { String transformId = "test_dest_index_on_update" + (deferValidation ? "-defer" : ""); String destIndex = transformId + "-dest"; String destAliasAll = transformId + ".all"; String destAliasLatest = transformId + ".latest"; List<DestAlias> destAliases = List.of(new DestAlias(destAliasAll, false), new DestAlias(destAliasLatest, true)); // Create and start the unattended transform SettingsConfig settingsConfig = new SettingsConfig.Builder().setUnattended(true).build(); createPivotReviewsTransform(transformId, destIndex, null, null, destAliases, settingsConfig, null, null, REVIEWS_INDEX_NAME); assertFalse(indexExists(destIndex)); startTransform(transformId); // Update the unattended transform. This will trigger destination index creation. // The update has to change something in the config (here, max_page_search_size). Otherwise it would have been optimized away. // Note that at this point the destination index could have already been created by the indexing process of the running transform // but the update code should cope with this situation. updateTransform(transformId, """ { "settings": { "max_page_search_size": 123 } }""", deferValidation); // Verify that the destination index now exists assertTrue(indexExists(destIndex)); // Verify that both aliases are configured on the dest index assertAliases(destIndex, destAliasAll, destAliasLatest); } public void testUnattendedTransformDestIndexCreatedDuringUpdate_EmptySourceIndex_NoDeferValidation() throws Exception { testUnattendedTransformDestIndexCreatedDuringUpdate_EmptySourceIndex(false); } public void testUnattendedTransformDestIndexCreatedDuringUpdate_EmptySourceIndex_DeferValidation() throws Exception { testUnattendedTransformDestIndexCreatedDuringUpdate_EmptySourceIndex(true); } private void testUnattendedTransformDestIndexCreatedDuringUpdate_EmptySourceIndex(boolean deferValidation) throws Exception { String transformId = "test_dest_index_on_update-empty" + (deferValidation ? "-defer" : ""); String sourceIndexIndex = transformId + "-src"; String destIndex = transformId + "-dest"; String destAliasAll = transformId + ".all"; String destAliasLatest = transformId + ".latest"; List<DestAlias> destAliases = List.of(new DestAlias(destAliasAll, false), new DestAlias(destAliasLatest, true)); // We want to use an empty source index to make sure transform will not write to the destination index putReviewsIndex(sourceIndexIndex, "date", false); assertFalse(indexExists(destIndex)); // Create and start the unattended transform SettingsConfig settingsConfig = new SettingsConfig.Builder().setUnattended(true).build(); createPivotReviewsTransform(transformId, destIndex, null, null, destAliases, settingsConfig, null, null, sourceIndexIndex); startTransform(transformId); // Verify that the destination index creation got skipped assertFalse(indexExists(destIndex)); // Update the unattended transform. This will trigger destination index creation. // The update has to change something in the config (here, max_page_search_size). Otherwise it would have been optimized away. updateTransform(transformId, """ { "settings": { "max_page_search_size": 123 } }""", deferValidation); // Verify that the destination index now exists assertTrue(indexExists(destIndex)); // Verify that both aliases are configured on the dest index assertAliases(destIndex, destAliasAll, destAliasLatest); } public void testUnattendedTransformDestIndexCreatedByIndexer() throws Exception { String transformId = "test_dest_index_in_indexer"; String destIndex = transformId + "-dest"; String destAliasAll = transformId + ".all"; String destAliasLatest = transformId + ".latest"; List<DestAlias> destAliases = List.of(new DestAlias(destAliasAll, false), new DestAlias(destAliasLatest, true)); // Create and start the unattended transform SettingsConfig settingsConfig = new SettingsConfig.Builder().setUnattended(true).build(); createPivotReviewsTransform(transformId, destIndex, null, null, destAliases, settingsConfig, null, null, REVIEWS_INDEX_NAME); startTransform(transformId); waitForTransformCheckpoint(transformId, 1); // Verify that the destination index exists assertTrue(indexExists(destIndex)); // Verify that both aliases are configured on the dest index assertAliases(destIndex, destAliasAll, destAliasLatest); } public void testTransformDestIndexMappings_DeduceMappings() throws Exception { testTransformDestIndexMappings("test_dest_index_mappings_deduce", true); } public void testTransformDestIndexMappings_NoDeduceMappings() throws Exception { testTransformDestIndexMappings("test_dest_index_mappings_no_deduce", false); } private void testTransformDestIndexMappings(String transformId, boolean deduceMappings) throws Exception { String destIndex = transformId + "-dest"; { String destIndexTemplate = Strings.format(""" { "index_patterns": [ "%s*" ], "mappings": { "properties": { "timestamp": { "type": "date" }, "reviewer": { "type": "keyword" }, "avg_rating": { "type": "double" } } } }""", destIndex); Request createIndexTemplateRequest = new Request("PUT", "_template/test_dest_index_mappings_template"); createIndexTemplateRequest.setJsonEntity(destIndexTemplate); createIndexTemplateRequest.setOptions(expectWarnings(RestPutIndexTemplateAction.DEPRECATION_WARNING)); Map<String, Object> createIndexTemplateResponse = entityAsMap(client().performRequest(createIndexTemplateRequest)); assertThat(createIndexTemplateResponse.get("acknowledged"), equalTo(Boolean.TRUE)); } // Verify that the destination index does not exist yet, even though the template already exists assertFalse(indexExists(destIndex)); { String config = Strings.format(""" { "dest": { "index": "%s" }, "source": { "index": "%s" }, "sync": { "time": { "field": "timestamp", "delay": "15m" } }, "frequency": "1s", "pivot": { "group_by": { "timestamp": { "date_histogram": { "field": "timestamp", "fixed_interval": "10s" } }, "reviewer": { "terms": { "field": "user_id" } } }, "aggregations": { "avg_rating": { "avg": { "field": "stars" } } } }, "settings": { "unattended": true, "deduce_mappings": %s } }""", destIndex, REVIEWS_INDEX_NAME, deduceMappings); createReviewsTransform(transformId, null, null, config); startTransform(transformId); waitForTransformCheckpoint(transformId, 1); } // Verify that the destination index now exists and has correct mappings from the template assertTrue(indexExists(destIndex)); assertThat( getIndexMappingAsMap(destIndex), hasEntry( "properties", Map.of("avg_rating", Map.of("type", "double"), "reviewer", Map.of("type", "keyword"), "timestamp", Map.of("type", "date")) ) ); Map<String, Object> searchResult = getAsMap(destIndex + "/_search?q=reviewer:user_0"); String timestamp = (String) ((List<?>) XContentMapValues.extractValue("hits.hits._source.timestamp", searchResult)).get(0); assertThat(timestamp, is(equalTo("2017-01-10T10:10:10.000Z"))); } private static void assertAliases(String index, String... aliases) throws IOException { Map<String, Map<?, ?>> expectedAliases = Arrays.stream(aliases).collect(Collectors.toMap(a -> a, a -> Map.of())); Response aliasesResponse = client().performRequest(new Request("GET", index + "/_alias")); assertEquals(expectedAliases, XContentMapValues.extractValue(index + ".aliases", entityAsMap(aliasesResponse))); } private static void assertHitsAreTheSame(String index, String... aliases) throws IOException { Response indexSearchResponse = client().performRequest(new Request("GET", index + "/_search")); Object indexSearchHits = XContentMapValues.extractValue("hits", entityAsMap(indexSearchResponse)); for (String alias : aliases) { Response aliasSearchResponse = client().performRequest(new Request("GET", alias + "/_search")); Object aliasSearchHits = XContentMapValues.extractValue("hits", entityAsMap(aliasSearchResponse)); assertEquals("index = " + index + ", alias = " + alias, indexSearchHits, aliasSearchHits); } } }
TransformDestIndexIT
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/streaming/runtime/SideOutputITCase.java
{ "start": 5777, "end": 41205 }
class ____ extends AbstractStreamOperator<String> implements OneInputStreamOperator<String, String> { private static final long serialVersionUID = 1L; @Override public void processElement(StreamRecord<String> element) throws Exception { output.collect(new StreamRecord<>("E:" + element.getValue())); } @Override public void processWatermark(Watermark mark) throws Exception { super.processWatermark(mark); output.collect(new StreamRecord<>("WM:" + mark.getTimestamp())); } } passThroughtStream .getSideOutput(sideOutputTag1) .transform( "ReifyWatermarks", BasicTypeInfo.STRING_TYPE_INFO, new WatermarkReifier()) .addSink(sideOutputResultSink1); passThroughtStream .getSideOutput(sideOutputTag2) .transform( "ReifyWatermarks", BasicTypeInfo.STRING_TYPE_INFO, new WatermarkReifier()) .addSink(sideOutputResultSink2); passThroughtStream .map( new MapFunction<Integer, String>() { private static final long serialVersionUID = 1L; @Override public String map(Integer value) throws Exception { return value.toString(); } }) .transform( "ReifyWatermarks", BasicTypeInfo.STRING_TYPE_INFO, new WatermarkReifier()) .addSink(resultSink); env.execute(); assertEquals( Arrays.asList( "E:sideout-1", "E:sideout-2", "E:sideout-3", "E:sideout-4", "E:sideout-5", "WM:0", "WM:0", "WM:0", "WM:2", "WM:2", "WM:2", "WM:" + Long.MAX_VALUE, "WM:" + Long.MAX_VALUE, "WM:" + Long.MAX_VALUE), sideOutputResultSink1.getSortedResult()); assertEquals( Arrays.asList( "E:sideout-1", "E:sideout-2", "E:sideout-3", "E:sideout-4", "E:sideout-5", "WM:0", "WM:0", "WM:0", "WM:2", "WM:2", "WM:2", "WM:" + Long.MAX_VALUE, "WM:" + Long.MAX_VALUE, "WM:" + Long.MAX_VALUE), sideOutputResultSink1.getSortedResult()); assertEquals( Arrays.asList( "E:1", "E:2", "E:3", "E:4", "E:5", "WM:0", "WM:0", "WM:0", "WM:2", "WM:2", "WM:2", "WM:" + Long.MAX_VALUE, "WM:" + Long.MAX_VALUE, "WM:" + Long.MAX_VALUE), resultSink.getSortedResult()); } @Test public void testSideOutputWithMultipleConsumers() throws Exception { final OutputTag<String> sideOutputTag = new OutputTag<String>("side") {}; TestListResultSink<String> sideOutputResultSink1 = new TestListResultSink<>(); TestListResultSink<String> sideOutputResultSink2 = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setParallelism(3); DataStream<Integer> dataStream = env.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = dataStream.process( new ProcessFunction<Integer, Integer>() { private static final long serialVersionUID = 1L; @Override public void processElement( Integer value, Context ctx, Collector<Integer> out) throws Exception { out.collect(value); ctx.output(sideOutputTag, "sideout-" + String.valueOf(value)); } }); passThroughtStream.getSideOutput(sideOutputTag).addSink(sideOutputResultSink1); passThroughtStream.getSideOutput(sideOutputTag).addSink(sideOutputResultSink2); passThroughtStream.addSink(resultSink); env.execute(); assertEquals( Arrays.asList("sideout-1", "sideout-2", "sideout-3", "sideout-4", "sideout-5"), sideOutputResultSink1.getSortedResult()); assertEquals( Arrays.asList("sideout-1", "sideout-2", "sideout-3", "sideout-4", "sideout-5"), sideOutputResultSink2.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } @Test public void testSideOutputWithMultipleConsumersWithObjectReuse() throws Exception { final OutputTag<String> sideOutputTag = new OutputTag<String>("side") {}; TestListResultSink<String> sideOutputResultSink1 = new TestListResultSink<>(); TestListResultSink<String> sideOutputResultSink2 = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.getConfig().enableObjectReuse(); env.setParallelism(3); DataStream<Integer> dataStream = env.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = dataStream.process( new ProcessFunction<Integer, Integer>() { private static final long serialVersionUID = 1L; @Override public void processElement( Integer value, Context ctx, Collector<Integer> out) throws Exception { out.collect(value); ctx.output(sideOutputTag, "sideout-" + String.valueOf(value)); } }); passThroughtStream.getSideOutput(sideOutputTag).addSink(sideOutputResultSink1); passThroughtStream.getSideOutput(sideOutputTag).addSink(sideOutputResultSink2); passThroughtStream.addSink(resultSink); env.execute(); assertEquals( Arrays.asList("sideout-1", "sideout-2", "sideout-3", "sideout-4", "sideout-5"), sideOutputResultSink1.getSortedResult()); assertEquals( Arrays.asList("sideout-1", "sideout-2", "sideout-3", "sideout-4", "sideout-5"), sideOutputResultSink2.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } @Test public void testDifferentSideOutputTypes() throws Exception { final OutputTag<String> sideOutputTag1 = new OutputTag<String>("string") {}; final OutputTag<Integer> sideOutputTag2 = new OutputTag<Integer>("int") {}; TestListResultSink<String> sideOutputResultSink1 = new TestListResultSink<>(); TestListResultSink<Integer> sideOutputResultSink2 = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.getConfig().enableObjectReuse(); env.setParallelism(3); DataStream<Integer> dataStream = env.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = dataStream.process( new ProcessFunction<Integer, Integer>() { private static final long serialVersionUID = 1L; @Override public void processElement( Integer value, Context ctx, Collector<Integer> out) throws Exception { out.collect(value); ctx.output(sideOutputTag1, "sideout-" + String.valueOf(value)); ctx.output(sideOutputTag2, 13); } }); passThroughtStream.getSideOutput(sideOutputTag1).addSink(sideOutputResultSink1); passThroughtStream.getSideOutput(sideOutputTag2).addSink(sideOutputResultSink2); passThroughtStream.addSink(resultSink); env.execute(); assertEquals( Arrays.asList("sideout-1", "sideout-2", "sideout-3", "sideout-4", "sideout-5"), sideOutputResultSink1.getSortedResult()); assertEquals(Arrays.asList(13, 13, 13, 13, 13), sideOutputResultSink2.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } @Test public void testSideOutputNameClash() throws Exception { final OutputTag<String> sideOutputTag1 = new OutputTag<String>("side") {}; final OutputTag<Integer> sideOutputTag2 = new OutputTag<Integer>("side") {}; TestListResultSink<String> sideOutputResultSink1 = new TestListResultSink<>(); TestListResultSink<Integer> sideOutputResultSink2 = new TestListResultSink<>(); StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); see.setParallelism(3); DataStream<Integer> dataStream = see.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = dataStream.process( new ProcessFunction<Integer, Integer>() { private static final long serialVersionUID = 1L; @Override public void processElement( Integer value, Context ctx, Collector<Integer> out) throws Exception { out.collect(value); ctx.output(sideOutputTag1, "sideout-" + String.valueOf(value)); ctx.output(sideOutputTag2, 13); } }); passThroughtStream.getSideOutput(sideOutputTag1).addSink(sideOutputResultSink1); expectedException.expect(UnsupportedOperationException.class); passThroughtStream.getSideOutput(sideOutputTag2).addSink(sideOutputResultSink2); } /** Test ProcessFunction side output. */ @Test public void testProcessFunctionSideOutput() throws Exception { final OutputTag<String> sideOutputTag = new OutputTag<String>("side") {}; TestListResultSink<String> sideOutputResultSink = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); see.setParallelism(3); DataStream<Integer> dataStream = see.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = dataStream.process( new ProcessFunction<Integer, Integer>() { private static final long serialVersionUID = 1L; @Override public void processElement( Integer value, Context ctx, Collector<Integer> out) throws Exception { out.collect(value); ctx.output(sideOutputTag, "sideout-" + String.valueOf(value)); } }); passThroughtStream.getSideOutput(sideOutputTag).addSink(sideOutputResultSink); passThroughtStream.addSink(resultSink); see.execute(); assertEquals( Arrays.asList("sideout-1", "sideout-2", "sideout-3", "sideout-4", "sideout-5"), sideOutputResultSink.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } /** Test CoProcessFunction side output. */ @Test public void testCoProcessFunctionSideOutput() throws Exception { final OutputTag<String> sideOutputTag = new OutputTag<String>("side") {}; TestListResultSink<String> sideOutputResultSink = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); see.setParallelism(3); DataStream<Integer> ds1 = see.fromData(elements); DataStream<Integer> ds2 = see.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = ds1.connect(ds2) .process( new CoProcessFunction<Integer, Integer, Integer>() { @Override public void processElement1( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value < 3) { out.collect(value); ctx.output( sideOutputTag, "sideout1-" + String.valueOf(value)); } } @Override public void processElement2( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value >= 3) { out.collect(value); ctx.output( sideOutputTag, "sideout2-" + String.valueOf(value)); } } }); passThroughtStream.getSideOutput(sideOutputTag).addSink(sideOutputResultSink); passThroughtStream.addSink(resultSink); see.execute(); assertEquals( Arrays.asList("sideout1-1", "sideout1-2", "sideout2-3", "sideout2-4", "sideout2-5"), sideOutputResultSink.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } /** Test CoProcessFunction side output with multiple consumers. */ @Test public void testCoProcessFunctionSideOutputWithMultipleConsumers() throws Exception { final OutputTag<String> sideOutputTag1 = new OutputTag<String>("side1") {}; final OutputTag<String> sideOutputTag2 = new OutputTag<String>("side2") {}; TestListResultSink<String> sideOutputResultSink1 = new TestListResultSink<>(); TestListResultSink<String> sideOutputResultSink2 = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); see.setParallelism(3); DataStream<Integer> ds1 = see.fromData(elements); DataStream<Integer> ds2 = see.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = ds1.connect(ds2) .process( new CoProcessFunction<Integer, Integer, Integer>() { @Override public void processElement1( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value < 4) { out.collect(value); ctx.output( sideOutputTag1, "sideout1-" + String.valueOf(value)); } } @Override public void processElement2( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value >= 4) { out.collect(value); ctx.output( sideOutputTag2, "sideout2-" + String.valueOf(value)); } } }); passThroughtStream.getSideOutput(sideOutputTag1).addSink(sideOutputResultSink1); passThroughtStream.getSideOutput(sideOutputTag2).addSink(sideOutputResultSink2); passThroughtStream.addSink(resultSink); see.execute(); assertEquals( Arrays.asList("sideout1-1", "sideout1-2", "sideout1-3"), sideOutputResultSink1.getSortedResult()); assertEquals( Arrays.asList("sideout2-4", "sideout2-5"), sideOutputResultSink2.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } /** Test keyed ProcessFunction side output. */ @Test public void testKeyedProcessFunctionSideOutput() throws Exception { final OutputTag<String> sideOutputTag = new OutputTag<String>("side") {}; TestListResultSink<String> sideOutputResultSink = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); see.setParallelism(3); DataStream<Integer> dataStream = see.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = dataStream .keyBy( new KeySelector<Integer, Integer>() { private static final long serialVersionUID = 1L; @Override public Integer getKey(Integer value) throws Exception { return value; } }) .process( new KeyedProcessFunction<Integer, Integer, Integer>() { @Override public void processElement( Integer value, KeyedProcessFunction<Integer, Integer, Integer>.Context ctx, Collector<Integer> out) { out.collect(value); ctx.output( sideOutputTag, "sideout-" + String.valueOf(value)); } }); passThroughtStream.getSideOutput(sideOutputTag).addSink(sideOutputResultSink); passThroughtStream.addSink(resultSink); see.execute(); assertEquals( Arrays.asList("sideout-1", "sideout-2", "sideout-3", "sideout-4", "sideout-5"), sideOutputResultSink.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } /** Test keyed CoProcessFunction side output. */ @Test public void testLegacyKeyedCoProcessFunctionSideOutput() throws Exception { final OutputTag<String> sideOutputTag = new OutputTag<String>("side") {}; TestListResultSink<String> sideOutputResultSink = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); see.setParallelism(3); DataStream<Integer> ds1 = see.fromData(elements); DataStream<Integer> ds2 = see.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = ds1.keyBy(i -> i) .connect(ds2.keyBy(i -> i)) .process( new CoProcessFunction<Integer, Integer, Integer>() { @Override public void processElement1( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value < 3) { out.collect(value); ctx.output( sideOutputTag, "sideout1-" + String.valueOf(value)); } } @Override public void processElement2( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value >= 3) { out.collect(value); ctx.output( sideOutputTag, "sideout2-" + String.valueOf(value)); } } }); passThroughtStream.getSideOutput(sideOutputTag).addSink(sideOutputResultSink); passThroughtStream.addSink(resultSink); see.execute(); assertEquals( Arrays.asList("sideout1-1", "sideout1-2", "sideout2-3", "sideout2-4", "sideout2-5"), sideOutputResultSink.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } /** Test keyed KeyedCoProcessFunction side output. */ @Test public void testKeyedCoProcessFunctionSideOutput() throws Exception { final OutputTag<String> sideOutputTag = new OutputTag<String>("side") {}; TestListResultSink<String> sideOutputResultSink = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); see.setParallelism(3); DataStream<Integer> ds1 = see.fromData(elements); DataStream<Integer> ds2 = see.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = ds1.keyBy(i -> i) .connect(ds2.keyBy(i -> i)) .process( new KeyedCoProcessFunction<Integer, Integer, Integer, Integer>() { @Override public void processElement1( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value < 3) { out.collect(value); ctx.output( sideOutputTag, "sideout1-" + ctx.getCurrentKey() + "-" + String.valueOf(value)); } } @Override public void processElement2( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value >= 3) { out.collect(value); ctx.output( sideOutputTag, "sideout2-" + ctx.getCurrentKey() + "-" + String.valueOf(value)); } } }); passThroughtStream.getSideOutput(sideOutputTag).addSink(sideOutputResultSink); passThroughtStream.addSink(resultSink); see.execute(); assertEquals( Arrays.asList( "sideout1-1-1", "sideout1-2-2", "sideout2-3-3", "sideout2-4-4", "sideout2-5-5"), sideOutputResultSink.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } /** Test keyed CoProcessFunction side output with multiple consumers. */ @Test public void testLegacyKeyedCoProcessFunctionSideOutputWithMultipleConsumers() throws Exception { final OutputTag<String> sideOutputTag1 = new OutputTag<String>("side1") {}; final OutputTag<String> sideOutputTag2 = new OutputTag<String>("side2") {}; TestListResultSink<String> sideOutputResultSink1 = new TestListResultSink<>(); TestListResultSink<String> sideOutputResultSink2 = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); see.setParallelism(3); DataStream<Integer> ds1 = see.fromData(elements); DataStream<Integer> ds2 = see.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = ds1.keyBy(i -> i) .connect(ds2.keyBy(i -> i)) .process( new CoProcessFunction<Integer, Integer, Integer>() { @Override public void processElement1( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value < 4) { out.collect(value); ctx.output( sideOutputTag1, "sideout1-" + String.valueOf(value)); } } @Override public void processElement2( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value >= 4) { out.collect(value); ctx.output( sideOutputTag2, "sideout2-" + String.valueOf(value)); } } }); passThroughtStream.getSideOutput(sideOutputTag1).addSink(sideOutputResultSink1); passThroughtStream.getSideOutput(sideOutputTag2).addSink(sideOutputResultSink2); passThroughtStream.addSink(resultSink); see.execute(); assertEquals( Arrays.asList("sideout1-1", "sideout1-2", "sideout1-3"), sideOutputResultSink1.getSortedResult()); assertEquals( Arrays.asList("sideout2-4", "sideout2-5"), sideOutputResultSink2.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } /** Test keyed KeyedCoProcessFunction side output with multiple consumers. */ @Test public void testKeyedCoProcessFunctionSideOutputWithMultipleConsumers() throws Exception { final OutputTag<String> sideOutputTag1 = new OutputTag<String>("side1") {}; final OutputTag<String> sideOutputTag2 = new OutputTag<String>("side2") {}; TestListResultSink<String> sideOutputResultSink1 = new TestListResultSink<>(); TestListResultSink<String> sideOutputResultSink2 = new TestListResultSink<>(); TestListResultSink<Integer> resultSink = new TestListResultSink<>(); StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); see.setParallelism(3); DataStream<Integer> ds1 = see.fromData(elements); DataStream<Integer> ds2 = see.fromData(elements); SingleOutputStreamOperator<Integer> passThroughtStream = ds1.keyBy(i -> i) .connect(ds2.keyBy(i -> i)) .process( new KeyedCoProcessFunction<Integer, Integer, Integer, Integer>() { @Override public void processElement1( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value < 4) { out.collect(value); ctx.output( sideOutputTag1, "sideout1-" + ctx.getCurrentKey() + "-" + String.valueOf(value)); } } @Override public void processElement2( Integer value, Context ctx, Collector<Integer> out) throws Exception { if (value >= 4) { out.collect(value); ctx.output( sideOutputTag2, "sideout2-" + ctx.getCurrentKey() + "-" + String.valueOf(value)); } } }); passThroughtStream.getSideOutput(sideOutputTag1).addSink(sideOutputResultSink1); passThroughtStream.getSideOutput(sideOutputTag2).addSink(sideOutputResultSink2); passThroughtStream.addSink(resultSink); see.execute(); assertEquals( Arrays.asList("sideout1-1-1", "sideout1-2-2", "sideout1-3-3"), sideOutputResultSink1.getSortedResult()); assertEquals( Arrays.asList("sideout2-4-4", "sideout2-5-5"), sideOutputResultSink2.getSortedResult()); assertEquals(Arrays.asList(1, 2, 3, 4, 5), resultSink.getSortedResult()); } /** Test ProcessFunction side outputs with wrong {@code OutputTag}. */ @Test public void testProcessFunctionSideOutputWithWrongTag() throws Exception { final OutputTag<String> sideOutputTag1 = new OutputTag<String>("side") {}; final OutputTag<String> sideOutputTag2 = new OutputTag<String>("other-side") {}; TestListResultSink<String> sideOutputResultSink = new TestListResultSink<>(); StreamExecutionEnvironment see = StreamExecutionEnvironment.getExecutionEnvironment(); see.setParallelism(3); DataStream<Integer> dataStream = see.fromData(elements); dataStream .process( new ProcessFunction<Integer, Integer>() { private static final long serialVersionUID = 1L; @Override public void processElement( Integer value, Context ctx, Collector<Integer> out) throws Exception { out.collect(value); ctx.output(sideOutputTag2, "sideout-" + String.valueOf(value)); } }) .getSideOutput(sideOutputTag1) .addSink(sideOutputResultSink); see.execute(); assertEquals(Arrays.asList(), sideOutputResultSink.getSortedResult()); } private static
WatermarkReifier
java
spring-projects__spring-framework
spring-messaging/src/test/java/org/springframework/messaging/core/MessageSendingTemplateTests.java
{ "start": 6984, "end": 7279 }
class ____ extends AbstractMessageSendingTemplate<String> { private String destination; private Message<?> message; @Override protected void doSend(String destination, Message<?> message) { this.destination = destination; this.message = message; } } }
TestMessageSendingTemplate
java
junit-team__junit5
junit-platform-commons/src/main/java/org/junit/platform/commons/util/ClasspathScannerLoader.java
{ "start": 597, "end": 1460 }
class ____ { static ClasspathScanner getInstance() { ServiceLoader<ClasspathScanner> serviceLoader = ServiceLoader.load(ClasspathScanner.class, ClassLoaderUtils.getDefaultClassLoader()); List<Provider<ClasspathScanner>> classpathScanners = serviceLoader.stream().toList(); if (classpathScanners.size() == 1) { return classpathScanners.get(0).get(); } if (classpathScanners.size() > 1) { throw new JUnitException( "There should not be more than one ClasspathScanner implementation present on the classpath but there were %d: %s".formatted( classpathScanners.size(), classpathScanners.stream().map(Provider::type).map(Class::getName).toList())); } return new DefaultClasspathScanner(ClassLoaderUtils::getDefaultClassLoader, ReflectionUtils::tryToLoadClass); } private ClasspathScannerLoader() { } }
ClasspathScannerLoader
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/map/MapAssert_containsOnlyKeys_with_Iterable_Test.java
{ "start": 1225, "end": 1918 }
class ____ extends MapAssertBaseTest { @Override protected MapAssert<Object, Object> invoke_api_method() { return assertions.containsOnlyKeys(list(1, 2)); } @Override protected void verify_internal_effects() { verify(maps).assertContainsOnlyKeys(getInfo(assertions), getActual(assertions), list(1, 2)); } @Test void should_work_with_iterable_of_subclass_of_key_type() { // GIVEN Map<Number, String> map = mapOf(entry(1, "int"), entry(2, "int")); // THEN List<Integer> ints = list(1, 2); // not a List<Number> assertThat(map).containsOnlyKeys(ints); } @Nested @DisplayName("given Path parameter")
MapAssert_containsOnlyKeys_with_Iterable_Test
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/qjournal/MiniJournalCluster.java
{ "start": 1819, "end": 1952 }
class ____ implements Closeable { public static final String CLUSTER_WAITACTIVE_URI = "waitactive"; public static
MiniJournalCluster
java
playframework__playframework
dev-mode/play-build-link/src/main/java/play/core/BuildLink.java
{ "start": 631, "end": 1438 }
interface ____ { /** * Check if anything has changed, and if so, return an updated classloader. * * <p>This method is called multiple times on every request, so it is advised that change * detection happens asynchronously to this call, and that this call just check a boolean. * * @return Either * <ul> * <li>Throwable - If something went wrong (eg, a compile error). {@link * play.api.PlayException} and its sub types can be used to provide specific details on * compile errors or other exceptions. * <li>ClassLoader - If the classloader has changed, and the application should be reloaded. * <li>null - If nothing changed. * </ul> */ Object reload(); /** * Find the original source file for the given
BuildLink
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableCheckerTest.java
{ "start": 62760, "end": 63768 }
class ____ { public final <A> void f1(A transform) {} public <B, @ImmutableTypeParameter C> C f2(Function<B, C> fn) { return null; } public final <D, E> void f3(Function<D, E> fn) { // BUG: Diagnostic contains: instantiation of 'C' is mutable // 'E' is a mutable type variable f1(f2(fn)); } } """) .doTest(); } // javac does not instantiate type variables when they are not used, so we cannot check whether // their instantiations are immutable. @Ignore @Test public void immutableTypeParameter_notAllTypeVarsInstantiated_shouldFail() { compilationHelper .addSourceLines( "Test.java", """ import com.google.errorprone.annotations.ImmutableTypeParameter; import com.google.errorprone.annotations.Immutable; import java.util.function.Function;
Test
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/BadImportTest.java
{ "start": 18821, "end": 19056 }
enum ____ { INSTANCE; } """) .expectUnchanged() .addInputLines( "Test.java", """ package pkg; import static a.E.INSTANCE;
E
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/genericsinheritance/ParentHierarchy1.java
{ "start": 209, "end": 269 }
class ____ extends Parent<ChildHierarchy1> { }
ParentHierarchy1
java
grpc__grpc-java
util/src/main/java/io/grpc/util/AdvancedTlsX509KeyManager.java
{ "start": 10467, "end": 12451 }
class ____ { boolean success; long certTime; long keyTime; public UpdateResult(boolean success, long certTime, long keyTime) { this.success = success; this.certTime = certTime; this.keyTime = keyTime; } } /** * Reads the private key and certificates specified in the path locations. Updates {@code key} and * {@code cert} if both of their modified time changed since last read. * * @param certFile the file on disk holding the certificate chain * @param keyFile the file on disk holding the private key * @param oldKeyTime the time when the private key file is modified during last execution * @param oldCertTime the time when the certificate chain file is modified during last execution * @return the result of this update execution */ private UpdateResult readAndUpdate(File certFile, File keyFile, long oldKeyTime, long oldCertTime) throws IOException, GeneralSecurityException { long newKeyTime = checkNotNull(keyFile, "keyFile").lastModified(); long newCertTime = checkNotNull(certFile, "certFile").lastModified(); // We only update when both the key and the certs are updated. if (newKeyTime != oldKeyTime && newCertTime != oldCertTime) { FileInputStream keyInputStream = new FileInputStream(keyFile); try { PrivateKey key = CertificateUtils.getPrivateKey(keyInputStream); FileInputStream certInputStream = new FileInputStream(certFile); try { X509Certificate[] certs = CertificateUtils.getX509Certificates(certInputStream); updateIdentityCredentials(certs, key); return new UpdateResult(true, newKeyTime, newCertTime); } finally { certInputStream.close(); } } finally { keyInputStream.close(); } } return new UpdateResult(false, oldKeyTime, oldCertTime); } /** * Mainly used to avoid throwing IO Exceptions in java.io.Closeable. */ public
UpdateResult
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/multithreaded/MultiThreadedBuilder.java
{ "start": 2513, "end": 2699 }
class ____ not part of any public api and can be changed or deleted without prior notice. * * @since 3.0 * Builds one or more lifecycles for a full module * NOTE: This
is
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/generated/NamespaceTableAggsHandleFunction.java
{ "start": 1027, "end": 1560 }
interface ____<N> extends NamespaceAggsHandleFunctionBase<N> { /** * Emits the result of the aggregation from the current accumulators and namespace properties * (like window start). * * @param namespace the namespace properties which should be calculated, such window start * @param key the group key for the current emit. * @param out the collector used to emit results. */ void emitValue(N namespace, RowData key, Collector<RowData> out) throws Exception; }
NamespaceTableAggsHandleFunction
java
elastic__elasticsearch
x-pack/plugin/slm/src/test/java/org/elasticsearch/xpack/slm/SnapshotLifecycleTaskTests.java
{ "start": 3511, "end": 33714 }
class ____ extends ESTestCase { private final ProjectId projectId = randomProjectIdOrDefault(); public void testGetSnapMetadata() { final String id = randomAlphaOfLength(4); final SnapshotLifecyclePolicyMetadata slpm = makePolicyMeta(id); final SnapshotLifecycleMetadata meta = new SnapshotLifecycleMetadata( Collections.singletonMap(id, slpm), OperationMode.RUNNING, new SnapshotLifecycleStats() ); final ProjectMetadata projectMetadata = ProjectMetadata.builder(projectId).putCustom(SnapshotLifecycleMetadata.TYPE, meta).build(); final Optional<SnapshotLifecyclePolicyMetadata> o = SnapshotLifecycleTask.getSnapPolicyMetadata( projectMetadata, SnapshotLifecycleService.getJobId(slpm) ); assertTrue("the policy metadata should be retrieved from the cluster state", o.isPresent()); assertThat(o.get(), equalTo(slpm)); assertFalse(SnapshotLifecycleTask.getSnapPolicyMetadata(projectMetadata, "bad-jobid").isPresent()); } public void testSkipCreatingSnapshotWhenJobDoesNotMatch() { final String id = randomAlphaOfLength(4); final SnapshotLifecyclePolicyMetadata slpm = makePolicyMeta(id); final SnapshotLifecycleMetadata meta = new SnapshotLifecycleMetadata( Collections.singletonMap(id, slpm), OperationMode.RUNNING, new SnapshotLifecycleStats() ); final ClusterState state = ClusterState.builder(new ClusterName("test")) .putProjectMetadata(ProjectMetadata.builder(projectId).putCustom(SnapshotLifecycleMetadata.TYPE, meta).build()) .build(); final ThreadPool threadPool = new TestThreadPool("test"); ClusterSettings settings = new ClusterSettings( Settings.EMPTY, Sets.union(ClusterSettings.BUILT_IN_CLUSTER_SETTINGS, Set.of(SLM_HISTORY_INDEX_ENABLED_SETTING)) ); try (ClusterService clusterService = ClusterServiceUtils.createClusterService(state, threadPool, settings)) { VerifyingClient client = new VerifyingClient(threadPool, (a, r, l) -> { fail("should not have tried to take a snapshot"); return null; }); SnapshotHistoryStore historyStore = new VerifyingHistoryStore( null, clusterService, item -> fail("should not have tried to store an item") ); SnapshotLifecycleTask task = new SnapshotLifecycleTask(projectId, client, clusterService, historyStore); // Trigger the event, but since the job name does not match, it should // not run the function to create a snapshot task.triggered(new SchedulerEngine.Event("nonexistent-job", System.currentTimeMillis(), System.currentTimeMillis())); } threadPool.shutdownNow(); } public void testCreateSnapshotOnTrigger() throws Exception { final String id = randomAlphaOfLength(4); final SnapshotLifecyclePolicyMetadata slpm = makePolicyMeta(id); final SnapshotLifecycleMetadata meta = new SnapshotLifecycleMetadata( Collections.singletonMap(id, slpm), OperationMode.RUNNING, new SnapshotLifecycleStats() ); final ClusterState state = ClusterState.builder(new ClusterName("test")) .putProjectMetadata(ProjectMetadata.builder(projectId).putCustom(SnapshotLifecycleMetadata.TYPE, meta).build()) .nodes( DiscoveryNodes.builder() .add(DiscoveryNodeUtils.builder("nodeId").name("nodeId").build()) .localNodeId("nodeId") .masterNodeId("nodeId") ) .build(); final ThreadPool threadPool = new TestThreadPool("test"); ClusterSettings settings = new ClusterSettings( Settings.EMPTY, Sets.union(ClusterSettings.BUILT_IN_CLUSTER_SETTINGS, Set.of(SLM_HISTORY_INDEX_ENABLED_SETTING)) ); final String createSnapResponse = Strings.format(""" { "snapshot": { "snapshot": "snapshot_1", "uuid": "bcP3ClgCSYO_TP7_FCBbBw", "version_id": %s, "version": "%s", "indices": [], "include_global_state": true, "state": "SUCCESS", "start_time": "2019-03-19T22:19:53.542Z", "start_time_in_millis": 1553033993542, "end_time": "2019-03-19T22:19:53.567Z", "end_time_in_millis": 1553033993567, "duration_in_millis": 25, "failures": [], "shards": { "total": 0, "failed": 0, "successful": 0 } } }""", Version.CURRENT.id, Version.CURRENT); final AtomicBoolean clientCalled = new AtomicBoolean(false); final SetOnce<String> snapshotName = new SetOnce<>(); try (ClusterService clusterService = ClusterServiceUtils.createClusterService(state, threadPool, settings)) { // This verifying client will verify that we correctly invoked // client.admin().createSnapshot(...) with the appropriate // request. It also returns a mock real response VerifyingClient client = new VerifyingClient(threadPool, (action, request, listener) -> { assertFalse(clientCalled.getAndSet(true)); assertThat(action, sameInstance(TransportCreateSnapshotAction.TYPE)); assertThat(request, instanceOf(CreateSnapshotRequest.class)); CreateSnapshotRequest req = (CreateSnapshotRequest) request; SnapshotLifecyclePolicy policy = slpm.getPolicy(); assertThat(req.snapshot(), startsWith(policy.getName() + "-")); assertThat(req.repository(), equalTo(policy.getRepository())); snapshotName.set(req.snapshot()); if (req.indices().length > 0) { assertThat(Arrays.asList(req.indices()), equalTo(policy.getConfig().get("indices"))); } boolean globalState = policy.getConfig().get("include_global_state") == null || Booleans.parseBoolean((String) policy.getConfig().get("include_global_state")); assertThat(req.includeGlobalState(), equalTo(globalState)); try { return SnapshotInfoUtils.createSnapshotResponseFromXContent( createParser(JsonXContent.jsonXContent, createSnapResponse) ); } catch (IOException e) { fail("failed to parse snapshot response"); return null; } }); final AtomicBoolean historyStoreCalled = new AtomicBoolean(false); SnapshotHistoryStore historyStore = new VerifyingHistoryStore(null, clusterService, item -> { assertFalse(historyStoreCalled.getAndSet(true)); final SnapshotLifecyclePolicy policy = slpm.getPolicy(); assertEquals(policy.getId(), item.getPolicyId()); assertEquals(policy.getRepository(), item.getRepository()); assertEquals(policy.getConfig(), item.getSnapshotConfiguration()); assertEquals(snapshotName.get(), item.getSnapshotName()); }); SnapshotLifecycleTask task = new SnapshotLifecycleTask(projectId, client, clusterService, historyStore); // Trigger the event with a matching job name for the policy task.triggered( new SchedulerEngine.Event(SnapshotLifecycleService.getJobId(slpm), System.currentTimeMillis(), System.currentTimeMillis()) ); assertBusy(() -> { assertTrue("snapshot should be triggered once", clientCalled.get()); assertTrue("history store should be called once", historyStoreCalled.get()); }); } finally { threadPool.shutdownNow(); } } public void testPartialFailureSnapshot() throws Exception { final String id = randomAlphaOfLength(4); final SnapshotLifecyclePolicyMetadata slpm = makePolicyMeta(id); final SnapshotLifecycleMetadata meta = new SnapshotLifecycleMetadata( Collections.singletonMap(id, slpm), OperationMode.RUNNING, new SnapshotLifecycleStats() ); final ClusterState state = ClusterState.builder(new ClusterName("test")) .putProjectMetadata(ProjectMetadata.builder(projectId).putCustom(SnapshotLifecycleMetadata.TYPE, meta).build()) .nodes( DiscoveryNodes.builder() .add(DiscoveryNodeUtils.builder("nodeId").name("nodeId").build()) .localNodeId("nodeId") .masterNodeId("nodeId") ) .build(); final ThreadPool threadPool = new TestThreadPool("test"); ClusterSettings settings = new ClusterSettings( Settings.EMPTY, Sets.union(ClusterSettings.BUILT_IN_CLUSTER_SETTINGS, Set.of(SLM_HISTORY_INDEX_ENABLED_SETTING)) ); final AtomicBoolean clientCalled = new AtomicBoolean(false); final SetOnce<String> snapshotName = new SetOnce<>(); try (ClusterService clusterService = ClusterServiceUtils.createClusterService(state, threadPool, settings)) { VerifyingClient client = new VerifyingClient(threadPool, (action, request, listener) -> { assertFalse(clientCalled.getAndSet(true)); assertThat(action, sameInstance(TransportCreateSnapshotAction.TYPE)); assertThat(request, instanceOf(CreateSnapshotRequest.class)); CreateSnapshotRequest req = (CreateSnapshotRequest) request; SnapshotLifecyclePolicy policy = slpm.getPolicy(); assertThat(req.snapshot(), startsWith(policy.getName() + "-")); assertThat(req.repository(), equalTo(policy.getRepository())); snapshotName.set(req.snapshot()); if (req.indices().length > 0) { assertThat(Arrays.asList(req.indices()), equalTo(policy.getConfig().get("indices"))); } boolean globalState = policy.getConfig().get("include_global_state") == null || Booleans.parseBoolean((String) policy.getConfig().get("include_global_state")); assertThat(req.includeGlobalState(), equalTo(globalState)); long startTime = randomNonNegativeLong(); long endTime = randomLongBetween(startTime, Long.MAX_VALUE); return new CreateSnapshotResponse( new SnapshotInfo( new Snapshot(projectId, req.repository(), new SnapshotId(req.snapshot(), "uuid")), Arrays.asList(req.indices()), Collections.emptyList(), Collections.emptyList(), "snapshot started", endTime, 3, Collections.singletonList(new SnapshotShardFailure("nodeId", new ShardId("index", "uuid", 0), "forced failure")), req.includeGlobalState(), req.userMetadata(), startTime, Collections.emptyMap() ) ); }); final AtomicBoolean historyStoreCalled = new AtomicBoolean(false); SnapshotHistoryStore historyStore = new VerifyingHistoryStore(null, clusterService, item -> { assertFalse(historyStoreCalled.getAndSet(true)); final SnapshotLifecyclePolicy policy = slpm.getPolicy(); assertEquals(policy.getId(), item.getPolicyId()); assertEquals(policy.getRepository(), item.getRepository()); assertEquals(policy.getConfig(), item.getSnapshotConfiguration()); assertEquals(snapshotName.get(), item.getSnapshotName()); assertFalse("item should be a failure", item.isSuccess()); assertThat( item.getErrorDetails(), containsString("failed to create snapshot successfully, 1 out of 3 total shards failed") ); }); SnapshotLifecycleTask task = new SnapshotLifecycleTask(projectId, client, clusterService, historyStore); // Trigger the event with a matching job name for the policy task.triggered( new SchedulerEngine.Event(SnapshotLifecycleService.getJobId(slpm), System.currentTimeMillis(), System.currentTimeMillis()) ); assertBusy(() -> { assertTrue("snapshot should be triggered once", clientCalled.get()); assertTrue("history store should be called once", historyStoreCalled.get()); }); } finally { threadPool.shutdownNow(); } } public void testDeletedPoliciesHaveRegisteredRemoved() throws Exception { final String policyId = randomAlphaOfLength(10); final SnapshotId initiatingSnap = randSnapshotId(); final String deletedPolicy = randomAlphaOfLength(10); final SnapshotId snapForDeletedPolicy = randSnapshotId(); SnapshotLifecycleTask.WriteJobStatus writeJobStatus = randomBoolean() ? SnapshotLifecycleTask.WriteJobStatus.success( projectId, policyId, initiatingSnap, randomLong(), randomLong(), Collections.emptyList() ) : SnapshotLifecycleTask.WriteJobStatus.failure( projectId, policyId, initiatingSnap, randomLong(), Collections.emptyList(), new RuntimeException() ); // deletedPolicy is no longer defined var definedSlmPolicies = List.of(policyId); var registeredSnapshots = Map.of(policyId, List.of(initiatingSnap), deletedPolicy, List.of(snapForDeletedPolicy)); // behavior is same whether initiatingSnap still in progress var inProgress = Map.of(policyId, randomBoolean() ? List.of(initiatingSnap) : List.<SnapshotId>of()); ClusterState clusterState = buildClusterState(projectId, definedSlmPolicies, registeredSnapshots, inProgress); ClusterState newClusterState = writeJobStatus.execute(clusterState); RegisteredPolicySnapshots newRegisteredPolicySnapshots = newClusterState.metadata() .getProject(projectId) .custom(RegisteredPolicySnapshots.TYPE); assertEquals(List.of(), newRegisteredPolicySnapshots.getSnapshots()); } public void testOtherDefinedPoliciesUneffected() throws Exception { final String policyId = randomAlphaOfLength(10); final SnapshotId initiatingSnap = randSnapshotId(); final String otherPolicy = randomAlphaOfLength(10); final SnapshotId otherSnapRunning = randSnapshotId(); final SnapshotId otherSnapNotRunning = randSnapshotId(); SnapshotLifecycleTask.WriteJobStatus writeJobStatus = randomBoolean() ? SnapshotLifecycleTask.WriteJobStatus.success( projectId, policyId, initiatingSnap, randomLong(), randomLong(), Collections.emptyList() ) : SnapshotLifecycleTask.WriteJobStatus.failure( projectId, policyId, initiatingSnap, randomLong(), Collections.emptyList(), new RuntimeException() ); var definedSlmPolicies = List.of(policyId, otherPolicy); var registeredSnapshots = Map.of(policyId, List.of(initiatingSnap), otherPolicy, List.of(otherSnapRunning, otherSnapNotRunning)); var inProgress = Map.of(policyId, List.<SnapshotId>of(), otherPolicy, List.of(otherSnapRunning)); ClusterState clusterState = buildClusterState(projectId, definedSlmPolicies, registeredSnapshots, inProgress); ClusterState newClusterState = writeJobStatus.execute(clusterState); RegisteredPolicySnapshots newRegisteredPolicySnapshots = newClusterState.metadata() .getProject(projectId) .custom(RegisteredPolicySnapshots.TYPE); assertEquals(List.of(otherSnapRunning, otherSnapNotRunning), newRegisteredPolicySnapshots.getSnapshotsByPolicy(otherPolicy)); assertEquals(List.of(), newRegisteredPolicySnapshots.getSnapshotsByPolicy(policyId)); } public void testInitiatingSnapRemovedButStillRunningRemains() throws Exception { final String policyId = randomAlphaOfLength(10); final SnapshotId initiatingSnap = randSnapshotId(); SnapshotLifecycleTask.WriteJobStatus writeJobStatus = randomBoolean() ? SnapshotLifecycleTask.WriteJobStatus.success( projectId, policyId, initiatingSnap, randomLong(), randomLong(), Collections.emptyList() ) : SnapshotLifecycleTask.WriteJobStatus.failure( projectId, policyId, initiatingSnap, randomLong(), Collections.emptyList(), new RuntimeException() ); final SnapshotId stillRunning = randSnapshotId(); var definedSlmPolicies = List.of(policyId); var registeredSnapshots = Map.of(policyId, List.of(stillRunning, initiatingSnap)); // behavior is same whether initiatingSnap still in progress var inProgress = Map.of(policyId, randomBoolean() ? List.of(stillRunning, initiatingSnap) : List.of(stillRunning)); ClusterState clusterState = buildClusterState(projectId, definedSlmPolicies, registeredSnapshots, inProgress); ClusterState newClusterState = writeJobStatus.execute(clusterState); RegisteredPolicySnapshots newRegisteredPolicySnapshots = newClusterState.metadata() .getProject(projectId) .custom(RegisteredPolicySnapshots.TYPE); assertEquals(List.of(stillRunning), newRegisteredPolicySnapshots.getSnapshotsByPolicy(policyId)); } public void testCleanUpRegisteredInitiatedBySuccess() throws Exception { final String policyId = randomAlphaOfLength(10); final SnapshotId initiatingSnapshot = randSnapshotId(); final SnapshotId inferredFailureSnapshot = randSnapshotId(); // currently running snapshots final SnapshotId stillRunning = randSnapshotId(); final SnapshotInfo snapshotInfoSuccess = randomSnapshotInfoSuccess(projectId); final SnapshotInfo snapshotInfoFailure = randomSnapshotInfoFailure(projectId); var definedSlmPolicies = List.of(policyId); var registeredSnapshots = Map.of( policyId, List.of(stillRunning, inferredFailureSnapshot, snapshotInfoSuccess.snapshotId(), snapshotInfoFailure.snapshotId()) ); var inProgress = Map.of(policyId, List.of(stillRunning)); ClusterState clusterState = buildClusterState(projectId, definedSlmPolicies, registeredSnapshots, inProgress); var writeJobTask = SnapshotLifecycleTask.WriteJobStatus.success( projectId, policyId, initiatingSnapshot, randomLong(), randomLong(), List.of(snapshotInfoSuccess, snapshotInfoFailure) ); ClusterState newClusterState = writeJobTask.execute(clusterState); // snapshotInfoSuccess, initiatingSnapshot int expectedSuccessCount = 2; // inferredFailureSnapshot, snapshotInfoFailure int expectedFailureCount = 2; // the last snapshot (initiatingSnapshot) was successful int expectedInvocationsSinceLastSuccess = 0; // registered snapshots state is now recorded in stats and metadata SnapshotLifecycleMetadata newSlmMetadata = newClusterState.metadata().getProject(projectId).custom(SnapshotLifecycleMetadata.TYPE); SnapshotLifecycleStats newStats = newSlmMetadata.getStats(); SnapshotLifecycleStats.SnapshotPolicyStats snapshotPolicyStats = newStats.getMetrics().get(policyId); assertEquals(expectedFailureCount, snapshotPolicyStats.getSnapshotFailedCount()); assertEquals(expectedSuccessCount, snapshotPolicyStats.getSnapshotTakenCount()); SnapshotLifecyclePolicyMetadata newSlmPolicyMetadata = newSlmMetadata.getSnapshotConfigurations().get(policyId); assertEquals(snapshotInfoFailure.snapshotId().getName(), newSlmPolicyMetadata.getLastFailure().getSnapshotName()); assertEquals(initiatingSnapshot.getName(), newSlmPolicyMetadata.getLastSuccess().getSnapshotName()); assertEquals(expectedInvocationsSinceLastSuccess, newSlmPolicyMetadata.getInvocationsSinceLastSuccess()); // completed snapshot no longer in registeredSnapshot set RegisteredPolicySnapshots newRegisteredPolicySnapshots = newClusterState.metadata() .getProject(projectId) .custom(RegisteredPolicySnapshots.TYPE); List<SnapshotId> newRegisteredSnapIds = newRegisteredPolicySnapshots.getSnapshotsByPolicy(policyId); assertEquals(List.of(stillRunning), newRegisteredSnapIds); } public void testCleanUpRegisteredInitiatedByFailure() throws Exception { final String policyId = randomAlphaOfLength(10); final SnapshotId initiatingSnapshot = randSnapshotId(); final SnapshotId inferredFailureSnapshot = randSnapshotId(); final SnapshotId stillRunning = randSnapshotId(); final SnapshotInfo snapshotInfoSuccess = randomSnapshotInfoSuccess(projectId); final SnapshotInfo snapshotInfoFailure1 = randomSnapshotInfoFailure(projectId); final SnapshotInfo snapshotInfoFailure2 = randomSnapshotInfoFailure(projectId); var definedSlmPolicies = List.of(policyId); var registeredSnapshots = Map.of( policyId, List.of( stillRunning, inferredFailureSnapshot, snapshotInfoSuccess.snapshotId(), snapshotInfoFailure1.snapshotId(), snapshotInfoFailure2.snapshotId(), initiatingSnapshot ) ); var inProgress = Map.of(policyId, List.of(stillRunning)); ClusterState clusterState = buildClusterState(projectId, definedSlmPolicies, registeredSnapshots, inProgress); var writeJobTask = SnapshotLifecycleTask.WriteJobStatus.failure( projectId, policyId, initiatingSnapshot, randomLong(), List.of(snapshotInfoSuccess, snapshotInfoFailure1, snapshotInfoFailure2), new RuntimeException() ); ClusterState newClusterState = writeJobTask.execute(clusterState); // snapshotInfoSuccess int expectedSuccessCount = 1; // inferredFailureSnapshot, snapshotInfoFailure1, snapshotInfoFailure2, initiatingSnapshot int expectedFailureCount = 4; // snapshotInfoFailure1, snapshotInfoFailure2, initiatingSnapshot int expectedInvocationsSinceLastSuccess = 3; // registered snapshots state is now recorded in stats and metadata SnapshotLifecycleMetadata newSlmMetadata = newClusterState.metadata().getProject(projectId).custom(SnapshotLifecycleMetadata.TYPE); SnapshotLifecycleStats newStats = newSlmMetadata.getStats(); SnapshotLifecycleStats.SnapshotPolicyStats snapshotPolicyStats = newStats.getMetrics().get(policyId); assertEquals(expectedFailureCount, snapshotPolicyStats.getSnapshotFailedCount()); assertEquals(expectedSuccessCount, snapshotPolicyStats.getSnapshotTakenCount()); SnapshotLifecyclePolicyMetadata newSlmPolicyMetadata = newSlmMetadata.getSnapshotConfigurations().get(policyId); assertEquals(initiatingSnapshot.getName(), newSlmPolicyMetadata.getLastFailure().getSnapshotName()); assertEquals(snapshotInfoSuccess.snapshotId().getName(), newSlmPolicyMetadata.getLastSuccess().getSnapshotName()); assertEquals(expectedInvocationsSinceLastSuccess, newSlmPolicyMetadata.getInvocationsSinceLastSuccess()); // completed snapshot no longer in registeredSnapshot set RegisteredPolicySnapshots newRegisteredPolicySnapshots = newClusterState.metadata() .getProject(projectId) .custom(RegisteredPolicySnapshots.TYPE); List<SnapshotId> newRegisteredSnapIds = newRegisteredPolicySnapshots.getSnapshotsByPolicy(policyId); assertEquals(List.of(stillRunning), newRegisteredSnapIds); } public void testGetCurrentlyRunningSnapshots() { final SnapshotId snapshot1 = randSnapshotId(); final SnapshotId snapshot2 = randSnapshotId(); final SnapshotId snapshot3 = randSnapshotId(); final SnapshotId snapshot4 = randSnapshotId(); final String repo1 = randomAlphaOfLength(10); final String repo2 = randomAlphaOfLength(10); final var snapshotsInProgress = SnapshotsInProgress.EMPTY.createCopyWithUpdatedEntriesForRepo( projectId, repo1, List.of( makeSnapshotInProgress(projectId, repo1, "some-policy", snapshot1), makeSnapshotInProgress(projectId, repo1, "some-policy", snapshot2), makeSnapshotInProgress(projectId, repo1, "other-policy", snapshot3) ) ) .createCopyWithUpdatedEntriesForRepo( projectId, repo2, List.of(makeSnapshotInProgress(projectId, repo2, "other-policy", snapshot4)) ); final ClusterState clusterState = ClusterState.builder(new ClusterName("cluster")) .putCustom(SnapshotsInProgress.TYPE, snapshotsInProgress) .build(); Set<SnapshotId> currentlyRunning = SnapshotLifecycleTask.currentlyRunningSnapshots(clusterState); assertEquals(currentlyRunning, Set.of(snapshot1, snapshot2, snapshot3, snapshot4)); } private static SnapshotId randSnapshotId() { return new SnapshotId(randomAlphaOfLength(10), randomUUID()); } private static ClusterState buildClusterState( ProjectId projectId, List<String> slmPolicies, Map<String, List<SnapshotId>> registeredSnaps, Map<String, List<SnapshotId>> inProgress ) { final String repo = randomAlphaOfLength(10); List<SnapshotsInProgress.Entry> inProgressEntries = new ArrayList<>(); for (String policy : inProgress.keySet()) { for (SnapshotId snap : inProgress.get(policy)) { inProgressEntries.add(makeSnapshotInProgress(projectId, repo, policy, snap)); } } final List<RegisteredPolicySnapshots.PolicySnapshot> policySnapshots = new ArrayList<>(); for (Map.Entry<String, List<SnapshotId>> policySnaps : registeredSnaps.entrySet()) { for (SnapshotId snapshotId : policySnaps.getValue()) { policySnapshots.add(new RegisteredPolicySnapshots.PolicySnapshot(policySnaps.getKey(), snapshotId)); } } final ClusterState clusterState = ClusterState.builder(new ClusterName("cluster")) .putProjectMetadata( ProjectMetadata.builder(projectId) .putCustom(SnapshotLifecycleMetadata.TYPE, makeSnapMeta(slmPolicies)) .putCustom(RegisteredPolicySnapshots.TYPE, new RegisteredPolicySnapshots(policySnapshots)) .build() ) .putCustom( SnapshotsInProgress.TYPE, SnapshotsInProgress.EMPTY.createCopyWithUpdatedEntriesForRepo(projectId, repo, inProgressEntries) ) .build(); return clusterState; } private static SnapshotLifecycleMetadata makeSnapMeta(List<String> policies) { Map<String, SnapshotLifecyclePolicyMetadata> slmMeta = new HashMap<>(); for (String policy : policies) { SnapshotLifecyclePolicyMetadata slmPolicyMeta = SnapshotLifecyclePolicyMetadata.builder() .setModifiedDate(randomLong()) .setPolicy(new SnapshotLifecyclePolicy(policy, "snap", "", "repo-name", null, null)) .build(); slmMeta.put(policy, slmPolicyMeta); } SnapshotLifecycleStats stats = new SnapshotLifecycleStats( randomNonNegativeLong(), randomNonNegativeLong(), randomNonNegativeLong(), randomNonNegativeLong(), new HashMap<>() ); return new SnapshotLifecycleMetadata(slmMeta, OperationMode.RUNNING, stats); } private static SnapshotsInProgress.Entry makeSnapshotInProgress( ProjectId projectId, String repo, String policyId, SnapshotId snapshotId ) { final Map<String, Object> metadata = Map.of(SnapshotsService.POLICY_ID_METADATA_FIELD, policyId); return SnapshotsInProgress.Entry.snapshot( new Snapshot(projectId, repo, snapshotId), randomBoolean(), randomBoolean(), SnapshotsInProgress.State.SUCCESS, Map.of(), List.of(), List.of(), randomNonNegativeLong(), randomNonNegativeLong(), Map.of(), null, metadata, IndexVersion.current() ); } /** * A client that delegates to a verifying function for action/request/listener */ public static
SnapshotLifecycleTaskTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/ImplicitJoinInSubqueryTest.java
{ "start": 899, "end": 2103 }
class ____ { @Test @JiraKey("HHH-16721") public void testImplicitJoinInSubquery(SessionFactoryScope scope) { SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); statementInspector.clear(); scope.inTransaction( entityManager -> { entityManager.createSelectionQuery( "select 1 from A a where exists (select 1 from B b where a.b.c.id = 5)" ).getResultList(); assertThat( statementInspector.getSqlQueries().get( 0 ) ).contains( "b2_0.id=a1_0.b_id" ); } ); } @Test @JiraKey("HHH-17445") public void testImplicitJoinInSubquery2(SessionFactoryScope scope) { SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); statementInspector.clear(); scope.inTransaction( entityManager -> { entityManager.createSelectionQuery( "select a from A a where exists (select 1 from B b where a.b.c is null)" ).getResultList(); assertThat( statementInspector.getSqlQueries().get( 0 ) ).contains( "b1_0.c_id is null" ); assertThat( statementInspector.getSqlQueries().get( 0 ) ).doesNotContain( ".id=b1_0.c_id" ); } ); } @Entity(name = "A") public static
ImplicitJoinInSubqueryTest
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/io/ratelimiting/GuavaFlinkConnectorRateLimiter.java
{ "start": 1135, "end": 2643 }
class ____ implements FlinkConnectorRateLimiter { private static final long serialVersionUID = -3680641524643737192L; /** Rate in bytes per second for the consumer on a whole. */ private long globalRateBytesPerSecond; /** Rate in bytes per second per subtask of the consumer. */ private long localRateBytesPerSecond; /** Runtime context. * */ private RuntimeContext runtimeContext; /** RateLimiter. * */ private RateLimiter rateLimiter; /** * Creates a rate limiter with the runtime context provided. * * @param runtimeContext */ @Override public void open(RuntimeContext runtimeContext) { this.runtimeContext = runtimeContext; localRateBytesPerSecond = globalRateBytesPerSecond / runtimeContext.getTaskInfo().getNumberOfParallelSubtasks(); this.rateLimiter = RateLimiter.create(localRateBytesPerSecond); } /** * Set the global per consumer and per sub-task rates. * * @param globalRate Value of rate in bytes per second. */ @Override public void setRate(long globalRate) { this.globalRateBytesPerSecond = globalRate; } @Override public void acquire(int permits) { // Ensure permits > 0 rateLimiter.acquire(Math.max(1, permits)); } @Override public long getRate() { return globalRateBytesPerSecond; } @Override public void close() {} }
GuavaFlinkConnectorRateLimiter
java
apache__kafka
metadata/src/main/java/org/apache/kafka/image/node/printer/MetadataNodePrinter.java
{ "start": 854, "end": 1447 }
interface ____ extends AutoCloseable { /** * Find out the redaction criteria to use when printing. * * @return The redaction criteria to use when printing. */ MetadataNodeRedactionCriteria redactionCriteria(); /** * Begin visiting a node. * * @param name The node name. */ void enterNode(String name); /** * Leave a node. */ void leaveNode(); /** * Print text. */ void output(String text); /** * Close this printer. */ default void close() { } }
MetadataNodePrinter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cache/polymorphism/PolymorphicCacheTest.java
{ "start": 1906, "end": 2232 }
class ____ id with a cache-hit scope.inTransaction( (session) -> { try { final CachedItem2 loaded = session.get( CachedItem2.class, 1 ); assertThat( loaded ).isNull(); } catch (WrongClassException legacyBehavior) { // the legacy behavior for loading an entity from a // cache hit when it is the wrong
by
java
FasterXML__jackson-databind
src/test/java/perf/RecordAsArray.java
{ "start": 116, "end": 324 }
class ____ extends RecordBase { protected RecordAsArray() { super(); } public RecordAsArray(int a, String fn, String ln, char g, boolean ins) { super(a, fn, ln, g, ins); } }
RecordAsArray
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ManyToOnePropertySource.java
{ "start": 461, "end": 1685 }
class ____ implements PropertySource { private final JaxbHbmManyToOneType manyToOneMapping; public ManyToOnePropertySource(JaxbHbmManyToOneType manyToOneMapping) { this.manyToOneMapping = manyToOneMapping; } @Override public XmlElementMetadata getSourceType() { return XmlElementMetadata.MANY_TO_ONE; } @Override public String getName() { return manyToOneMapping.getName(); } @Override public String getXmlNodeName() { return manyToOneMapping.getNode(); } @Override public String getPropertyAccessorName() { return manyToOneMapping.getAccess(); } @Override public String getCascadeStyleName() { return manyToOneMapping.getCascade(); } @Override public GenerationTiming getGenerationTiming() { return null; } @Override public Boolean isInsertable() { return manyToOneMapping.isInsert(); } @Override public Boolean isUpdatable() { return manyToOneMapping.isUpdate(); } @Override public boolean isUsedInOptimisticLocking() { return manyToOneMapping.isOptimisticLock(); } @Override public boolean isLazy() { return false; } @Override public List<JaxbHbmToolingHintType> getToolingHints() { return manyToOneMapping.getToolingHints(); } }
ManyToOnePropertySource
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/InlinerTest.java
{ "start": 46731, "end": 46951 }
class ____ {} void doTest() { Client.inlinedMethod("abc"); } } """) .addOutputLines( "out/Caller.java", """
Bar
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/type/contributor/ArrayTypeCompositionTest.java
{ "start": 2231, "end": 2580 }
class ____ { @Id private String userName; @JavaType( ArrayJavaType.class ) private Array emailAddresses = new Array(); public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Array getEmailAddresses() { return emailAddresses; } } }
CorporateUser
java
google__auto
value/src/main/java/com/google/auto/value/AutoBuilder.java
{ "start": 1445, "end": 1895 }
interface ____ { /** * The static method from {@link #ofClass} to call when the build-method of the builder is called. * By default this is empty, meaning that a constructor rather than a static method should be * called. There can be more than one method with the given name, or more than one constructor, in * which case the one to call is the one whose parameter names and types correspond to the * abstract methods of the
AutoBuilder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DoubleBraceInitializationTest.java
{ "start": 13581, "end": 13737 }
class ____ { private void test() { ImmutableMap.of(); } } """) .doTest(); } }
Test
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/secondary/BasicSecondary.java
{ "start": 818, "end": 2287 }
class ____ { private Integer id; @BeforeClassTemplate public void initData(SessionFactoryScope scope) { SecondaryTestEntity ste = new SecondaryTestEntity( "a", "1" ); // Revision 1 scope.inTransaction( em -> { em.persist( ste ); } ); // Revision 2 scope.inTransaction( em -> { SecondaryTestEntity entity = em.find( SecondaryTestEntity.class, ste.getId() ); entity.setS1( "b" ); entity.setS2( "2" ); } ); id = ste.getId(); } @Test public void testRevisionsCounts(SessionFactoryScope scope) { scope.inSession( em -> { final var auditReader = AuditReaderFactory.get( em ); assertEquals( Arrays.asList( 1, 2 ), auditReader.getRevisions( SecondaryTestEntity.class, id ) ); } ); } @Test public void testHistoryOfId(SessionFactoryScope scope) { SecondaryTestEntity ver1 = new SecondaryTestEntity( id, "a", "1" ); SecondaryTestEntity ver2 = new SecondaryTestEntity( id, "b", "2" ); scope.inSession( em -> { final var auditReader = AuditReaderFactory.get( em ); assertEquals( ver1, auditReader.find( SecondaryTestEntity.class, id, 1 ) ); assertEquals( ver2, auditReader.find( SecondaryTestEntity.class, id, 2 ) ); } ); } @Test public void testTableNames(DomainModelScope scope) { assertEquals( "secondary_AUD", scope.getDomainModel() .getEntityBinding( "org.hibernate.orm.test.envers.integration.secondary.SecondaryTestEntity_AUD" ) .getJoins().get( 0 ).getTable().getName() ); } }
BasicSecondary
java
apache__camel
components/camel-opentelemetry-metrics/src/main/java/org/apache/camel/opentelemetry/metrics/TimerProducer.java
{ "start": 1294, "end": 4437 }
class ____ extends AbstractOpenTelemetryProducer<LongHistogram> { private final Map<String, LongHistogram> timers = new ConcurrentHashMap<>(); private final Object lock = new Object(); public TimerProducer(OpenTelemetryEndpoint endpoint) { super(endpoint); } @Override protected LongHistogram getInstrument(String name, String description) { LongHistogram timer = timers.get(name); if (timer == null) { synchronized (lock) { timer = timers.get(name); if (timer == null) { Meter meter = getEndpoint().getMeter(); LongHistogramBuilder builder = meter.histogramBuilder(name).ofLongs(); if (description != null) { builder.setDescription(description); } builder.setUnit(getEndpoint().getUnit().name().toLowerCase()); timer = builder.build(); timers.put(name, timer); } } } return timer; } @Override protected void doProcess(Exchange exchange, String metricsName, String metricsDescription, Attributes attributes) { Message in = exchange.getIn(); OpenTelemetryTimerAction action = simple(exchange, getEndpoint().getAction(), OpenTelemetryTimerAction.class); OpenTelemetryTimerAction finalAction = in.getHeader(HEADER_TIMER_ACTION, action, OpenTelemetryTimerAction.class); if (finalAction == OpenTelemetryTimerAction.START) { handleStart(exchange, metricsName); } else if (finalAction == OpenTelemetryTimerAction.STOP) { handleStop(exchange, metricsName, metricsDescription, attributes); } } @Override protected void doProcess( Exchange exchange, String metricsName, LongHistogram timer, Attributes attributes) { String propertyName = getPropertyName(metricsName); TaskTimer timedTask = getTimerFromExchange(exchange, propertyName); timer.record(timedTask.duration(getEndpoint().getUnit()), attributes); exchange.removeProperty(propertyName); } private void handleStart(Exchange exchange, String metricsName) { String propertyName = getPropertyName(metricsName); TaskTimer timedTask = getTimerFromExchange(exchange, propertyName); if (timedTask == null) { exchange.setProperty(propertyName, new TaskTimer()); } } private void handleStop(Exchange exchange, String metricsName, String metricsDescription, Attributes attributes) { TaskTimer timer = getTimerFromExchange(exchange, getPropertyName(metricsName)); if (timer != null) { doProcess(exchange, metricsName, getInstrument(metricsName, metricsDescription), attributes); } } private String getPropertyName(String metricsName) { return "timer:" + metricsName; } private TaskTimer getTimerFromExchange(Exchange exchange, String propertyName) { return exchange.getProperty(propertyName, TaskTimer.class); } }
TimerProducer
java
grpc__grpc-java
services/src/test/java/io/grpc/protobuf/services/ProtoReflectionServiceTest.java
{ "start": 2704, "end": 26824 }
class ____ { @Rule public GrpcCleanupRule grpcCleanupRule = new GrpcCleanupRule(); private static final String TEST_HOST = "localhost"; private MutableHandlerRegistry handlerRegistry = new MutableHandlerRegistry(); @SuppressWarnings("deprecation") private BindableService reflectionService = ProtoReflectionService.newInstance(); private ServerServiceDefinition dynamicService = new DynamicServiceGrpc.DynamicServiceImplBase() {}.bindService(); private ServerServiceDefinition anotherDynamicService = new AnotherDynamicServiceGrpc.AnotherDynamicServiceImplBase() {}.bindService(); private ServerReflectionGrpc.ServerReflectionStub stub; @Before public void setUp() throws Exception { Server server = InProcessServerBuilder.forName("proto-reflection-test") .directExecutor() .addService(reflectionService) .addService(new ReflectableServiceGrpc.ReflectableServiceImplBase() {}) .fallbackHandlerRegistry(handlerRegistry) .build() .start(); grpcCleanupRule.register(server); ManagedChannel channel = grpcCleanupRule.register( InProcessChannelBuilder.forName("proto-reflection-test").directExecutor().build()); stub = ServerReflectionGrpc.newStub(channel); } @Test public void listServices() throws Exception { Set<ServiceResponse> originalServices = new HashSet<>( Arrays.asList( ServiceResponse.newBuilder() .setName("grpc.reflection.v1alpha.ServerReflection") .build(), ServiceResponse.newBuilder() .setName("grpc.reflection.testing.ReflectableService") .build())); assertServiceResponseEquals(originalServices); handlerRegistry.addService(dynamicService); assertServiceResponseEquals( new HashSet<>( Arrays.asList( ServiceResponse.newBuilder() .setName("grpc.reflection.v1alpha.ServerReflection") .build(), ServiceResponse.newBuilder() .setName("grpc.reflection.testing.ReflectableService") .build(), ServiceResponse.newBuilder() .setName("grpc.reflection.testing.DynamicService") .build()))); handlerRegistry.addService(anotherDynamicService); assertServiceResponseEquals( new HashSet<>( Arrays.asList( ServiceResponse.newBuilder() .setName("grpc.reflection.v1alpha.ServerReflection") .build(), ServiceResponse.newBuilder() .setName("grpc.reflection.testing.ReflectableService") .build(), ServiceResponse.newBuilder() .setName("grpc.reflection.testing.DynamicService") .build(), ServiceResponse.newBuilder() .setName("grpc.reflection.testing.AnotherDynamicService") .build()))); handlerRegistry.removeService(dynamicService); assertServiceResponseEquals( new HashSet<>( Arrays.asList( ServiceResponse.newBuilder() .setName("grpc.reflection.v1alpha.ServerReflection") .build(), ServiceResponse.newBuilder() .setName("grpc.reflection.testing.ReflectableService") .build(), ServiceResponse.newBuilder() .setName("grpc.reflection.testing.AnotherDynamicService") .build()))); handlerRegistry.removeService(anotherDynamicService); assertServiceResponseEquals(originalServices); } @Test public void fileByFilename() throws Exception { ServerReflectionRequest request = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setFileByFilename("io/grpc/reflection/testing/reflection_test_depth_three.proto") .build(); ServerReflectionResponse goldenResponse = ServerReflectionResponse.newBuilder() .setValidHost(TEST_HOST) .setOriginalRequest(request) .setFileDescriptorResponse( FileDescriptorResponse.newBuilder() .addFileDescriptorProto( ReflectionTestDepthThreeProto.getDescriptor().toProto().toByteString()) .build()) .build(); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub.serverReflectionInfo(responseObserver); requestObserver.onNext(request); requestObserver.onCompleted(); assertEquals(goldenResponse, responseObserver.firstValue().get()); } @Test public void fileByFilenameConsistentForMutableServices() throws Exception { ServerReflectionRequest request = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setFileByFilename("io/grpc/reflection/testing/dynamic_reflection_test_depth_two.proto") .build(); ServerReflectionResponse goldenResponse = ServerReflectionResponse.newBuilder() .setValidHost(TEST_HOST) .setOriginalRequest(request) .setFileDescriptorResponse( FileDescriptorResponse.newBuilder() .addFileDescriptorProto( DynamicReflectionTestDepthTwoProto.getDescriptor().toProto().toByteString()) .build()) .build(); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub.serverReflectionInfo(responseObserver); handlerRegistry.addService(dynamicService); requestObserver.onNext(request); requestObserver.onCompleted(); StreamRecorder<ServerReflectionResponse> responseObserver2 = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver2 = stub.serverReflectionInfo(responseObserver2); handlerRegistry.removeService(dynamicService); requestObserver2.onNext(request); requestObserver2.onCompleted(); StreamRecorder<ServerReflectionResponse> responseObserver3 = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver3 = stub.serverReflectionInfo(responseObserver3); requestObserver3.onNext(request); requestObserver3.onCompleted(); assertEquals( ServerReflectionResponse.MessageResponseCase.ERROR_RESPONSE, responseObserver.firstValue().get().getMessageResponseCase()); assertEquals(goldenResponse, responseObserver2.firstValue().get()); assertEquals( ServerReflectionResponse.MessageResponseCase.ERROR_RESPONSE, responseObserver3.firstValue().get().getMessageResponseCase()); } @Test public void fileContainingSymbol() throws Exception { ServerReflectionRequest request = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setFileContainingSymbol("grpc.reflection.testing.ReflectableService.Method") .build(); List<ByteString> goldenResponse = Arrays.asList( ReflectionTestProto.getDescriptor().toProto().toByteString(), ReflectionTestDepthTwoProto.getDescriptor().toProto().toByteString(), ReflectionTestDepthTwoAlternateProto.getDescriptor().toProto().toByteString(), ReflectionTestDepthThreeProto.getDescriptor().toProto().toByteString()); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub.serverReflectionInfo(responseObserver); requestObserver.onNext(request); requestObserver.onCompleted(); List<ByteString> response = responseObserver .firstValue() .get() .getFileDescriptorResponse() .getFileDescriptorProtoList(); assertEquals(goldenResponse.size(), response.size()); assertEquals(new HashSet<>(goldenResponse), new HashSet<>(response)); } @Test public void fileContainingNestedSymbol() throws Exception { ServerReflectionRequest request = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setFileContainingSymbol("grpc.reflection.testing.NestedTypeOuter.Middle.Inner") .build(); ServerReflectionResponse goldenResponse = ServerReflectionResponse.newBuilder() .setValidHost(TEST_HOST) .setOriginalRequest(request) .setFileDescriptorResponse( FileDescriptorResponse.newBuilder() .addFileDescriptorProto( ReflectionTestDepthThreeProto.getDescriptor().toProto().toByteString()) .build()) .build(); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub.serverReflectionInfo(responseObserver); requestObserver.onNext(request); requestObserver.onCompleted(); assertEquals(goldenResponse, responseObserver.firstValue().get()); } @Test public void fileContainingSymbolForMutableServices() throws Exception { ServerReflectionRequest request = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setFileContainingSymbol("grpc.reflection.testing.DynamicRequest") .build(); ServerReflectionResponse goldenResponse = ServerReflectionResponse.newBuilder() .setValidHost(TEST_HOST) .setOriginalRequest(request) .setFileDescriptorResponse( FileDescriptorResponse.newBuilder() .addFileDescriptorProto( DynamicReflectionTestDepthTwoProto.getDescriptor().toProto().toByteString()) .build()) .build(); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub.serverReflectionInfo(responseObserver); handlerRegistry.addService(dynamicService); requestObserver.onNext(request); requestObserver.onCompleted(); StreamRecorder<ServerReflectionResponse> responseObserver2 = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver2 = stub.serverReflectionInfo(responseObserver2); handlerRegistry.removeService(dynamicService); requestObserver2.onNext(request); requestObserver2.onCompleted(); StreamRecorder<ServerReflectionResponse> responseObserver3 = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver3 = stub.serverReflectionInfo(responseObserver3); requestObserver3.onNext(request); requestObserver3.onCompleted(); assertEquals( ServerReflectionResponse.MessageResponseCase.ERROR_RESPONSE, responseObserver.firstValue().get().getMessageResponseCase()); assertEquals(goldenResponse, responseObserver2.firstValue().get()); assertEquals( ServerReflectionResponse.MessageResponseCase.ERROR_RESPONSE, responseObserver3.firstValue().get().getMessageResponseCase()); } @Test public void fileContainingExtension() throws Exception { ServerReflectionRequest request = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setFileContainingExtension( ExtensionRequest.newBuilder() .setContainingType("grpc.reflection.testing.ThirdLevelType") .setExtensionNumber(100) .build()) .build(); List<ByteString> goldenResponse = Arrays.asList( ReflectionTestProto.getDescriptor().toProto().toByteString(), ReflectionTestDepthTwoProto.getDescriptor().toProto().toByteString(), ReflectionTestDepthTwoAlternateProto.getDescriptor().toProto().toByteString(), ReflectionTestDepthThreeProto.getDescriptor().toProto().toByteString()); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub.serverReflectionInfo(responseObserver); requestObserver.onNext(request); requestObserver.onCompleted(); List<ByteString> response = responseObserver .firstValue() .get() .getFileDescriptorResponse() .getFileDescriptorProtoList(); assertEquals(goldenResponse.size(), response.size()); assertEquals(new HashSet<>(goldenResponse), new HashSet<>(response)); } @Test public void fileContainingNestedExtension() throws Exception { ServerReflectionRequest request = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setFileContainingExtension( ExtensionRequest.newBuilder() .setContainingType("grpc.reflection.testing.ThirdLevelType") .setExtensionNumber(101) .build()) .build(); ServerReflectionResponse goldenResponse = ServerReflectionResponse.newBuilder() .setValidHost(TEST_HOST) .setOriginalRequest(request) .setFileDescriptorResponse( FileDescriptorResponse.newBuilder() .addFileDescriptorProto( ReflectionTestDepthTwoProto.getDescriptor().toProto().toByteString()) .addFileDescriptorProto( ReflectionTestDepthThreeProto.getDescriptor().toProto().toByteString()) .build()) .build(); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub.serverReflectionInfo(responseObserver); requestObserver.onNext(request); requestObserver.onCompleted(); assertEquals(goldenResponse, responseObserver.firstValue().get()); } @Test public void fileContainingExtensionForMutableServices() throws Exception { ServerReflectionRequest request = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setFileContainingExtension( ExtensionRequest.newBuilder() .setContainingType("grpc.reflection.testing.TypeWithExtensions") .setExtensionNumber(200) .build()) .build(); ServerReflectionResponse goldenResponse = ServerReflectionResponse.newBuilder() .setValidHost(TEST_HOST) .setOriginalRequest(request) .setFileDescriptorResponse( FileDescriptorResponse.newBuilder() .addFileDescriptorProto( DynamicReflectionTestDepthTwoProto.getDescriptor().toProto().toByteString()) .build()) .build(); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub.serverReflectionInfo(responseObserver); handlerRegistry.addService(dynamicService); requestObserver.onNext(request); requestObserver.onCompleted(); StreamRecorder<ServerReflectionResponse> responseObserver2 = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver2 = stub.serverReflectionInfo(responseObserver2); handlerRegistry.removeService(dynamicService); requestObserver2.onNext(request); requestObserver2.onCompleted(); StreamRecorder<ServerReflectionResponse> responseObserver3 = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver3 = stub.serverReflectionInfo(responseObserver3); requestObserver3.onNext(request); requestObserver3.onCompleted(); assertEquals( ServerReflectionResponse.MessageResponseCase.ERROR_RESPONSE, responseObserver.firstValue().get().getMessageResponseCase()); assertEquals(goldenResponse, responseObserver2.firstValue().get()); assertEquals( ServerReflectionResponse.MessageResponseCase.ERROR_RESPONSE, responseObserver3.firstValue().get().getMessageResponseCase()); } @Test public void allExtensionNumbersOfType() throws Exception { ServerReflectionRequest request = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setAllExtensionNumbersOfType("grpc.reflection.testing.ThirdLevelType") .build(); Set<Integer> goldenResponse = new HashSet<>(Arrays.asList(100, 101)); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub.serverReflectionInfo(responseObserver); requestObserver.onNext(request); requestObserver.onCompleted(); Set<Integer> extensionNumberResponseSet = new HashSet<>( responseObserver .firstValue() .get() .getAllExtensionNumbersResponse() .getExtensionNumberList()); assertEquals(goldenResponse, extensionNumberResponseSet); } @Test public void allExtensionNumbersOfTypeForMutableServices() throws Exception { String type = "grpc.reflection.testing.TypeWithExtensions"; ServerReflectionRequest request = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setAllExtensionNumbersOfType(type) .build(); ServerReflectionResponse goldenResponse = ServerReflectionResponse.newBuilder() .setValidHost(TEST_HOST) .setOriginalRequest(request) .setAllExtensionNumbersResponse( ExtensionNumberResponse.newBuilder() .setBaseTypeName(type) .addExtensionNumber(200) .build()) .build(); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub.serverReflectionInfo(responseObserver); handlerRegistry.addService(dynamicService); requestObserver.onNext(request); requestObserver.onCompleted(); StreamRecorder<ServerReflectionResponse> responseObserver2 = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver2 = stub.serverReflectionInfo(responseObserver2); handlerRegistry.removeService(dynamicService); requestObserver2.onNext(request); requestObserver2.onCompleted(); StreamRecorder<ServerReflectionResponse> responseObserver3 = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver3 = stub.serverReflectionInfo(responseObserver3); requestObserver3.onNext(request); requestObserver3.onCompleted(); assertEquals( ServerReflectionResponse.MessageResponseCase.ERROR_RESPONSE, responseObserver.firstValue().get().getMessageResponseCase()); assertEquals(goldenResponse, responseObserver2.firstValue().get()); assertEquals( ServerReflectionResponse.MessageResponseCase.ERROR_RESPONSE, responseObserver3.firstValue().get().getMessageResponseCase()); } @Test public void sharedServiceBetweenServers() throws IOException, ExecutionException, InterruptedException { Server anotherServer = InProcessServerBuilder.forName("proto-reflection-test-2") .directExecutor() .addService(reflectionService) .addService(new AnotherReflectableServiceGrpc.AnotherReflectableServiceImplBase() {}) .build() .start(); grpcCleanupRule.register(anotherServer); ManagedChannel anotherChannel = grpcCleanupRule.register( InProcessChannelBuilder.forName("proto-reflection-test-2").directExecutor().build()); ServerReflectionGrpc.ServerReflectionStub stub2 = ServerReflectionGrpc.newStub(anotherChannel); ServerReflectionRequest request = ServerReflectionRequest.newBuilder().setHost(TEST_HOST).setListServices("services").build(); StreamRecorder<ServerReflectionResponse> responseObserver = StreamRecorder.create(); StreamObserver<ServerReflectionRequest> requestObserver = stub2.serverReflectionInfo(responseObserver); requestObserver.onNext(request); requestObserver.onCompleted(); List<ServiceResponse> response = responseObserver.firstValue().get().getListServicesResponse().getServiceList(); assertEquals(new HashSet<>( Arrays.asList( ServiceResponse.newBuilder() .setName("grpc.reflection.v1alpha.ServerReflection") .build(), ServiceResponse.newBuilder() .setName("grpc.reflection.testing.AnotherReflectableService") .build())), new HashSet<>(response)); } @Test public void flowControl() throws Exception { FlowControlClientResponseObserver clientResponseObserver = new FlowControlClientResponseObserver(); ClientCallStreamObserver<ServerReflectionRequest> requestObserver = (ClientCallStreamObserver<ServerReflectionRequest>) stub.serverReflectionInfo(clientResponseObserver); // Verify we don't receive a response until we request it. requestObserver.onNext(flowControlRequest); assertEquals(0, clientResponseObserver.getResponses().size()); requestObserver.request(1); assertEquals(1, clientResponseObserver.getResponses().size()); assertEquals(flowControlGoldenResponse, clientResponseObserver.getResponses().get(0)); // Verify we don't receive an additional response until we request it. requestObserver.onNext(flowControlRequest); assertEquals(1, clientResponseObserver.getResponses().size()); requestObserver.request(1); assertEquals(2, clientResponseObserver.getResponses().size()); assertEquals(flowControlGoldenResponse, clientResponseObserver.getResponses().get(1)); requestObserver.onCompleted(); assertTrue(clientResponseObserver.onCompleteCalled()); } @Test public void flowControlOnCompleteWithPendingRequest() throws Exception { FlowControlClientResponseObserver clientResponseObserver = new FlowControlClientResponseObserver(); ClientCallStreamObserver<ServerReflectionRequest> requestObserver = (ClientCallStreamObserver<ServerReflectionRequest>) stub.serverReflectionInfo(clientResponseObserver); requestObserver.onNext(flowControlRequest); requestObserver.onCompleted(); assertEquals(0, clientResponseObserver.getResponses().size()); assertFalse(clientResponseObserver.onCompleteCalled()); requestObserver.request(1); assertTrue(clientResponseObserver.onCompleteCalled()); assertEquals(1, clientResponseObserver.getResponses().size()); assertEquals(flowControlGoldenResponse, clientResponseObserver.getResponses().get(0)); } private final ServerReflectionRequest flowControlRequest = ServerReflectionRequest.newBuilder() .setHost(TEST_HOST) .setFileByFilename("io/grpc/reflection/testing/reflection_test_depth_three.proto") .build(); private final ServerReflectionResponse flowControlGoldenResponse = ServerReflectionResponse.newBuilder() .setValidHost(TEST_HOST) .setOriginalRequest(flowControlRequest) .setFileDescriptorResponse( FileDescriptorResponse.newBuilder() .addFileDescriptorProto( ReflectionTestDepthThreeProto.getDescriptor().toProto().toByteString()) .build()) .build(); private static
ProtoReflectionServiceTest
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/config/property/EngineSpec.java
{ "start": 825, "end": 1376 }
class ____ { @Test void testStartVehicleWithConfiguration() { LinkedHashMap<String, Object> map = new LinkedHashMap<>(1); map.put("spec.name", "VehicleConfigPropertySpec"); map.put("my.engine.cylinders", "8"); map.put("my.engine.manufacturer", "Honda"); ApplicationContext ctx = ApplicationContext.run(map); Engine engine = ctx.getBean(Engine.class); assertEquals("Honda", engine.getManufacturer()); assertEquals(8, engine.getCylinders()); ctx.close(); } }
EngineSpec
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/cluster/pubsub/StatefulRedisClusterPubSubConnection.java
{ "start": 3014, "end": 9593 }
interface ____<K, V> extends StatefulRedisPubSubConnection<K, V> { /** * Returns the {@link RedisClusterPubSubCommands} API for the current connection. Does not create a new connection. * * @return the synchronous API for the underlying connection. */ RedisClusterPubSubCommands<K, V> sync(); /** * Returns the {@link RedisClusterPubSubAsyncCommands} API for the current connection. Does not create a new connection. * * @return the asynchronous API for the underlying connection. */ RedisClusterPubSubAsyncCommands<K, V> async(); /** * Returns the {@link RedisClusterPubSubReactiveCommands} API for the current connection. Does not create a new connection. * * @return the reactive API for the underlying connection. */ RedisClusterPubSubReactiveCommands<K, V> reactive(); /** * Retrieve a connection to the specified cluster node using the nodeId. Host and port are looked up in the node list. This * connection is bound to the node id. Once the cluster topology view is updated, the connection will try to reconnect the * to the node with the specified {@code nodeId}, that behavior can also lead to a closed connection once the node with the * specified {@code nodeId} is no longer part of the cluster. * <p> * Do not close the connections. Otherwise, unpredictable behavior will occur. The nodeId must be part of the cluster and is * validated against the current topology view in {@link io.lettuce.core.cluster.models.partitions.Partitions}. * * @param nodeId the node Id * @return a connection to the requested cluster node * @throws RedisException if the requested node identified by {@code nodeId} is not part of the cluster */ StatefulRedisPubSubConnection<K, V> getConnection(String nodeId); /** * Retrieve asynchronously a connection to the specified cluster node using the nodeId. Host and port are looked up in the * node list. This connection is bound to the node id. Once the cluster topology view is updated, the connection will try to * reconnect the to the node with the specified {@code nodeId}, that behavior can also lead to a closed connection once the * node with the specified {@code nodeId} is no longer part of the cluster. * <p> * Do not close the connections. Otherwise, unpredictable behavior will occur. The nodeId must be part of the cluster and is * validated against the current topology view in {@link io.lettuce.core.cluster.models.partitions.Partitions}. * * @param nodeId the node Id * @return {@link CompletableFuture} to indicate success or failure to connect to the requested cluster node. * @throws RedisException if the requested node identified by {@code nodeId} is not part of the cluster * @since 5.0 */ CompletableFuture<StatefulRedisPubSubConnection<K, V>> getConnectionAsync(String nodeId); /** * Retrieve a connection to the specified cluster node using host and port. This connection is bound to a host and port. * Updates to the cluster topology view can close the connection once the host, identified by {@code host} and {@code port}, * are no longer part of the cluster. * <p> * Do not close the connections. Otherwise, unpredictable behavior will occur. Host and port connections are verified by * default for cluster membership, see {@link ClusterClientOptions#isValidateClusterNodeMembership()}. * * @param host the host * @param port the port * @return a connection to the requested cluster node * @throws RedisException if the requested node identified by {@code host} and {@code port} is not part of the cluster */ StatefulRedisPubSubConnection<K, V> getConnection(String host, int port); /** * Retrieve a connection to the specified cluster node using host and port. This connection is bound to a host and port. * Updates to the cluster topology view can close the connection once the host, identified by {@code host} and {@code port}, * are no longer part of the cluster. * <p> * Do not close the connections. Otherwise, unpredictable behavior will occur. Host and port connections are verified by * default for cluster membership, see {@link ClusterClientOptions#isValidateClusterNodeMembership()}. * * @param host the host * @param port the port * @return {@link CompletableFuture} to indicate success or failure to connect to the requested cluster node. * @throws RedisException if the requested node identified by {@code host} and {@code port} is not part of the cluster * @since 5.0 */ CompletableFuture<StatefulRedisPubSubConnection<K, V>> getConnectionAsync(String host, int port); /** * @return Known partitions for this connection. */ Partitions getPartitions(); /** * Enables/disables node message propagation to {@code this} {@link StatefulRedisClusterPubSubConnection connections} * {@link RedisPubSubListener listeners}. * <p> * If {@code enabled} is {@code true}, then Pub/Sub messages received on node-specific connections are propagated to this * connection facade. Registered {@link RedisPubSubListener} will receive messages from individual node subscriptions. * <p> * Node event propagation is disabled by default. * * @param enabled {@code true} to enable node message propagation; {@code false} (default) to disable message propagation. */ void setNodeMessagePropagation(boolean enabled); /** * Add a new {@link RedisClusterPubSubListener listener}. * * @param listener the listener, must not be {@code null}. */ void addListener(RedisClusterPubSubListener<K, V> listener); /** * Remove an existing {@link RedisClusterPubSubListener listener}. * * @param listener the listener, must not be {@code null}. */ void removeListener(RedisClusterPubSubListener<K, V> listener); /** * Add a new {@link RedisClusterPushListener listener} to consume push messages. * * @param listener the listener, must not be {@code null}. * @since 6.0 */ void addListener(RedisClusterPushListener listener); /** * Remove an existing {@link RedisClusterPushListener listener}. * * @param listener the listener, must not be {@code null}. * @since 6.0 */ void removeListener(RedisClusterPushListener listener); }
StatefulRedisClusterPubSubConnection
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/token/delegation/SQLDelegationTokenSecretManager.java
{ "start": 1686, "end": 19271 }
class ____<TokenIdent extends AbstractDelegationTokenIdentifier> extends AbstractDelegationTokenSecretManager<TokenIdent> { private static final Logger LOG = LoggerFactory.getLogger(SQLDelegationTokenSecretManager.class); public static final String SQL_DTSM_CONF_PREFIX = "sql-dt-secret-manager."; private static final String SQL_DTSM_TOKEN_SEQNUM_BATCH_SIZE = SQL_DTSM_CONF_PREFIX + "token.seqnum.batch.size"; public static final int DEFAULT_SEQ_NUM_BATCH_SIZE = 10; public static final String SQL_DTSM_TOKEN_MAX_CLEANUP_RESULTS = SQL_DTSM_CONF_PREFIX + "token.max.cleanup.results"; public static final int SQL_DTSM_TOKEN_MAX_CLEANUP_RESULTS_DEFAULT = 1000; public static final String SQL_DTSM_TOKEN_LOADING_CACHE_EXPIRATION = SQL_DTSM_CONF_PREFIX + "token.loading.cache.expiration"; public static final long SQL_DTSM_TOKEN_LOADING_CACHE_EXPIRATION_DEFAULT = TimeUnit.SECONDS.toMillis(10); public static final String SQL_DTSM_TOKEN_LOADING_CACHE_MAX_SIZE = SQL_DTSM_CONF_PREFIX + "token.loading.cache.max.size"; public static final long SQL_DTSM_TOKEN_LOADING_CACHE_MAX_SIZE_DEFAULT = 100000; // Batch of sequence numbers that will be requested by the sequenceNumCounter. // A new batch is requested once the sequenceNums available to a secret manager are // exhausted, including during initialization. private final int seqNumBatchSize; // Number of tokens to obtain from SQL during the cleanup process. private final int maxTokenCleanupResults; // Last sequenceNum in the current batch that has been allocated to a token. private int currentSeqNum; // Max sequenceNum in the current batch that can be allocated to a token. // Unused sequenceNums in the current batch cannot be reused by other routers. private int currentMaxSeqNum; public SQLDelegationTokenSecretManager(Configuration conf) { super(conf.getLong(DelegationTokenManager.UPDATE_INTERVAL, DelegationTokenManager.UPDATE_INTERVAL_DEFAULT) * 1000, conf.getLong(DelegationTokenManager.MAX_LIFETIME, DelegationTokenManager.MAX_LIFETIME_DEFAULT) * 1000, conf.getLong(DelegationTokenManager.RENEW_INTERVAL, DelegationTokenManager.RENEW_INTERVAL_DEFAULT) * 1000, conf.getLong(DelegationTokenManager.REMOVAL_SCAN_INTERVAL, DelegationTokenManager.REMOVAL_SCAN_INTERVAL_DEFAULT) * 1000); this.seqNumBatchSize = conf.getInt(SQL_DTSM_TOKEN_SEQNUM_BATCH_SIZE, DEFAULT_SEQ_NUM_BATCH_SIZE); this.maxTokenCleanupResults = conf.getInt(SQL_DTSM_TOKEN_MAX_CLEANUP_RESULTS, SQL_DTSM_TOKEN_MAX_CLEANUP_RESULTS_DEFAULT); long cacheExpirationMs = conf.getTimeDuration(SQL_DTSM_TOKEN_LOADING_CACHE_EXPIRATION, SQL_DTSM_TOKEN_LOADING_CACHE_EXPIRATION_DEFAULT, TimeUnit.MILLISECONDS); long maximumCacheSize = conf.getLong(SQL_DTSM_TOKEN_LOADING_CACHE_MAX_SIZE, SQL_DTSM_TOKEN_LOADING_CACHE_MAX_SIZE_DEFAULT); this.currentTokens = new DelegationTokenLoadingCache<>(cacheExpirationMs, maximumCacheSize, this::getTokenInfoFromSQL); } /** * Persists a TokenIdentifier and its corresponding TokenInformation into * the SQL database. The TokenIdentifier is expected to be unique and any * duplicate token attempts will result in an IOException. * @param ident TokenIdentifier to persist. * @param tokenInfo DelegationTokenInformation associated with the TokenIdentifier. */ @Override protected void storeToken(TokenIdent ident, DelegationTokenInformation tokenInfo) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos)) { tokenInfo.write(dos); // Add token to SQL database insertToken(ident.getSequenceNumber(), ident.getBytes(), bos.toByteArray()); // Add token to local cache super.storeToken(ident, tokenInfo); } catch (SQLException e) { throw new IOException("Failed to store token in SQL secret manager", e); } } /** * Updates the TokenInformation of an existing TokenIdentifier in * the SQL database. * @param ident Existing TokenIdentifier in the SQL database. * @param tokenInfo Updated DelegationTokenInformation associated with the TokenIdentifier. */ @Override protected void updateToken(TokenIdent ident, DelegationTokenInformation tokenInfo) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { try (DataOutputStream dos = new DataOutputStream(bos)) { tokenInfo.write(dos); // Update token in SQL database updateToken(ident.getSequenceNumber(), ident.getBytes(), bos.toByteArray()); // Update token in local cache super.updateToken(ident, tokenInfo); } } catch (SQLException e) { throw new IOException("Failed to update token in SQL secret manager", e); } } /** * Cancels a token by removing it from the SQL database. This will * call the corresponding method in {@link AbstractDelegationTokenSecretManager} * to perform validation and remove the token from the cache. * @return Identifier of the canceled token */ @Override public synchronized TokenIdent cancelToken(Token<TokenIdent> token, String canceller) throws IOException { TokenIdent id = createTokenIdent(token.getIdentifier()); // Calling getTokenInfo to load token into local cache if not present. // super.cancelToken() requires token to be present in local cache. getTokenInfo(id); return super.cancelToken(token, canceller); } /** * Obtain a list of tokens that will be considered for cleanup, based on the last * time the token was updated in SQL. This list may include tokens that are not * expired and should not be deleted (e.g. if the token was last renewed using a * higher renewal interval). * The number of results is limited to reduce performance impact. Some level of * contention is expected when multiple routers run cleanup simultaneously. * @return Map of tokens that have not been updated in SQL after the token renewal * period. */ @Override protected Map<TokenIdent, DelegationTokenInformation> getCandidateTokensForCleanup() { Map<TokenIdent, DelegationTokenInformation> tokens = new HashMap<>(); try { // Query SQL for tokens that haven't been updated after // the last token renewal period. long maxModifiedTime = Time.now() - getTokenRenewInterval(); Map<byte[], byte[]> tokenInfoBytesList = selectStaleTokenInfos(maxModifiedTime, this.maxTokenCleanupResults); LOG.info("Found {} tokens for cleanup", tokenInfoBytesList.size()); for (Map.Entry<byte[], byte[]> tokenInfoBytes : tokenInfoBytesList.entrySet()) { TokenIdent tokenIdent = createTokenIdent(tokenInfoBytes.getKey()); DelegationTokenInformation tokenInfo = createTokenInfo(tokenInfoBytes.getValue()); tokens.put(tokenIdent, tokenInfo); } } catch (IOException | SQLException e) { LOG.error("Failed to get candidate tokens for cleanup in SQL secret manager", e); } return tokens; } /** * Removes the existing TokenInformation from the SQL database to * invalidate it. * @param ident TokenInformation to remove from the SQL database. */ @Override protected void removeStoredToken(TokenIdent ident) throws IOException { try { deleteToken(ident.getSequenceNumber(), ident.getBytes()); } catch (SQLException e) { LOG.warn("Failed to remove token in SQL secret manager", e); } } @Override protected void removeExpiredStoredToken(TokenIdent ident) { try { // Ensure that the token has not been renewed in SQL by // another secret manager DelegationTokenInformation tokenInfo = getTokenInfoFromSQL(ident); if (tokenInfo.getRenewDate() >= Time.now()) { LOG.info("Token was renewed by a different router and has not been deleted: {}", ident); return; } removeStoredToken(ident); } catch (NoSuchElementException e) { LOG.info("Token has already been deleted by a different router: {}", ident); } catch (Exception e) { LOG.warn("Could not remove token {}", ident, e); } } /** * Obtains the DelegationTokenInformation associated with the given * TokenIdentifier in the SQL database. * @param ident Existing TokenIdentifier in the SQL database. * @return DelegationTokenInformation that matches the given TokenIdentifier or * null if it doesn't exist in the database. */ @VisibleForTesting protected DelegationTokenInformation getTokenInfoFromSQL(TokenIdent ident) { try { byte[] tokenInfoBytes = selectTokenInfo(ident.getSequenceNumber(), ident.getBytes()); if (tokenInfoBytes == null) { // Throw exception so value is not added to cache throw new NoSuchElementException("Token not found in SQL secret manager: " + ident); } return createTokenInfo(tokenInfoBytes); } catch (SQLException | IOException e) { LOG.error("Failed to get token in SQL secret manager", e); throw new RuntimeException(e); } } private TokenIdent createTokenIdent(byte[] tokenIdentBytes) throws IOException { try (ByteArrayInputStream bis = new ByteArrayInputStream(tokenIdentBytes); DataInputStream din = new DataInputStream(bis)) { TokenIdent id = createIdentifier(); id.readFields(din); return id; } } private DelegationTokenInformation createTokenInfo(byte[] tokenInfoBytes) throws IOException { DelegationTokenInformation tokenInfo = new DelegationTokenInformation(); try (ByteArrayInputStream bis = new ByteArrayInputStream(tokenInfoBytes)) { try (DataInputStream dis = new DataInputStream(bis)) { tokenInfo.readFields(dis); } } return tokenInfo; } /** * Obtains the value of the last reserved sequence number. * @return Last reserved sequence number. */ @Override public int getDelegationTokenSeqNum() { try { return selectSequenceNum(); } catch (SQLException e) { throw new RuntimeException( "Failed to get token sequence number in SQL secret manager", e); } } /** * Updates the value of the last reserved sequence number. * @param seqNum Value to update the sequence number to. */ @Override public void setDelegationTokenSeqNum(int seqNum) { try { updateSequenceNum(seqNum); } catch (SQLException e) { throw new RuntimeException( "Failed to update token sequence number in SQL secret manager", e); } } /** * Obtains the next available sequence number that can be allocated to a Token. * Sequence numbers need to be reserved using the shared sequenceNumberCounter once * the local batch has been exhausted, which handles sequenceNumber allocation * concurrently with other secret managers. * This method ensures that sequence numbers are incremental in a single secret manager, * but not across secret managers. * @return Next available sequence number. */ @Override public synchronized int incrementDelegationTokenSeqNum() { if (currentSeqNum >= currentMaxSeqNum) { try { // Request a new batch of sequence numbers and use the // lowest one available. currentSeqNum = incrementSequenceNum(seqNumBatchSize); currentMaxSeqNum = currentSeqNum + seqNumBatchSize; } catch (SQLException e) { throw new RuntimeException( "Failed to increment token sequence number in SQL secret manager", e); } } return ++currentSeqNum; } /** * Persists a DelegationKey into the SQL database. The delegation keyId * is expected to be unique and any duplicate key attempts will result * in an IOException. * @param key DelegationKey to persist into the SQL database. */ @Override protected void storeDelegationKey(DelegationKey key) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos)) { key.write(dos); // Add delegation key to SQL database insertDelegationKey(key.getKeyId(), bos.toByteArray()); // Add delegation key to local cache super.storeDelegationKey(key); } catch (SQLException e) { throw new IOException("Failed to store delegation key in SQL secret manager", e); } } /** * Updates an existing DelegationKey in the SQL database. * @param key Updated DelegationKey. */ @Override protected void updateDelegationKey(DelegationKey key) throws IOException { try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos)) { key.write(dos); // Update delegation key in SQL database updateDelegationKey(key.getKeyId(), bos.toByteArray()); // Update delegation key in local cache super.updateDelegationKey(key); } catch (SQLException e) { throw new IOException("Failed to update delegation key in SQL secret manager", e); } } /** * Removes the existing DelegationKey from the SQL database to * invalidate it. * @param key DelegationKey to remove from the SQL database. */ @Override protected void removeStoredMasterKey(DelegationKey key) { try { deleteDelegationKey(key.getKeyId()); } catch (SQLException e) { LOG.warn("Failed to remove delegation key in SQL secret manager", e); } } /** * Obtains the DelegationKey from the SQL database. * @param keyId KeyId of the DelegationKey to obtain. * @return DelegationKey that matches the given keyId or null * if it doesn't exist in the database. */ @Override protected DelegationKey getDelegationKey(int keyId) { // Look for delegation key in local cache DelegationKey delegationKey = super.getDelegationKey(keyId); if (delegationKey == null) { try { // Look for delegation key in SQL database byte[] delegationKeyBytes = selectDelegationKey(keyId); if (delegationKeyBytes != null) { delegationKey = new DelegationKey(); try (ByteArrayInputStream bis = new ByteArrayInputStream(delegationKeyBytes)) { try (DataInputStream dis = new DataInputStream(bis)) { delegationKey.readFields(dis); } } // Update delegation key in local cache allKeys.put(keyId, delegationKey); } } catch (IOException | SQLException e) { LOG.error("Failed to get delegation key in SQL secret manager", e); } } return delegationKey; } /** * Obtains the value of the last delegation key id. * @return Last delegation key id. */ @Override public int getCurrentKeyId() { try { return selectKeyId(); } catch (SQLException e) { throw new RuntimeException( "Failed to get delegation key id in SQL secret manager", e); } } /** * Updates the value of the last delegation key id. * @param keyId Value to update the delegation key id to. */ @Override public void setCurrentKeyId(int keyId) { try { updateKeyId(keyId); } catch (SQLException e) { throw new RuntimeException( "Failed to set delegation key id in SQL secret manager", e); } } /** * Obtains the next available delegation key id that can be allocated to a DelegationKey. * Delegation key id need to be reserved using the shared delegationKeyIdCounter, * which handles keyId allocation concurrently with other secret managers. * @return Next available delegation key id. */ @Override public int incrementCurrentKeyId() { try { return incrementKeyId(1) + 1; } catch (SQLException e) { throw new RuntimeException( "Failed to increment delegation key id in SQL secret manager", e); } } // Token operations in SQL database protected abstract byte[] selectTokenInfo(int sequenceNum, byte[] tokenIdentifier) throws SQLException; protected abstract Map<byte[], byte[]> selectStaleTokenInfos(long maxModifiedTime, int maxResults) throws SQLException; protected abstract void insertToken(int sequenceNum, byte[] tokenIdentifier, byte[] tokenInfo) throws SQLException; protected abstract void updateToken(int sequenceNum, byte[] tokenIdentifier, byte[] tokenInfo) throws SQLException; protected abstract void deleteToken(int sequenceNum, byte[] tokenIdentifier) throws SQLException; // Delegation key operations in SQL database protected abstract byte[] selectDelegationKey(int keyId) throws SQLException; protected abstract void insertDelegationKey(int keyId, byte[] delegationKey) throws SQLException; protected abstract void updateDelegationKey(int keyId, byte[] delegationKey) throws SQLException; protected abstract void deleteDelegationKey(int keyId) throws SQLException; // Counter operations in SQL database protected abstract int selectSequenceNum() throws SQLException; protected abstract void updateSequenceNum(int value) throws SQLException; protected abstract int incrementSequenceNum(int amount) throws SQLException; protected abstract int selectKeyId() throws SQLException; protected abstract void updateKeyId(int value) throws SQLException; protected abstract int incrementKeyId(int amount) throws SQLException; }
SQLDelegationTokenSecretManager
java
apache__camel
components/camel-digitalocean/src/main/java/org/apache/camel/component/digitalocean/DigitalOceanException.java
{ "start": 860, "end": 1119 }
class ____ extends Exception { private static final long serialVersionUID = 1L; public DigitalOceanException(Throwable e) { super(e); } public DigitalOceanException(String message) { super(message); } }
DigitalOceanException
java
quarkusio__quarkus
extensions/amazon-lambda-rest/runtime/src/main/java/io/quarkus/amazon/lambda/http/LambdaIdentityProvider.java
{ "start": 472, "end": 1456 }
interface ____ extends IdentityProvider<LambdaAuthenticationRequest> { @Override default public Class<LambdaAuthenticationRequest> getRequestType() { return LambdaAuthenticationRequest.class; } @Override default Uni<SecurityIdentity> authenticate(LambdaAuthenticationRequest request, AuthenticationRequestContext context) { AwsProxyRequest event = request.getEvent(); SecurityIdentity identity = authenticate(event); if (identity == null) { return Uni.createFrom().optional(Optional.empty()); } return Uni.createFrom().item(identity); } /** * You must override this method unless you directly override * IdentityProvider.authenticate * * @param event * @return */ default SecurityIdentity authenticate(AwsProxyRequest event) { throw new IllegalStateException("You must override this method or IdentityProvider.authenticate"); } }
LambdaIdentityProvider
java
redisson__redisson
redisson/src/test/java/org/redisson/executor/ScheduledLongRunnableTask.java
{ "start": 154, "end": 801 }
class ____ implements Runnable, Serializable { @RInject private RedissonClient redisson; private String objectName; public ScheduledLongRunnableTask() { } public ScheduledLongRunnableTask(String objectName) { super(); this.objectName = objectName; } @Override public void run() { for (long i = 0; i < Long.MAX_VALUE; i++) { if (Thread.currentThread().isInterrupted()) { System.out.println("interrupted " + i); redisson.getBucket(objectName).set(i); return; } } } }
ScheduledLongRunnableTask
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/BadImportTest.java
{ "start": 8762, "end": 9273 }
class ____ {} } """) .doTest(); } @Test public void negative_nested() { compilationTestHelper .addSourceLines( "BadImportNegativeCases.java", """ package com.google.errorprone.bugpatterns.testdata; import com.google.common.collect.ImmutableList; /** * Tests for {@link BadImport}. * * @author awturner@google.com (Andy Turner) */ public
B
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/WildcardImportTest.java
{ "start": 12509, "end": 12730 }
class ____ { Inner i; } """) .addOutputLines( "out/test/Test.java", """ package test; import a.Two.Inner; public
Test
java
alibaba__fastjson
src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectI2.java
{ "start": 92, "end": 539 }
class ____ { private int a; private List<Integer> b; private boolean c; public int getA() { return a; } public void setA(int a) { this.a = a; } public List<Integer> getB() { return b; } public void setB(List<Integer> b) { this.b = b; } public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } }
ObjectI2
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/google/SetGenerators.java
{ "start": 13257, "end": 13628 }
class ____ extends AbstractContiguousSetGenerator { @Override protected SortedSet<Integer> create(Integer[] elements) { SortedSet<Integer> set = nullCheckedTreeSet(elements); int tooHigh = set.isEmpty() ? 0 : set.last() + 1; set.add(tooHigh); return checkedCreate(set).headSet(tooHigh); } } public static
ContiguousSetHeadsetGenerator
java
hibernate__hibernate-orm
hibernate-jcache/src/test/java/org/hibernate/orm/test/jcache/RefreshUpdatedDataTest.java
{ "start": 10365, "end": 11202 }
class ____ { @Id @GeneratedValue(generator = "increment") private Long id; private String name; @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @ElementCollection private List<String> tags = new ArrayList<>(); public NonStrictReadWriteCacheableItem() { } public NonStrictReadWriteCacheableItem(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getTags() { return tags; } } @Entity(name = "NrwVersionedItem") @Table(name = "RW_NOSTRICT_VER_ITEM") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "item") public static
NonStrictReadWriteCacheableItem
java
elastic__elasticsearch
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/predicate/regex/Like.java
{ "start": 478, "end": 1102 }
class ____ extends RegexMatch<LikePattern> { public Like(Source source, Expression left, LikePattern pattern) { this(source, left, pattern, false); } public Like(Source source, Expression left, LikePattern pattern, boolean caseInsensitive) { super(source, left, pattern, caseInsensitive); } @Override protected NodeInfo<Like> info() { return NodeInfo.create(this, Like::new, field(), pattern(), caseInsensitive()); } @Override protected Like replaceChild(Expression newLeft) { return new Like(source(), newLeft, pattern(), caseInsensitive()); } }
Like
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java
{ "start": 3401, "end": 9554 }
class ____ extends AbstractExpressionPointcut implements ClassFilter, IntroductionAwareMethodMatcher, BeanFactoryAware { private static final String AJC_MAGIC = "ajc$"; private static final Set<PointcutPrimitive> SUPPORTED_PRIMITIVES = Set.of( PointcutPrimitive.EXECUTION, PointcutPrimitive.ARGS, PointcutPrimitive.REFERENCE, PointcutPrimitive.THIS, PointcutPrimitive.TARGET, PointcutPrimitive.WITHIN, PointcutPrimitive.AT_ANNOTATION, PointcutPrimitive.AT_WITHIN, PointcutPrimitive.AT_ARGS, PointcutPrimitive.AT_TARGET); private static final Log logger = LogFactory.getLog(AspectJExpressionPointcut.class); private @Nullable Class<?> pointcutDeclarationScope; private boolean aspectCompiledByAjc; private String[] pointcutParameterNames = new String[0]; private Class<?>[] pointcutParameterTypes = new Class<?>[0]; private @Nullable BeanFactory beanFactory; private transient volatile @Nullable ClassLoader pointcutClassLoader; private transient volatile @Nullable PointcutExpression pointcutExpression; private transient volatile boolean pointcutParsingFailed; /** * Create a new default AspectJExpressionPointcut. */ public AspectJExpressionPointcut() { } /** * Create a new AspectJExpressionPointcut with the given settings. * @param declarationScope the declaration scope for the pointcut * @param paramNames the parameter names for the pointcut * @param paramTypes the parameter types for the pointcut */ public AspectJExpressionPointcut(Class<?> declarationScope, String[] paramNames, Class<?>[] paramTypes) { setPointcutDeclarationScope(declarationScope); if (paramNames.length != paramTypes.length) { throw new IllegalStateException( "Number of pointcut parameter names must match number of pointcut parameter types"); } this.pointcutParameterNames = paramNames; this.pointcutParameterTypes = paramTypes; } /** * Set the declaration scope for the pointcut. */ public void setPointcutDeclarationScope(Class<?> pointcutDeclarationScope) { this.pointcutDeclarationScope = pointcutDeclarationScope; this.aspectCompiledByAjc = compiledByAjc(pointcutDeclarationScope); } /** * Set the parameter names for the pointcut. */ public void setParameterNames(String... names) { this.pointcutParameterNames = names; } /** * Set the parameter types for the pointcut. */ public void setParameterTypes(Class<?>... types) { this.pointcutParameterTypes = types; } @Override public void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; } @Override public ClassFilter getClassFilter() { checkExpression(); return this; } @Override public MethodMatcher getMethodMatcher() { checkExpression(); return this; } /** * Check whether this pointcut is ready to match. */ private void checkExpression() { if (getExpression() == null) { throw new IllegalStateException("Must set property 'expression' before attempting to match"); } } /** * Lazily build the underlying AspectJ pointcut expression. */ private PointcutExpression obtainPointcutExpression() { PointcutExpression pointcutExpression = this.pointcutExpression; if (pointcutExpression == null) { ClassLoader pointcutClassLoader = determinePointcutClassLoader(); pointcutExpression = buildPointcutExpression(pointcutClassLoader); this.pointcutClassLoader = pointcutClassLoader; this.pointcutExpression = pointcutExpression; } return pointcutExpression; } /** * Determine the ClassLoader to use for pointcut evaluation. */ private @Nullable ClassLoader determinePointcutClassLoader() { if (this.beanFactory instanceof ConfigurableBeanFactory cbf) { return cbf.getBeanClassLoader(); } if (this.pointcutDeclarationScope != null) { return this.pointcutDeclarationScope.getClassLoader(); } return ClassUtils.getDefaultClassLoader(); } /** * Build the underlying AspectJ pointcut expression. */ private PointcutExpression buildPointcutExpression(@Nullable ClassLoader classLoader) { PointcutParser parser = initializePointcutParser(classLoader); PointcutParameter[] pointcutParameters = new PointcutParameter[this.pointcutParameterNames.length]; for (int i = 0; i < pointcutParameters.length; i++) { pointcutParameters[i] = parser.createPointcutParameter( this.pointcutParameterNames[i], this.pointcutParameterTypes[i]); } return parser.parsePointcutExpression(replaceBooleanOperators(resolveExpression()), this.pointcutDeclarationScope, pointcutParameters); } private String resolveExpression() { String expression = getExpression(); Assert.state(expression != null, "No expression set"); return expression; } /** * Initialize the underlying AspectJ pointcut parser. */ private PointcutParser initializePointcutParser(@Nullable ClassLoader classLoader) { PointcutParser parser = PointcutParser .getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution( SUPPORTED_PRIMITIVES, classLoader); parser.registerPointcutDesignatorHandler(new BeanPointcutDesignatorHandler()); return parser; } /** * If a pointcut expression has been specified in XML, the user cannot * write "and" as "&&" (though {@code &amp;&amp;} will work). * <p>We also allow "and" between two pointcut sub-expressions. * <p>This method converts back to {@code &&} for the AspectJ pointcut parser. */ private String replaceBooleanOperators(String pcExpr) { String result = StringUtils.replace(pcExpr, " and ", " && "); result = StringUtils.replace(result, " or ", " || "); result = StringUtils.replace(result, " not ", " ! "); return result; } /** * Return the underlying AspectJ pointcut expression. */ public PointcutExpression getPointcutExpression() { return obtainPointcutExpression(); } @Override public boolean matches(Class<?> targetClass) { if (this.pointcutParsingFailed) { // Pointcut parsing failed before below -> avoid trying again. return false; } if (this.aspectCompiledByAjc && compiledByAjc(targetClass)) { // ajc-compiled aspect
AspectJExpressionPointcut
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/superclass/SuperclassInjectionTest.java
{ "start": 2573, "end": 2703 }
class ____ extends FooHarvester { @Inject Head head5; } @ApplicationScoped static
SuperCombineHarvester
java
quarkusio__quarkus
extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/ConnectionRecyclingTest.java
{ "start": 353, "end": 1406 }
class ____ extends DatasourceTestBase { RedisDataSource ds = new BlockingRedisDataSourceImpl(vertx, redis, api, Duration.ofSeconds(1)); ReactiveRedisDataSource rds = new ReactiveRedisDataSourceImpl(vertx, redis, api); @AfterEach public void tearDown() { ds.flushall(); } @Test void verifyThatConnectionsAreClosed() { String k = "increment"; for (int i = 0; i < 1000; i++) { ds.withConnection(x -> x.value(String.class, Integer.class).incr(k)); } assertThat(ds.value(String.class, Integer.class).get(k)).isEqualTo(1000); } @Test void verifyThatConnectionsAreClosedWithTheReactiveDataSource() { String k = "increment"; for (int i = 0; i < 1000; i++) { rds.withConnection(x -> x.value(String.class, Integer.class).incr(k) .replaceWithVoid()).await().indefinitely(); } assertThat(rds.value(String.class, Integer.class).get(k).await().indefinitely()).isEqualTo(1000); } }
ConnectionRecyclingTest
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/producer/KafkaProducer.java
{ "start": 96045, "end": 99031 }
class ____ implements RecordAccumulator.AppendCallbacks { private final Callback userCallback; private final ProducerInterceptors<K, V> interceptors; private final String topic; private final Integer recordPartition; private final String recordLogString; private volatile int partition = RecordMetadata.UNKNOWN_PARTITION; private volatile TopicPartition topicPartition; private final Headers headers; private AppendCallbacks(Callback userCallback, ProducerInterceptors<K, V> interceptors, ProducerRecord<K, V> record) { this.userCallback = userCallback; this.interceptors = interceptors; // Extract record info as we don't want to keep a reference to the record during // whole lifetime of the batch. // We don't want to have an NPE here, because the interceptors would not be notified (see .doSend). topic = record != null ? record.topic() : null; if (record != null) { headers = record.headers(); } else { headers = new RecordHeaders(); ((RecordHeaders) headers).setReadOnly(); } recordPartition = record != null ? record.partition() : null; recordLogString = log.isTraceEnabled() && record != null ? record.toString() : ""; } @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (metadata == null) { metadata = new RecordMetadata(topicPartition(), -1, -1, RecordBatch.NO_TIMESTAMP, -1, -1); } this.interceptors.onAcknowledgement(metadata, exception, headers); if (this.userCallback != null) this.userCallback.onCompletion(metadata, exception); } @Override public void setPartition(int partition) { assert partition != RecordMetadata.UNKNOWN_PARTITION; this.partition = partition; if (log.isTraceEnabled()) { // Log the message here, because we don't know the partition before that. log.trace("Attempting to append record {} with callback {} to topic {} partition {}", recordLogString, userCallback, topic, partition); } } public int getPartition() { return partition; } public TopicPartition topicPartition() { if (topicPartition == null && topic != null) { if (partition != RecordMetadata.UNKNOWN_PARTITION) topicPartition = new TopicPartition(topic, partition); else if (recordPartition != null) topicPartition = new TopicPartition(topic, recordPartition); else topicPartition = new TopicPartition(topic, RecordMetadata.UNKNOWN_PARTITION); } return topicPartition; } } }
AppendCallbacks
java
spring-projects__spring-security
oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jose/jws/JwsAlgorithm.java
{ "start": 757, "end": 1414 }
interface ____ cryptographic algorithms defined by the JSON Web Algorithms (JWA) * specification and used by JSON Web Signature (JWS) to digitally sign or create a MAC of * the contents of the JWS Protected Header and JWS Payload. * * @author Joe Grandja * @since 5.2 * @see JwaAlgorithm * @see <a target="_blank" href="https://tools.ietf.org/html/rfc7518">JSON Web Algorithms * (JWA)</a> * @see <a target="_blank" href="https://tools.ietf.org/html/rfc7515">JSON Web Signature * (JWS)</a> * @see <a target="_blank" href= * "https://tools.ietf.org/html/rfc7518#section-3">Cryptographic Algorithms for Digital * Signatures and MACs</a> */ public
for
java
netty__netty
transport/src/main/java/io/netty/bootstrap/ServerBootstrapConfig.java
{ "start": 1010, "end": 3443 }
class ____ extends AbstractBootstrapConfig<ServerBootstrap, ServerChannel> { ServerBootstrapConfig(ServerBootstrap bootstrap) { super(bootstrap); } /** * Returns the configured {@link EventLoopGroup} which will be used for the child channels or {@code null} * if non is configured yet. */ @SuppressWarnings("deprecation") public EventLoopGroup childGroup() { return bootstrap.childGroup(); } /** * Returns the configured {@link ChannelHandler} be used for the child channels or {@code null} * if non is configured yet. */ public ChannelHandler childHandler() { return bootstrap.childHandler(); } /** * Returns a copy of the configured options which will be used for the child channels. */ public Map<ChannelOption<?>, Object> childOptions() { return bootstrap.childOptions(); } /** * Returns a copy of the configured attributes which will be used for the child channels. */ public Map<AttributeKey<?>, Object> childAttrs() { return bootstrap.childAttrs(); } @Override public String toString() { StringBuilder buf = new StringBuilder(super.toString()); buf.setLength(buf.length() - 1); buf.append(", "); EventLoopGroup childGroup = childGroup(); if (childGroup != null) { buf.append("childGroup: "); buf.append(StringUtil.simpleClassName(childGroup)); buf.append(", "); } Map<ChannelOption<?>, Object> childOptions = childOptions(); if (!childOptions.isEmpty()) { buf.append("childOptions: "); buf.append(childOptions); buf.append(", "); } Map<AttributeKey<?>, Object> childAttrs = childAttrs(); if (!childAttrs.isEmpty()) { buf.append("childAttrs: "); buf.append(childAttrs); buf.append(", "); } ChannelHandler childHandler = childHandler(); if (childHandler != null) { buf.append("childHandler: "); buf.append(childHandler); buf.append(", "); } if (buf.charAt(buf.length() - 1) == '(') { buf.append(')'); } else { buf.setCharAt(buf.length() - 2, ')'); buf.setLength(buf.length() - 1); } return buf.toString(); } }
ServerBootstrapConfig
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/gwt/GwtValueTypeWithBuilder.java
{ "start": 1527, "end": 1926 }
interface ____<T> { Builder<T> string(String x); Builder<T> integer(int x); Builder<T> other(@Nullable GwtValueTypeWithBuilder<T> x); Builder<T> others(List<GwtValueTypeWithBuilder<T>> x); Builder<T> list(ImmutableList<T> x); Builder<T> otherList(List<T> x); ImmutableList.Builder<String> listWithBuilderBuilder(); GwtValueTypeWithBuilder<T> build(); } }
Builder
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/web/servlet/result/MockMvcResultMatchers.java
{ "start": 1493, "end": 9676 }
class ____ { private static final AntPathMatcher pathMatcher = new AntPathMatcher(); /** * Access to request-related assertions. */ public static RequestResultMatchers request() { return new RequestResultMatchers(); } /** * Access to assertions for the handler that handled the request. */ public static HandlerResultMatchers handler() { return new HandlerResultMatchers(); } /** * Access to model-related assertions. */ public static ModelResultMatchers model() { return new ModelResultMatchers(); } /** * Access to assertions on the selected view. */ public static ViewResultMatchers view() { return new ViewResultMatchers(); } /** * Access to flash attribute assertions. */ public static FlashAttributeResultMatchers flash() { return new FlashAttributeResultMatchers(); } /** * Asserts the request was forwarded to the given URL. * <p>This method accepts only exact matches. * @param expectedUrl the exact URL expected */ public static ResultMatcher forwardedUrl(@Nullable String expectedUrl) { return result -> assertEquals("Forwarded URL", expectedUrl, result.getResponse().getForwardedUrl()); } /** * Asserts the request was forwarded to the given URL template. * <p>This method accepts exact matches against the expanded and encoded URL template. * @param urlTemplate a URL template; the expanded URL will be encoded * @param uriVars zero or more URI variables to populate the template * @see UriComponentsBuilder#fromUriString(String) */ public static ResultMatcher forwardedUrlTemplate(String urlTemplate, @Nullable Object... uriVars) { String uri = UriComponentsBuilder.fromUriString(urlTemplate).buildAndExpand(uriVars).encode().toUriString(); return forwardedUrl(uri); } /** * Asserts the request was forwarded to the given URL. * <p>This method accepts {@link org.springframework.util.AntPathMatcher} * patterns. * @param urlPattern an Ant-style path pattern to match against * @since 4.0 * @see org.springframework.util.AntPathMatcher */ public static ResultMatcher forwardedUrlPattern(String urlPattern) { return result -> { assertTrue("'" + urlPattern + "' is not an Ant-style path pattern", pathMatcher.isPattern(urlPattern)); String url = result.getResponse().getForwardedUrl(); assertTrue("Forwarded URL '" + url + "' does not match the expected URL pattern '" + urlPattern + "'", (url != null && pathMatcher.match(urlPattern, url))); }; } /** * Asserts the request was redirected to the given URL. * <p>This method accepts only exact matches. * @param expectedUrl the exact URL expected */ public static ResultMatcher redirectedUrl(String expectedUrl) { return result -> assertEquals("Redirected URL", expectedUrl, result.getResponse().getRedirectedUrl()); } /** * Asserts the request was redirected to the given URL template. * <p>This method accepts exact matches against the expanded and encoded URL template. * @param urlTemplate a URL template; the expanded URL will be encoded * @param uriVars zero or more URI variables to populate the template * @see UriComponentsBuilder#fromUriString(String) */ public static ResultMatcher redirectedUrlTemplate(String urlTemplate, @Nullable Object... uriVars) { String uri = UriComponentsBuilder.fromUriString(urlTemplate).buildAndExpand(uriVars).encode().toUriString(); return redirectedUrl(uri); } /** * Asserts the request was redirected to the given URL. * <p>This method accepts {@link org.springframework.util.AntPathMatcher} * patterns. * @param urlPattern an Ant-style path pattern to match against * @since 4.0 * @see org.springframework.util.AntPathMatcher */ public static ResultMatcher redirectedUrlPattern(String urlPattern) { return result -> { assertTrue("'" + urlPattern + "' is not an Ant-style path pattern", pathMatcher.isPattern(urlPattern)); String url = result.getResponse().getRedirectedUrl(); assertTrue("Redirected URL '" + url + "' does not match the expected URL pattern '" + urlPattern + "'", (url != null && pathMatcher.match(urlPattern, url))); }; } /** * Access to response status assertions. */ public static StatusResultMatchers status() { return new StatusResultMatchers(); } /** * Access to response header assertions. */ public static HeaderResultMatchers header() { return new HeaderResultMatchers(); } /** * Access to response body assertions. */ public static ContentResultMatchers content() { return new ContentResultMatchers(); } /** * Access to response body assertions using a * <a href="https://github.com/jayway/JsonPath">JsonPath</a> expression * to inspect a specific subset of the body. * <p>The JSON path expression can be a parameterized string using * formatting specifiers as defined in * {@link String#format(String, Object...)}. * @param expression the JSON path expression, optionally parameterized with arguments * @param args arguments to parameterize the JSON path expression with * @see #jsonPath(String, Matcher) * @see #jsonPath(String, Matcher, Class) */ public static JsonPathResultMatchers jsonPath(String expression, Object... args) { return new JsonPathResultMatchers(expression, args); } /** * Evaluate the given <a href="https://github.com/jayway/JsonPath">JsonPath</a> * expression against the response body and assert the resulting value with * the given Hamcrest {@link Matcher}. * @param expression the JSON path expression * @param matcher a matcher for the value expected at the JSON path * @see #jsonPath(String, Object...) * @see #jsonPath(String, Matcher, Class) */ public static <T> ResultMatcher jsonPath(String expression, Matcher<? super T> matcher) { return new JsonPathResultMatchers(expression).value(matcher); } /** * Evaluate the given <a href="https://github.com/jayway/JsonPath">JsonPath</a> * expression against the response body and assert the resulting value with * the given Hamcrest {@link Matcher}, coercing the resulting value into the * given target type before applying the matcher. * <p>This can be useful for matching numbers reliably &mdash; for example, * to coerce an integer into a double. * @param expression the JSON path expression * @param matcher a matcher for the value expected at the JSON path * @param targetType the target type to coerce the matching value into * @since 5.2 * @see #jsonPath(String, Object...) * @see #jsonPath(String, Matcher) */ public static <T> ResultMatcher jsonPath(String expression, Matcher<? super T> matcher, Class<T> targetType) { return new JsonPathResultMatchers(expression).value(matcher, targetType); } /** * Access to response body assertions using an XPath expression to * inspect a specific subset of the body. * <p>The XPath expression can be a parameterized string using formatting * specifiers as defined in {@link String#format(String, Object...)}. * @param expression the XPath expression, optionally parameterized with arguments * @param args arguments to parameterize the XPath expression with */ public static XpathResultMatchers xpath(String expression, Object... args) throws XPathExpressionException { return new XpathResultMatchers(expression, null, args); } /** * Access to response body assertions using an XPath expression to * inspect a specific subset of the body. * <p>The XPath expression can be a parameterized string using formatting * specifiers as defined in {@link String#format(String, Object...)}. * @param expression the XPath expression, optionally parameterized with arguments * @param namespaces the namespaces referenced in the XPath expression * @param args arguments to parameterize the XPath expression with */ public static XpathResultMatchers xpath(String expression, Map<String, String> namespaces, Object... args) throws XPathExpressionException { return new XpathResultMatchers(expression, namespaces, args); } /** * Access to response cookie assertions. */ public static CookieResultMatchers cookie() { return new CookieResultMatchers(); } }
MockMvcResultMatchers
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/internals/SecurityManagerCompatibilityTest.java
{ "start": 8010, "end": 8248 }
class ____-in for the AccessControlContext in the mocked signatures below, because we can't have a * compile-time dependency on the real class. This needs no methods and is just a dummy class. */ public static
stands
java
apache__kafka
metadata/src/test/java/org/apache/kafka/metadata/BrokerRegistrationFencingChangeTest.java
{ "start": 1021, "end": 1951 }
class ____ { @Test public void testValues() { assertEquals((byte) 1, BrokerRegistrationFencingChange.FENCE.value()); assertEquals((byte) 0, BrokerRegistrationFencingChange.NONE.value()); assertEquals((byte) -1, BrokerRegistrationFencingChange.UNFENCE.value()); } @Test public void testAsBoolean() { assertEquals(Optional.of(true), BrokerRegistrationFencingChange.FENCE.asBoolean()); assertEquals(Optional.empty(), BrokerRegistrationFencingChange.NONE.asBoolean()); assertEquals(Optional.of(false), BrokerRegistrationFencingChange.UNFENCE.asBoolean()); } @Test public void testValueRoundTrip() { for (BrokerRegistrationFencingChange change : BrokerRegistrationFencingChange.values()) { assertEquals(Optional.of(change), BrokerRegistrationFencingChange.fromValue(change.value())); } } }
BrokerRegistrationFencingChangeTest
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/logger/slf4j/Slf4jLoggerAdapter.java
{ "start": 1105, "end": 2815 }
class ____ implements LoggerAdapter { public static final String NAME = "slf4j"; private Level level; private File file; private static final org.slf4j.Logger ROOT_LOGGER = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); public Slf4jLoggerAdapter() { this.level = Slf4jLogger.getLevel(ROOT_LOGGER); } @Override public Logger getLogger(String key) { return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(key)); } @Override public Logger getLogger(Class<?> key) { return new Slf4jLogger(org.slf4j.LoggerFactory.getLogger(key)); } @Override public Logger getLogger(String fqcn, Class<?> key) { return new Slf4jLogger(fqcn, org.slf4j.LoggerFactory.getLogger(key)); } @Override public Logger getLogger(String fqcn, String key) { return new Slf4jLogger(fqcn, org.slf4j.LoggerFactory.getLogger(key)); } @Override public Level getLevel() { return level; } @Override public void setLevel(Level level) { System.err.printf( "The level of slf4j logger current can not be set, using the default level: %s \n", Slf4jLogger.getLevel(ROOT_LOGGER)); this.level = level; } @Override public File getFile() { return file; } @Override public void setFile(File file) { this.file = file; } @Override public boolean isConfigured() { try { ClassUtils.forName("org.slf4j.impl.StaticLoggerBinder"); return true; } catch (ClassNotFoundException ignore) { // ignore } return false; } }
Slf4jLoggerAdapter
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/short_/ShortAssert_isOdd_Test.java
{ "start": 873, "end": 1166 }
class ____ extends ShortAssertBaseTest { @Override protected ShortAssert invoke_api_method() { return assertions.isOdd(); } @Override protected void verify_internal_effects() { verify(shorts).assertIsOdd(getInfo(assertions), getActual(assertions)); } }
ShortAssert_isOdd_Test
java
spring-projects__spring-boot
core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/RunningService.java
{ "start": 917, "end": 1841 }
interface ____ { /** * Return the name of the service. * @return the service name */ String name(); /** * Return the image being used by the service. * @return the service image */ ImageReference image(); /** * Return the host that can be used to connect to the service. * @return the service host */ String host(); /** * Return the ports that can be used to connect to the service. * @return the service ports */ ConnectionPorts ports(); /** * Return the environment defined for the service. * @return the service env */ Map<String, @Nullable String> env(); /** * Return the labels attached to the service. * @return the service labels */ Map<String, String> labels(); /** * Return the Docker Compose file for the service. * @return the Docker Compose file * @since 3.5.0 */ default @Nullable DockerComposeFile composeFile() { return null; } }
RunningService
java
bumptech__glide
library/src/main/java/com/bumptech/glide/load/resource/bitmap/ImageReader.java
{ "start": 2534, "end": 4774 }
class ____ implements ImageReader { private final File file; private final List<ImageHeaderParser> parsers; private final ArrayPool byteArrayPool; FileReader(File file, List<ImageHeaderParser> parsers, ArrayPool byteArrayPool) { this.file = file; this.parsers = parsers; this.byteArrayPool = byteArrayPool; } @Nullable @Override public Bitmap decodeBitmap(Options options) throws FileNotFoundException { InputStream is = null; try { is = new RecyclableBufferedInputStream(new FileInputStream(file), byteArrayPool); return GlideBitmapFactory.decodeStream(is, options, this); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignored. } } } } @Override public ImageType getImageType() throws IOException { InputStream is = null; try { is = new RecyclableBufferedInputStream(new FileInputStream(file), byteArrayPool); return ImageHeaderParserUtils.getType(parsers, is, byteArrayPool); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignored. } } } } @Override public int getImageOrientation() throws IOException { InputStream is = null; try { is = new RecyclableBufferedInputStream(new FileInputStream(file), byteArrayPool); return ImageHeaderParserUtils.getOrientation(parsers, is, byteArrayPool); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignored. } } } } @Override public boolean hasJpegMpf() throws IOException { InputStream is = null; try { is = new FileInputStream(file); return ImageHeaderParserUtils.hasJpegMpf(parsers, is, byteArrayPool); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignored. } } } } @Override public void stopGrowingBuffers() {} } final
FileReader
java
mockito__mockito
mockito-core/src/main/java/org/mockito/ArgumentMatchers.java
{ "start": 4140, "end": 6273 }
class ____ { /** * Matches <strong>anything</strong>, including nulls. * * <p> * See examples in javadoc for {@link ArgumentMatchers} class * </p> * * <p> * <strong>Notes : </strong><br/> * <ul> * <li>For primitive types use {@link #anyChar()} family or {@link #isA(Class)} or {@link #any(Class)}.</li> * <li>Since Mockito 2.1.0 {@link #any(Class)} is not anymore an alias of this method.</li> * <li>Since Mockito 5.0.0 this no longer matches varargs. Use {@link #any(Class)} instead.</li> * </ul> * </p> * * @return <code>null</code>. * * @see #any(Class) * @see #anyChar() * @see #anyInt() * @see #anyBoolean() */ public static <T> T any() { reportMatcher(Any.ANY); return null; } /** * Matches any object of given type, excluding nulls. * * <p> * This matcher will perform a type check with the given type, thus excluding values. * See examples in javadoc for {@link ArgumentMatchers} class. * * This is an alias of: {@link #isA(Class)}} * </p> * * <p> * Since Mockito 2.1.0, only allow non-null instance of <code></code>, thus <code>null</code> is not anymore a valid value. * As reference are nullable, the suggested API to <strong>match</strong> <code>null</code> * would be {@link #isNull()}. We felt this change would make test harnesses much safer than they were with Mockito * 1.x. * </p> * * <p><strong>Notes : </strong><br/> * <ul> * <li>For primitive types use {@link #anyChar()} family.</li> * <li>Since Mockito 2.1.0 this method will perform a type check thus <code>null</code> values are not authorized.</li> * <li>Since Mockito 2.1.0 {@link #any()} is no longer an alias of this method.</li> * <li>Since Mockito 5.0.0 this method can match varargs if the array type is specified, for example <code>any(String[].class)</code>.</li> * </ul> * </p> * * @param <T> The accepted type * @param type the
ArgumentMatchers
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/analytics/event/AnalyticsEventTests.java
{ "start": 789, "end": 2253 }
class ____ extends AbstractWireSerializingTestCase<AnalyticsEvent> { @Override protected Writeable.Reader<AnalyticsEvent> instanceReader() { return AnalyticsEvent::new; } @Override protected AnalyticsEvent createTestInstance() { return randomAnalyticsEvent(); } @Override protected AnalyticsEvent mutateInstance(AnalyticsEvent instance) throws IOException { String eventCollectionName = instance.eventCollectionName(); long eventTime = instance.eventTime(); AnalyticsEvent.Type eventType = instance.eventType(); XContentType xContentType = instance.xContentType(); BytesReference payload = instance.payload(); switch (between(0, 4)) { case 0 -> eventCollectionName = randomValueOtherThan(eventCollectionName, () -> randomIdentifier()); case 1 -> eventTime = randomValueOtherThan(eventTime, () -> randomLong()); case 2 -> eventType = randomValueOtherThan(eventType, () -> randomFrom(AnalyticsEvent.Type.values())); case 3 -> xContentType = randomValueOtherThan(xContentType, () -> randomFrom(XContentType.values())); case 4 -> payload = randomValueOtherThan(payload, () -> randomPayload()); default -> throw new AssertionError("Illegal randomisation branch"); } return new AnalyticsEvent(eventCollectionName, eventTime, eventType, xContentType, payload); } }
AnalyticsEventTests
java
apache__spark
mllib/src/test/java/org/apache/spark/ml/feature/JavaPCASuite.java
{ "start": 1349, "end": 1414 }
class ____ extends SharedSparkSession { public static
JavaPCASuite
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/event/internal/DefaultFlushEntityEventListener.java
{ "start": 21075, "end": 22455 }
class ____ implements CustomEntityDirtinessStrategy.DirtyCheckContext { private int[] found; @Override public void doDirtyChecking(CustomEntityDirtinessStrategy.AttributeChecker attributeChecker) { found = new DirtyCheckAttributeInfoImpl( event ).visitAttributes( attributeChecker ); if ( found.length == 0 ) { found = null; } } } final var context = new DirtyCheckContextImpl(); event.getFactory().getCustomEntityDirtinessStrategy() .findDirty( event.getEntity(), event.getEntityEntry().getPersister(), event.getSession(), context ); return context.found; } private static int[] getDirtyPropertiesFromSelfDirtinessTracker(SelfDirtinessTracker tracker, FlushEntityEvent event) { final var entry = event.getEntityEntry(); final var persister = entry.getPersister(); return tracker.$$_hibernate_hasDirtyAttributes() || persister.hasMutableProperties() ? resolveDirtyAttributeIndex( tracker, event, persister, entry ) : EMPTY_INT_ARRAY; } private static int[] resolveDirtyAttributeIndex( SelfDirtinessTracker tracker, FlushEntityEvent event, EntityPersister persister, EntityEntry entry) { return persister.resolveDirtyAttributeIndexes( event.getPropertyValues(), entry.getLoadedState(), tracker.$$_hibernate_getDirtyAttributes(), event.getSession() ); } private static
DirtyCheckContextImpl
java
quarkusio__quarkus
extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/jdbc/QuarkusObjectInputStream.java
{ "start": 261, "end": 531 }
class ____ extends ObjectInputStream { public QuarkusObjectInputStream(InputStream in) throws IOException { super(in); } /** * We override the {@link ObjectInputStream#resolveClass(ObjectStreamClass)} method to workaround a
QuarkusObjectInputStream
java
google__dagger
javatests/dagger/internal/codegen/ComponentProcessorTest.java
{ "start": 48555, "end": 48751 }
class ____ {", " @Inject", " NoInjectMemberWithConstructor() {}", " }", "", " public abstract static
NoInjectMemberWithConstructor
java
apache__camel
components/camel-whatsapp/src/main/java/org/apache/camel/component/whatsapp/model/Phone.java
{ "start": 917, "end": 1533 }
class ____ { private String phone; /** * Standard Values: CELL, MAIN, IPHONE, HOME, WORK */ private String type; @JsonProperty("wa_id") private String waId; public Phone() { } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getWaId() { return waId; } public void setWaId(String waId) { this.waId = waId; } }
Phone
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/util/ProcessIdFileReader.java
{ "start": 1306, "end": 3411 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(ProcessIdFileReader.class); /** * Get the process id from specified file path. * Parses each line to find a valid number * and returns the first one found. * @return Process Id if obtained from path specified else null * @throws IOException */ public static String getProcessId(Path path) throws IOException { if (path == null) { throw new IOException("Trying to access process id from a null path"); } LOG.debug("Accessing pid from pid file {}", path); String processId = null; BufferedReader bufReader = null; try { File file = new File(path.toString()); if (file.exists()) { FileInputStream fis = new FileInputStream(file); bufReader = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8)); while (true) { String line = bufReader.readLine(); if (line == null) { break; } String temp = line.trim(); if (!temp.isEmpty()) { if (Shell.WINDOWS) { // On Windows, pid is expected to be a container ID, so find first // line that parses successfully as a container ID. try { ContainerId.fromString(temp); processId = temp; break; } catch (Exception e) { // do nothing } } else { // Otherwise, find first line containing a numeric pid. try { long pid = Long.parseLong(temp); if (pid > 0) { processId = temp; break; } } catch (Exception e) { // do nothing } } } } } } finally { if (bufReader != null) { bufReader.close(); } } LOG.debug("Got pid {} from path {}", (processId != null ? processId : "null"), path); return processId; } }
ProcessIdFileReader
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/TopDoubleAggregatorFunctionSupplier.java
{ "start": 648, "end": 1779 }
class ____ implements AggregatorFunctionSupplier { private final int limit; private final boolean ascending; public TopDoubleAggregatorFunctionSupplier(int limit, boolean ascending) { this.limit = limit; this.ascending = ascending; } @Override public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() { return TopDoubleAggregatorFunction.intermediateStateDesc(); } @Override public List<IntermediateStateDesc> groupingIntermediateStateDesc() { return TopDoubleGroupingAggregatorFunction.intermediateStateDesc(); } @Override public TopDoubleAggregatorFunction aggregator(DriverContext driverContext, List<Integer> channels) { return TopDoubleAggregatorFunction.create(driverContext, channels, limit, ascending); } @Override public TopDoubleGroupingAggregatorFunction groupingAggregator(DriverContext driverContext, List<Integer> channels) { return TopDoubleGroupingAggregatorFunction.create(channels, driverContext, limit, ascending); } @Override public String describe() { return "top of doubles"; } }
TopDoubleAggregatorFunctionSupplier
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/http/codec/json/CustomizedJacksonJsonEncoderTests.java
{ "start": 1244, "end": 2649 }
class ____ extends AbstractEncoderTests<JacksonJsonEncoder> { CustomizedJacksonJsonEncoderTests() { super(new JacksonJsonEncoderWithCustomization()); } @Override public void canEncode() throws Exception { // Not Testing, covered under JacksonJsonEncoderTests } @Test @Override public void encode() throws Exception { Flux<MyCustomizedEncoderBean> input = Flux.just( new MyCustomizedEncoderBean(MyCustomEncoderEnum.VAL1), new MyCustomizedEncoderBean(MyCustomEncoderEnum.VAL2) ); testEncodeAll(input, ResolvableType.forClass(MyCustomizedEncoderBean.class), APPLICATION_NDJSON, null, step -> step .consumeNextWith(expectString("{\"property\":\"Value1\"}\n")) .consumeNextWith(expectString("{\"property\":\"Value2\"}\n")) .verifyComplete() ); } @Test void encodeNonStream() { Flux<MyCustomizedEncoderBean> input = Flux.just( new MyCustomizedEncoderBean(MyCustomEncoderEnum.VAL1), new MyCustomizedEncoderBean(MyCustomEncoderEnum.VAL2) ); testEncode(input, MyCustomizedEncoderBean.class, step -> step .consumeNextWith(expectString("[{\"property\":\"Value1\"}").andThen(DataBufferUtils::release)) .consumeNextWith(expectString(",{\"property\":\"Value2\"}").andThen(DataBufferUtils::release)) .consumeNextWith(expectString("]").andThen(DataBufferUtils::release)) .verifyComplete()); } private static
CustomizedJacksonJsonEncoderTests
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/cluster/pubsub/api/async/RedisClusterPubSubAsyncCommands.java
{ "start": 558, "end": 3764 }
interface ____<K, V> extends RedisPubSubAsyncCommands<K, V> { /** * @return the underlying connection. */ StatefulRedisClusterPubSubConnection<K, V> getStatefulConnection(); /** * Select all upstream nodes. * * @return API with asynchronous executed commands on a selection of upstream cluster nodes. * @deprecated since 6.0 in favor of {@link #upstream()}. */ @Deprecated default PubSubAsyncNodeSelection<K, V> masters() { return nodes(redisClusterNode -> redisClusterNode.is(RedisClusterNode.NodeFlag.UPSTREAM)); } /** * Select all upstream nodes. * * @return API with asynchronous executed commands on a selection of upstream cluster nodes. */ default PubSubAsyncNodeSelection<K, V> upstream() { return nodes(redisClusterNode -> redisClusterNode.is(RedisClusterNode.NodeFlag.UPSTREAM)); } /** * Select all replicas. * * @return API with asynchronous executed commands on a selection of replica cluster nodes. * @deprecated since 5.2, use {@link #replicas()} */ @Deprecated default PubSubAsyncNodeSelection<K, V> slaves() { return nodes(redisClusterNode -> redisClusterNode.is(RedisClusterNode.NodeFlag.REPLICA)); } /** * Select all replicas. * * @param predicate Predicate to filter nodes * @return API with asynchronous executed commands on a selection of replica cluster nodes. * @deprecated since 5.2, use {@link #replicas(Predicate)} */ @Deprecated default PubSubAsyncNodeSelection<K, V> slaves(Predicate<RedisClusterNode> predicate) { return nodes( redisClusterNode -> predicate.test(redisClusterNode) && redisClusterNode.is(RedisClusterNode.NodeFlag.REPLICA)); } /** * Select all replicas. * * @return API with asynchronous executed commands on a selection of replica cluster nodes. * @since 5.2 */ @Deprecated default PubSubAsyncNodeSelection<K, V> replicas() { return nodes(redisClusterNode -> redisClusterNode.is(RedisClusterNode.NodeFlag.REPLICA)); } /** * Select all replicas. * * @param predicate Predicate to filter nodes * @return API with asynchronous executed commands on a selection of replica cluster nodes. * @since 5.2 */ default PubSubAsyncNodeSelection<K, V> replicas(Predicate<RedisClusterNode> predicate) { return nodes( redisClusterNode -> predicate.test(redisClusterNode) && redisClusterNode.is(RedisClusterNode.NodeFlag.REPLICA)); } /** * Select all known cluster nodes. * * @return API with asynchronous executed commands on a selection of all cluster nodes. */ default PubSubAsyncNodeSelection<K, V> all() { return nodes(redisClusterNode -> true); } /** * Select nodes by a predicate. * * @param predicate Predicate to filter nodes * @return API with asynchronous executed commands on a selection of cluster nodes matching {@code predicate} */ PubSubAsyncNodeSelection<K, V> nodes(Predicate<RedisClusterNode> predicate); }
RedisClusterPubSubAsyncCommands
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestFastNumberFormat.java
{ "start": 1052, "end": 1764 }
class ____ { private final int MIN_DIGITS = 6; @Test @Timeout(value = 1) public void testLongWithPadding() throws Exception { NumberFormat numberFormat = NumberFormat.getInstance(); numberFormat.setGroupingUsed(false); numberFormat.setMinimumIntegerDigits(6); long[] testLongs = {1, 23, 456, 7890, 12345, 678901, 2345689, 0, -0, -1, -23, -456, -7890, -12345, -678901, -2345689}; for (long l: testLongs) { StringBuilder sb = new StringBuilder(); FastNumberFormat.format(sb, l, MIN_DIGITS); String fastNumberStr = sb.toString(); assertEquals( numberFormat.format(l), fastNumberStr, "Number formats should be equal"); } } }
TestFastNumberFormat
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/docker/transport/HttpClientTransport.java
{ "start": 6764, "end": 7976 }
class ____ extends AbstractHttpEntity { private final IOConsumer<OutputStream> writer; WritableHttpEntity(String contentType, IOConsumer<OutputStream> writer) { super(contentType, "UTF-8"); this.writer = writer; } @Override public boolean isRepeatable() { return false; } @Override public long getContentLength() { if (this.getContentType() != null && this.getContentType().equals("application/json")) { return calculateStringContentLength(); } return -1; } @Override public InputStream getContent() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void writeTo(OutputStream outputStream) throws IOException { this.writer.accept(outputStream); } @Override public boolean isStreaming() { return true; } private int calculateStringContentLength() { try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); this.writer.accept(bytes); return bytes.toByteArray().length; } catch (IOException ex) { return -1; } } @Override public void close() throws IOException { } } /** * An HTTP operation response. */ private static
WritableHttpEntity
java
quarkusio__quarkus
extensions/oidc-client-filter/deployment/src/test/java/io/quarkus/oidc/client/filter/OidcClientFilterRevokedAccessTokenDevModeTest.java
{ "start": 3184, "end": 3371 }
interface ____ extends MyClient { } @RegisterRestClient @RegisterProvider(value = DefaultClientRefreshDisabled.class) @Path(MY_SERVER_RESOURCE_PATH) public
MyNamedClient
java
square__retrofit
retrofit/src/main/java/retrofit2/CompletableFutureCallAdapterFactory.java
{ "start": 2297, "end": 2842 }
class ____<R> implements CallAdapter<R, CompletableFuture<R>> { private final Type responseType; BodyCallAdapter(Type responseType) { this.responseType = responseType; } @Override public Type responseType() { return responseType; } @Override public CompletableFuture<R> adapt(final Call<R> call) { CompletableFuture<R> future = new CallCancelCompletableFuture<>(call); call.enqueue(new BodyCallback(future)); return future; } @IgnoreJRERequirement private
BodyCallAdapter
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2278/Issue2278MapperA.java
{ "start": 380, "end": 1031 }
interface ____ { Issue2278MapperA INSTANCE = Mappers.getMapper( Issue2278MapperA.class ); @Mapping( target = "detailsDTO", source = "details" ) @Mapping( target = "detailsDTO.fuelType", ignore = true ) CarDTO map(Car in); // checkout the Issue2278ReferenceMapper, the @InheritInverseConfiguration // is de-facto @Mapping( target = "details", source = "detailsDTO" ) @InheritInverseConfiguration @Mapping( target = "details.model", ignore = true ) @Mapping( target = "details.type", constant = "gto") @Mapping( target = "details.fuel", source = "detailsDTO.fuelType") Car map(CarDTO in);
Issue2278MapperA
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/TestHedgingRequestRMFailoverProxyProvider.java
{ "start": 1544, "end": 4580 }
class ____ { @Test public void testHedgingRequestProxyProvider() throws Exception { Configuration conf = new YarnConfiguration(); conf.setBoolean(YarnConfiguration.RM_HA_ENABLED, true); conf.setBoolean(YarnConfiguration.AUTO_FAILOVER_ENABLED, false); conf.set(YarnConfiguration.RM_CLUSTER_ID, "cluster1"); conf.set(YarnConfiguration.RM_HA_IDS, "rm1,rm2,rm3,rm4,rm5"); conf.set(YarnConfiguration.CLIENT_FAILOVER_PROXY_PROVIDER, RequestHedgingRMFailoverProxyProvider.class.getName()); conf.setLong(YarnConfiguration.RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_MS, 2000); try (MiniYARNCluster cluster = new MiniYARNCluster("testHedgingRequestProxyProvider", 5, 0, 1, 1)) { HATestUtil.setRpcAddressForRM("rm1", 10000, conf); HATestUtil.setRpcAddressForRM("rm2", 20000, conf); HATestUtil.setRpcAddressForRM("rm3", 30000, conf); HATestUtil.setRpcAddressForRM("rm4", 40000, conf); HATestUtil.setRpcAddressForRM("rm5", 50000, conf); conf.setBoolean(YarnConfiguration.YARN_MINICLUSTER_FIXED_PORTS, true); cluster.init(conf); cluster.start(); final YarnClient client = YarnClient.createYarnClient(); client.init(conf); client.start(); // Transition rm5 to active; long start = System.currentTimeMillis(); makeRMActive(cluster, 4); validateActiveRM(client); long end = System.currentTimeMillis(); System.out.println("Client call succeeded at " + end); // should return the response fast assertTrue(end - start <= 10000); // transition rm5 to standby cluster.getResourceManager(4).getRMContext().getRMAdminService() .transitionToStandby(new HAServiceProtocol.StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER)); makeRMActive(cluster, 2); validateActiveRM(client); } } private void validateActiveRM(YarnClient client) throws IOException { // first check if exception is thrown correctly; try { // client will retry until the rm becomes active. client.getApplicationReport(null); fail(); } catch (YarnException e) { assertTrue(e instanceof ApplicationNotFoundException); } // now make a valid call. try { client.getAllQueues(); } catch (YarnException e) { fail(e.toString()); } } private void makeRMActive(final MiniYARNCluster cluster, final int index) { SubjectInheritingThread t = new SubjectInheritingThread() { @Override public void work() { try { System.out.println("Transition rm" + index + " to active"); cluster.getResourceManager(index).getRMContext().getRMAdminService() .transitionToActive(new HAServiceProtocol.StateChangeRequestInfo( HAServiceProtocol.RequestSource.REQUEST_BY_USER)); } catch (Exception e) { e.printStackTrace(); } } }; t.start(); } }
TestHedgingRequestRMFailoverProxyProvider
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/WallSelectWhereTest0.java
{ "start": 794, "end": 1128 }
class ____ extends TestCase { private String sql = "SELECT F1, F2 from t WHERE 1 = 1 AND F1 = ?"; public void testMySql() throws Exception { assertTrue(WallUtils.isValidateMySql(sql)); } public void testORACLE() throws Exception { assertTrue(WallUtils.isValidateOracle(sql)); } }
WallSelectWhereTest0
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/json/JsonConfiguration.java
{ "start": 11225, "end": 11344 }
enum ____ { CLASS_NOT_FOUND } /** * Status for recording errors. */ private static
ErrorType
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/type/JavaTypeTest.java
{ "start": 696, "end": 743 }
class ____ extends BaseType { } static
SubType
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1320/Issue1320Mapper.java
{ "start": 369, "end": 677 }
interface ____ { Issue1320Mapper INSTANCE = Mappers.getMapper( Issue1320Mapper.class ); @Mappings({ @Mapping(target = "address.city.cityName", constant = "myCity"), @Mapping(target = "address.city.stateName", constant = "myState") }) Target map(Integer dummy); }
Issue1320Mapper
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hbm/inheritance/CatName.java
{ "start": 150, "end": 406 }
class ____ { private long id; private String name; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
CatName
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/LprComponentBuilderFactory.java
{ "start": 1358, "end": 1783 }
interface ____ { /** * Printer (camel-printer) * Send print jobs to printers. * * Category: document * Since: 2.1 * Maven coordinates: org.apache.camel:camel-printer * * @return the dsl builder */ static LprComponentBuilder lpr() { return new LprComponentBuilderImpl(); } /** * Builder for the Printer component. */
LprComponentBuilderFactory
java
spring-projects__spring-boot
core/spring-boot-test/src/main/java/org/springframework/boot/test/context/filter/annotation/TypeIncludes.java
{ "start": 1472, "end": 2377 }
class ____ implements Iterable<Class<?>> { private static final String LOCATION = "META-INF/spring/%s.includes"; private static final String COMMENT_START = "#"; private final Set<Class<?>> includes; private TypeIncludes(Set<Class<?>> includes) { Assert.notNull(includes, "'includes' must not be null"); this.includes = Collections.unmodifiableSet(includes); } @Override public Iterator<Class<?>> iterator() { return this.includes.iterator(); } Set<Class<?>> getIncludes() { return this.includes; } /** * Loads the includes from the classpath. The names of the includes are stored in * files named {@code META-INF/spring/fully-qualified-annotation-name.includes} on the * classpath. Every line contains the fully qualified name of the included class. * Comments are supported using the # character. * @param annotation annotation to load * @param classLoader
TypeIncludes
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/errors/StreamsInvalidTopologyException.java
{ "start": 847, "end": 1001 }
class ____ extends ApiException { public StreamsInvalidTopologyException(String message) { super(message); } }
StreamsInvalidTopologyException
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/jdbc/JdbcTypeIndicators.java
{ "start": 829, "end": 1429 }
interface ____ { int NO_COLUMN_LENGTH = -1; int NO_COLUMN_PRECISION = -1; int NO_COLUMN_SCALE = -1; /** * Was nationalized character datatype requested for the given Java type? * * @return {@code true} if nationalized character datatype should be used; * {@code false} otherwise. */ default boolean isNationalized() { return false; } /** * Was LOB datatype requested for the given Java type? * * @return {@code true} if LOB datatype should be used; * {@code false} otherwise. */ default boolean isLob() { return false; } /** * For
JdbcTypeIndicators
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/io/DefaultVFS.java
{ "start": 3832, "end": 12043 }
class ____ * as a child of the current resource. If any line fails then we assume the current resource is not a * directory. */ is = url.openStream(); List<String> lines = new ArrayList<>(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { for (String line; (line = reader.readLine()) != null;) { if (log.isDebugEnabled()) { log.debug("Reader entry: " + line); } lines.add(line); if (getResources(path + "/" + line).isEmpty()) { lines.clear(); break; } } } catch (InvalidPathException | FileSystemException e) { // #1974 #2598 lines.clear(); } if (!lines.isEmpty()) { if (log.isDebugEnabled()) { log.debug("Listing " + url); } children.addAll(lines); } } } catch (FileNotFoundException e) { /* * For file URLs the openStream() call might fail, depending on the servlet container, because directories * can't be opened for reading. If that happens, then list the directory directly instead. */ if (!"file".equals(url.getProtocol())) { // No idea where the exception came from so rethrow it throw e; } File file = Path.of(url.getFile()).toFile(); if (log.isDebugEnabled()) { log.debug("Listing directory " + file.getAbsolutePath()); } if (Files.isDirectory(file.toPath())) { if (log.isDebugEnabled()) { log.debug("Listing " + url); } children = Arrays.asList(file.list()); } } // The URL prefix to use when recursively listing child resources String prefix = url.toExternalForm(); if (!prefix.endsWith("/")) { prefix = prefix + "/"; } // Iterate over immediate children, adding files and recurring into directories for (String child : children) { String resourcePath = path + "/" + child; resources.add(resourcePath); URL childUrl = new URL(prefix + child); resources.addAll(list(childUrl, resourcePath)); } } return resources; } finally { if (is != null) { try { is.close(); } catch (Exception e) { // Ignore } } } } /** * List the names of the entries in the given {@link JarInputStream} that begin with the specified {@code path}. * Entries will match with or without a leading slash. * * @param jar * The JAR input stream * @param path * The leading path to match * * @return The names of all the matching entries * * @throws IOException * If I/O errors occur */ protected List<String> listResources(JarInputStream jar, String path) throws IOException { // Include the leading and trailing slash when matching names if (!path.startsWith("/")) { path = "/" + path; } if (!path.endsWith("/")) { path = path + "/"; } // Iterate over the entries and collect those that begin with the requested path List<String> resources = new ArrayList<>(); for (JarEntry entry; (entry = jar.getNextJarEntry()) != null;) { if (!entry.isDirectory()) { // Add leading slash if it's missing StringBuilder name = new StringBuilder(entry.getName()); if (name.charAt(0) != '/') { name.insert(0, '/'); } // Check file name if (name.indexOf(path) == 0) { if (log.isDebugEnabled()) { log.debug("Found resource: " + name); } // Trim leading slash resources.add(name.substring(1)); } } } return resources; } /** * Attempts to deconstruct the given URL to find a JAR file containing the resource referenced by the URL. That is, * assuming the URL references a JAR entry, this method will return a URL that references the JAR file containing the * entry. If the JAR cannot be located, then this method returns null. * * @param url * The URL of the JAR entry. * * @return The URL of the JAR file, if one is found. Null if not. * * @throws MalformedURLException * the malformed URL exception */ protected URL findJarForResource(URL url) throws MalformedURLException { if (log.isDebugEnabled()) { log.debug("Find JAR URL: " + url); } // If the file part of the URL is itself a URL, then that URL probably points to the JAR boolean continueLoop = true; while (continueLoop) { try { url = new URL(url.getFile()); if (log.isDebugEnabled()) { log.debug("Inner URL: " + url); } } catch (MalformedURLException e) { // This will happen at some point and serves as a break in the loop continueLoop = false; } } // Look for the .jar extension and chop off everything after that StringBuilder jarUrl = new StringBuilder(url.toExternalForm()); int index = jarUrl.lastIndexOf(".jar"); if (index < 0) { if (log.isDebugEnabled()) { log.debug("Not a JAR: " + jarUrl); } return null; } jarUrl.setLength(index + 4); if (log.isDebugEnabled()) { log.debug("Extracted JAR URL: " + jarUrl); } // Try to open and test it try { URL testUrl = new URL(jarUrl.toString()); if (isJar(testUrl)) { return testUrl; } // WebLogic fix: check if the URL's file exists in the filesystem. if (log.isDebugEnabled()) { log.debug("Not a JAR: " + jarUrl); } jarUrl.replace(0, jarUrl.length(), testUrl.getFile()); File file = Path.of(jarUrl.toString()).toFile(); // File name might be URL-encoded if (!file.exists()) { file = Path.of(URLEncoder.encode(jarUrl.toString(), StandardCharsets.UTF_8)).toFile(); } if (file.exists()) { if (log.isDebugEnabled()) { log.debug("Trying real file: " + file.getAbsolutePath()); } testUrl = file.toURI().toURL(); if (isJar(testUrl)) { return testUrl; } } } catch (MalformedURLException e) { log.warn("Invalid JAR URL: " + jarUrl); } if (log.isDebugEnabled()) { log.debug("Not a JAR: " + jarUrl); } return null; } /** * Converts a Java package name to a path that can be looked up with a call to * {@link ClassLoader#getResources(String)}. * * @param packageName * The Java package name to convert to a path * * @return the package path */ protected String getPackagePath(String packageName) { return packageName == null ? null : packageName.replace('.', '/'); } /** * Returns true if the resource located at the given URL is a JAR file. * * @param url * The URL of the resource to test. * * @return true, if is jar */ protected boolean isJar(URL url) { return isJar(url, new byte[JAR_MAGIC.length]); } /** * Returns true if the resource located at the given URL is a JAR file. * * @param url * The URL of the resource to test. * @param buffer * A buffer into which the first few bytes of the resource are read. The buffer must be at least the size of * {@link #JAR_MAGIC}. (The same buffer may be reused for multiple calls as an optimization.) * * @return true, if is jar */ protected boolean isJar(URL url, byte[] buffer) { try (InputStream is = url.openStream()) { is.read(buffer, 0, JAR_MAGIC.length); if (Arrays.equals(buffer, JAR_MAGIC)) { if (log.isDebugEnabled()) { log.debug("Found JAR: " + url); } return true; } } catch (Exception e) { // Failure to read the stream means this is not a JAR } return false; } }
loader
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecTableSourceScan.java
{ "start": 2767, "end": 8052 }
class ____ extends CommonExecTableSourceScan implements BatchExecNode<RowData> { // Avoids creating different ids if translated multiple times private final String dynamicFilteringDataListenerID = UUID.randomUUID().toString(); private final ReadableConfig tableConfig; // This constructor can be used only when table source scan has // BatchExecDynamicFilteringDataCollector input public BatchExecTableSourceScan( ReadableConfig tableConfig, DynamicTableSourceSpec tableSourceSpec, InputProperty inputProperty, RowType outputType, String description) { super( ExecNodeContext.newNodeId(), ExecNodeContext.newContext(BatchExecTableSourceScan.class), ExecNodeContext.newPersistedConfig(BatchExecTableSourceScan.class, tableConfig), tableSourceSpec, Collections.singletonList(inputProperty), outputType, description); this.tableConfig = tableConfig; } public BatchExecTableSourceScan( ReadableConfig tableConfig, DynamicTableSourceSpec tableSourceSpec, RowType outputType, String description) { super( ExecNodeContext.newNodeId(), ExecNodeContext.newContext(BatchExecTableSourceScan.class), ExecNodeContext.newPersistedConfig(BatchExecTableSourceScan.class, tableConfig), tableSourceSpec, Collections.emptyList(), outputType, description); this.tableConfig = tableConfig; } @JsonCreator public BatchExecTableSourceScan( @JsonProperty(FIELD_NAME_ID) int id, @JsonProperty(FIELD_NAME_TYPE) ExecNodeContext context, @JsonProperty(FIELD_NAME_CONFIGURATION) ReadableConfig tableConfig, @JsonProperty(FIELD_NAME_SCAN_TABLE_SOURCE) DynamicTableSourceSpec tableSourceSpec, @JsonProperty(FIELD_NAME_OUTPUT_TYPE) RowType outputType, @JsonProperty(FIELD_NAME_DESCRIPTION) String description) { super( id, context, tableConfig, tableSourceSpec, Collections.emptyList(), outputType, description); this.tableConfig = tableConfig; } public String getDynamicFilteringDataListenerID() { return dynamicFilteringDataListenerID; } @Override protected Transformation<RowData> translateToPlanInternal( PlannerBase planner, ExecNodeConfig config) { final Transformation<RowData> transformation = super.translateToPlanInternal(planner, config); // the boundedness has been checked via the runtime provider already, so we can safely // declare all legacy transformations as bounded to make the stream graph generator happy ExecNodeUtil.makeLegacySourceTransformationsBounded(transformation); return transformation; } public static BatchExecDynamicFilteringDataCollector getDynamicFilteringDataCollector( BatchExecNode<?> node) { Preconditions.checkState( node.getInputEdges().size() == 1, "The fact source must have one " + "input representing dynamic filtering data collector"); BatchExecNode<?> input = (BatchExecNode<?>) node.getInputEdges().get(0).getSource(); if (input instanceof BatchExecDynamicFilteringDataCollector) { return (BatchExecDynamicFilteringDataCollector) input; } Preconditions.checkState( input instanceof BatchExecExchange, "There could only be BatchExecExchange " + "between fact source and dynamic filtering data collector"); return getDynamicFilteringDataCollector(input); } @Override public Transformation<RowData> createInputFormatTransformation( StreamExecutionEnvironment env, InputFormat<RowData, ?> inputFormat, InternalTypeInfo<RowData> outputTypeInfo, String operatorName) { // env.createInput will use ContinuousFileReaderOperator, but it do not support multiple // paths. If read partitioned source, after partition pruning, we need let InputFormat // to read multiple partitions which are multiple paths. // We can use InputFormatSourceFunction directly to support InputFormat. final InputFormatSourceFunction<RowData> function = new InputFormatSourceFunction<>(inputFormat, outputTypeInfo); return env.addSource(function, operatorName, outputTypeInfo).getTransformation(); } public BatchExecTableSourceScan copyAndRemoveInputs() { BatchExecTableSourceScan tableSourceScan = new BatchExecTableSourceScan( tableConfig, getTableSourceSpec(), (RowType) getOutputType(), getDescription()); tableSourceScan.setInputEdges(Collections.emptyList()); return tableSourceScan; } }
BatchExecTableSourceScan
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/test/engine/ThrowingLeafReaderWrapper.java
{ "start": 4599, "end": 6562 }
class ____ extends FilterTermsEnum { private final Thrower thrower; ThrowingTermsEnum(TermsEnum in, Thrower thrower) { super(in); this.thrower = thrower; } @Override public PostingsEnum postings(PostingsEnum reuse, int flags) throws IOException { if ((flags & PostingsEnum.POSITIONS) != 0) { thrower.maybeThrow(Flags.DocsAndPositionsEnum); } else { thrower.maybeThrow(Flags.DocsEnum); } return super.postings(reuse, flags); } } @Override public NumericDocValues getNumericDocValues(String field) throws IOException { thrower.maybeThrow(Flags.NumericDocValues); return super.getNumericDocValues(field); } @Override public BinaryDocValues getBinaryDocValues(String field) throws IOException { thrower.maybeThrow(Flags.BinaryDocValues); return super.getBinaryDocValues(field); } @Override public SortedDocValues getSortedDocValues(String field) throws IOException { thrower.maybeThrow(Flags.SortedDocValues); return super.getSortedDocValues(field); } @Override public SortedSetDocValues getSortedSetDocValues(String field) throws IOException { thrower.maybeThrow(Flags.SortedSetDocValues); return super.getSortedSetDocValues(field); } @Override public NumericDocValues getNormValues(String field) throws IOException { thrower.maybeThrow(Flags.Norms); return super.getNormValues(field); } @Override public CacheHelper getCoreCacheHelper() { return in.getCoreCacheHelper(); } @Override public CacheHelper getReaderCacheHelper() { return in.getReaderCacheHelper(); } @Override protected StoredFieldsReader doGetSequentialStoredFieldsReader(StoredFieldsReader reader) { return reader; } }
ThrowingTermsEnum
java
apache__camel
components/camel-ai/camel-openai/src/main/java/org/apache/camel/component/openai/OpenAIConstants.java
{ "start": 926, "end": 2304 }
class ____ { // Input Headers public static final String USER_MESSAGE = "CamelOpenAIUserMessage"; public static final String SYSTEM_MESSAGE = "CamelOpenAISystemMessage"; public static final String DEVELOPER_MESSAGE = "CamelOpenAIDeveloperMessage"; public static final String MODEL = "CamelOpenAIModel"; public static final String TEMPERATURE = "CamelOpenAITemperature"; public static final String TOP_P = "CamelOpenAITopP"; public static final String MAX_TOKENS = "CamelOpenAIMaxTokens"; public static final String STREAMING = "CamelOpenAIStreaming"; public static final String OUTPUT_CLASS = "CamelOpenAIOutputClass"; public static final String JSON_SCHEMA = "CamelOpenAIJsonSchema"; // Output Headers public static final String RESPONSE_MODEL = "CamelOpenAIResponseModel"; public static final String RESPONSE_ID = "CamelOpenAIResponseId"; public static final String FINISH_REASON = "CamelOpenAIFinishReason"; public static final String PROMPT_TOKENS = "CamelOpenAIPromptTokens"; public static final String COMPLETION_TOKENS = "CamelOpenAICompletionTokens"; public static final String TOTAL_TOKENS = "CamelOpenAITotalTokens"; // Output Exchange Properties public static final String RESPONSE = "CamelOpenAIResponse"; private OpenAIConstants() { // Utility class } }
OpenAIConstants
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/datatransfer/DataTransferProtocol.java
{ "start": 1762, "end": 9982 }
interface ____ { Logger LOG = LoggerFactory.getLogger(DataTransferProtocol.class); /** Version for data transfers between clients and datanodes * This should change when serialization of DatanodeInfo, not just * when protocol changes. It is not very obvious. */ /* * Version 28: * Declare methods in DataTransferProtocol interface. */ int DATA_TRANSFER_VERSION = 28; /** * Read a block. * * @param blk the block being read. * @param blockToken security token for accessing the block. * @param clientName client's name. * @param blockOffset offset of the block. * @param length maximum number of bytes for this read. * @param sendChecksum if false, the DN should skip reading and sending * checksums * @param cachingStrategy The caching strategy to use. */ void readBlock(final ExtendedBlock blk, final Token<BlockTokenIdentifier> blockToken, final String clientName, final long blockOffset, final long length, final boolean sendChecksum, final CachingStrategy cachingStrategy) throws IOException; /** * Write a block to a datanode pipeline. * The receiver datanode of this call is the next datanode in the pipeline. * The other downstream datanodes are specified by the targets parameter. * Note that the receiver {@link DatanodeInfo} is not required in the * parameter list since the receiver datanode knows its info. However, the * {@link StorageType} for storing the replica in the receiver datanode is a * parameter since the receiver datanode may support multiple storage types. * * @param blk the block being written. * @param storageType for storing the replica in the receiver datanode. * @param blockToken security token for accessing the block. * @param clientName client's name. * @param targets other downstream datanodes in the pipeline. * @param targetStorageTypes target {@link StorageType}s corresponding * to the target datanodes. * @param source source datanode. * @param stage pipeline stage. * @param pipelineSize the size of the pipeline. * @param minBytesRcvd minimum number of bytes received. * @param maxBytesRcvd maximum number of bytes received. * @param latestGenerationStamp the latest generation stamp of the block. * @param requestedChecksum the requested checksum mechanism * @param cachingStrategy the caching strategy * @param allowLazyPersist hint to the DataNode that the block can be * allocated on transient storage i.e. memory and * written to disk lazily * @param pinning whether to pin the block, so Balancer won't move it. * @param targetPinnings whether to pin the block on target datanode * @param storageID optional StorageIDs designating where to write the * block. An empty String or null indicates that this * has not been provided. * @param targetStorageIDs target StorageIDs corresponding to the target * datanodes. */ void writeBlock(final ExtendedBlock blk, final StorageType storageType, final Token<BlockTokenIdentifier> blockToken, final String clientName, final DatanodeInfo[] targets, final StorageType[] targetStorageTypes, final DatanodeInfo source, final BlockConstructionStage stage, final int pipelineSize, final long minBytesRcvd, final long maxBytesRcvd, final long latestGenerationStamp, final DataChecksum requestedChecksum, final CachingStrategy cachingStrategy, final boolean allowLazyPersist, final boolean pinning, final boolean[] targetPinnings, final String storageID, final String[] targetStorageIDs) throws IOException; /** * Transfer a block to another datanode. * The block stage must be * either {@link BlockConstructionStage#TRANSFER_RBW} * or {@link BlockConstructionStage#TRANSFER_FINALIZED}. * * @param blk the block being transferred. * @param blockToken security token for accessing the block. * @param clientName client's name. * @param targets target datanodes. * @param targetStorageIDs StorageID designating where to write the * block. */ void transferBlock(final ExtendedBlock blk, final Token<BlockTokenIdentifier> blockToken, final String clientName, final DatanodeInfo[] targets, final StorageType[] targetStorageTypes, final String[] targetStorageIDs) throws IOException; /** * Request short circuit access file descriptors from a DataNode. * * @param blk The block to get file descriptors for. * @param blockToken Security token for accessing the block. * @param slotId The shared memory slot id to use, or null * to use no slot id. * @param maxVersion Maximum version of the block data the client * can understand. * @param supportsReceiptVerification True if the client supports * receipt verification. */ void requestShortCircuitFds(final ExtendedBlock blk, final Token<BlockTokenIdentifier> blockToken, SlotId slotId, int maxVersion, boolean supportsReceiptVerification) throws IOException; /** * Release a pair of short-circuit FDs requested earlier. * * @param slotId SlotID used by the earlier file descriptors. */ void releaseShortCircuitFds(final SlotId slotId) throws IOException; /** * Request a short circuit shared memory area from a DataNode. * * @param clientName The name of the client. */ void requestShortCircuitShm(String clientName) throws IOException; /** * Receive a block from a source datanode * and then notifies the namenode * to remove the copy from the original datanode. * Note that the source datanode and the original datanode can be different. * It is used for balancing purpose. * * @param blk the block being replaced. * @param storageType the {@link StorageType} for storing the block. * @param blockToken security token for accessing the block. * @param delHint the hint for deleting the block in the original datanode. * @param source the source datanode for receiving the block. * @param storageId an optional storage ID to designate where the block is * replaced to. */ void replaceBlock(final ExtendedBlock blk, final StorageType storageType, final Token<BlockTokenIdentifier> blockToken, final String delHint, final DatanodeInfo source, final String storageId) throws IOException; /** * Copy a block. * It is used for balancing purpose. * * @param blk the block being copied. * @param blockToken security token for accessing the block. */ void copyBlock(final ExtendedBlock blk, final Token<BlockTokenIdentifier> blockToken) throws IOException; /** * Get block checksum (MD5 of CRC32). * * @param blk a block. * @param blockToken security token for accessing the block. * @param blockChecksumOptions determines how the block-level checksum is * computed from underlying block metadata. * @throws IOException */ void blockChecksum(ExtendedBlock blk, Token<BlockTokenIdentifier> blockToken, BlockChecksumOptions blockChecksumOptions) throws IOException; /** * Get striped block group checksum (MD5 of CRC32). * * @param stripedBlockInfo a striped block info. * @param blockToken security token for accessing the block. * @param requestedNumBytes requested number of bytes in the block group * to compute the checksum. * @param blockChecksumOptions determines how the block-level checksum is * computed from underlying block metadata. * @throws IOException */ void blockGroupChecksum(StripedBlockInfo stripedBlockInfo, Token<BlockTokenIdentifier> blockToken, long requestedNumBytes, BlockChecksumOptions blockChecksumOptions) throws IOException; }
DataTransferProtocol
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/OptionalIdentifiedDefinition.java
{ "start": 1578, "end": 7095 }
class ____<T extends OptionalIdentifiedDefinition<T>> implements NamedNode, IdAware, CamelContextAware { private CamelContext camelContext; private String id; private Boolean customId; private String description; private String note; private int lineNumber = -1; private String location; protected OptionalIdentifiedDefinition() { } protected OptionalIdentifiedDefinition(OptionalIdentifiedDefinition<?> source) { this.camelContext = source.camelContext; this.id = source.id; this.customId = source.customId; this.description = source.description; this.note = source.note; this.lineNumber = source.lineNumber; this.location = source.location; } @Override public CamelContext getCamelContext() { return camelContext; } @Override @XmlTransient public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public String getId() { return id; } @Override public String getNodePrefixId() { // prefix is only for nodes in the route (not the route id) String prefix = null; boolean iAmRoute = this instanceof RouteDefinition; boolean allowPrefix = !iAmRoute; if (allowPrefix) { RouteDefinition route = ProcessorDefinitionHelper.getRoute(this); if (route != null) { prefix = route.getNodePrefixId(); } } return prefix; } /** * Sets the id of this node */ @XmlAttribute @Metadata(description = "The id of this node") public void setId(String id) { this.id = id; customId = id != null ? true : null; } @Override public void setGeneratedId(String id) { this.id = id; customId = null; } public String getDescription() { return description; } /** * Sets the description of this node * * @param description sets the text description, use null to not set a text */ @XmlAttribute @Metadata(description = "The description for this node") public void setDescription(String description) { this.description = description; } public String getNote() { return note; } /** * Sets the note of this node * * @param note sets the text note, use null to not set a text */ @XmlAttribute @Metadata(description = "The note for this node") public void setNote(String note) { this.note = note; } @Override public NamedNode getParent() { return null; } @Override public int getLineNumber() { return lineNumber; } @Override @XmlTransient public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; } @Override public String getLocation() { return location; } @Override @XmlTransient public void setLocation(String location) { this.location = location; } // Fluent API // ------------------------------------------------------------------------- /** * Sets the description of this node * * @param description sets the text description, use null to not set a text * @return the builder */ @SuppressWarnings("unchecked") public T description(String description) { this.description = description; return (T) this; } /** * Sets the note of this node * * @param note sets the text note, use null to not set a text * @return the builder */ @SuppressWarnings("unchecked") public T note(String note) { this.note = note; return (T) this; } /** * Sets the id of this node. * <p/> * <b>Important:</b> If you want to set the id of the route, then you <b>must</b> use <tt>routeId(String)</tt> * instead. * * @param id the id * @return the builder */ @SuppressWarnings("unchecked") public T id(String id) { setId(id); return (T) this; } /** * Gets the node id, creating one if not already set. */ public String idOrCreate(NodeIdFactory factory) { if (id == null) { setGeneratedId(factory.createId(this)); } // return with prefix if configured boolean iAmRoute = this instanceof RouteDefinition; boolean allowPrefix = !iAmRoute; if (allowPrefix) { String prefix = getNodePrefixId(); if (prefix != null) { return prefix + id; } } return id; } public Boolean getCustomId() { return customId; } /** * Whether the node id was explicit set, or was auto generated by Camel. */ @XmlAttribute public void setCustomId(Boolean customId) { this.customId = customId; } /** * Returns whether a custom id has been assigned */ public boolean hasCustomIdAssigned() { return customId != null && customId; } /** * Returns the description text or null if there is no description text associated with this node */ @Override public String getDescriptionText() { return description; } // Implementation methods // ------------------------------------------------------------------------- }
OptionalIdentifiedDefinition
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng0449PluginVersionResolutionTest.java
{ "start": 1906, "end": 3377 }
class ____ locks the artifacts so we can't delete them } verifier.addCliArgument("--settings"); verifier.addCliArgument("settings.xml"); verifier.filterFile("../settings-template.xml", "settings.xml"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); // Maven 3.x prefers RELEASE over LATEST (see MNG-4206) // Inline version check: (,3.0-alpha-3) - current Maven version doesn't match this range verifier.verifyFilePresent("target/touch-release.txt"); verifier.verifyFileNotPresent("target/touch-snapshot.txt"); verifier.verifyFilePresent("target/package.txt"); } /** * Verify that versions for plugins are automatically resolved if not given in the POM by checking LATEST and * RELEASE in the repo metadata when the plugin is invoked directly from the command line. * * @throws Exception in case of failure */ @Test public void testitCliInvocation() throws Exception { File testDir = extractResources("/mng-0449"); testDir = new File(testDir, "direct"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); try { verifier.deleteArtifacts("org.apache.maven.its.mng0449"); } catch (Exception e) { // when we run Maven embedded, the plugin
realm
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/rest/action/cat/RestTasksActionTests.java
{ "start": 1234, "end": 2649 }
class ____ extends ESTestCase { public void testConsumesParameters() throws Exception { RestTasksAction action = new RestTasksAction(() -> DiscoveryNodes.EMPTY_NODES); FakeRestRequest fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withParams( Map.of("parent_task_id", "the node:3", "nodes", "node1,node2", "actions", "*") ).build(); FakeRestChannel fakeRestChannel = new FakeRestChannel(fakeRestRequest, randomBoolean(), 1); try (var threadPool = createThreadPool()) { final var nodeClient = buildNodeClient(threadPool); action.handleRequest(fakeRestRequest, fakeRestChannel, nodeClient); } assertThat(fakeRestChannel.errors().get(), is(0)); assertThat(fakeRestChannel.responses().get(), is(1)); } private NoOpNodeClient buildNodeClient(ThreadPool threadPool) { return new NoOpNodeClient(threadPool) { @Override @SuppressWarnings("unchecked") public <Request extends ActionRequest, Response extends ActionResponse> void doExecute( ActionType<Response> action, Request request, ActionListener<Response> listener ) { listener.onResponse((Response) new ListTasksResponse(List.of(), List.of(), List.of())); } }; } }
RestTasksActionTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/columnoptions/AnotherTestEntity.java
{ "start": 514, "end": 562 }
class ____ extends TestEntity { }
AnotherTestEntity
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/streamrecord/StreamElementSerializer.java
{ "start": 12016, "end": 13154 }
class ____<T> extends CompositeTypeSerializerSnapshot<StreamElement, StreamElementSerializer<T>> { private static final int VERSION = 2; @SuppressWarnings("WeakerAccess") public StreamElementSerializerSnapshot() {} StreamElementSerializerSnapshot(StreamElementSerializer<T> serializerInstance) { super(serializerInstance); } @Override protected int getCurrentOuterSnapshotVersion() { return VERSION; } @Override protected TypeSerializer<?>[] getNestedSerializers( StreamElementSerializer<T> outerSerializer) { return new TypeSerializer[] {outerSerializer.getContainedTypeSerializer()}; } @Override protected StreamElementSerializer<T> createOuterSerializerWithNestedSerializers( TypeSerializer<?>[] nestedSerializers) { @SuppressWarnings("unchecked") TypeSerializer<T> casted = (TypeSerializer<T>) nestedSerializers[0]; return new StreamElementSerializer<>(casted); } } }
StreamElementSerializerSnapshot
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequest.java
{ "start": 1929, "end": 32886 }
class ____ implements MavenExecutionRequest { private RepositoryCache repositoryCache = new DefaultRepositoryCache(); private WorkspaceReader workspaceReader; private ArtifactRepository localRepository; private EventSpyDispatcher eventSpyDispatcher; private File localRepositoryPath; private boolean offline = false; private boolean interactiveMode = true; private boolean cacheTransferError = false; private boolean cacheNotFound = false; private boolean ignoreMissingArtifactDescriptor = true; private boolean ignoreInvalidArtifactDescriptor = true; private boolean ignoreTransitiveRepositories; private List<Proxy> proxies; private List<Server> servers; private List<Mirror> mirrors; private List<Profile> profiles; private final ProjectActivation projectActivation = new ProjectActivation(); private final ProfileActivation profileActivation = new ProfileActivation(); private List<String> pluginGroups; private boolean isProjectPresent = true; // ---------------------------------------------------------------------------- // We need to allow per execution user and global settings as the embedder // might be running in a mode where it's executing many threads with totally // different settings. // ---------------------------------------------------------------------------- private File userSettingsFile; private File projectSettingsFile; private File installationSettingsFile; private File userToolchainsFile; private File installationToolchainsFile; // ---------------------------------------------------------------------------- // Request // ---------------------------------------------------------------------------- private File multiModuleProjectDirectory; private File basedir; private Path rootDirectory; private Path topDirectory; private List<String> goals; private boolean useReactor = false; private boolean recursive = true; private File pom; private String reactorFailureBehavior = REACTOR_FAIL_FAST; private boolean resume = false; private String resumeFrom; private String makeBehavior; private Properties systemProperties; private Properties userProperties; private Instant startTime = MonotonicClock.now(); private boolean showErrors = false; private TransferListener transferListener; private int loggingLevel = LOGGING_LEVEL_INFO; private String globalChecksumPolicy; private boolean updateSnapshots = false; private List<ArtifactRepository> remoteRepositories; private List<ArtifactRepository> pluginArtifactRepositories; private ExecutionListener executionListener; private int degreeOfConcurrency = 1; private String builderId = "singlethreaded"; private Map<String, List<ToolchainModel>> toolchains; /** * Suppress SNAPSHOT updates. * * @issue MNG-2681 */ private boolean noSnapshotUpdates = false; private boolean useLegacyLocalRepositoryManager = false; private Map<String, Object> data; public DefaultMavenExecutionRequest() {} public static MavenExecutionRequest copy(MavenExecutionRequest original) { DefaultMavenExecutionRequest copy = new DefaultMavenExecutionRequest(); copy.setLocalRepository(original.getLocalRepository()); copy.setLocalRepositoryPath(original.getLocalRepositoryPath()); copy.setOffline(original.isOffline()); copy.setInteractiveMode(original.isInteractiveMode()); copy.setCacheNotFound(original.isCacheNotFound()); copy.setCacheTransferError(original.isCacheTransferError()); copy.setIgnoreMissingArtifactDescriptor(original.isIgnoreMissingArtifactDescriptor()); copy.setIgnoreInvalidArtifactDescriptor(original.isIgnoreInvalidArtifactDescriptor()); copy.setIgnoreTransitiveRepositories(original.isIgnoreTransitiveRepositories()); copy.setProxies(original.getProxies()); copy.setServers(original.getServers()); copy.setMirrors(original.getMirrors()); copy.setProfiles(original.getProfiles()); copy.setPluginGroups(original.getPluginGroups()); copy.setProjectPresent(original.isProjectPresent()); copy.setUserSettingsFile(original.getUserSettingsFile()); copy.setInstallationSettingsFile(original.getInstallationSettingsFile()); copy.setUserToolchainsFile(original.getUserToolchainsFile()); copy.setInstallationToolchainsFile(original.getInstallationToolchainsFile()); copy.setBaseDirectory((original.getBaseDirectory() != null) ? new File(original.getBaseDirectory()) : null); copy.setGoals(original.getGoals()); copy.setRecursive(original.isRecursive()); copy.setPom(original.getPom()); copy.setSystemProperties(original.getSystemProperties()); copy.setUserProperties(original.getUserProperties()); copy.setShowErrors(original.isShowErrors()); copy.setActiveProfiles(original.getActiveProfiles()); copy.setInactiveProfiles(original.getInactiveProfiles()); copy.setTransferListener(original.getTransferListener()); copy.setLoggingLevel(original.getLoggingLevel()); copy.setGlobalChecksumPolicy(original.getGlobalChecksumPolicy()); copy.setUpdateSnapshots(original.isUpdateSnapshots()); copy.setRemoteRepositories(original.getRemoteRepositories()); copy.setPluginArtifactRepositories(original.getPluginArtifactRepositories()); copy.setRepositoryCache(original.getRepositoryCache()); copy.setWorkspaceReader(original.getWorkspaceReader()); copy.setNoSnapshotUpdates(original.isNoSnapshotUpdates()); copy.setExecutionListener(original.getExecutionListener()); copy.setUseLegacyLocalRepository(original.isUseLegacyLocalRepository()); copy.setBuilderId(original.getBuilderId()); copy.setStartInstant(original.getStartInstant()); return copy; } @Override public String getBaseDirectory() { if (basedir == null) { return null; } return basedir.getAbsolutePath(); } @Override public ArtifactRepository getLocalRepository() { return localRepository; } @Override public File getLocalRepositoryPath() { return localRepositoryPath; } @Override public List<String> getGoals() { if (goals == null) { goals = new ArrayList<>(); } return goals; } @Override public Properties getSystemProperties() { if (systemProperties == null) { systemProperties = new Properties(); } return systemProperties; } @Override public Properties getUserProperties() { if (userProperties == null) { userProperties = new Properties(); } return userProperties; } @Override public File getPom() { return pom; } @Override public String getReactorFailureBehavior() { return reactorFailureBehavior; } @Override public List<String> getSelectedProjects() { return this.projectActivation.getSelectedProjects(); } @Override public List<String> getExcludedProjects() { return this.projectActivation.getExcludedProjects(); } @Override public boolean isResume() { return resume; } @Override public String getResumeFrom() { return resumeFrom; } @Override public String getMakeBehavior() { return makeBehavior; } @Override @Deprecated public Date getStartTime() { return new Date(startTime.toEpochMilli()); } @Override public Instant getStartInstant() { return startTime; } @Override public MavenExecutionRequest setStartInstant(Instant startTime) { this.startTime = startTime; return this; } @Override public boolean isShowErrors() { return showErrors; } @Override public boolean isInteractiveMode() { return interactiveMode; } @Override public MavenExecutionRequest setActiveProfiles(List<String> activeProfiles) { if (activeProfiles != null) { this.profileActivation.overwriteActiveProfiles(activeProfiles); } return this; } @Override public MavenExecutionRequest setInactiveProfiles(List<String> inactiveProfiles) { if (inactiveProfiles != null) { this.profileActivation.overwriteInactiveProfiles(inactiveProfiles); } return this; } @Override public ProjectActivation getProjectActivation() { return this.projectActivation; } @Override public ProfileActivation getProfileActivation() { return this.profileActivation; } @Override public MavenExecutionRequest setRemoteRepositories(List<ArtifactRepository> remoteRepositories) { if (remoteRepositories != null) { this.remoteRepositories = new ArrayList<>(remoteRepositories); } else { this.remoteRepositories = null; } return this; } @Override public MavenExecutionRequest setPluginArtifactRepositories(List<ArtifactRepository> pluginArtifactRepositories) { if (pluginArtifactRepositories != null) { this.pluginArtifactRepositories = new ArrayList<>(pluginArtifactRepositories); } else { this.pluginArtifactRepositories = null; } return this; } public void setProjectBuildingConfiguration(ProjectBuildingRequest projectBuildingConfiguration) { this.projectBuildingRequest = projectBuildingConfiguration; } @Override public List<String> getActiveProfiles() { return this.profileActivation.getActiveProfiles(); } @Override public List<String> getInactiveProfiles() { return this.profileActivation.getInactiveProfiles(); } @Override public TransferListener getTransferListener() { return transferListener; } @Override public int getLoggingLevel() { return loggingLevel; } @Override public boolean isOffline() { return offline; } @Override public boolean isUpdateSnapshots() { return updateSnapshots; } @Override public boolean isNoSnapshotUpdates() { return noSnapshotUpdates; } @Override public String getGlobalChecksumPolicy() { return globalChecksumPolicy; } @Override public boolean isRecursive() { return recursive; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- @Override public MavenExecutionRequest setBaseDirectory(File basedir) { this.basedir = basedir; return this; } @Deprecated @Override public MavenExecutionRequest setStartTime(Date startTime) { this.startTime = Instant.ofEpochMilli(startTime.getTime()); return this; } @Override public MavenExecutionRequest setShowErrors(boolean showErrors) { this.showErrors = showErrors; return this; } @Override public MavenExecutionRequest setGoals(List<String> goals) { if (goals != null) { this.goals = new ArrayList<>(goals); } else { this.goals = null; } return this; } @Override public MavenExecutionRequest setLocalRepository(ArtifactRepository localRepository) { this.localRepository = localRepository; if (localRepository != null) { setLocalRepositoryPath(new File(localRepository.getBasedir()).getAbsoluteFile()); } return this; } @Override public MavenExecutionRequest setLocalRepositoryPath(File localRepository) { localRepositoryPath = localRepository; return this; } @Override public MavenExecutionRequest setLocalRepositoryPath(String localRepository) { localRepositoryPath = (localRepository != null) ? new File(localRepository) : null; return this; } @Override public MavenExecutionRequest setSystemProperties(Properties properties) { if (properties != null) { this.systemProperties = SystemProperties.copyProperties(properties); } else { this.systemProperties = null; } return this; } @Override public MavenExecutionRequest setUserProperties(Properties userProperties) { if (userProperties != null) { this.userProperties = new Properties(); this.userProperties.putAll(userProperties); } else { this.userProperties = null; } return this; } @Override public MavenExecutionRequest setReactorFailureBehavior(String failureBehavior) { reactorFailureBehavior = failureBehavior; return this; } @Override public MavenExecutionRequest setSelectedProjects(List<String> selectedProjects) { if (selectedProjects != null) { this.projectActivation.overwriteActiveProjects(selectedProjects); } return this; } @Override public MavenExecutionRequest setExcludedProjects(List<String> excludedProjects) { if (excludedProjects != null) { this.projectActivation.overwriteInactiveProjects(excludedProjects); } return this; } @Override public MavenExecutionRequest setResume(boolean resume) { this.resume = resume; return this; } @Override public MavenExecutionRequest setResumeFrom(String project) { this.resumeFrom = project; return this; } @Override public MavenExecutionRequest setMakeBehavior(String makeBehavior) { this.makeBehavior = makeBehavior; return this; } @Override public MavenExecutionRequest addActiveProfile(String profile) { if (!getActiveProfiles().contains(profile)) { getActiveProfiles().add(profile); } return this; } @Override public MavenExecutionRequest addInactiveProfile(String profile) { if (!getInactiveProfiles().contains(profile)) { getInactiveProfiles().add(profile); } return this; } @Override public MavenExecutionRequest addActiveProfiles(List<String> profiles) { for (String profile : profiles) { addActiveProfile(profile); } return this; } @Override public MavenExecutionRequest addInactiveProfiles(List<String> profiles) { for (String profile : profiles) { addInactiveProfile(profile); } return this; } public MavenExecutionRequest setUseReactor(boolean reactorActive) { useReactor = reactorActive; return this; } public boolean useReactor() { return useReactor; } /** @deprecated use {@link #setPom(File)} */ @Deprecated public MavenExecutionRequest setPomFile(String pomFilename) { if (pomFilename != null) { pom = new File(pomFilename); } return this; } @Override public MavenExecutionRequest setPom(File pom) { this.pom = pom; return this; } @Override public MavenExecutionRequest setInteractiveMode(boolean interactive) { interactiveMode = interactive; return this; } @Override public MavenExecutionRequest setTransferListener(TransferListener transferListener) { this.transferListener = transferListener; return this; } @Override public MavenExecutionRequest setLoggingLevel(int loggingLevel) { this.loggingLevel = loggingLevel; return this; } @Override public MavenExecutionRequest setOffline(boolean offline) { this.offline = offline; return this; } @Override public MavenExecutionRequest setUpdateSnapshots(boolean updateSnapshots) { this.updateSnapshots = updateSnapshots; return this; } @Override public MavenExecutionRequest setNoSnapshotUpdates(boolean noSnapshotUpdates) { this.noSnapshotUpdates = noSnapshotUpdates; return this; } @Override public MavenExecutionRequest setGlobalChecksumPolicy(String globalChecksumPolicy) { this.globalChecksumPolicy = globalChecksumPolicy; return this; } // ---------------------------------------------------------------------------- // Settings equivalents // ---------------------------------------------------------------------------- @Override public List<Proxy> getProxies() { if (proxies == null) { proxies = new ArrayList<>(); } return proxies; } @Override public MavenExecutionRequest setProxies(List<Proxy> proxies) { if (proxies != null) { this.proxies = new ArrayList<>(proxies); } else { this.proxies = null; } return this; } @Override public MavenExecutionRequest addProxy(Proxy proxy) { Objects.requireNonNull(proxy, "proxy cannot be null"); for (Proxy p : getProxies()) { if (p.getId() != null && p.getId().equals(proxy.getId())) { return this; } } getProxies().add(proxy); return this; } @Override public List<Server> getServers() { if (servers == null) { servers = new ArrayList<>(); } return servers; } @Override public MavenExecutionRequest setServers(List<Server> servers) { if (servers != null) { this.servers = new ArrayList<>(servers); } else { this.servers = null; } return this; } @Override public MavenExecutionRequest addServer(Server server) { Objects.requireNonNull(server, "server cannot be null"); for (Server p : getServers()) { if (p.getId() != null && p.getId().equals(server.getId())) { return this; } } getServers().add(server); return this; } @Override public List<Mirror> getMirrors() { if (mirrors == null) { mirrors = new ArrayList<>(); } return mirrors; } @Override public MavenExecutionRequest setMirrors(List<Mirror> mirrors) { if (mirrors != null) { this.mirrors = new ArrayList<>(mirrors); } else { this.mirrors = null; } return this; } @Override public MavenExecutionRequest addMirror(Mirror mirror) { Objects.requireNonNull(mirror, "mirror cannot be null"); for (Mirror p : getMirrors()) { if (p.getId() != null && p.getId().equals(mirror.getId())) { return this; } } getMirrors().add(mirror); return this; } @Override public List<Profile> getProfiles() { if (profiles == null) { profiles = new ArrayList<>(); } return profiles; } @Override public MavenExecutionRequest setProfiles(List<Profile> profiles) { if (profiles != null) { this.profiles = new ArrayList<>(profiles); } else { this.profiles = null; } return this; } @Override public List<String> getPluginGroups() { if (pluginGroups == null) { pluginGroups = new ArrayList<>(); } return pluginGroups; } @Override public MavenExecutionRequest setPluginGroups(List<String> pluginGroups) { if (pluginGroups != null) { this.pluginGroups = new ArrayList<>(pluginGroups); } else { this.pluginGroups = null; } return this; } @Override public MavenExecutionRequest addPluginGroup(String pluginGroup) { if (!getPluginGroups().contains(pluginGroup)) { getPluginGroups().add(pluginGroup); } return this; } @Override public MavenExecutionRequest addPluginGroups(List<String> pluginGroups) { for (String pluginGroup : pluginGroups) { addPluginGroup(pluginGroup); } return this; } @Override public MavenExecutionRequest setRecursive(boolean recursive) { this.recursive = recursive; return this; } // calculated from request attributes. private ProjectBuildingRequest projectBuildingRequest; @Override public boolean isProjectPresent() { return isProjectPresent; } @Override public MavenExecutionRequest setProjectPresent(boolean projectPresent) { isProjectPresent = projectPresent; return this; } // Settings files @Override public File getUserSettingsFile() { return userSettingsFile; } @Override public MavenExecutionRequest setUserSettingsFile(File userSettingsFile) { this.userSettingsFile = userSettingsFile; return this; } @Override public File getProjectSettingsFile() { return projectSettingsFile; } @Override public MavenExecutionRequest setProjectSettingsFile(File projectSettingsFile) { this.projectSettingsFile = projectSettingsFile; return this; } @Override @Deprecated public File getGlobalSettingsFile() { return getInstallationSettingsFile(); } @Override @Deprecated public MavenExecutionRequest setGlobalSettingsFile(File globalSettingsFile) { return setInstallationSettingsFile(globalSettingsFile); } @Override public File getInstallationSettingsFile() { return installationSettingsFile; } @Override public MavenExecutionRequest setInstallationSettingsFile(File installationSettingsFile) { this.installationSettingsFile = installationSettingsFile; return this; } @Override public File getUserToolchainsFile() { return userToolchainsFile; } @Override public MavenExecutionRequest setUserToolchainsFile(File userToolchainsFile) { this.userToolchainsFile = userToolchainsFile; return this; } @Override @Deprecated public File getGlobalToolchainsFile() { return installationToolchainsFile; } @Override @Deprecated public MavenExecutionRequest setGlobalToolchainsFile(File installationToolchainsFile) { this.installationToolchainsFile = installationToolchainsFile; return this; } @Override public File getInstallationToolchainsFile() { return installationToolchainsFile; } @Override public MavenExecutionRequest setInstallationToolchainsFile(File installationToolchainsFile) { this.installationToolchainsFile = installationToolchainsFile; return this; } @Override public MavenExecutionRequest addRemoteRepository(ArtifactRepository repository) { for (ArtifactRepository repo : getRemoteRepositories()) { if (repo.getId() != null && repo.getId().equals(repository.getId())) { return this; } } getRemoteRepositories().add(repository); return this; } @Override public List<ArtifactRepository> getRemoteRepositories() { if (remoteRepositories == null) { remoteRepositories = new ArrayList<>(); } return remoteRepositories; } @Override public MavenExecutionRequest addPluginArtifactRepository(ArtifactRepository repository) { for (ArtifactRepository repo : getPluginArtifactRepositories()) { if (repo.getId() != null && repo.getId().equals(repository.getId())) { return this; } } getPluginArtifactRepositories().add(repository); return this; } @Override public List<ArtifactRepository> getPluginArtifactRepositories() { if (pluginArtifactRepositories == null) { pluginArtifactRepositories = new ArrayList<>(); } return pluginArtifactRepositories; } // TODO this does not belong here. @Override public ProjectBuildingRequest getProjectBuildingRequest() { if (projectBuildingRequest == null) { projectBuildingRequest = new DefaultProjectBuildingRequest(); projectBuildingRequest.setLocalRepository(getLocalRepository()); projectBuildingRequest.setSystemProperties(getSystemProperties()); projectBuildingRequest.setUserProperties(getUserProperties()); projectBuildingRequest.setRemoteRepositories(getRemoteRepositories()); projectBuildingRequest.setPluginArtifactRepositories(getPluginArtifactRepositories()); projectBuildingRequest.setActiveProfileIds(getActiveProfiles()); projectBuildingRequest.setInactiveProfileIds(getInactiveProfiles()); projectBuildingRequest.setProfiles(getProfiles()); projectBuildingRequest.setProcessPlugins(true); projectBuildingRequest.setBuildStartInstant(getStartInstant()); } return projectBuildingRequest; } @Override public MavenExecutionRequest addProfile(Profile profile) { Objects.requireNonNull(profile, "profile cannot be null"); for (Profile p : getProfiles()) { if (p.getId() != null && p.getId().equals(profile.getId())) { return this; } } getProfiles().add(profile); return this; } @Override public RepositoryCache getRepositoryCache() { return repositoryCache; } @Override public MavenExecutionRequest setRepositoryCache(RepositoryCache repositoryCache) { this.repositoryCache = repositoryCache; return this; } @Override public ExecutionListener getExecutionListener() { return executionListener; } @Override public MavenExecutionRequest setExecutionListener(ExecutionListener executionListener) { this.executionListener = executionListener; return this; } @Override public void setDegreeOfConcurrency(final int degreeOfConcurrency) { this.degreeOfConcurrency = degreeOfConcurrency; } @Override public int getDegreeOfConcurrency() { return degreeOfConcurrency; } @Override public WorkspaceReader getWorkspaceReader() { return workspaceReader; } @Override public MavenExecutionRequest setWorkspaceReader(WorkspaceReader workspaceReader) { this.workspaceReader = workspaceReader; return this; } @Override public boolean isCacheTransferError() { return cacheTransferError; } @Override public MavenExecutionRequest setCacheTransferError(boolean cacheTransferError) { this.cacheTransferError = cacheTransferError; return this; } @Override public boolean isCacheNotFound() { return cacheNotFound; } @Override public MavenExecutionRequest setCacheNotFound(boolean cacheNotFound) { this.cacheNotFound = cacheNotFound; return this; } @Override public boolean isIgnoreMissingArtifactDescriptor() { return ignoreMissingArtifactDescriptor; } @Override public MavenExecutionRequest setIgnoreMissingArtifactDescriptor(boolean ignoreMissing) { this.ignoreMissingArtifactDescriptor = ignoreMissing; return this; } @Override public boolean isIgnoreInvalidArtifactDescriptor() { return ignoreInvalidArtifactDescriptor; } @Override public boolean isIgnoreTransitiveRepositories() { return ignoreTransitiveRepositories; } @Override public MavenExecutionRequest setIgnoreInvalidArtifactDescriptor(boolean ignoreInvalid) { this.ignoreInvalidArtifactDescriptor = ignoreInvalid; return this; } @Override public MavenExecutionRequest setIgnoreTransitiveRepositories(boolean ignoreTransitiveRepositories) { this.ignoreTransitiveRepositories = ignoreTransitiveRepositories; return this; } @Override public boolean isUseLegacyLocalRepository() { return this.useLegacyLocalRepositoryManager; } @Override public MavenExecutionRequest setUseLegacyLocalRepository(boolean useLegacyLocalRepositoryManager) { this.useLegacyLocalRepositoryManager = false; return this; } @Override public MavenExecutionRequest setBuilderId(String builderId) { this.builderId = builderId; return this; } @Override public String getBuilderId() { return builderId; } @Override public Map<String, List<ToolchainModel>> getToolchains() { if (toolchains == null) { toolchains = new HashMap<>(); } return toolchains; } @Override public MavenExecutionRequest setToolchains(Map<String, List<ToolchainModel>> toolchains) { this.toolchains = toolchains; return this; } @Deprecated @Override public void setMultiModuleProjectDirectory(File directory) { this.multiModuleProjectDirectory = directory; } @Deprecated @Override public File getMultiModuleProjectDirectory() { return multiModuleProjectDirectory; } @Override public Path getRootDirectory() { if (rootDirectory == null) { throw new IllegalStateException(RootLocator.UNABLE_TO_FIND_ROOT_PROJECT_MESSAGE); } return rootDirectory; } @Override public MavenExecutionRequest setRootDirectory(Path rootDirectory) { this.rootDirectory = rootDirectory; return this; } @Override public Path getTopDirectory() { return topDirectory; } @Override public MavenExecutionRequest setTopDirectory(Path topDirectory) { this.topDirectory = topDirectory; return this; } @Override public MavenExecutionRequest setEventSpyDispatcher(EventSpyDispatcher eventSpyDispatcher) { this.eventSpyDispatcher = eventSpyDispatcher; return this; } @Override public EventSpyDispatcher getEventSpyDispatcher() { return eventSpyDispatcher; } @Override public Map<String, Object> getData() { if (data == null) { data = new HashMap<>(); } return data; } }
DefaultMavenExecutionRequest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/javadoc/NotJavadocTest.java
{ "start": 2869, "end": 2961 }
class ____ { void test() { /* Not Javadoc. */
Test
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/resource/DnsResolver.java
{ "start": 135, "end": 273 }
interface ____ override the normal DNS lookup offered by the OS. * * @author Mark Paluch * @author Euiyoung Nam * @since 4.2 */ public
to
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authc/service/ServiceAccountTokenTests.java
{ "start": 775, "end": 4371 }
class ____ extends ESTestCase { public void testNewToken() { final ServiceAccountId accountId = new ServiceAccountId(randomAlphaOfLengthBetween(3, 8), randomAlphaOfLengthBetween(3, 8)); ServiceAccountToken.newToken(accountId, ValidationTests.randomTokenName()); final String invalidTokeName = ValidationTests.randomInvalidTokenName(); final IllegalArgumentException e1 = expectThrows( IllegalArgumentException.class, () -> ServiceAccountToken.newToken(accountId, invalidTokeName) ); assertThat(e1.getMessage(), containsString(Validation.INVALID_SERVICE_ACCOUNT_TOKEN_NAME_MESSAGE)); assertThat(e1.getMessage(), containsString("invalid service token name [" + invalidTokeName + "]")); final NullPointerException e2 = expectThrows( NullPointerException.class, () -> ServiceAccountToken.newToken(null, ValidationTests.randomTokenName()) ); assertThat(e2.getMessage(), containsString("service account ID cannot be null")); } public void testServiceAccountTokenNew() { final ServiceAccountId accountId = new ServiceAccountId(randomAlphaOfLengthBetween(3, 8), randomAlphaOfLengthBetween(3, 8)); final SecureString secret = new SecureString(randomAlphaOfLength(20).toCharArray()); new ServiceAccountToken(accountId, ValidationTests.randomTokenName(), secret); final NullPointerException e1 = expectThrows( NullPointerException.class, () -> new ServiceAccountToken(null, ValidationTests.randomTokenName(), secret) ); assertThat(e1.getMessage(), containsString("service account ID cannot be null")); final String invalidTokenName = ValidationTests.randomInvalidTokenName(); final IllegalArgumentException e2 = expectThrows( IllegalArgumentException.class, () -> new ServiceAccountToken(accountId, invalidTokenName, secret) ); assertThat(e2.getMessage(), containsString(Validation.INVALID_SERVICE_ACCOUNT_TOKEN_NAME_MESSAGE)); assertThat(e2.getMessage(), containsString("invalid service token name [" + invalidTokenName + "]")); final NullPointerException e3 = expectThrows( NullPointerException.class, () -> new ServiceAccountToken(accountId, ValidationTests.randomTokenName(), null) ); assertThat(e3.getMessage(), containsString("service account token secret cannot be null")); } public void testBearerString() throws IOException { final ServiceAccountToken serviceAccountToken = new ServiceAccountToken( new ServiceAccountId("elastic", "fleet-server"), "token1", new SecureString("supersecret".toCharArray()) ); assertThat(serviceAccountToken.asBearerString(), equalTo("AAEAAWVsYXN0aWMvZmxlZXQtc2VydmVyL3Rva2VuMTpzdXBlcnNlY3JldA")); assertThat( ServiceAccountToken.fromBearerString( new SecureString("AAEAAWVsYXN0aWMvZmxlZXQtc2VydmVyL3Rva2VuMTpzdXBlcnNlY3JldA".toCharArray()) ), equalTo(serviceAccountToken) ); final ServiceAccountId accountId = new ServiceAccountId(randomAlphaOfLengthBetween(3, 8), randomAlphaOfLengthBetween(3, 8)); final ServiceAccountToken serviceAccountToken1 = ServiceAccountToken.newToken(accountId, ValidationTests.randomTokenName()); assertThat(ServiceAccountToken.fromBearerString(serviceAccountToken1.asBearerString()), equalTo(serviceAccountToken1)); } }
ServiceAccountTokenTests
java
quarkusio__quarkus
extensions/vertx/deployment/src/test/java/io/quarkus/vertx/mdc/InMemoryLogHandlerProducer.java
{ "start": 368, "end": 1053 }
class ____ { public volatile boolean initialized = false; @Produces @Singleton public InMemoryLogHandler inMemoryLogHandler() { return new InMemoryLogHandler(); } public boolean isInitialized() { return initialized; } void onStart(@Observes StartupEvent ev, InMemoryLogHandler inMemoryLogHandler) { InitialConfigurator.DELAYED_HANDLER.addHandler(inMemoryLogHandler); initialized = true; } void onStop(@Observes ShutdownEvent ev, InMemoryLogHandler inMemoryLogHandler) { initialized = false; InitialConfigurator.DELAYED_HANDLER.removeHandler(inMemoryLogHandler); } }
InMemoryLogHandlerProducer