language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/RailRoadDiagram.java
{ "start": 7541, "end": 11519 }
class ____ extends Literal { private static final String LITERAL_CLASS = "l"; private static final String SYNTAX_CLASS = "lsyn"; private static final String LITERAL_TEXT_CLASS = "j"; private static final String SYNTAX_TEXT_CLASS = "syn"; private static final String SYNTAX_GREY = "8D8D8D"; private final String text; private Syntax(String text) { super(text); this.text = text; } @Override protected RRElement toRRElement(GrammarToRRDiagram grammarToRRDiagram) { /* * This performs a monumentally rude hack to replace the text color of this element. * It renders a "literal" element but intercepts the layer that defines it's css class * and replaces it with our own. */ return new RRText(RRText.Type.LITERAL, text, null) { @Override protected void toSVG(RRDiagramToSVG rrDiagramToSVG, int xOffset, int yOffset, RRDiagram.SvgContent svgContent) { super.toSVG(rrDiagramToSVG, xOffset, yOffset, new RRDiagram.SvgContent() { @Override public String getDefinedCSSClass(String style) { if (style.equals(LITERAL_CLASS)) { return svgContent.getDefinedCSSClass(SYNTAX_CLASS); } if (style.equals(LITERAL_TEXT_CLASS)) { return svgContent.getDefinedCSSClass(SYNTAX_TEXT_CLASS); } return svgContent.getDefinedCSSClass(style); } @Override public String setCSSClass(String cssClass, String definition) { if (cssClass.equals(LITERAL_CLASS)) { svgContent.setCSSClass(cssClass, definition); return svgContent.setCSSClass(SYNTAX_CLASS, definition); } if (cssClass.equals(LITERAL_TEXT_CLASS)) { svgContent.setCSSClass(cssClass, definition); return svgContent.setCSSClass( SYNTAX_TEXT_CLASS, definition.replace("fill:#000000", "fill:#" + SYNTAX_GREY) ); } return svgContent.setCSSClass(cssClass, definition); } @Override public void addPathConnector(int x1, int y1, String path, int x2, int y2) { svgContent.addPathConnector(x1, y1, path, x2, y2); } @Override public void addLineConnector(int x1, int y1, int x2, int y2) { svgContent.addLineConnector(x1, y1, x2, y2); } @Override public void addElement(String element) { svgContent.addElement(element); } }); } }; } } private static Font loadFont() throws IOException { try { InputStream woff = RailRoadDiagram.class.getClassLoader() .getResourceAsStream("META-INF/resources/webjars/fontsource__roboto-mono/4.5.7/files/roboto-mono-latin-400-normal.woff"); if (woff == null) { throw new IllegalArgumentException("can't find roboto mono"); } return Font.createFont(Font.TRUETYPE_FONT, new WoffConverter().convertToTTFOutputStream(woff)); } catch (FontFormatException e) { throw new IOException(e); } } }
Syntax
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/A320.java
{ "start": 302, "end": 534 }
class ____ extends Plane { private String javaEmbeddedVersion; public String getJavaEmbeddedVersion() { return javaEmbeddedVersion; } public void setJavaEmbeddedVersion(String string) { javaEmbeddedVersion = string; } }
A320
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-documentstore/src/test/java/org/apache/hadoop/yarn/server/timelineservice/documentstore/writer/DummyDocumentStoreWriter.java
{ "start": 1172, "end": 1561 }
class ____<Document extends TimelineDocument> implements DocumentStoreWriter<Document> { @Override public void createDatabase() { } @Override public void createCollection(String collectionName) { } @Override public void writeDocument(Document timelineDocument, CollectionType collectionType) { } @Override public void close() { } }
DummyDocumentStoreWriter
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/exc/ExceptionSerializationTest.java
{ "start": 507, "end": 625 }
class ____ { @SuppressWarnings("serial") @JsonIgnoreProperties({ "bogus1" }) static
ExceptionSerializationTest
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/firewall/HttpStatusRequestRejectedHandler.java
{ "start": 1114, "end": 2065 }
class ____ implements RequestRejectedHandler { private static final Log logger = LogFactory.getLog(HttpStatusRequestRejectedHandler.class); private final int httpError; /** * Constructs an instance which uses {@code 400} as response code. */ public HttpStatusRequestRejectedHandler() { this.httpError = HttpServletResponse.SC_BAD_REQUEST; } /** * Constructs an instance which uses a configurable http code as response. * @param httpError http status code to use */ public HttpStatusRequestRejectedHandler(int httpError) { this.httpError = httpError; } @Override public void handle(HttpServletRequest request, HttpServletResponse response, RequestRejectedException requestRejectedException) throws IOException { logger.debug(LogMessage.format("Rejecting request due to: %s", requestRejectedException.getMessage()), requestRejectedException); response.sendError(this.httpError); } }
HttpStatusRequestRejectedHandler
java
google__error-prone
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
{ "start": 32521, "end": 32995 }
class ____ { void test() { verifyNotNull(2); verifyNotNull(1); } } """) .doTest(); } @Test public void qualifyStaticImport_whenIdentifierNamesClash_usesQualifiedName() { BugCheckerRefactoringTestHelper.newInstance(ReplaceMethodInvocations.class, getClass()) .addInputLines( "pkg/Lib.java", """ package pkg; public
Test
java
alibaba__nacos
console/src/main/java/com/alibaba/nacos/console/proxy/core/ClusterProxy.java
{ "start": 1155, "end": 2538 }
class ____ { private final ClusterHandler clusterHandler; /** * Constructs a new ClusterProxy with the given ClusterInnerHandler and ConsoleConfig. * * @param clusterHandler the default implementation of ClusterHandler */ public ClusterProxy(ClusterHandler clusterHandler) { this.clusterHandler = clusterHandler; } /** * Retrieve a list of cluster members with an optional search keyword. * * @param ipKeyWord the search keyword for filtering members * @return a collection of matching members * @throws IllegalArgumentException if the deployment type is invalid */ public Collection<NacosMember> getNodeList(String ipKeyWord) throws NacosException { Collection<? extends NacosMember> members = clusterHandler.getNodeList(ipKeyWord); List<NacosMember> result = new ArrayList<>(); members.forEach(member -> { if (StringUtils.isBlank(ipKeyWord)) { result.add(member); return; } final String address = member.getAddress(); if (StringUtils.equals(address, ipKeyWord) || StringUtils.startsWith(address, ipKeyWord)) { result.add(member); } }); result.sort(Comparator.comparing(NacosMember::getAddress)); return result; } }
ClusterProxy
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/api/dto/CreateSObjectResult.java
{ "start": 890, "end": 1461 }
class ____ extends AbstractDTOBase { private String id; private List<RestError> errors; private Boolean success; public String getId() { return id; } public void setId(String id) { this.id = id; } public List<RestError> getErrors() { return errors; } public void setErrors(List<RestError> errors) { this.errors = errors; } public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } }
CreateSObjectResult
java
elastic__elasticsearch
modules/ingest-geoip/src/main/java/org/elasticsearch/ingest/geoip/GeoIpProcessor.java
{ "start": 7282, "end": 9567 }
class ____ implements CheckedSupplier<IpDatabase, IOException> { private final IpDatabaseProvider ipDatabaseProvider; private final String databaseFile; private final String databaseType; private final ProjectId projectId; public DatabaseVerifyingSupplier( IpDatabaseProvider ipDatabaseProvider, String databaseFile, String databaseType, ProjectId projectId ) { this.ipDatabaseProvider = ipDatabaseProvider; this.databaseFile = databaseFile; this.databaseType = databaseType; this.projectId = projectId; } @Override public IpDatabase get() throws IOException { IpDatabase loader = ipDatabaseProvider.getDatabase(projectId, databaseFile); if (loader == null) { return null; } if (Assertions.ENABLED) { // Note that the expected suffix might be null for providers that aren't amenable to using dashes as separator for // determining the database type. int last = databaseType.lastIndexOf('-'); final String expectedSuffix = last == -1 ? null : databaseType.substring(last); // If the entire database type matches, then that's a match. Otherwise, if there's a suffix to compare on, then // check whether the suffix has changed (not the entire database type). // This is to sanity check, for example, that a city db isn't overwritten with a country or asn db. // But there are permissible overwrites that make sense, for example overwriting a geolite city db with a geoip city db // is a valid change, but the db type is slightly different -- by checking just the suffix this assertion won't fail. final String loaderType = loader.getDatabaseType(); assert loaderType.equals(databaseType) || expectedSuffix == null || loaderType.endsWith(expectedSuffix) : "database type [" + loaderType + "] doesn't match with expected suffix [" + expectedSuffix + "]"; } return loader; } } public static final
DatabaseVerifyingSupplier
java
quarkusio__quarkus
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/globals/TemplateGlobalOverrideTest.java
{ "start": 484, "end": 1315 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot(root -> root .addClasses(Globals.class, User.class) .addAsResource(new StringAsset( // Note that we need to override the param declaration as well "{@io.quarkus.qute.deployment.globals.User user}Hello {user.name}!"), "templates/hello.txt") .addAsResource(new StringAsset( // We don't need to override the param declaration for @CheckedTemplate "Hello {user.name}!"), "templates/foo/hello.txt")); @CheckedTemplate(basePath = "foo") static
TemplateGlobalOverrideTest
java
google__truth
core/src/main/java/com/google/common/truth/SubjectUtils.java
{ "start": 4530, "end": 6183 }
class ____. * * <p>Example: {@code countDuplicatesAndAddTypeInfo([1, 2, 2, 3]) == "[1, 2 [3 copies]] * (java.lang.Integer)"} and {@code countDuplicatesAndAddTypeInfo([1, 2L]) == "[1 * (java.lang.Integer), 2 (java.lang.Long)]"}. */ static String countDuplicatesAndAddTypeInfo(Iterable<?> itemsIterable) { Collection<?> items = iterableToCollection(itemsIterable); String homogeneousTypeName = getHomogeneousTypeName(items); return homogeneousTypeName != null ? lenientFormat("%s (%s)", countDuplicates(items), homogeneousTypeName) : countDuplicates(addTypeInfoToEveryItem(items)); } /** * Similar to {@link #countDuplicatesAndAddTypeInfo} and {@link #countDuplicates} but: * * <ul> * <li>only adds type info if requested * <li>returns a richer object containing the data * </ul> */ static DuplicateGroupedAndTyped countDuplicatesAndMaybeAddTypeInfoReturnObject( Iterable<?> itemsIterable, boolean addTypeInfo) { if (addTypeInfo) { Collection<?> items = iterableToCollection(itemsIterable); String homogeneousTypeName = getHomogeneousTypeName(items); NonHashingMultiset<?> valuesWithCountsAndMaybeTypes = homogeneousTypeName != null ? countDuplicatesToMultiset(items) : countDuplicatesToMultiset(addTypeInfoToEveryItem(items)); return DuplicateGroupedAndTyped.create(valuesWithCountsAndMaybeTypes, homogeneousTypeName); } else { return DuplicateGroupedAndTyped.create( countDuplicatesToMultiset(itemsIterable), /* homogeneousTypeToDisplay= */ null); } } private static final
info
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/support/SerializableResponseDto.java
{ "start": 889, "end": 1169 }
class ____ implements Serializable { private static final long serialVersionUID = 1L; public boolean success; public SerializableResponseDto() { } public SerializableResponseDto(boolean success) { this.success = success; } }
SerializableResponseDto
java
micronaut-projects__micronaut-core
discovery-core/src/main/java/io/micronaut/discovery/DefaultCompositeDiscoveryClient.java
{ "start": 940, "end": 1654 }
class ____ extends CompositeDiscoveryClient { /** * Create a default composite discovery for the discovery clients. * * @param discoveryClients The Discovery clients used for service discovery */ @Inject public DefaultCompositeDiscoveryClient(List<DiscoveryClient> discoveryClients) { super(discoveryClients.toArray(new DiscoveryClient[0])); } /** * Create a default composite discovery for the discovery clients. * * @param discoveryClients The Discovery clients used for service discovery */ public DefaultCompositeDiscoveryClient(DiscoveryClient... discoveryClients) { super(discoveryClients); } }
DefaultCompositeDiscoveryClient
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableDoAfterNext.java
{ "start": 1769, "end": 2795 }
class ____<T> extends BasicFuseableSubscriber<T, T> { final Consumer<? super T> onAfterNext; DoAfterSubscriber(Subscriber<? super T> actual, Consumer<? super T> onAfterNext) { super(actual); this.onAfterNext = onAfterNext; } @Override public void onNext(T t) { if (done) { return; } downstream.onNext(t); if (sourceMode == NONE) { try { onAfterNext.accept(t); } catch (Throwable ex) { fail(ex); } } } @Override public int requestFusion(int mode) { return transitiveBoundaryFusion(mode); } @Nullable @Override public T poll() throws Throwable { T v = qs.poll(); if (v != null) { onAfterNext.accept(v); } return v; } } static final
DoAfterSubscriber
java
spring-projects__spring-boot
module/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/context/properties/ConfigurationPropertiesReportEndpointProxyTests.java
{ "start": 5034, "end": 5146 }
class ____ implements Executor { } @Component @ConfigurationProperties("executor.sql") static
AbstractExecutor
java
quarkusio__quarkus
extensions/jackson/deployment/src/test/java/io/quarkus/jackson/deployment/JacksonMixinsWithoutCustomizerTest.java
{ "start": 491, "end": 966 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest(); @Inject ObjectMapper objectMapper; @Test public void test() throws JsonProcessingException { assertThat(objectMapper.writeValueAsString(new Fruit("test"))).isEqualTo("{\"nm\":\"test\"}"); assertThat(objectMapper.writeValueAsString(new Fruit2("test"))).isEqualTo("{\"nm\":\"test\"}"); } public static
JacksonMixinsWithoutCustomizerTest
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/bean/override/BeanOverrideRegistry.java
{ "start": 1591, "end": 5671 }
class ____ { static final String BEAN_NAME = "org.springframework.test.context.bean.override.internalBeanOverrideRegistry"; private static final Log logger = LogFactory.getLog(BeanOverrideRegistry.class); private final Map<BeanOverrideHandler, String> handlerToBeanNameMap = new LinkedHashMap<>(); private final Map<String, BeanOverrideHandler> wrappingBeanOverrideHandlers = new LinkedHashMap<>(); private final ConfigurableBeanFactory beanFactory; @Nullable private final BeanOverrideRegistry parent; BeanOverrideRegistry(ConfigurableBeanFactory beanFactory) { Assert.notNull(beanFactory, "ConfigurableBeanFactory must not be null"); this.beanFactory = beanFactory; BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory(); this.parent = (parentBeanFactory != null && parentBeanFactory.containsBean(BEAN_NAME) ? parentBeanFactory.getBean(BEAN_NAME, BeanOverrideRegistry.class) : null); } /** * Register the provided {@link BeanOverrideHandler} and associate it with the * given {@code beanName}. * <p>Also associates a {@linkplain BeanOverrideStrategy#WRAP "wrapping"} handler * with the given {@code beanName}, allowing for subsequent wrapping of the * bean via {@link #wrapBeanIfNecessary(Object, String)}. * @see #getBeanForHandler(BeanOverrideHandler, Class) */ void registerBeanOverrideHandler(BeanOverrideHandler handler, String beanName) { Assert.state(!this.handlerToBeanNameMap.containsKey(handler), () -> "Cannot register BeanOverrideHandler for bean with name '%s'; detected multiple registrations for %s" .formatted(beanName, handler)); // Check if beanName was already registered, before adding the new mapping. boolean beanNameAlreadyRegistered = this.handlerToBeanNameMap.containsValue(beanName); // Add new mapping before potentially logging a warning, to ensure that // the current handler is logged as well. this.handlerToBeanNameMap.put(handler, beanName); if (beanNameAlreadyRegistered && logger.isWarnEnabled()) { List<BeanOverrideHandler> competingHandlers = this.handlerToBeanNameMap.entrySet().stream() .filter(entry -> entry.getValue().equals(beanName)) .map(Entry::getKey) .toList(); logger.warn("Bean with name '%s' was overridden by multiple handlers: %s" .formatted(beanName, competingHandlers)); } if (handler.getStrategy() == BeanOverrideStrategy.WRAP) { this.wrappingBeanOverrideHandlers.put(beanName, handler); } } /** * Use the registered {@linkplain BeanOverrideStrategy#WRAP "wrapping"} * {@link BeanOverrideHandler} to create an override instance by wrapping the * supplied bean. * <p>If no suitable {@code BeanOverrideHandler} has been registered, this * method returns the supplied bean unmodified. * @see #registerBeanOverrideHandler(BeanOverrideHandler, String) */ Object wrapBeanIfNecessary(Object bean, String beanName) { if (!this.wrappingBeanOverrideHandlers.containsKey(beanName)) { return bean; } BeanOverrideHandler handler = this.wrappingBeanOverrideHandlers.get(beanName); Assert.state(handler != null, () -> "Failed to find wrapping BeanOverrideHandler for bean '" + beanName + "'"); return handler.createOverrideInstance(beanName, null, bean, this.beanFactory); } /** * Get the bean instance that was created by the provided {@link BeanOverrideHandler}. * @param handler the {@code BeanOverrideHandler} that created the bean * @param requiredType the required bean type * @return the bean instance, or {@code null} if the provided handler is not * registered in this registry or a parent registry * @since 6.2.6 * @see #registerBeanOverrideHandler(BeanOverrideHandler, String) */ @Nullable Object getBeanForHandler(BeanOverrideHandler handler, Class<?> requiredType) { String beanName = this.handlerToBeanNameMap.get(handler); if (beanName != null) { return this.beanFactory.getBean(beanName, requiredType); } if (this.parent != null) { return this.parent.getBeanForHandler(handler, requiredType); } return null; } }
BeanOverrideRegistry
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java
{ "start": 1250, "end": 3096 }
class ____ { @Test void simpleBeanConfigured() { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( new ClassPathResource("simplePropertyNamespaceHandlerTests.xml", getClass())); ITestBean rob = (TestBean) beanFactory.getBean("rob"); ITestBean sally = (TestBean) beanFactory.getBean("sally"); assertThat(rob.getName()).isEqualTo("Rob Harrop"); assertThat(rob.getAge()).isEqualTo(24); assertThat(sally).isEqualTo(rob.getSpouse()); } @Test void innerBeanConfigured() { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( new ClassPathResource("simplePropertyNamespaceHandlerTests.xml", getClass())); TestBean sally = (TestBean) beanFactory.getBean("sally2"); ITestBean rob = sally.getSpouse(); assertThat(rob.getName()).isEqualTo("Rob Harrop"); assertThat(rob.getAge()).isEqualTo(24); assertThat(sally).isEqualTo(rob.getSpouse()); } @Test void withPropertyDefinedTwice() { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); assertThatExceptionOfType(BeanDefinitionStoreException.class).isThrownBy(() -> new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( new ClassPathResource("simplePropertyNamespaceHandlerTestsWithErrors.xml", getClass()))); } @Test void propertyWithNameEndingInRef() { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(beanFactory).loadBeanDefinitions( new ClassPathResource("simplePropertyNamespaceHandlerTests.xml", getClass())); ITestBean sally = (TestBean) beanFactory.getBean("derivedSally"); assertThat(sally.getSpouse().getName()).isEqualTo("r"); } }
SimplePropertyNamespaceHandlerTests
java
apache__camel
components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyTcpWithInOutUsingPlainSocketTest.java
{ "start": 1396, "end": 5305 }
class ____ extends BaseNettyTest { @Test public void testSendAndReceiveOnce() throws Exception { String response = sendAndReceive("World"); assertNotNull(response, "Nothing received from Mina"); assertEquals("Hello World", response); } @Test public void testSendAndReceiveTwice() throws Exception { String london = sendAndReceive("London"); String paris = sendAndReceive("Paris"); assertNotNull(london, "Nothing received from Mina"); assertNotNull(paris, "Nothing received from Mina"); assertEquals("Hello London", london); assertEquals("Hello Paris", paris); } @Test public void testReceiveNoResponseSinceOutBodyIsNull() throws Exception { String out = sendAndReceive("force-null-out-body"); assertNull(out, "no data should be received"); } @Test public void testReceiveNoResponseSinceOutBodyIsNullTwice() throws Exception { String out = sendAndReceive("force-null-out-body"); assertNull(out, "no data should be received"); out = sendAndReceive("force-null-out-body"); assertNull(out, "no data should be received"); } @Test public void testExchangeFailedOutShouldBeNull() throws Exception { String out = sendAndReceive("force-exception"); assertNotEquals("force-exception", out, "out should not be the same as in when the exchange has failed"); assertEquals("java.lang.IllegalArgumentException: Forced exception", out, "should get the exception here"); } private String sendAndReceive(String input) throws IOException { byte buf[] = new byte[128]; Socket soc = new Socket(); soc.connect(new InetSocketAddress("localhost", getPort())); // Send message using plain Socket to test if this works OutputStream os = null; InputStream is = null; try { os = soc.getOutputStream(); // must append the line delimiter os.write((input + "\n").getBytes()); is = soc.getInputStream(); int len = is.read(buf); if (len == -1) { // no data received return null; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } soc.close(); } // convert the buffer to chars StringBuilder sb = new StringBuilder(); for (byte b : buf) { char ch = (char) b; if (ch == '\n' || ch == 0) { // newline denotes end of text (added in the end in the processor below) break; } else { sb.append(ch); } } return sb.toString(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("netty:tcp://localhost:{{port}}?textline=true&sync=true").process(new Processor() { public void process(Exchange e) { String in = e.getIn().getBody(String.class); if ("force-null-out-body".equals(in)) { // forcing a null out body e.getMessage().setBody(null); } else if ("force-exception".equals(in)) { // clear out before throwing exception e.getMessage().setBody(null); throw new IllegalArgumentException("Forced exception"); } else { e.getMessage().setBody("Hello " + in); } } }); } }; } }
NettyTcpWithInOutUsingPlainSocketTest
java
spring-projects__spring-boot
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/ValidationFailureAnalyzerTests.java
{ "start": 2485, "end": 2849 }
class ____ { @Bean NewRelicMeterRegistry meterRegistry() { return new NewRelicMeterRegistry(new NewRelicConfig() { @Override public @Nullable String get(String key) { return null; } @Override public String prefix() { return "newrelic.metrics.export"; } }, Clock.SYSTEM); } } }
MissingAccountIdAndApiKeyConfiguration
java
apache__camel
components/camel-couchdb/src/test/java/org/apache/camel/component/couchdb/CouchDbEndpointTest.java
{ "start": 1073, "end": 2534 }
class ____ { @Test void assertSingleton() throws Exception { try (CouchDbEndpoint endpoint = new CouchDbEndpoint("couchdb:http://localhost/db", "http://localhost/db", new CouchDbComponent())) { assertTrue(endpoint.isSingleton()); } } @Test void testDbRequired() { final CouchDbComponent component = new CouchDbComponent(); assertThrows(IllegalArgumentException.class, () -> { new CouchDbEndpoint("couchdb:http://localhost:80", "http://localhost:80", component); }); } @Test void testDefaultPortIsSet() throws Exception { try (CouchDbEndpoint endpoint = new CouchDbEndpoint("couchdb:http://localhost/db", "http://localhost/db", new CouchDbComponent())) { assertEquals(CouchDbEndpoint.DEFAULT_PORT, endpoint.getPort()); } } @Test void testHostnameRequired() { final CouchDbComponent component = new CouchDbComponent(); assertThrows(IllegalArgumentException.class, () -> { new CouchDbEndpoint("couchdb:http://:80/db", "http://:80/db", component); }); } @Test void testSchemeRequired() { final CouchDbComponent component = new CouchDbComponent(); assertThrows(IllegalArgumentException.class, () -> { new CouchDbEndpoint("couchdb:localhost:80/db", "localhost:80/db", component); }); } }
CouchDbEndpointTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/consumer/EndOfInputChannelStateEvent.java
{ "start": 1125, "end": 2145 }
class ____ extends RuntimeEvent { /** The singleton instance of this event. */ public static final EndOfInputChannelStateEvent INSTANCE = new EndOfInputChannelStateEvent(); // ------------------------------------------------------------------------ // not instantiable private EndOfInputChannelStateEvent() {} // ------------------------------------------------------------------------ @Override public void read(DataInputView in) { // Nothing to do here } @Override public void write(DataOutputView out) { // Nothing to do here } // ------------------------------------------------------------------------ @Override public int hashCode() { return 20250813; } @Override public boolean equals(Object obj) { return obj != null && obj.getClass() == EndOfInputChannelStateEvent.class; } @Override public String toString() { return getClass().getSimpleName(); } }
EndOfInputChannelStateEvent
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/KeywordScriptFieldType.java
{ "start": 2216, "end": 2423 }
class ____ extends AbstractScriptFieldType<StringFieldScript.LeafFactory> { public static final RuntimeField.Parser PARSER = new RuntimeField.Parser(Builder::new); private static
KeywordScriptFieldType
java
elastic__elasticsearch
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/optimizer/OptimizerRules.java
{ "start": 30686, "end": 58684 }
class ____ extends OptimizerExpressionRule<BinaryLogic> { public CombineBinaryComparisons() { super(TransformDirection.DOWN); } @Override public Expression rule(BinaryLogic e) { if (e instanceof And) { return combine((And) e); } else if (e instanceof Or) { return combine((Or) e); } return e; } // combine conjunction private static Expression combine(And and) { List<Range> ranges = new ArrayList<>(); List<BinaryComparison> bcs = new ArrayList<>(); List<Expression> exps = new ArrayList<>(); boolean changed = false; List<Expression> andExps = Predicates.splitAnd(and); // Ranges need to show up before BinaryComparisons in list, to allow the latter be optimized away into a Range, if possible. // NotEquals need to be last in list, to have a complete set of Ranges (ranges) and BinaryComparisons (bcs) and allow these to // optimize the NotEquals away. andExps.sort((o1, o2) -> { if (o1 instanceof Range && o2 instanceof Range) { return 0; // keep ranges' order } else if (o1 instanceof Range || o2 instanceof Range) { return o2 instanceof Range ? 1 : -1; // push Ranges down } else if (o1 instanceof NotEquals && o2 instanceof NotEquals) { return 0; // keep NotEquals' order } else if (o1 instanceof NotEquals || o2 instanceof NotEquals) { return o1 instanceof NotEquals ? 1 : -1; // push NotEquals up } else { return 0; // keep non-Ranges' and non-NotEquals' order } }); for (Expression ex : andExps) { if (ex instanceof Range r) { if (findExistingRange(r, ranges, true)) { changed = true; } else { ranges.add(r); } } else if (ex instanceof BinaryComparison bc && (ex instanceof Equals || ex instanceof NotEquals) == false) { if (bc.right().foldable() && (findConjunctiveComparisonInRange(bc, ranges) || findExistingComparison(bc, bcs, true))) { changed = true; } else { bcs.add(bc); } } else if (ex instanceof NotEquals neq) { if (neq.right().foldable() && notEqualsIsRemovableFromConjunction(neq, ranges, bcs)) { // the non-equality can simply be dropped: either superfluous or has been merged with an updated range/inequality changed = true; } else { // not foldable OR not overlapping exps.add(ex); } } else { exps.add(ex); } } // finally try combining any left BinaryComparisons into possible Ranges // this could be a different rule but it's clearer here wrt the order of comparisons for (int i = 0, step = 1; i < bcs.size() - 1; i += step, step = 1) { BinaryComparison main = bcs.get(i); for (int j = i + 1; j < bcs.size(); j++) { BinaryComparison other = bcs.get(j); if (main.left().semanticEquals(other.left())) { // >/>= AND </<= if ((main instanceof GreaterThan || main instanceof GreaterThanOrEqual) && (other instanceof LessThan || other instanceof LessThanOrEqual)) { bcs.remove(j); bcs.remove(i); ranges.add( new Range( and.source(), main.left(), main.right(), main instanceof GreaterThanOrEqual, other.right(), other instanceof LessThanOrEqual, main.zoneId() ) ); changed = true; step = 0; break; } // </<= AND >/>= else if ((other instanceof GreaterThan || other instanceof GreaterThanOrEqual) && (main instanceof LessThan || main instanceof LessThanOrEqual)) { bcs.remove(j); bcs.remove(i); ranges.add( new Range( and.source(), main.left(), other.right(), other instanceof GreaterThanOrEqual, main.right(), main instanceof LessThanOrEqual, main.zoneId() ) ); changed = true; step = 0; break; } } } } return changed ? Predicates.combineAnd(CollectionUtils.combine(exps, bcs, ranges)) : and; } // combine disjunction private static Expression combine(Or or) { List<BinaryComparison> bcs = new ArrayList<>(); List<Range> ranges = new ArrayList<>(); List<Expression> exps = new ArrayList<>(); boolean changed = false; for (Expression ex : Predicates.splitOr(or)) { if (ex instanceof Range r) { if (findExistingRange(r, ranges, false)) { changed = true; } else { ranges.add(r); } } else if (ex instanceof BinaryComparison bc) { if (bc.right().foldable() && findExistingComparison(bc, bcs, false)) { changed = true; } else { bcs.add(bc); } } else { exps.add(ex); } } return changed ? Predicates.combineOr(CollectionUtils.combine(exps, bcs, ranges)) : or; } private static boolean findExistingRange(Range main, List<Range> ranges, boolean conjunctive) { if (main.lower().foldable() == false && main.upper().foldable() == false) { return false; } // NB: the loop modifies the list (hence why the int is used) for (int i = 0; i < ranges.size(); i++) { Range other = ranges.get(i); if (main.value().semanticEquals(other.value())) { // make sure the comparison was done boolean compared = false; boolean lower = false; boolean upper = false; // boundary equality (useful to differentiate whether a range is included or not) // and thus whether it should be preserved or ignored boolean lowerEq = false; boolean upperEq = false; // evaluate lower if (main.lower().foldable() && other.lower().foldable()) { compared = true; Integer comp = BinaryComparison.compare(main.lower().fold(), other.lower().fold()); // values are comparable if (comp != null) { // boundary equality lowerEq = comp == 0 && main.includeLower() == other.includeLower(); // AND if (conjunctive) { // (2 < a < 3) AND (1 < a < 3) -> (2 < a < 3) lower = comp > 0 || // (2 < a < 3) AND (2 <= a < 3) -> (2 < a < 3) (comp == 0 && main.includeLower() == false && other.includeLower()); } // OR else { // (1 < a < 3) OR (2 < a < 3) -> (1 < a < 3) lower = comp < 0 || // (2 <= a < 3) OR (2 < a < 3) -> (2 <= a < 3) (comp == 0 && main.includeLower() && other.includeLower() == false) || lowerEq; } } } // evaluate upper if (main.upper().foldable() && other.upper().foldable()) { compared = true; Integer comp = BinaryComparison.compare(main.upper().fold(), other.upper().fold()); // values are comparable if (comp != null) { // boundary equality upperEq = comp == 0 && main.includeUpper() == other.includeUpper(); // AND if (conjunctive) { // (1 < a < 2) AND (1 < a < 3) -> (1 < a < 2) upper = comp < 0 || // (1 < a < 2) AND (1 < a <= 2) -> (1 < a < 2) (comp == 0 && main.includeUpper() == false && other.includeUpper()); } // OR else { // (1 < a < 3) OR (1 < a < 2) -> (1 < a < 3) upper = comp > 0 || // (1 < a <= 3) OR (1 < a < 3) -> (2 < a < 3) (comp == 0 && main.includeUpper() && other.includeUpper() == false) || upperEq; } } } // AND - at least one of lower or upper if (conjunctive) { // can tighten range if (lower || upper) { ranges.set( i, new Range( main.source(), main.value(), lower ? main.lower() : other.lower(), lower ? main.includeLower() : other.includeLower(), upper ? main.upper() : other.upper(), upper ? main.includeUpper() : other.includeUpper(), main.zoneId() ) ); } // range was comparable return compared; } // OR - needs both upper and lower to loosen range else { // can loosen range if (lower && upper) { ranges.set( i, new Range( main.source(), main.value(), main.lower(), main.includeLower(), main.upper(), main.includeUpper(), main.zoneId() ) ); return true; } // if the range in included, no need to add it return compared && (((lower && lowerEq == false) || (upper && upperEq == false)) == false); } } } return false; } private static boolean findConjunctiveComparisonInRange(BinaryComparison main, List<Range> ranges) { Object value = main.right().fold(); // NB: the loop modifies the list (hence why the int is used) for (int i = 0; i < ranges.size(); i++) { Range other = ranges.get(i); if (main.left().semanticEquals(other.value())) { if (main instanceof GreaterThan || main instanceof GreaterThanOrEqual) { if (other.lower().foldable()) { Integer comp = BinaryComparison.compare(value, other.lower().fold()); if (comp != null) { // 2 < a AND (2 <= a < 3) -> 2 < a < 3 boolean lowerEq = comp == 0 && other.includeLower() && main instanceof GreaterThan; // 2 < a AND (1 < a < 3) -> 2 < a < 3 boolean lower = comp > 0 || lowerEq; if (lower) { ranges.set( i, new Range( other.source(), other.value(), main.right(), lowerEq ? false : main instanceof GreaterThanOrEqual, other.upper(), other.includeUpper(), other.zoneId() ) ); } // found a match return true; } } } else if (main instanceof LessThan || main instanceof LessThanOrEqual) { if (other.upper().foldable()) { Integer comp = BinaryComparison.compare(value, other.upper().fold()); if (comp != null) { // a < 2 AND (1 < a <= 2) -> 1 < a < 2 boolean upperEq = comp == 0 && other.includeUpper() && main instanceof LessThan; // a < 2 AND (1 < a < 3) -> 1 < a < 2 boolean upper = comp < 0 || upperEq; if (upper) { ranges.set( i, new Range( other.source(), other.value(), other.lower(), other.includeLower(), main.right(), upperEq ? false : main instanceof LessThanOrEqual, other.zoneId() ) ); } // found a match return true; } } } return false; } } return false; } /** * Find commonalities between the given comparison in the given list. * The method can be applied both for conjunctive (AND) or disjunctive purposes (OR). */ private static boolean findExistingComparison(BinaryComparison main, List<BinaryComparison> bcs, boolean conjunctive) { Object value = main.right().fold(); // NB: the loop modifies the list (hence why the int is used) for (int i = 0; i < bcs.size(); i++) { BinaryComparison other = bcs.get(i); // skip if cannot evaluate if (other.right().foldable() == false) { continue; } // if bc is a higher/lower value or gte vs gt, use it instead if ((other instanceof GreaterThan || other instanceof GreaterThanOrEqual) && (main instanceof GreaterThan || main instanceof GreaterThanOrEqual)) { if (main.left().semanticEquals(other.left())) { Integer compare = BinaryComparison.compare(value, other.right().fold()); if (compare != null) { // AND if ((conjunctive && // a > 3 AND a > 2 -> a > 3 (compare > 0 || // a > 2 AND a >= 2 -> a > 2 (compare == 0 && main instanceof GreaterThan && other instanceof GreaterThanOrEqual))) || // OR (conjunctive == false && // a > 2 OR a > 3 -> a > 2 (compare < 0 || // a >= 2 OR a > 2 -> a >= 2 (compare == 0 && main instanceof GreaterThanOrEqual && other instanceof GreaterThan)))) { bcs.remove(i); bcs.add(i, main); } // found a match return true; } return false; } } // if bc is a lower/higher value or lte vs lt, use it instead else if ((other instanceof LessThan || other instanceof LessThanOrEqual) && (main instanceof LessThan || main instanceof LessThanOrEqual)) { if (main.left().semanticEquals(other.left())) { Integer compare = BinaryComparison.compare(value, other.right().fold()); if (compare != null) { // AND if ((conjunctive && // a < 2 AND a < 3 -> a < 2 (compare < 0 || // a < 2 AND a <= 2 -> a < 2 (compare == 0 && main instanceof LessThan && other instanceof LessThanOrEqual))) || // OR (conjunctive == false && // a < 2 OR a < 3 -> a < 3 (compare > 0 || // a <= 2 OR a < 2 -> a <= 2 (compare == 0 && main instanceof LessThanOrEqual && other instanceof LessThan)))) { bcs.remove(i); bcs.add(i, main); } // found a match return true; } return false; } } } return false; } private static boolean notEqualsIsRemovableFromConjunction(NotEquals notEquals, List<Range> ranges, List<BinaryComparison> bcs) { Object neqVal = notEquals.right().fold(); Integer comp; // check on "condition-overlapping" ranges: // a != 2 AND 3 < a < 5 -> 3 < a < 5; a != 2 AND 0 < a < 1 -> 0 < a < 1 (discard NotEquals) // a != 2 AND 2 <= a < 3 -> 2 < a < 3; a != 3 AND 2 < a <= 3 -> 2 < a < 3 (discard NotEquals, plus update Range) // a != 2 AND 1 < a < 3 -> nop (do nothing) for (int i = 0; i < ranges.size(); i++) { Range range = ranges.get(i); if (notEquals.left().semanticEquals(range.value())) { comp = range.lower().foldable() ? BinaryComparison.compare(neqVal, range.lower().fold()) : null; if (comp != null) { if (comp <= 0) { if (comp == 0 && range.includeLower()) { // a != 2 AND 2 <= a < ? -> 2 < a < ? ranges.set( i, new Range( range.source(), range.value(), range.lower(), false, range.upper(), range.includeUpper(), range.zoneId() ) ); } // else: !.includeLower() : a != 2 AND 2 < a < 3 -> 2 < a < 3; or: // else: comp < 0 : a != 2 AND 3 < a < ? -> 3 < a < ? return true; } else { // comp > 0 : a != 4 AND 2 < a < ? : can only remove NotEquals if outside the range comp = range.upper().foldable() ? BinaryComparison.compare(neqVal, range.upper().fold()) : null; if (comp != null && comp >= 0) { if (comp == 0 && range.includeUpper()) { // a != 4 AND 2 < a <= 4 -> 2 < a < 4 ranges.set( i, new Range( range.source(), range.value(), range.lower(), range.includeLower(), range.upper(), false, range.zoneId() ) ); } // else: !.includeUpper() : a != 4 AND 2 < a < 4 -> 2 < a < 4 // else: comp > 0 : a != 4 AND 2 < a < 3 -> 2 < a < 3 return true; } // else: comp < 0 : a != 4 AND 2 < a < 5 -> nop; or: // else: comp == null : upper bound not comparable -> nop } } // else: comp == null : lower bound not comparable: evaluate upper bound, in case non-equality value is ">=" comp = range.upper().foldable() ? BinaryComparison.compare(neqVal, range.upper().fold()) : null; if (comp != null && comp >= 0) { if (comp == 0 && range.includeUpper()) { // a != 3 AND ?? < a <= 3 -> ?? < a < 3 ranges.set( i, new Range( range.source(), range.value(), range.lower(), range.includeLower(), range.upper(), false, range.zoneId() ) ); } // else: !.includeUpper() : a != 3 AND ?? < a < 3 -> ?? < a < 3 // else: comp > 0 : a != 3 and ?? < a < 2 -> ?? < a < 2 return true; } // else: comp < 0 : a != 3 AND ?? < a < 4 -> nop, as a decision can't be drawn; or: // else: comp == null : a != 3 AND ?? < a < ?? -> nop } } // check on "condition-overlapping" inequalities: // a != 2 AND a > 3 -> a > 3 (discard NotEquals) // a != 2 AND a >= 2 -> a > 2 (discard NotEquals plus update inequality) // a != 2 AND a > 1 -> nop (do nothing) // // a != 2 AND a < 3 -> nop // a != 2 AND a <= 2 -> a < 2 // a != 2 AND a < 1 -> a < 1 for (int i = 0; i < bcs.size(); i++) { BinaryComparison bc = bcs.get(i); if (notEquals.left().semanticEquals(bc.left())) { if (bc instanceof LessThan || bc instanceof LessThanOrEqual) { comp = bc.right().foldable() ? BinaryComparison.compare(neqVal, bc.right().fold()) : null; if (comp != null) { if (comp >= 0) { if (comp == 0 && bc instanceof LessThanOrEqual) { // a != 2 AND a <= 2 -> a < 2 bcs.set(i, new LessThan(bc.source(), bc.left(), bc.right(), bc.zoneId())); } // else : comp > 0 (a != 2 AND a </<= 1 -> a </<= 1), or == 0 && bc i.of "<" (a != 2 AND a < 2 -> a < 2) return true; } // else: comp < 0 : a != 2 AND a </<= 3 -> nop } // else: non-comparable, nop } else if (bc instanceof GreaterThan || bc instanceof GreaterThanOrEqual) { comp = bc.right().foldable() ? BinaryComparison.compare(neqVal, bc.right().fold()) : null; if (comp != null) { if (comp <= 0) { if (comp == 0 && bc instanceof GreaterThanOrEqual) { // a != 2 AND a >= 2 -> a > 2 bcs.set(i, new GreaterThan(bc.source(), bc.left(), bc.right(), bc.zoneId())); } // else: comp < 0 (a != 2 AND a >/>= 3 -> a >/>= 3), or == 0 && bc i.of ">" (a != 2 AND a > 2 -> a > 2) return true; } // else: comp > 0 : a != 2 AND a >/>= 1 -> nop } // else: non-comparable, nop } // else: other non-relevant type } } return false; } } /** * Combine disjunctions on the same field into an In expression. * This rule looks for both simple equalities: * 1. a == 1 OR a == 2 becomes a IN (1, 2) * and combinations of In * 2. a == 1 OR a IN (2) becomes a IN (1, 2) * 3. a IN (1) OR a IN (2) becomes a IN (1, 2) * * By default (see {@link #shouldValidateIn()}), this rule does NOT check for type compatibility as that phase has * already been verified in the analyzer, but this behavior can be changed by subclasses. */ public static
CombineBinaryComparisons
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/search/fieldcaps/FieldCapabilitiesIT.java
{ "start": 58332, "end": 59235 }
class ____ extends Plugin implements MapperPlugin { @Override public Map<String, MetadataFieldMapper.TypeParser> getMetadataMappers() { return Collections.singletonMap(TestMetadataMapper.CONTENT_TYPE, TestMetadataMapper.PARSER); } @Override public Function<String, FieldPredicate> getFieldFilter() { return index -> new FieldPredicate() { @Override public boolean test(String field) { return field.equals("playlist") == false; } @Override public String modifyHash(String hash) { return "not-playlist:" + hash; } @Override public long ramBytesUsed() { return 0; } }; } } private static final
TestMapperPlugin
java
google__auto
value/src/test/java/com/google/auto/value/processor/PropertyAnnotationsTest.java
{ "start": 1962, "end": 2505 }
interface ____ { byte testByte() default 1; short testShort() default 2; int testInt() default 3; long testLong() default 4L; float testFloat() default 5.6f; double testDouble() default 7.8d; char testChar() default 'a'; String testString() default "10"; boolean testBoolean() default false; Class<?> testClass() default TestEnum.class; TestEnum testEnum() default TestEnum.A; OtherAnnotation testAnnotation() default @OtherAnnotation(foo = 23, bar = "baz"); } public @
TestAnnotation
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/writing/DelegateRequestRepresentation.java
{ "start": 6629, "end": 7034 }
enum ____ { UNSCOPED, SINGLE_CHECK, DOUBLE_CHECK, ; static ScopeKind get(Binding binding) { return binding .scope() .map(scope -> scope.isReusable() ? SINGLE_CHECK : DOUBLE_CHECK) .orElse(UNSCOPED); } boolean isStrongerScopeThan(ScopeKind other) { return this.ordinal() > other.ordinal(); } } @AssistedFactory static
ScopeKind
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLNullConstraint.java
{ "start": 722, "end": 1125 }
class ____ extends SQLConstraintImpl implements SQLColumnConstraint { public SQLNullConstraint() { } @Override protected void accept0(SQLASTVisitor visitor) { visitor.visit(this); visitor.endVisit(this); } public SQLNullConstraint clone() { SQLNullConstraint x = new SQLNullConstraint(); super.cloneTo(x); return x; } }
SQLNullConstraint
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1523/java8/Source.java
{ "start": 264, "end": 639 }
class ____ { private ZonedDateTime value; private Calendar value2; public ZonedDateTime getValue() { return value; } public void setValue(ZonedDateTime value) { this.value = value; } public Calendar getValue2() { return value2; } public void setValue2(Calendar value2) { this.value2 = value2; } }
Source
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/inference/SettingsConfiguration.java
{ "start": 1897, "end": 11426 }
class ____ implements Writeable, ToXContentObject { @Nullable private final Object defaultValue; @Nullable private final String description; private final String label; private final boolean required; private final boolean sensitive; private final boolean updatable; private final SettingsConfigurationFieldType type; private final EnumSet<TaskType> supportedTaskTypes; /** * Constructs a new {@link SettingsConfiguration} instance with specified properties. * * @param defaultValue The default value for the configuration. * @param description A description of the configuration. * @param label The display label associated with the config field. * @param required A boolean indicating whether the configuration is required. * @param sensitive A boolean indicating whether the configuration contains sensitive information. * @param updatable A boolean indicating whether the configuration can be updated. * @param type The type of the configuration field, defined by {@link SettingsConfigurationFieldType}. * @param supportedTaskTypes The task types that support this field. */ private SettingsConfiguration( Object defaultValue, String description, String label, boolean required, boolean sensitive, boolean updatable, SettingsConfigurationFieldType type, EnumSet<TaskType> supportedTaskTypes ) { this.defaultValue = defaultValue; this.description = description; this.label = label; this.required = required; this.sensitive = sensitive; this.updatable = updatable; this.type = type; this.supportedTaskTypes = supportedTaskTypes; } public SettingsConfiguration(StreamInput in) throws IOException { this.defaultValue = in.readGenericValue(); this.description = in.readOptionalString(); this.label = in.readString(); this.required = in.readBoolean(); this.sensitive = in.readBoolean(); this.updatable = in.readBoolean(); this.type = in.readEnum(SettingsConfigurationFieldType.class); this.supportedTaskTypes = in.readEnumSet(TaskType.class); } static final ParseField DEFAULT_VALUE_FIELD = new ParseField("default_value"); static final ParseField DESCRIPTION_FIELD = new ParseField("description"); static final ParseField LABEL_FIELD = new ParseField("label"); static final ParseField REQUIRED_FIELD = new ParseField("required"); static final ParseField SENSITIVE_FIELD = new ParseField("sensitive"); static final ParseField UPDATABLE_FIELD = new ParseField("updatable"); static final ParseField TYPE_FIELD = new ParseField("type"); static final ParseField SUPPORTED_TASK_TYPES = new ParseField("supported_task_types"); @SuppressWarnings("unchecked") private static final ConstructingObjectParser<SettingsConfiguration, Void> PARSER = new ConstructingObjectParser<>( "service_configuration", true, args -> { int i = 0; EnumSet<TaskType> supportedTaskTypes = EnumSet.noneOf(TaskType.class); var supportedTaskTypesListOfStrings = (List<String>) args[i++]; for (var supportedTaskTypeString : supportedTaskTypesListOfStrings) { supportedTaskTypes.add(TaskType.fromString(supportedTaskTypeString)); } return new SettingsConfiguration.Builder(supportedTaskTypes).setDefaultValue(args[i++]) .setDescription((String) args[i++]) .setLabel((String) args[i++]) .setRequired((Boolean) args[i++]) .setSensitive((Boolean) args[i++]) .setUpdatable((Boolean) args[i++]) .setType((SettingsConfigurationFieldType) args[i++]) .build(); } ); static { PARSER.declareStringArray(constructorArg(), SUPPORTED_TASK_TYPES); PARSER.declareField(optionalConstructorArg(), (p, c) -> { if (p.currentToken() == XContentParser.Token.VALUE_STRING) { return p.text(); } else if (p.currentToken() == XContentParser.Token.VALUE_NUMBER) { return p.numberValue(); } else if (p.currentToken() == XContentParser.Token.VALUE_BOOLEAN) { return p.booleanValue(); } else if (p.currentToken() == XContentParser.Token.VALUE_NULL) { return null; } throw new XContentParseException("Unsupported token [" + p.currentToken() + "]"); }, DEFAULT_VALUE_FIELD, ObjectParser.ValueType.VALUE); PARSER.declareStringOrNull(optionalConstructorArg(), DESCRIPTION_FIELD); PARSER.declareString(constructorArg(), LABEL_FIELD); PARSER.declareBoolean(optionalConstructorArg(), REQUIRED_FIELD); PARSER.declareBoolean(optionalConstructorArg(), SENSITIVE_FIELD); PARSER.declareBoolean(optionalConstructorArg(), UPDATABLE_FIELD); PARSER.declareField( optionalConstructorArg(), (p, c) -> p.currentToken() == XContentParser.Token.VALUE_NULL ? null : SettingsConfigurationFieldType.fieldType(p.text()), TYPE_FIELD, ObjectParser.ValueType.STRING_OR_NULL ); } public Object getDefaultValue() { return defaultValue; } public String getDescription() { return description; } public String getLabel() { return label; } public boolean isRequired() { return required; } public boolean isSensitive() { return sensitive; } public boolean isUpdatable() { return updatable; } public SettingsConfigurationFieldType getType() { return type; } public Set<TaskType> getSupportedTaskTypes() { return supportedTaskTypes; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); { if (defaultValue != null) { builder.field(DEFAULT_VALUE_FIELD.getPreferredName(), defaultValue); } if (description != null) { builder.field(DESCRIPTION_FIELD.getPreferredName(), description); } builder.field(LABEL_FIELD.getPreferredName(), label); builder.field(REQUIRED_FIELD.getPreferredName(), required); builder.field(SENSITIVE_FIELD.getPreferredName(), sensitive); builder.field(UPDATABLE_FIELD.getPreferredName(), updatable); if (type != null) { builder.field(TYPE_FIELD.getPreferredName(), type.toString()); } builder.field(SUPPORTED_TASK_TYPES.getPreferredName(), supportedTaskTypes); } builder.endObject(); return builder; } public static SettingsConfiguration fromXContent(XContentParser parser) throws IOException { return PARSER.parse(parser, null); } public static SettingsConfiguration fromXContentBytes(BytesReference source, XContentType xContentType) { try (XContentParser parser = XContentHelper.createParser(XContentParserConfiguration.EMPTY, source, xContentType)) { return SettingsConfiguration.fromXContent(parser); } catch (IOException e) { throw new ElasticsearchParseException("Failed to parse service configuration.", e); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeGenericValue(defaultValue); out.writeOptionalString(description); out.writeString(label); out.writeBoolean(required); out.writeBoolean(sensitive); out.writeBoolean(updatable); out.writeEnum(type); out.writeEnumSet(supportedTaskTypes); } public Map<String, Object> toMap() { Map<String, Object> map = new HashMap<>(); map.put(DEFAULT_VALUE_FIELD.getPreferredName(), defaultValue); Optional.ofNullable(description).ifPresent(t -> map.put(DESCRIPTION_FIELD.getPreferredName(), t)); map.put(LABEL_FIELD.getPreferredName(), label); map.put(REQUIRED_FIELD.getPreferredName(), required); map.put(SENSITIVE_FIELD.getPreferredName(), sensitive); map.put(UPDATABLE_FIELD.getPreferredName(), updatable); Optional.ofNullable(type).ifPresent(t -> map.put(TYPE_FIELD.getPreferredName(), t.toString())); map.put(SUPPORTED_TASK_TYPES.getPreferredName(), supportedTaskTypes); return map; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SettingsConfiguration that = (SettingsConfiguration) o; return required == that.required && sensitive == that.sensitive && updatable == that.updatable && Objects.equals(defaultValue, that.defaultValue) && Objects.equals(description, that.description) && Objects.equals(label, that.label) && type == that.type && Objects.equals(supportedTaskTypes, that.supportedTaskTypes); } @Override public int hashCode() { return Objects.hash(defaultValue, description, label, required, sensitive, updatable, type, supportedTaskTypes); } public static
SettingsConfiguration
java
quarkusio__quarkus
independent-projects/qute/core/src/test/java/io/quarkus/qute/MutinyTest.java
{ "start": 579, "end": 3691 }
class ____ { @Test public void testCreateMulti() throws InterruptedException { Engine engine = Engine.builder().addDefaults().build(); Template template = engine.parse("{#each}{it}{/}"); List<String> data = Arrays.asList("foo", "foo", "alpha"); Multi<String> multi = template.data(data).createMulti(); assertMulti(multi, "foofooalpha"); assertMulti(multi.select().distinct(), "fooalpha"); assertMulti(multi.select().first(), "foo"); } @Test public void testCreateUni() throws InterruptedException { Engine engine = Engine.builder().addDefaults().build(); Template template = engine.parse("{#each}{it}{/}"); List<Object> data = new ArrayList<>(Arrays.asList("foo", "foo", "alpha")); Uni<String> uni = template.data(data).createUni(); BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>(); uni.subscribe().with(synchronizer::add); assertEquals("foofooalpha", synchronizer.poll(2, TimeUnit.SECONDS)); data.remove(0); uni.subscribe().with(synchronizer::add); assertEquals("fooalpha", synchronizer.poll(2, TimeUnit.SECONDS)); data.add(new Object() { @Override public String toString() { throw new IllegalStateException("foo"); } }); uni.subscribe().with(synchronizer::add, synchronizer::add); assertEquals(IllegalStateException.class, synchronizer.poll(2, TimeUnit.SECONDS).getClass()); } @Test public void testUniResolution() { Engine engine = Engine.builder().addDefaults().addValueResolver(new ReflectionValueResolver()).build(); Template template = engine.parse("{foo.toLowerCase}::{#each items}{it_count}.{it}{#if it_hasNext},{/if}{/each}"); Uni<Object> fooUni = Uni.createFrom().item("FOO"); Uni<List<String>> itemsUni = Uni.createFrom().item(() -> Arrays.asList("foo", "bar", "baz")); assertEquals("foo::1.foo,2.bar,3.baz", template.data("foo", fooUni, "items", itemsUni).render()); } @Test public void testUniFailure() { Engine engine = Engine.builder().addDefaults().addValueResolver(new ReflectionValueResolver()).build(); Template template = engine.parse("{foo.toLowerCase}"); Uni<String> fooUni = Uni.createFrom().item(() -> { throw new IllegalStateException("Foo!"); }); assertThatIllegalStateException() .isThrownBy(() -> template.data("foo", fooUni).render()) .withMessage("Foo!"); } private void assertMulti(Multi<String> multi, String expected) throws InterruptedException { StringBuilder builder = new StringBuilder(); CountDownLatch latch = new CountDownLatch(1); multi .subscribe().with( builder::append, latch::countDown); if (latch.await(2, TimeUnit.SECONDS)) { assertEquals(expected, builder.toString()); } else { fail(); } } }
MutinyTest
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/stream/compact/CompactOperator.java
{ "start": 3114, "end": 9397 }
class ____<T> extends AbstractStreamOperator<PartitionCommitInfo> implements OneInputStreamOperator<CoordinatorOutput, PartitionCommitInfo>, BoundedOneInput { private static final long serialVersionUID = 1L; public static final String UNCOMPACTED_PREFIX = ".uncompacted-"; public static final String COMPACTED_PREFIX = "compacted-"; private final SupplierWithException<FileSystem, IOException> fsFactory; private final CompactReader.Factory<T> readerFactory; private final CompactWriter.Factory<T> writerFactory; private transient FileSystem fileSystem; private transient ListState<Map<Long, List<Path>>> expiredFilesState; private transient TreeMap<Long, List<Path>> expiredFiles; private transient List<Path> currentExpiredFiles; private transient Set<String> partitions; public CompactOperator( SupplierWithException<FileSystem, IOException> fsFactory, CompactReader.Factory<T> readerFactory, CompactWriter.Factory<T> writerFactory) { this.fsFactory = fsFactory; this.readerFactory = readerFactory; this.writerFactory = writerFactory; } @Override public void initializeState(StateInitializationContext context) throws Exception { super.initializeState(context); this.partitions = new HashSet<>(); this.fileSystem = fsFactory.get(); ListStateDescriptor<Map<Long, List<Path>>> metaDescriptor = new ListStateDescriptor<>( "expired-files", new MapSerializer<>( LongSerializer.INSTANCE, new ListSerializer<>( new KryoSerializer<>( Path.class, getExecutionConfig().getSerializerConfig())))); this.expiredFilesState = context.getOperatorStateStore().getListState(metaDescriptor); this.expiredFiles = new TreeMap<>(); this.currentExpiredFiles = new ArrayList<>(); if (context.isRestored()) { this.expiredFiles.putAll(this.expiredFilesState.get().iterator().next()); } } @Override public void processElement(StreamRecord<CoordinatorOutput> element) throws Exception { CoordinatorOutput value = element.getValue(); if (value instanceof CompactionUnit) { CompactionUnit unit = (CompactionUnit) value; if (unit.isTaskMessage( getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks(), getRuntimeContext().getTaskInfo().getIndexOfThisSubtask())) { String partition = unit.getPartition(); List<Path> paths = unit.getPaths(); // create a target file to compact to Path targetPath = createCompactedFile(paths); // do compaction CompactFileUtils.doCompact( fileSystem, partition, paths, targetPath, getContainingTask() .getEnvironment() .getTaskManagerInfo() .getConfiguration(), readerFactory, writerFactory); this.partitions.add(partition); // Only after the current checkpoint is successfully executed can delete // the expired files, so as to ensure the existence of the files. this.currentExpiredFiles.addAll(paths); } } else if (value instanceof EndCompaction) { endCompaction(((EndCompaction) value).getCheckpointId()); } } private void endCompaction(long checkpoint) { this.output.collect( new StreamRecord<>( new PartitionCommitInfo( checkpoint, getRuntimeContext().getTaskInfo().getIndexOfThisSubtask(), getRuntimeContext().getTaskInfo().getNumberOfParallelSubtasks(), this.partitions.toArray(new String[0])))); this.partitions.clear(); } @Override public void snapshotState(StateSnapshotContext context) throws Exception { snapshotState(context.getCheckpointId()); } private void snapshotState(long checkpointId) throws Exception { expiredFiles.put(checkpointId, new ArrayList<>(currentExpiredFiles)); expiredFilesState.update(Collections.singletonList(expiredFiles)); currentExpiredFiles.clear(); } @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { super.notifyCheckpointComplete(checkpointId); clearExpiredFiles(checkpointId); } @Override public void endInput() throws Exception { endCompaction(Long.MAX_VALUE); snapshotState(Long.MAX_VALUE); clearExpiredFiles(Long.MAX_VALUE); } private void clearExpiredFiles(long checkpointId) throws IOException { // Don't need these metas anymore. NavigableMap<Long, List<Path>> outOfDateMetas = expiredFiles.headMap(checkpointId, true); for (List<Path> paths : outOfDateMetas.values()) { for (Path meta : paths) { fileSystem.delete(meta, true); } } outOfDateMetas.clear(); } private static Path createCompactedFile(List<Path> uncompactedFiles) { Path path = convertFromUncompacted(uncompactedFiles.get(0)); return new Path(path.getParent(), COMPACTED_PREFIX + path.getName()); } public static String convertToUncompacted(String path) { return UNCOMPACTED_PREFIX + path; } public static Path convertFromUncompacted(Path path) { Preconditions.checkArgument( path.getName().startsWith(UNCOMPACTED_PREFIX), "This should be uncompacted file: " + path); return new Path(path.getParent(), path.getName().substring(UNCOMPACTED_PREFIX.length())); } }
CompactOperator
java
alibaba__druid
core/src/main/java/com/alibaba/druid/pool/ha/selector/RandomDataSourceValidateFilter.java
{ "start": 1028, "end": 1952 }
class ____ extends FilterEventAdapter { protected void statementExecuteUpdateAfter(StatementProxy statement, String sql, int updateCount) { recordTime(statement); } protected void statementExecuteQueryAfter(StatementProxy statement, String sql, ResultSetProxy resultSet) { recordTime(statement); } protected void statementExecuteAfter(StatementProxy statement, String sql, boolean result) { recordTime(statement); } protected void statementExecuteBatchAfter(StatementProxy statement, int[] result) { recordTime(statement); } private void recordTime(StatementProxy statement) { ConnectionProxy conn = statement.getConnectionProxy(); if (conn != null) { DataSourceProxy dataSource = conn.getDirectDataSource(); RandomDataSourceValidateThread.logSuccessTime(dataSource); } } }
RandomDataSourceValidateFilter
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/InputProperty.java
{ "start": 1671, "end": 2754 }
class ____ { /** The input does not require any specific data distribution. */ public static final RequiredDistribution ANY_DISTRIBUTION = new RequiredDistribution(DistributionType.ANY) {}; /** * The input will read all records for each parallelism of the target node. All records appear * in each parallelism. */ public static final RequiredDistribution BROADCAST_DISTRIBUTION = new RequiredDistribution(DistributionType.BROADCAST) {}; /** The input will read all records, and the parallelism of the target node must be 1. */ public static final RequiredDistribution SINGLETON_DISTRIBUTION = new RequiredDistribution(DistributionType.SINGLETON) {}; /** * Returns a place-holder required distribution. * * <p>Currently {@link InputProperty} is only used for deadlock breakup and multi-input in batch * mode, so for {@link ExecNode}s not affecting the algorithm we use this place-holder. * * <p>We should fill out the detailed {@link InputProperty} for each sub-
InputProperty
java
quarkusio__quarkus
extensions/spring-cloud-config-client/runtime/src/main/java/io/quarkus/spring/cloud/config/client/runtime/Response.java
{ "start": 926, "end": 1414 }
class ____ { private final String name; private final Map<String, String> source; @JsonCreator public PropertySource(@JsonProperty("name") String name, @JsonProperty("source") Map<String, String> source) { this.name = name; this.source = source; } public String getName() { return name; } public Map<String, String> getSource() { return source; } } }
PropertySource
java
quarkusio__quarkus
independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanConfiguratorBase.java
{ "start": 5405, "end": 5458 }
class ____ a managed bean. * * @param type a
of
java
apache__spark
mllib/src/test/java/org/apache/spark/ml/JavaPipelineSuite.java
{ "start": 1425, "end": 2382 }
class ____ extends SharedSparkSession { private transient Dataset<Row> dataset; @Override @BeforeEach public void setUp() throws IOException { super.setUp(); JavaRDD<LabeledPoint> points = jsc.parallelize(generateLogisticInputAsList(1.0, 1.0, 100, 42), 2); dataset = spark.createDataFrame(points, LabeledPoint.class); } @Test public void pipeline() { StandardScaler scaler = new StandardScaler() .setInputCol("features") .setOutputCol("scaledFeatures"); LogisticRegression lr = new LogisticRegression() .setFeaturesCol("scaledFeatures"); Pipeline pipeline = new Pipeline() .setStages(new PipelineStage[]{scaler, lr}); PipelineModel model = pipeline.fit(dataset); model.transform(dataset).createOrReplaceTempView("prediction"); Dataset<Row> predictions = spark.sql("SELECT label, probability, prediction FROM prediction"); predictions.collectAsList(); } }
JavaPipelineSuite
java
apache__flink
flink-formats/flink-avro-confluent-registry/src/main/java/org/apache/flink/formats/avro/registry/confluent/ConfluentRegistryAvroDeserializationSchema.java
{ "start": 8112, "end": 8937 }
class ____ record to be produced * @param url URL of schema registry to connect * @param identityMapCapacity maximum number of cached schema versions * @param registryConfigs map with additional schema registry configs (for example SSL * properties) * @return deserialized record */ public static <T extends SpecificRecord> ConfluentRegistryAvroDeserializationSchema<T> forSpecific( Class<T> tClass, String url, int identityMapCapacity, @Nullable Map<String, ?> registryConfigs) { return new ConfluentRegistryAvroDeserializationSchema<>( tClass, null, new CachedSchemaCoderProvider(null, url, identityMapCapacity, registryConfigs)); } }
of
java
apache__dubbo
dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/mesh/rule/virtualservice/match/ListStringMatch.java
{ "start": 910, "end": 1351 }
class ____ { private List<StringMatch> oneof; public List<StringMatch> getOneof() { return oneof; } public void setOneof(List<StringMatch> oneof) { this.oneof = oneof; } public boolean isMatch(String input) { for (StringMatch stringMatch : oneof) { if (stringMatch.isMatch(input)) { return true; } } return false; } }
ListStringMatch
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/resume/ResumeAction.java
{ "start": 925, "end": 1248 }
interface ____ { /** * Runs an action on an resumable (entry) * * @param key the resumable key * @param value the resumable value * * @return true if the entry addressed should be invalidated or false otherwise */ boolean evalEntry(Object key, Object value); }
ResumeAction
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest90.java
{ "start": 942, "end": 4491 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "CREATE TABLE \"XZZYYY\".\"ZT_TJ_ASJ_ALL\" \n" + " ( \"XZQH\" VARCHAR2(50), \n" + " \"SJLX\" VARCHAR2(20), \n" + " \"FAS\" NUMBER, \n" + " \"SQFAS\" NUMBER, \n" + " \"TQFAS\" NUMBER, \n" + " \"TJSJ\" DATE DEFAULT SYSDATE, \n" + " \"FATB\" NUMBER GENERATED ALWAYS AS (ROUND((\"FAS\"-\"TQFAS\")/DECODE(\"TQFAS\",0,1,\"TQFAS\"),2)*100) VIRTUAL VISIBLE , \n" + " \"FAHB\" NUMBER GENERATED ALWAYS AS (ROUND((\"FAS\"-\"SQFAS\")/DECODE(\"SQFAS\",0,1,\"SQFAS\"),2)*100) VIRTUAL VISIBLE \n" + " ) SEGMENT CREATION IMMEDIATE \n" + " PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" + " NOCOMPRESS LOGGING\n" + " STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645\n" + " PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1\n" + " BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)\n" + " TABLESPACE \"TBS_XZZYYY\" "; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals("CREATE TABLE \"XZZYYY\".\"ZT_TJ_ASJ_ALL\" (\n" + "\t\"XZQH\" VARCHAR2(50),\n" + "\t\"SJLX\" VARCHAR2(20),\n" + "\t\"FAS\" NUMBER,\n" + "\t\"SQFAS\" NUMBER,\n" + "\t\"TQFAS\" NUMBER,\n" + "\t\"TJSJ\" DATE DEFAULT SYSDATE,\n" + "\t\"FATB\" NUMBER GENERATED ALWAYS AS (ROUND((\"FAS\" - \"TQFAS\") / DECODE(\"TQFAS\", 0, 1, \"TQFAS\"), 2) * 100) VIRTUAL VISIBLE,\n" + "\t\"FAHB\" NUMBER GENERATED ALWAYS AS (ROUND((\"FAS\" - \"SQFAS\") / DECODE(\"SQFAS\", 0, 1, \"SQFAS\"), 2) * 100) VIRTUAL VISIBLE\n" + ")\n" + "PCTFREE 10\n" + "PCTUSED 40\n" + "INITRANS 1\n" + "MAXTRANS 255\n" + "NOCOMPRESS\n" + "LOGGING\n" + "TABLESPACE \"TBS_XZZYYY\"\n" + "STORAGE (\n" + "\tINITIAL 65536\n" + "\tNEXT 1048576\n" + "\tMINEXTENTS 1\n" + "\tMAXEXTENTS 2147483645\n" + "\tPCTINCREASE 0\n" + "\tFREELISTS 1\n" + "\tFREELIST GROUPS 1\n" + "\tBUFFER_POOL DEFAULT\n" + "\tFLASH_CACHE DEFAULT\n" + "\tCELL_FLASH_CACHE DEFAULT\n" + ")", stmt.toString()); } }
OracleCreateTableTest90
java
quarkusio__quarkus
extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/ListCommandTest.java
{ "start": 814, "end": 16475 }
class ____ extends DatasourceTestBase { private RedisDataSource ds; static String key = "key-list"; private ListCommands<String, Person> lists; @BeforeEach void initialize() { ds = new BlockingRedisDataSourceImpl(vertx, redis, api, Duration.ofSeconds(5)); lists = ds.list(Person.class); } @AfterEach public void clear() { ds.flushall(); } @Test void getDataSource() { assertThat(ds).isEqualTo(lists.getDataSource()); } @Test void blpop() { lists.rpush("two", Person.person2, Person.person3); assertThat(lists.blpop(Duration.ofSeconds(1), "one", "two")).isEqualTo(KeyValue.of("two", Person.person2)); } @Test @RequiresRedis7OrHigher void blmpop() { lists.rpush("two", Person.person1, Person.person2, Person.person3); assertThat(lists.blmpop(Duration.ofSeconds(1), Position.RIGHT, "one", "two")) .isEqualTo(KeyValue.of("two", Person.person3)); assertThat(lists.blmpop(Duration.ofSeconds(1), Position.LEFT, "one", "two")) .isEqualTo(KeyValue.of("two", Person.person1)); assertThat(lists.blmpop(Duration.ofSeconds(1), Position.LEFT, "one", "two")) .isEqualTo(KeyValue.of("two", Person.person2)); assertThat(lists.blmpop(Duration.ofSeconds(1), Position.LEFT, "one", "two")).isNull(); } @Test @RequiresRedis7OrHigher void blmpopMany() { lists.rpush("two", Person.person1, Person.person2, Person.person3); assertThat(lists.blmpop(Duration.ofSeconds(1), Position.RIGHT, 2, "one", "two")) .containsExactly(KeyValue.of("two", Person.person3), KeyValue.of("two", Person.person2)); assertThat(lists.blmpop(Duration.ofSeconds(1), Position.RIGHT, 2, "one", "two")) .containsExactly(KeyValue.of("two", Person.person1)); assertThat(lists.blmpop(Duration.ofSeconds(1), Position.RIGHT, 2, "one", "two")).isEmpty(); } @Test void blpopTimeout() { assertThat(lists.blpop(Duration.ofSeconds(1), key)).isNull(); } @Test void brpop() { lists.rpush("two", Person.person2, Person.person3); assertThat(lists.brpop(Duration.ofSeconds(1), "one", "two")).isEqualTo(KeyValue.of("two", Person.person3)); } @Test void brpopDoubleTimeout() { lists.rpush("two", Person.person2, Person.person3); assertThat(lists.brpop(Duration.ofSeconds(1), "one", "two")).isEqualTo(KeyValue.of("two", Person.person3)); } @Test void brpoplpush() { lists.rpush("one", Person.person1, Person.person2); lists.rpush("two", Person.person3, Person.person4); assertThat(lists.brpoplpush(Duration.ofSeconds(1), "one", "two")).isEqualTo(Person.person2); assertThat(lists.lrange("one", 0, -1)).isEqualTo(List.of(Person.person1)); assertThat(lists.lrange("two", 0, -1)).isEqualTo(List.of(Person.person2, Person.person3, Person.person4)); } @Test void lindex() { assertThat(lists.lindex(key, 0)).isNull(); lists.rpush(key, Person.person1); assertThat(lists.lindex(key, 0)).isEqualTo(Person.person1); } @Test void linsertBefore() { assertThat(lists.linsertBeforePivot(key, Person.person1, Person.person2)).isEqualTo(0); lists.rpush(key, Person.person1); lists.rpush(key, Person.person3); assertThat(lists.linsertBeforePivot(key, Person.person3, Person.person2)).isEqualTo(3); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person2, Person.person3)); } @Test void linsertAfter() { assertThat(lists.linsertAfterPivot(key, Person.person1, Person.person2)).isEqualTo(0); lists.rpush(key, Person.person1); lists.rpush(key, Person.person3); assertThat(lists.linsertAfterPivot(key, Person.person3, Person.person2)).isEqualTo(3); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person3, Person.person2)); } @Test void llen() { assertThat(lists.llen(key)).isEqualTo(0); lists.lpush(key, Person.person1); assertThat(lists.llen(key)).isEqualTo(1); } @Test void lpop() { assertThat(lists.lpop(key)).isNull(); lists.rpush(key, Person.person1, Person.person2); assertThat(lists.lpop(key)).isEqualTo(Person.person1); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person2)); } @Test @RequiresRedis7OrHigher void lmpop() { assertThat(lists.lmpop(Position.RIGHT, key)).isNull(); lists.rpush(key, Person.person1, Person.person2); assertThat(lists.lmpop(Position.RIGHT, key)).isEqualTo(KeyValue.of(key, Person.person2)); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1)); } @Test @RequiresRedis7OrHigher void lmpopMany() { assertThat(lists.lmpop(Position.RIGHT, 2, key)).isEmpty(); lists.rpush(key, Person.person1, Person.person2); assertThat(lists.lmpop(Position.RIGHT, 2, key)).containsExactly(KeyValue.of(key, Person.person2), KeyValue.of(key, Person.person1)); assertThat(lists.lrange(key, 0, -1)).isEmpty(); assertThat(lists.lmpop(Position.RIGHT, 2, key)).isEmpty(); } @Test @RequiresRedis6OrHigher void lpopCount() { assertThat(lists.lpop(key, 1)).isEqualTo(List.of()); lists.rpush(key, Person.person1, Person.person2); assertThat(lists.lpop(key, 3)).isEqualTo(List.of(Person.person1, Person.person2)); } @Test @RequiresRedis6OrHigher void lpos() { lists.rpush(key, Person.person4, Person.person5, Person.person6, Person.person1, Person.person2, Person.person3, Person.person6, Person.person6); assertThat(lists.lpos("nope", Person.person4)).isEmpty(); assertThat(lists.lpos(key, new Person("john", "doe"))).isEmpty(); assertThat(lists.lpos(key, Person.person4)).hasValue(0); assertThat(lists.lpos(key, Person.person6)).hasValue(2); Assertions.assertThat(lists.lpos(key, Person.person6, new LPosArgs().rank(1))).hasValue(2); Assertions.assertThat(lists.lpos(key, Person.person6, new LPosArgs().rank(2))).hasValue(6); Assertions.assertThat(lists.lpos(key, Person.person6, new LPosArgs().rank(4))).isEmpty(); Assertions.assertThat(lists.lpos(key, Person.person6, 0)).contains(2L, 6L, 7L); assertThat(lists.lpos(key, Person.person6, 0, new LPosArgs().maxlen(1))).isEmpty(); } @Test void lpush() { Assertions.assertThat(lists.lpush(key, Person.person2)).isEqualTo(1); Assertions.assertThat(lists.lpush(key, Person.person1)).isEqualTo(2); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person2)); assertThat(lists.lpush(key, Person.person3, Person.person4)).isEqualTo(4); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person4, Person.person3, Person.person1, Person.person2)); } @Test void lpushx() { Assertions.assertThat(lists.lpushx(key, Person.person2)).isEqualTo(0); lists.lpush(key, Person.person2); Assertions.assertThat(lists.lpushx(key, Person.person1)).isEqualTo(2); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person2)); } @Test void lpushxMultiple() { assertThat(lists.lpushx(key, Person.person1, Person.person2)).isEqualTo(0); lists.lpush(key, Person.person2); assertThat(lists.lpushx(key, Person.person1, Person.person3)).isEqualTo(3); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person3, Person.person1, Person.person2)); } @Test void lrange() { assertThat(lists.lrange(key, 0, 10).isEmpty()).isTrue(); lists.rpush(key, Person.person1, Person.person2, Person.person3); List<Person> range = lists.lrange(key, 0, 1); assertThat(range).hasSize(2); assertThat(range.get(0)).isEqualTo(Person.person1); assertThat(range.get(1)).isEqualTo(Person.person2); assertThat(lists.lrange(key, 0, -1)).hasSize(3); } @Test void lrem() { assertThat(lists.lrem(key, 0, Person.person6)).isEqualTo(0); lists.rpush(key, Person.person1, Person.person2, Person.person1, Person.person2, Person.person1); assertThat(lists.lrem(key, 1, Person.person1)).isEqualTo(1); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person2, Person.person1, Person.person2, Person.person1)); lists.lpush(key, Person.person1); assertThat(lists.lrem(key, -1, Person.person1)).isEqualTo(1); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person2, Person.person1, Person.person2)); lists.lpush(key, Person.person1); assertThat(lists.lrem(key, 0, Person.person1)).isEqualTo(3); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person2, Person.person2)); } @Test void lset() { lists.rpush(key, Person.person1, Person.person2, Person.person3); lists.lset(key, 2, Person.person6); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person2, Person.person6)); } @Test void ltrim() { lists.rpush(key, Person.person1, Person.person2, Person.person3, Person.person4, Person.person5, Person.person6); lists.ltrim(key, 0, 3); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person2, Person.person3, Person.person4)); lists.ltrim(key, -2, -1); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person3, Person.person4)); } @Test void rpop() { assertThat(lists.rpop(key)).isNull(); lists.rpush(key, Person.person1, Person.person2); assertThat(lists.rpop(key)).isEqualTo(Person.person2); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1)); } @Test @RequiresRedis6OrHigher void rpopCount() { assertThat(lists.rpop(key, 1)).isEqualTo(List.of()); lists.rpush(key, Person.person1, Person.person2); assertThat(lists.rpop(key, 3)).isEqualTo(List.of(Person.person2, Person.person1)); } @Test void rpoplpush() { assertThat(lists.rpoplpush("one", "two")).isNull(); lists.rpush("one", Person.person1, Person.person2); lists.rpush("two", Person.person3, Person.person4); assertThat(lists.rpoplpush("one", "two")).isEqualTo(Person.person2); assertThat(lists.lrange("one", 0, -1)).isEqualTo(List.of(Person.person1)); assertThat(lists.lrange("two", 0, -1)).isEqualTo(List.of(Person.person2, Person.person3, Person.person4)); } @Test void rpush() { Assertions.assertThat(lists.rpush(key, Person.person1)).isEqualTo(1); Assertions.assertThat(lists.rpush(key, Person.person2)).isEqualTo(2); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person2)); assertThat(lists.rpush(key, Person.person3, Person.person4)).isEqualTo(4); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person2, Person.person3, Person.person4)); } @Test void rpushx() { Assertions.assertThat(lists.rpushx(key, Person.person1)).isEqualTo(0); lists.rpush(key, Person.person1); Assertions.assertThat(lists.rpushx(key, Person.person2)).isEqualTo(2); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person2)); } @Test void rpushxMultiple() { assertThat(lists.rpushx(key, Person.person2, Person.person3)).isEqualTo(0); lists.rpush(key, Person.person1); assertThat(lists.rpushx(key, Person.person2, Person.person3)).isEqualTo(3); assertThat(lists.lrange(key, 0, -1)).isEqualTo(List.of(Person.person1, Person.person2, Person.person3)); } @Test @RequiresRedis6OrHigher void lmove() { String list1 = key; String list2 = key + "-2"; lists.rpush(list1, Person.person1, Person.person2, Person.person3); lists.lmove(list1, list2, Position.RIGHT, Position.LEFT); assertThat(lists.lrange(list1, 0, -1)).containsExactly(Person.person1, Person.person2); assertThat(lists.lrange(list2, 0, -1)).containsOnly(Person.person3); } @Test @RequiresRedis6OrHigher void blmove() { String list1 = key; String list2 = key + "-2"; lists.rpush(list1, Person.person1, Person.person2, Person.person3); lists.blmove(list1, list2, Position.LEFT, Position.RIGHT, Duration.ofSeconds(1)); assertThat(lists.lrange(list1, 0, -1)).containsExactly(Person.person2, Person.person3); assertThat(lists.lrange(list2, 0, -1)).containsOnly(Person.person1); } @Test @RequiresRedis6OrHigher void sort() { ListCommands<String, String> commands = ds.list(String.class, String.class); commands.rpush(key, "9", "5", "1", "3", "5", "8", "7", "6", "2", "4"); assertThat(commands.sort(key)).containsExactly("1", "2", "3", "4", "5", "5", "6", "7", "8", "9"); assertThat(commands.sort(key, new SortArgs().descending())).containsExactly("9", "8", "7", "6", "5", "5", "4", "3", "2", "1"); String k = key + "-alpha"; commands.rpush(k, "a", "e", "f", "b"); assertThat(commands.sort(k, new SortArgs().alpha())).containsExactly("a", "b", "e", "f"); commands.sortAndStore(k, "dest1", new SortArgs().alpha()); commands.sortAndStore(key, "dest2"); assertThat(commands.lpop("dest1", 100)).containsExactly("a", "b", "e", "f"); assertThat(commands.lpop("dest2", 100)).containsExactly("1", "2", "3", "4", "5", "5", "6", "7", "8", "9"); } @Test void testListWithTypeReference() { var lists = ds.list(new TypeReference<List<Person>>() { // Empty on purpose }); var l1 = List.of(Person.person1, Person.person2); var l2 = List.of(Person.person1, Person.person3); lists.rpush(key, l1, l2); assertThat(lists.blpop(Duration.ofSeconds(1), "one", key)).isEqualTo(KeyValue.of(key, l1)); } @Test void testJacksonPolymorphism() { var cmd = ds.list(Animal.class); var cat = new Cat(); cat.setId("1234"); cat.setName("the cat"); var rabbit = new Rabbit(); rabbit.setName("roxanne"); rabbit.setColor("grey"); cmd.lpush(key, cat, rabbit); var shouldBeACat = cmd.rpop(key); var shouldBeARabbit = cmd.rpop(key); assertThat(shouldBeACat).isInstanceOf(Cat.class) .satisfies(animal -> { assertThat(animal.getName()).isEqualTo("the cat"); assertThat(((Cat) animal).getId()).isEqualTo("1234"); }); assertThat(shouldBeARabbit).isInstanceOf(Rabbit.class) .satisfies(animal -> { assertThat(animal.getName()).isEqualTo("roxanne"); assertThat(((Rabbit) animal).getColor()).isEqualTo("grey"); }); } @JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonSubTypes({ @JsonSubTypes.Type(value = Cat.class, name = "Cat"), @JsonSubTypes.Type(value = Rabbit.class, name = "Rabbit") }) public static
ListCommandTest
java
junit-team__junit5
junit-platform-suite-api/src/main/java/org/junit/platform/suite/api/SelectMethod.java
{ "start": 2022, "end": 4107 }
class ____ for the types of parameters accepted * by the method. * * <p>Array parameter types may be specified using either the JVM's internal * String representation (e.g., {@code [[I} for {@code int[][]}, * {@code [Ljava.lang.String;} for {@code java.lang.String[]}, etc.) or * <em>source code syntax</em> (e.g., {@code int[][]}, {@code java.lang.String[]}, * etc.). * * <table class="plain"> * <caption>Examples</caption> * <tr><th>Method</th><th>Fully Qualified Method Name</th></tr> * <tr><td>{@code java.lang.String.chars()}</td><td>{@code java.lang.String#chars}</td></tr> * <tr><td>{@code java.lang.String.chars()}</td><td>{@code java.lang.String#chars()}</td></tr> * <tr><td>{@code java.lang.String.equalsIgnoreCase(String)}</td><td>{@code java.lang.String#equalsIgnoreCase(java.lang.String)}</td></tr> * <tr><td>{@code java.lang.String.substring(int, int)}</td><td>{@code java.lang.String#substring(int, int)}</td></tr> * <tr><td>{@code example.Calc.avg(int[])}</td><td>{@code example.Calc#avg([I)}</td></tr> * <tr><td>{@code example.Calc.avg(int[])}</td><td>{@code example.Calc#avg(int[])}</td></tr> * <tr><td>{@code example.Matrix.multiply(double[][])}</td><td>{@code example.Matrix#multiply([[D)}</td></tr> * <tr><td>{@code example.Matrix.multiply(double[][])}</td><td>{@code example.Matrix#multiply(double[][])}</td></tr> * <tr><td>{@code example.Service.process(String[])}</td><td>{@code example.Service#process([Ljava.lang.String;)}</td></tr> * <tr><td>{@code example.Service.process(String[])}</td><td>{@code example.Service#process(java.lang.String[])}</td></tr> * <tr><td>{@code example.Service.process(String[][])}</td><td>{@code example.Service#process([[Ljava.lang.String;)}</td></tr> * <tr><td>{@code example.Service.process(String[][])}</td><td>{@code example.Service#process(java.lang.String[][])}</td></tr> * </table> * * <p>Cannot be combined with any other attribute. * * @see org.junit.platform.engine.discovery.DiscoverySelectors#selectMethod(String) */ String value() default ""; /** * The
names
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 21061, "end": 21594 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return dialect instanceof H2Dialect || dialect instanceof HSQLDialect || dialect instanceof MySQLDialect || dialect instanceof PostgreSQLDialect || dialect instanceof HANADialect || dialect instanceof CockroachDialect || dialect instanceof DB2Dialect || dialect instanceof OracleDialect || dialect instanceof SpannerDialect || dialect instanceof SQLServerDialect; } } public static
SupportsStringAggregation
java
apache__spark
core/src/test/java/org/apache/spark/launcher/SparkLauncherSuite.java
{ "start": 11027, "end": 12024 }
class ____ { /** * SPARK-23020: there's a race caused by a child app finishing too quickly. This would cause * the InProcessAppHandle to dispose of itself even before the child connection was properly * established, so no state changes would be detected for the application and its final * state would be LOST. * * It's not really possible to fix that race safely in the handle code itself without changing * the way in-process apps talk to the launcher library, so we work around that in the test by * synchronizing on this object. */ public static final Object LOCK = new Object(); public static void main(String[] args) throws Exception { assertNotEquals(0, args.length); assertEquals("hello", args[0]); new SparkContext().stop(); synchronized (LOCK) { LOCK.notifyAll(); } } } /** * Similar to {@link InProcessTestApp} except it throws an exception */ public static
InProcessTestApp
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/params/provider/FieldArgumentsProviderTests.java
{ "start": 1840, "end": 7429 }
class ____ { @Test void providesArgumentsUsingStreamSupplier() { var arguments = provideArguments("stringStreamSupplier"); assertThat(arguments).containsExactly(array("foo"), array("bar")); } @Test void providesArgumentsUsingIntStreamSupplier() { var arguments = provideArguments("intStreamSupplier"); assertThat(arguments).containsExactly(array(1), array(2)); } @Test void providesArgumentsUsingLongStreamSupplier() { var arguments = provideArguments("longStreamSupplier"); assertThat(arguments).containsExactly(array(1L), array(2L)); } @Test void providesArgumentsUsingDoubleStreamSupplier() { var arguments = provideArguments("doubleStreamSupplier"); assertThat(arguments).containsExactly(array(1.2), array(3.4)); } @Test void providesArgumentsUsingStreamSupplierOfIntArrays() { var arguments = provideArguments("intArrayStreamSupplier"); assertThat(arguments).containsExactly( // new Object[] { new int[] { 1, 2 } }, // new Object[] { new int[] { 3, 4 } } // ); } @Test void providesArgumentsUsingStreamSupplierOfTwoDimensionalIntArrays() { var arguments = provideArguments("twoDimensionalIntArrayStreamSupplier"); assertThat(arguments).containsExactly( // array((Object) new int[][] { { 1, 2 }, { 2, 3 } }), // array((Object) new int[][] { { 4, 5 }, { 5, 6 } }) // ); } @Test void providesArgumentsUsingStreamSupplierOfObjectArrays() { var arguments = provideArguments("objectArrayStreamSupplier"); assertThat(arguments).containsExactly(array("foo", 42), array("bar", 23)); } @Test void providesArgumentsUsingStreamSupplierOfTwoDimensionalObjectArrays() { var arguments = provideArguments("twoDimensionalObjectArrayStreamSupplier"); assertThat(arguments).containsExactly( // array((Object) array(array("a", 1), array("b", 2))), // array((Object) array(array("c", 3), array("d", 4))) // ); } @Test void providesArgumentsUsingStreamSupplierOfArguments() { var arguments = provideArguments("argumentsStreamSupplier"); assertThat(arguments).containsExactly(array("foo", 42), array("bar", 23)); } @Test void providesArgumentsUsingIterable() { var arguments = provideArguments("stringIterable"); assertThat(arguments).containsExactly(array("foo"), array("bar")); } @Test void providesArgumentsUsingMultipleFields() { var arguments = provideArguments("stringStreamSupplier", "stringIterable"); assertThat(arguments).containsExactly(array("foo"), array("bar"), array("foo"), array("bar")); } @Test void providesArgumentsUsingIterableOfObjectArrays() { var arguments = provideArguments("objectArrayIterable"); assertThat(arguments).containsExactly(array("foo", 42), array("bar", 23)); } @Test void providesArgumentsUsingListOfStrings() { var arguments = provideArguments("stringList"); assertThat(arguments).containsExactly(array("foo"), array("bar")); } @Test void providesArgumentsUsingListOfObjectArrays() { var arguments = provideArguments("objectArrayList"); assertThat(arguments).containsExactly(array("foo", 42), array("bar", 23)); } @Test void providesArgumentsFromNonStaticFieldWhenStaticIsNotRequired() { var lifecyclePerClass = true; var arguments = provideArguments(NonStaticTestCase.class, lifecyclePerClass, "nonStaticStringStreamSupplier"); assertThat(arguments).containsExactly(array("foo"), array("bar")); } @Test void providesArgumentsUsingDefaultFieldName() { var testClass = DefaultFieldNameTestCase.class; var methodName = "testDefaultFieldName"; var testMethod = findMethod(testClass, methodName, String.class).get(); var arguments = provideArguments(testClass, testMethod, false, new String[0]); assertThat(arguments).containsExactly(array("foo"), array("bar")); } @Test void providesArgumentsUsingExternalField() { var arguments = provideArguments(ExternalFields.class.getName() + "#strings"); assertThat(arguments).containsExactly(array("string1"), array("string2")); } @Test void providesArgumentsUsingExternalFieldInTypeFromDifferentClassLoader() throws Exception { try (var testClassLoader = TestClassLoader.forClasses(TestCase.class, ExternalFields.class)) { var testClass = testClassLoader.loadClass(TestCase.class.getName()); var fullyQualifiedFieldName = ExternalFields.class.getName() + "#strings"; assertThat(testClass.getClassLoader()).isSameAs(testClassLoader); var arguments = provideArguments(testClass, false, fullyQualifiedFieldName); assertThat(arguments).containsExactly(array("string1"), array("string2")); var field = FieldArgumentsProvider.findField(testClass, fullyQualifiedFieldName); assertThat(field).isNotNull(); assertThat(field.getName()).isEqualTo("strings"); var declaringClass = field.getDeclaringClass(); assertThat(declaringClass.getName()).isEqualTo(ExternalFields.class.getName()); assertThat(declaringClass).isNotEqualTo(ExternalFields.class); assertThat(declaringClass.getClassLoader()).isSameAs(testClassLoader); } } @Test void providesArgumentsUsingExternalFieldFromStaticNestedClass() { var arguments = provideArguments(ExternalFields.Nested.class.getName() + "#strings"); assertThat(arguments).containsExactly(array("nested string1"), array("nested string2")); } @Test void providesArgumentsUsingExternalAndInternalFieldsCombined() { var arguments = provideArguments("stringStreamSupplier", ExternalFields.class.getName() + "#strings"); assertThat(arguments).containsExactly(array("foo"), array("bar"), array("string1"), array("string2")); } @Nested
FieldArgumentsProviderTests
java
apache__maven
impl/maven-di/src/test/java/org/apache/maven/di/impl/InjectorImplTest.java
{ "start": 11748, "end": 12174 }
class ____ { @Inject @Nullable MyService service; } } @Test void testNullableOnConstructor() { Injector injector = Injector.create().bindImplicit(NullableOnConstructor.class); NullableOnConstructor.MyMojo mojo = injector.getInstance(NullableOnConstructor.MyMojo.class); assertNotNull(mojo); assertNull(mojo.service); } static
MyMojo
java
google__dagger
javatests/dagger/internal/codegen/DependencyCycleValidationTest.java
{ "start": 17536, "end": 17676 }
interface ____ {", " Grandchild.Builder grandchild();", "", " @Subcomponent.Builder", "
Child
java
quarkusio__quarkus
extensions/hibernate-reactive/deployment/src/test/java/io/quarkus/hibernate/reactive/context/ContextFruitResource.java
{ "start": 548, "end": 935 }
class ____ { @Inject Mutiny.SessionFactory sf; @GET @Path("valid") public Uni<Fruit> get() { return sf.withTransaction((s, t) -> s.find(Fruit.class, 1)); } @GET @Path("invalid") public Uni<Fruit> getSingle(@RestPath Integer id) { VertxContextSafetyToggle.setCurrentContextSafe(false); return get(); } }
ContextFruitResource
java
redisson__redisson
redisson-spring-data/redisson-spring-data-21/src/main/java/org/redisson/spring/data/connection/RedissonReactiveHashCommands.java
{ "start": 2359, "end": 11986 }
class ____ extends RedissonBaseReactive implements ReactiveHashCommands { RedissonReactiveHashCommands(CommandReactiveExecutor executorService) { super(executorService); } private static final RedisCommand<String> HMSET = new RedisCommand<String>("HMSET"); @Override public Flux<BooleanResponse<HSetCommand>> hSet(Publisher<HSetCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getFieldValueMap(), "FieldValueMap must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); if (command.getFieldValueMap().size() == 1) { Entry<ByteBuffer, ByteBuffer> entry = command.getFieldValueMap().entrySet().iterator().next(); byte[] mapKeyBuf = toByteArray(entry.getKey()); byte[] mapValueBuf = toByteArray(entry.getValue()); RedisCommand<Boolean> cmd = RedisCommands.HSETNX; if (command.isUpsert()) { cmd = RedisCommands.HSET; } Mono<Boolean> m = write(keyBuf, StringCodec.INSTANCE, cmd, keyBuf, mapKeyBuf, mapValueBuf); return m.map(v -> new BooleanResponse<>(command, v)); } else { List<Object> params = new ArrayList<Object>(command.getFieldValueMap().size()*2 + 1); params.add(keyBuf); for (Entry<ByteBuffer, ByteBuffer> entry : command.getFieldValueMap().entrySet()) { params.add(toByteArray(entry.getKey())); params.add(toByteArray(entry.getValue())); } Mono<String> m = write(keyBuf, StringCodec.INSTANCE, HMSET, params.toArray()); return m.map(v -> new BooleanResponse<>(command, true)); } }); } private static final RedisCommand<List<Object>> HMGET = new RedisCommand<List<Object>>("HMGET", new MultiDecoder<List<Object>>() { @Override public List<Object> decode(List<Object> parts, State state) { List<Object> list = parts.stream().filter(e -> e != null).collect(Collectors.toList()); if (list.isEmpty()) { return null; } return parts; } }); @Override public Flux<MultiValueResponse<HGetCommand, ByteBuffer>> hMGet(Publisher<HGetCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getFields(), "Fields must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); List<Object> args = new ArrayList<Object>(command.getFields().size() + 1); args.add(keyBuf); args.addAll(command.getFields().stream().map(buf -> toByteArray(buf)).collect(Collectors.toList())); Mono<List<byte[]>> m = read(keyBuf, ByteArrayCodec.INSTANCE, HMGET, args.toArray()); return m.map(v -> { List<ByteBuffer> values = v.stream().map(array -> { if (array != null) { return ByteBuffer.wrap(array); } return null; }).collect(Collectors.toList()); return new MultiValueResponse<>(command, values); }); }); } @Override public Flux<BooleanResponse<HExistsCommand>> hExists(Publisher<HExistsCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getField(), "Field must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); byte[] fieldBuf = toByteArray(command.getField()); Mono<Boolean> m =read(keyBuf, StringCodec.INSTANCE, RedisCommands.HEXISTS, keyBuf, fieldBuf); return m.map(v -> new BooleanResponse<>(command, v)); }); } @Override public Flux<NumericResponse<HDelCommand, Long>> hDel(Publisher<HDelCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getFields(), "Fields must not be null!"); List<Object> args = new ArrayList<Object>(command.getFields().size() + 1); args.add(toByteArray(command.getKey())); args.addAll(command.getFields().stream().map(v -> toByteArray(v)).collect(Collectors.toList())); Mono<Long> m = write((byte[])args.get(0), StringCodec.INSTANCE, RedisCommands.HDEL, args.toArray()); return m.map(v -> new NumericResponse<>(command, v)); }); } @Override public Flux<NumericResponse<KeyCommand, Long>> hLen(Publisher<KeyCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); Mono<Long> m = read(keyBuf, StringCodec.INSTANCE, RedisCommands.HLEN_LONG, keyBuf); return m.map(v -> new NumericResponse<>(command, v)); }); } @Override public Flux<CommandResponse<KeyCommand, Flux<ByteBuffer>>> hKeys(Publisher<KeyCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); Mono<Set<byte[]>> m = read(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.HKEYS, keyBuf); return m.map(v -> new CommandResponse<>(command, Flux.fromIterable(v).map(e -> ByteBuffer.wrap(e)))); }); } @Override public Flux<CommandResponse<KeyCommand, Flux<ByteBuffer>>> hVals(Publisher<KeyCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); Mono<List<byte[]>> m = read(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.HVALS, keyBuf); return m.map(v -> new CommandResponse<>(command, Flux.fromIterable(v).map(e -> ByteBuffer.wrap(e)))); }); } @Override public Flux<CommandResponse<KeyCommand, Flux<Entry<ByteBuffer, ByteBuffer>>>> hGetAll( Publisher<KeyCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); Mono<Map<byte[], byte[]>> m = read(keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.HGETALL, keyBuf); Mono<Map<ByteBuffer, ByteBuffer>> f = m.map(v -> v.entrySet().stream().collect(Collectors.toMap(e -> ByteBuffer.wrap(e.getKey()), e -> ByteBuffer.wrap(e.getValue())))); return f.map(v -> new CommandResponse<>(command, Flux.fromIterable(v.entrySet()))); }); } @Override public Flux<CommandResponse<KeyCommand, Flux<Entry<ByteBuffer, ByteBuffer>>>> hScan( Publisher<KeyScanCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getOptions(), "ScanOptions must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); Flux<Entry<Object, Object>> flux = Flux.create(new MapReactiveIterator<Object, Object, Entry<Object, Object>>(null, null, 0) { @Override public RFuture<ScanResult<Object>> scanIterator(RedisClient client, String nextIterPos) { if (command.getOptions().getPattern() == null) { return executorService.readAsync(client, keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.HSCAN, keyBuf, nextIterPos, "COUNT", Optional.ofNullable(command.getOptions().getCount()).orElse(10L)); } return executorService.readAsync(client, keyBuf, ByteArrayCodec.INSTANCE, RedisCommands.HSCAN, keyBuf, nextIterPos, "MATCH", command.getOptions().getPattern(), "COUNT", Optional.ofNullable(command.getOptions().getCount()).orElse(10L)); } }); Flux<Entry<ByteBuffer, ByteBuffer>> f = flux.map(v -> Collections.singletonMap(ByteBuffer.wrap((byte[])v.getKey()), ByteBuffer.wrap((byte[])v.getValue())).entrySet().iterator().next()); return Mono.just(new CommandResponse<>(command, f)); }); } private static final RedisCommand<Long> HSTRLEN = new RedisCommand<Long>("HSTRLEN"); @Override public Flux<NumericResponse<HStrLenCommand, Long>> hStrLen(Publisher<HStrLenCommand> commands) { return execute(commands, command -> { Assert.notNull(command.getKey(), "Key must not be null!"); Assert.notNull(command.getField(), "Field must not be null!"); byte[] keyBuf = toByteArray(command.getKey()); byte[] fieldBuf = toByteArray(command.getField()); Mono<Long> m = read(keyBuf, StringCodec.INSTANCE, HSTRLEN, keyBuf, fieldBuf); return m.map(v -> new NumericResponse<>(command, v)); }); } }
RedissonReactiveHashCommands
java
redisson__redisson
redisson/src/main/java/org/redisson/api/listener/StreamRemoveConsumerListener.java
{ "start": 953, "end": 1164 }
interface ____ extends ObjectListener { /** * Invoked when a Stream Consumer is removed * * @param name object name */ void onRemoveConsumer(String name); }
StreamRemoveConsumerListener
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/InitDestroyMethodLifecycleTests.java
{ "start": 14675, "end": 14989 }
class ____ extends CustomInitDestroyBean implements InitializingBean, DisposableBean { @Override public void afterPropertiesSet() { this.initMethods.add("afterPropertiesSet"); } @Override public void destroy() { this.destroyMethods.add("destroy"); } } static
CustomInitializingDisposableBean
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/mutation/UpdateEntitiesWithPackageNamesStartingWithKeywordsTest.java
{ "start": 661, "end": 2031 }
class ____ { @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Test public void testUpdateEntityWithPackageNameStartingWithIn(SessionFactoryScope scope) { Any entity = new Any(); entity.setProp( "1" ); scope.inTransaction( session -> session.persist( entity ) ); scope.inTransaction( session -> { final Query query = session.createQuery( "UPDATE Any set prop = :prop WHERE id = :id " ); query.setParameter( "prop", "1" ); query.setParameter( "id", entity.getId() ); query.executeUpdate(); } ); scope.inTransaction( session -> session.createQuery( "DELETE FROM Any" ).executeUpdate() ); } @Test public void testUpdateEntityWithPackageNameStartingWithFrom(SessionFactoryScope scope) { In entity = new In(); entity.setProp( "1" ); scope.inTransaction( session -> session.persist( entity ) ); scope.inTransaction( session -> { final Query query = session.createQuery( "UPDATE In set prop = :prop WHERE id = :id " ); query.setParameter( "prop", "1" ); query.setParameter( "id", entity.getId() ); query.executeUpdate(); } ); scope.inTransaction( session -> session.createQuery( "DELETE FROM In" ).executeUpdate() ); } }
UpdateEntitiesWithPackageNamesStartingWithKeywordsTest
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/test/tls/Cert.java
{ "start": 723, "end": 4042 }
interface ____<K extends KeyCertOptions> extends Supplier<K> { Cert<KeyCertOptions> NONE = () -> null; Cert<JksOptions> SERVER_JKS = () -> new JksOptions().setPath("tls/server-keystore.jks").setPassword("wibble"); Cert<JksOptions> CLIENT_JKS = () -> new JksOptions().setPath("tls/client-keystore.jks").setPassword("wibble"); Cert<PfxOptions> SERVER_PKCS12 = () -> new PfxOptions().setPath("tls/server-keystore.p12").setPassword("wibble"); Cert<PfxOptions> CLIENT_PKCS12 = () -> new PfxOptions().setPath("tls/client-keystore.p12").setPassword("wibble"); Cert<PemKeyCertOptions> SERVER_PEM = () -> new PemKeyCertOptions().setKeyPath("tls/server-key.pem").setCertPath("tls/server-cert.pem"); Cert<PemKeyCertOptions> SERVER_PEM_RSA = () -> new PemKeyCertOptions().setKeyPath("tls/server-key-pkcs1.pem").setCertPath("tls/server-cert.pem"); Cert<PemKeyCertOptions> CLIENT_PEM = () -> new PemKeyCertOptions().setKeyPath("tls/client-key.pem").setCertPath("tls/client-cert.pem"); Cert<JksOptions> SERVER_JKS_ROOT_CA = () -> new JksOptions().setPath("tls/server-keystore-root-ca.jks").setPassword("wibble"); Cert<PfxOptions> SERVER_PKCS12_ROOT_CA = () -> new PfxOptions().setPath("tls/server-keystore-root-ca.p12").setPassword("wibble"); Cert<PemKeyCertOptions> SERVER_PEM_ROOT_CA = () -> new PemKeyCertOptions().setKeyPath("tls/server-key.pem").setCertPath("tls/server-cert-root-ca.pem"); Cert<PemKeyCertOptions> CLIENT_PEM_ROOT_CA = () -> new PemKeyCertOptions().setKeyPath("tls/client-key.pem").setCertPath("tls/client-cert-root-ca.pem"); Cert<PemKeyCertOptions> SERVER_PEM_INT_CA = () -> new PemKeyCertOptions().setKeyPath("tls/server-key.pem").setCertPath("tls/server-cert-int-ca.pem"); Cert<PemKeyCertOptions> SERVER_PEM_CA_CHAIN = () -> new PemKeyCertOptions().setKeyPath("tls/server-key.pem").setCertPath("tls/server-cert-ca-chain.pem"); Cert<PemKeyCertOptions> SERVER_PEM_OTHER_CA = () -> new PemKeyCertOptions().setKeyPath("tls/server-key.pem").setCertPath("tls/server-cert-other-ca.pem"); Cert<JksOptions> SERVER_MIM = () -> new JksOptions().setPath("tls/mim-server-keystore.jks").setPassword("wibble"); Cert<JksOptions> SNI_JKS = () -> new JksOptions().setPath("tls/sni-keystore.jks").setPassword("wibble"); Cert<PfxOptions> SNI_PKCS12 = () -> new PfxOptions().setPath("tls/sni-keystore.p12").setPassword("wibble"); Cert<PemKeyCertOptions> SNI_PEM = () -> new PemKeyCertOptions() .addKeyPath("tls/server-key.pem").addCertPath("tls/server-cert.pem") .addKeyPath("tls/host1-key.pem").addCertPath("tls/host1-cert.pem") .addKeyPath("tls/host2-key.pem").addCertPath("tls/host2-cert.pem") .addKeyPath("tls/host3-key.pem").addCertPath("tls/host3-cert.pem") .addKeyPath("tls/host4-key.pem").addCertPath("tls/host4-cert.pem") .addKeyPath("tls/host5-key.pem").addCertPath("tls/host5-cert.pem"); Cert<JksOptions> MULTIPLE_JKS = () -> new JksOptions().setPath("tls/multiple.jks").setPassword("wibble").setAlias("precious"); Cert<JksOptions> MULTIPLE_JKS_WRONG_ALIAS = () -> new JksOptions().setPath("tls/multiple.jks").setPassword("wibble").setAlias("preciouss"); Cert<JksOptions> MULTIPLE_JKS_ALIAS_PASSWORD = () -> new JksOptions().setPath("tls/multiple-alias-password.jks").setPassword("wibble").setAlias("fonky").setAliasPassword("family"); }
Cert
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/state/internals/RocksDBTimestampedSegmentedBytesStoreTest.java
{ "start": 857, "end": 1458 }
class ____ extends AbstractRocksDBSegmentedBytesStoreTest<TimestampedSegment> { private static final String METRICS_SCOPE = "metrics-scope"; RocksDBTimestampedSegmentedBytesStore getBytesStore() { return new RocksDBTimestampedSegmentedBytesStore( storeName, METRICS_SCOPE, retention, segmentInterval, schema ); } @Override TimestampedSegments newSegments() { return new TimestampedSegments(storeName, METRICS_SCOPE, retention, segmentInterval); } }
RocksDBTimestampedSegmentedBytesStoreTest
java
google__dagger
javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java
{ "start": 6704, "end": 6765 }
interface ____ {}", "", " static final
A
java
google__guava
android/guava-tests/test/com/google/common/collect/ImmutableMapTest.java
{ "start": 18907, "end": 29625 }
class ____ implements Comparable<ClassWithTerribleHashCode> { private final int value; ClassWithTerribleHashCode(int value) { this.value = value; } @Override public int compareTo(ClassWithTerribleHashCode that) { return Integer.compare(this.value, that.value); } @Override public boolean equals(@Nullable Object x) { return x instanceof ClassWithTerribleHashCode && ((ClassWithTerribleHashCode) x).value == value; } @Override public int hashCode() { return 23; } @Override public String toString() { return "ClassWithTerribleHashCode(" + value + ")"; } } @GwtIncompatible public void testBuildKeepingLast_collisions() { Map<ClassWithTerribleHashCode, Integer> expected = new LinkedHashMap<>(); Builder<ClassWithTerribleHashCode, Integer> builder = new Builder<>(); int size = 18; for (int i = 0; i < size; i++) { ClassWithTerribleHashCode key = new ClassWithTerribleHashCode(i); builder.put(key, i); builder.put(key, -i); expected.put(key, -i); } ImmutableMap<ClassWithTerribleHashCode, Integer> map = builder.buildKeepingLast(); assertThat(map).containsExactlyEntriesIn(expected).inOrder(); } @GwtIncompatible // Pattern, Matcher public void testBuilder_keepingLast_thenOrThrow() { ImmutableMap.Builder<String, Integer> builder = new Builder<String, Integer>() .put("three", 3) .put("one", 1) .put("five", 5) .put("four", 3) .put("four", 5) .put("four", 4) // this should win because it's last .put("two", 2); assertMapEquals( builder.buildKeepingLast(), "three", 3, "one", 1, "five", 5, "four", 4, "two", 2); IllegalArgumentException expected = assertThrows(IllegalArgumentException.class, () -> builder.buildOrThrow()); // We don't really care which values the exception message contains, but they should be // different from each other. If buildKeepingLast() collapsed duplicates, that might end up not // being true. Pattern pattern = Pattern.compile("Multiple entries with same key: four=(.*) and four=(.*)"); assertThat(expected).hasMessageThat().matches(pattern); Matcher matcher = pattern.matcher(expected.getMessage()); assertThat(matcher.matches()).isTrue(); assertThat(matcher.group(1)).isNotEqualTo(matcher.group(2)); } public void testOf() { assertMapEquals(ImmutableMap.of("one", 1), "one", 1); assertMapEquals(ImmutableMap.of("one", 1, "two", 2), "one", 1, "two", 2); assertMapEquals( ImmutableMap.of("one", 1, "two", 2, "three", 3), "one", 1, "two", 2, "three", 3); assertMapEquals( ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4), "one", 1, "two", 2, "three", 3, "four", 4); assertMapEquals( ImmutableMap.of("one", 1, "two", 2, "three", 3, "four", 4, "five", 5), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5); assertMapEquals( ImmutableMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6); assertMapEquals( ImmutableMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7); assertMapEquals( ImmutableMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8); assertMapEquals( ImmutableMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8, "nine", 9), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8, "nine", 9); assertMapEquals( ImmutableMap.of( "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8, "nine", 9, "ten", 10), "one", 1, "two", 2, "three", 3, "four", 4, "five", 5, "six", 6, "seven", 7, "eight", 8, "nine", 9, "ten", 10); } public void testOfNullKey() { assertThrows(NullPointerException.class, () -> ImmutableMap.of(null, 1)); assertThrows(NullPointerException.class, () -> ImmutableMap.of("one", 1, null, 2)); } public void testOfNullValue() { assertThrows(NullPointerException.class, () -> ImmutableMap.of("one", null)); assertThrows(NullPointerException.class, () -> ImmutableMap.of("one", 1, "two", null)); } public void testOfWithDuplicateKey() { assertThrows(IllegalArgumentException.class, () -> ImmutableMap.of("one", 1, "one", 1)); } public void testCopyOfEmptyMap() { ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(Collections.<String, Integer>emptyMap()); assertEquals(Collections.<String, Integer>emptyMap(), copy); assertSame(copy, ImmutableMap.copyOf(copy)); } public void testCopyOfSingletonMap() { ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(singletonMap("one", 1)); assertMapEquals(copy, "one", 1); assertSame(copy, ImmutableMap.copyOf(copy)); } public void testCopyOf() { Map<String, Integer> original = new LinkedHashMap<>(); original.put("one", 1); original.put("two", 2); original.put("three", 3); ImmutableMap<String, Integer> copy = ImmutableMap.copyOf(original); assertMapEquals(copy, "one", 1, "two", 2, "three", 3); assertSame(copy, ImmutableMap.copyOf(copy)); } // TODO(b/172823566): Use mainline testToImmutableMap once CollectorTester is usable to java7. public void testToImmutableMap_java7_combine() { ImmutableMap.Builder<String, Integer> zis = ImmutableMap.<String, Integer>builder().put("one", 1); ImmutableMap.Builder<String, Integer> zat = ImmutableMap.<String, Integer>builder().put("two", 2).put("three", 3); assertMapEquals(zis.combine(zat).build(), "one", 1, "two", 2, "three", 3); } // TODO(b/172823566): Use mainline testToImmutableMap once CollectorTester is usable to java7. public void testToImmutableMap_exceptionOnDuplicateKey_java7_combine() { ImmutableMap.Builder<String, Integer> zis = ImmutableMap.<String, Integer>builder().put("one", 1).put("two", 2); ImmutableMap.Builder<String, Integer> zat = ImmutableMap.<String, Integer>builder().put("two", 22).put("three", 3); assertThrows(IllegalArgumentException.class, () -> zis.combine(zat).build()); } public static void hashtableTestHelper(ImmutableList<Integer> sizes) { for (int size : sizes) { Builder<Integer, Integer> builder = ImmutableMap.builderWithExpectedSize(size); for (int i = 0; i < size; i++) { Integer integer = i; builder.put(integer, integer); } ImmutableMap<Integer, Integer> map = builder.build(); assertEquals(size, map.size()); int entries = 0; for (Integer key : map.keySet()) { assertEquals(entries, key.intValue()); assertSame(key, map.get(key)); entries++; } assertEquals(size, entries); } } public void testByteArrayHashtable() { hashtableTestHelper(ImmutableList.of(2, 89)); } public void testShortArrayHashtable() { hashtableTestHelper(ImmutableList.of(90, 22937)); } public void testIntArrayHashtable() { hashtableTestHelper(ImmutableList.of(22938)); } // Non-creation tests public void testNullGet() { ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1); assertThat(map.get(null)).isNull(); } public void testAsMultimap() { ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1, "won", 1, "two", 2, "too", 2, "three", 3); ImmutableSetMultimap<String, Integer> expected = ImmutableSetMultimap.of("one", 1, "won", 1, "two", 2, "too", 2, "three", 3); assertEquals(expected, map.asMultimap()); } public void testAsMultimapWhenEmpty() { ImmutableMap<String, Integer> map = ImmutableMap.of(); ImmutableSetMultimap<String, Integer> expected = ImmutableSetMultimap.of(); assertEquals(expected, map.asMultimap()); } public void testAsMultimapCaches() { ImmutableMap<String, Integer> map = ImmutableMap.of("one", 1); ImmutableSetMultimap<String, Integer> multimap1 = map.asMultimap(); ImmutableSetMultimap<String, Integer> multimap2 = map.asMultimap(); assertEquals(1, multimap1.asMap().size()); assertSame(multimap1, multimap2); } @J2ktIncompatible @GwtIncompatible // NullPointerTester public void testNullPointers() { NullPointerTester tester = new NullPointerTester(); tester.testAllPublicStaticMethods(ImmutableMap.class); tester.testAllPublicInstanceMethods(new ImmutableMap.Builder<Object, Object>()); tester.testAllPublicInstanceMethods(ImmutableMap.of()); tester.testAllPublicInstanceMethods(ImmutableMap.of("one", 1)); tester.testAllPublicInstanceMethods(ImmutableMap.of("one", 1, "two", 2, "three", 3)); } private static <K, V> void assertMapEquals(Map<K, V> map, Object... alternatingKeysAndValues) { Map<Object, Object> expected = new LinkedHashMap<>(); for (int i = 0; i < alternatingKeysAndValues.length; i += 2) { expected.put(alternatingKeysAndValues[i], alternatingKeysAndValues[i + 1]); } assertThat(map).containsExactlyEntriesIn(expected).inOrder(); } private static
ClassWithTerribleHashCode
java
google__guava
android/guava/src/com/google/common/collect/Maps.java
{ "start": 147454, "end": 149732 }
class ____<K extends @Nullable Object, V extends @Nullable Object> extends SortedKeySet<K, V> implements NavigableSet<K> { NavigableKeySet(NavigableMap<K, V> map) { super(map); } @Override NavigableMap<K, V> map() { return (NavigableMap<K, V>) map; } @Override public @Nullable K lower(@ParametricNullness K e) { return map().lowerKey(e); } @Override public @Nullable K floor(@ParametricNullness K e) { return map().floorKey(e); } @Override public @Nullable K ceiling(@ParametricNullness K e) { return map().ceilingKey(e); } @Override public @Nullable K higher(@ParametricNullness K e) { return map().higherKey(e); } @Override public @Nullable K pollFirst() { return keyOrNull(map().pollFirstEntry()); } @Override public @Nullable K pollLast() { return keyOrNull(map().pollLastEntry()); } @Override public NavigableSet<K> descendingSet() { return map().descendingKeySet(); } @Override public Iterator<K> descendingIterator() { return descendingSet().iterator(); } @Override public NavigableSet<K> subSet( @ParametricNullness K fromElement, boolean fromInclusive, @ParametricNullness K toElement, boolean toInclusive) { return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet(); } @Override public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) { return subSet(fromElement, true, toElement, false); } @Override public NavigableSet<K> headSet(@ParametricNullness K toElement, boolean inclusive) { return map().headMap(toElement, inclusive).navigableKeySet(); } @Override public SortedSet<K> headSet(@ParametricNullness K toElement) { return headSet(toElement, false); } @Override public NavigableSet<K> tailSet(@ParametricNullness K fromElement, boolean inclusive) { return map().tailMap(fromElement, inclusive).navigableKeySet(); } @Override public SortedSet<K> tailSet(@ParametricNullness K fromElement) { return tailSet(fromElement, true); } } static
NavigableKeySet
java
apache__camel
tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/GeneratePostCompileMojo.java
{ "start": 1512, "end": 1888 }
class ____ extends AbstractGenerateMojo { @Inject public GeneratePostCompileMojo(MavenProjectHelper projectHelper, BuildContext buildContext) { super(projectHelper, buildContext); } protected void doExecute() throws MojoFailureException, MojoExecutionException { // jandex invoke(PackageJandexMojo.class); } }
GeneratePostCompileMojo
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/java/typeutils/TypeExtractorInputFormatsTest.java
{ "start": 1509, "end": 4369 }
class ____ { @Test void testExtractInputFormatType() { InputFormat<?, ?> format = new DummyFloatInputFormat(); TypeInformation<?> typeInfo = TypeExtractor.getInputFormatTypes(format); assertThat(typeInfo).isEqualTo(BasicTypeInfo.FLOAT_TYPE_INFO); } @Test void testExtractDerivedInputFormatType() { // simple type { InputFormat<?, ?> format = new DerivedInputFormat(); TypeInformation<?> typeInfo = TypeExtractor.getInputFormatTypes(format); assertThat(typeInfo).isEqualTo(BasicTypeInfo.SHORT_TYPE_INFO); } // composite type { InputFormat<?, ?> format = new DerivedTupleInputFormat(); TypeInformation<?> typeInfo = TypeExtractor.getInputFormatTypes(format); assertThat(typeInfo.isTupleType()).isTrue(); assertThat(typeInfo).isInstanceOf(TupleTypeInfo.class); @SuppressWarnings("unchecked") TupleTypeInfo<Tuple3<String, Short, Double>> tupleInfo = (TupleTypeInfo<Tuple3<String, Short, Double>>) typeInfo; assertThat(tupleInfo.getArity()).isEqualTo(3); assertThat(tupleInfo.getTypeAt(0)).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); assertThat(tupleInfo.getTypeAt(1)).isEqualTo(BasicTypeInfo.SHORT_TYPE_INFO); assertThat(tupleInfo.getTypeAt(2)).isEqualTo(BasicTypeInfo.DOUBLE_TYPE_INFO); } } @Test void testMultiLevelDerivedInputFormatType() { // composite type InputFormat<?, ?> format = new FinalRelativeInputFormat(); TypeInformation<?> typeInfo = TypeExtractor.getInputFormatTypes(format); assertThat(typeInfo.isTupleType()).isTrue(); assertThat(typeInfo).isInstanceOf(TupleTypeInfo.class); @SuppressWarnings("unchecked") TupleTypeInfo<Tuple3<String, Integer, Double>> tupleInfo = (TupleTypeInfo<Tuple3<String, Integer, Double>>) typeInfo; assertThat(tupleInfo.getArity()).isEqualTo(3); assertThat(tupleInfo.getTypeAt(0)).isEqualTo(BasicTypeInfo.STRING_TYPE_INFO); assertThat(tupleInfo.getTypeAt(1)).isEqualTo(BasicTypeInfo.INT_TYPE_INFO); assertThat(tupleInfo.getTypeAt(2)).isEqualTo(BasicTypeInfo.DOUBLE_TYPE_INFO); } @Test void testQueryableFormatType() { InputFormat<?, ?> format = new QueryableInputFormat(); TypeInformation<?> typeInfo = TypeExtractor.getInputFormatTypes(format); assertThat(typeInfo).isEqualTo(BasicTypeInfo.DOUBLE_TYPE_INFO); } // -------------------------------------------------------------------------------------------- // Test formats // -------------------------------------------------------------------------------------------- public static final
TypeExtractorInputFormatsTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/objects/Objects_assertNotSame_Test.java
{ "start": 1279, "end": 1798 }
class ____ extends ObjectsBaseTest { @Test void should_pass_if_objects_are_not_same() { objects.assertNotSame(someInfo(), "Yoda", "Luke"); } @Test void should_fail_if_objects_are_same() { AssertionInfo info = someInfo(); Object actual = new Person("Yoda"); Throwable error = catchThrowable(() -> objects.assertNotSame(info, actual, actual)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldNotBeSame(actual)); } }
Objects_assertNotSame_Test
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/impl/pb/RegisterDistributedSchedulingAMResponsePBImpl.java
{ "start": 1717, "end": 10546 }
class ____ extends RegisterDistributedSchedulingAMResponse { YarnServerCommonServiceProtos.RegisterDistributedSchedulingAMResponseProto proto = YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProto .getDefaultInstance(); YarnServerCommonServiceProtos.RegisterDistributedSchedulingAMResponseProto. Builder builder = null; boolean viaProto = false; private Resource maxContainerResource; private Resource minContainerResource; private Resource incrContainerResource; private List<RemoteNode> nodesForScheduling; private RegisterApplicationMasterResponse registerApplicationMasterResponse; public RegisterDistributedSchedulingAMResponsePBImpl() { builder = YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProto.newBuilder(); } public RegisterDistributedSchedulingAMResponsePBImpl( YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProto proto) { this.proto = proto; viaProto = true; } public YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProto.newBuilder(proto); } viaProto = false; } private synchronized void mergeLocalToProto() { if (viaProto) maybeInitBuilder(); mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private synchronized void mergeLocalToBuilder() { if (this.nodesForScheduling != null) { builder.clearNodesForScheduling(); Iterable<YarnServerCommonServiceProtos.RemoteNodeProto> iterable = getNodeIdProtoIterable(this.nodesForScheduling); builder.addAllNodesForScheduling(iterable); } if (this.maxContainerResource != null) { builder.setMaxContainerResource(ProtoUtils.convertToProtoFormat( this.maxContainerResource)); } if (this.minContainerResource != null) { builder.setMinContainerResource(ProtoUtils.convertToProtoFormat( this.minContainerResource)); } if (this.incrContainerResource != null) { builder.setIncrContainerResource( ProtoUtils.convertToProtoFormat(this.incrContainerResource)); } if (this.registerApplicationMasterResponse != null) { builder.setRegisterResponse( ((RegisterApplicationMasterResponsePBImpl) this.registerApplicationMasterResponse).getProto()); } } @Override public void setRegisterResponse(RegisterApplicationMasterResponse resp) { maybeInitBuilder(); if (registerApplicationMasterResponse == null) { builder.clearRegisterResponse(); } this.registerApplicationMasterResponse = resp; } @Override public RegisterApplicationMasterResponse getRegisterResponse() { if (this.registerApplicationMasterResponse != null) { return this.registerApplicationMasterResponse; } YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasRegisterResponse()) { return null; } this.registerApplicationMasterResponse = new RegisterApplicationMasterResponsePBImpl(p.getRegisterResponse()); return this.registerApplicationMasterResponse; } @Override public void setMaxContainerResource(Resource maxResource) { maybeInitBuilder(); if (maxContainerResource == null) { builder.clearMaxContainerResource(); } this.maxContainerResource = maxResource; } @Override public Resource getMaxContainerResource() { if (this.maxContainerResource != null) { return this.maxContainerResource; } YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasMaxContainerResource()) { return null; } this.maxContainerResource = ProtoUtils.convertFromProtoFormat(p .getMaxContainerResource()); return this.maxContainerResource; } @Override public void setMinContainerResource(Resource minResource) { maybeInitBuilder(); if (minContainerResource == null) { builder.clearMinContainerResource(); } this.minContainerResource = minResource; } @Override public Resource getMinContainerResource() { if (this.minContainerResource != null) { return this.minContainerResource; } YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasMinContainerResource()) { return null; } this.minContainerResource = ProtoUtils.convertFromProtoFormat(p .getMinContainerResource()); return this.minContainerResource; } @Override public void setIncrContainerResource(Resource incrResource) { maybeInitBuilder(); if (incrContainerResource == null) { builder.clearIncrContainerResource(); } this.incrContainerResource = incrResource; } @Override public Resource getIncrContainerResource() { if (this.incrContainerResource != null) { return this.incrContainerResource; } YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasIncrContainerResource()) { return null; } this.incrContainerResource = ProtoUtils.convertFromProtoFormat(p .getIncrContainerResource()); return this.incrContainerResource; } @Override public void setContainerTokenExpiryInterval(int interval) { maybeInitBuilder(); builder.setContainerTokenExpiryInterval(interval); } @Override public int getContainerTokenExpiryInterval() { YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasContainerTokenExpiryInterval()) { return 0; } return p.getContainerTokenExpiryInterval(); } @Override public void setContainerIdStart(long containerIdStart) { maybeInitBuilder(); builder.setContainerIdStart(containerIdStart); } @Override public long getContainerIdStart() { YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasContainerIdStart()) { return 0; } return p.getContainerIdStart(); } @Override public void setNodesForScheduling(List<RemoteNode> nodesForScheduling) { maybeInitBuilder(); if (nodesForScheduling == null || nodesForScheduling.isEmpty()) { if (this.nodesForScheduling != null) { this.nodesForScheduling.clear(); } builder.clearNodesForScheduling(); return; } this.nodesForScheduling = new ArrayList<>(); this.nodesForScheduling.addAll(nodesForScheduling); } @Override public List<RemoteNode> getNodesForScheduling() { if (nodesForScheduling != null) { return nodesForScheduling; } initLocalNodesForSchedulingList(); return nodesForScheduling; } private synchronized void initLocalNodesForSchedulingList() { YarnServerCommonServiceProtos. RegisterDistributedSchedulingAMResponseProtoOrBuilder p = viaProto ? proto : builder; List<YarnServerCommonServiceProtos.RemoteNodeProto> list = p.getNodesForSchedulingList(); nodesForScheduling = new ArrayList<>(); if (list != null) { for (YarnServerCommonServiceProtos.RemoteNodeProto t : list) { nodesForScheduling.add(new RemoteNodePBImpl(t)); } } } private synchronized Iterable<RemoteNodeProto> getNodeIdProtoIterable( final List<RemoteNode> nodeList) { maybeInitBuilder(); return new Iterable<RemoteNodeProto>() { @Override public synchronized Iterator<RemoteNodeProto> iterator() { return new Iterator<RemoteNodeProto>() { Iterator<RemoteNode> iter = nodeList.iterator(); @Override public boolean hasNext() { return iter.hasNext(); } @Override public RemoteNodeProto next() { return ((RemoteNodePBImpl)iter.next()).getProto(); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } @Override public String toString() { return TextFormat.shortDebugString(getProto()); } }
RegisterDistributedSchedulingAMResponsePBImpl
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/common/CalcMergeTestBase.java
{ "start": 1280, "end": 4277 }
class ____ extends TableTestBase { private TableTestUtil util; protected abstract boolean isBatchMode(); protected abstract TableTestUtil getTableTestUtil(); @BeforeEach void setup() { util = getTableTestUtil(); util.tableEnv() .executeSql( "CREATE TABLE MyTable (\n" + " a INTEGER,\n" + " b INTEGER,\n" + " c VARCHAR\n" + ") WITH (\n" + " 'connector' = 'values'\n" + " ,'bounded' = '" + isBatchMode() + "'\n" + ")"); util.addTemporarySystemFunction( "random_udf", new JavaUserDefinedScalarFunctions.NonDeterministicUdf()); } @Test void testCalcMergeWithSameDigest() { util.verifyExecPlan("SELECT a, b FROM (SELECT * FROM MyTable WHERE a = b) t WHERE b = a"); } @Test void testCalcMergeWithNonDeterministicExpr1() { util.verifyExecPlan( "SELECT a, a1 FROM (SELECT a, random_udf(a) AS a1 FROM MyTable) t WHERE a1 > 10"); } @Test void testCalcMergeWithNonDeterministicExpr2() { util.verifyExecPlan( "SELECT random_udf(a1) as a2 FROM (SELECT random_udf(a) as" + " a1, b FROM MyTable) t WHERE b > 10"); } @Test void testCalcMergeWithTopMultiNonDeterministicExpr() { util.verifyExecPlan( "SELECT random_udf(a1) as a2, random_udf(a1) as a3 FROM" + " (SELECT random_udf(a) as a1, b FROM MyTable) t WHERE b > 10"); } @Test void testCalcMergeTopFilterHasNonDeterministicExpr() { util.verifyExecPlan( "SELECT a, c FROM" + " (SELECT a, random_udf(b) as b1, c FROM MyTable) t WHERE b1 > 10"); } @Test void testCalcMergeWithBottomMultiNonDeterministicExpr() { util.verifyExecPlan( "SELECT a1, b2 FROM" + " (SELECT random_udf(a) as a1, random_udf(b) as b2, c FROM MyTable) t WHERE c > 10"); } @Test void testCalcMergeWithBottomMultiNonDeterministicInConditionExpr() { util.verifyExecPlan( "SELECT c FROM" + " (SELECT random_udf(a) as a1, random_udf(b) as b2, c FROM MyTable) t WHERE a1 > b2"); } @Test void testCalcMergeWithoutInnerNonDeterministicExpr() { util.verifyExecPlan( "SELECT a, c FROM (SELECT a, random_udf(a) as a1, c FROM MyTable) t WHERE c > 10"); } @Test void testCalcMergeWithNonDeterministicNestedExpr() { util.verifyExecPlan( "SELECT a, a1 FROM (SELECT a, substr(cast(random_udf(a) as varchar), 1, 2) AS a1 FROM MyTable) t WHERE a1 > '10'"); } }
CalcMergeTestBase
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/http/HttpRequest.java
{ "start": 872, "end": 980 }
interface ____ the request's content as well as methods to be used * to generate a response. */ public
exposes
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/messaging/SubProtocolHandler.java
{ "start": 1320, "end": 1651 }
interface ____ be configured on a * {@link SubProtocolWebSocketHandler} which selects a sub-protocol handler to * delegate messages to based on the sub-protocol requested by the client through * the {@code Sec-WebSocket-Protocol} request header. * * @author Andy Wilkinson * @author Rossen Stoyanchev * @since 4.0 */ public
can
java
google__dagger
javatests/dagger/internal/codegen/ComponentProcessorTest.java
{ "start": 65001, "end": 65407 }
interface ____ extends Supertype {", " Child child();", "}"); Source testModule = CompilerTests.javaSource( "test.TestModule", "package test;", "", "import dagger.Module;", "import dagger.Provides;", "import javax.inject.Singleton;", "", "@Module", "abstract
Parent
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/struct/TestUnwrapped.java
{ "start": 1359, "end": 1661 }
class ____ { public String name; @JsonUnwrapped public Location location; @JsonCreator public UnwrappingWithCreator(@JsonProperty("name") String n) { name = n; } } // Class with two unwrapped properties static
UnwrappingWithCreator
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/WorkdayEndpointBuilderFactory.java
{ "start": 4678, "end": 8411 }
interface ____ extends EndpointProducerBuilder { default WorkdayEndpointBuilder basic() { return (WorkdayEndpointBuilder) this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedWorkdayEndpointBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer (advanced) * * @param lazyStartProducer the value to set * @return the dsl builder */ default AdvancedWorkdayEndpointBuilder lazyStartProducer(String lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Pool connection manager for advanced configuration. * * The option is a: * <code>org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager</code> type. * * Group: advanced * * @param httpConnectionManager the value to set * @return the dsl builder */ default AdvancedWorkdayEndpointBuilder httpConnectionManager(org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager httpConnectionManager) { doSetProperty("httpConnectionManager", httpConnectionManager); return this; } /** * Pool connection manager for advanced configuration. * * The option will be converted to a * <code>org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager</code> type. * * Group: advanced * * @param httpConnectionManager the value to set * @return the dsl builder */ default AdvancedWorkdayEndpointBuilder httpConnectionManager(String httpConnectionManager) { doSetProperty("httpConnectionManager", httpConnectionManager); return this; } } public
AdvancedWorkdayEndpointBuilder
java
bumptech__glide
library/test/src/test/java/com/bumptech/glide/request/target/AppWidgetTargetTest.java
{ "start": 5035, "end": 5587 }
class ____ extends ShadowAppWidgetManager { int[] updatedWidgetIds; RemoteViews updatedRemoteViews; ComponentName updatedComponentName; @Implementation @Override public void updateAppWidget(int[] appWidgetIds, RemoteViews views) { updatedWidgetIds = appWidgetIds; updatedRemoteViews = views; } @Implementation public void updateAppWidget(ComponentName componentName, RemoteViews views) { updatedComponentName = componentName; updatedRemoteViews = views; } } }
UpdateShadowAppWidgetManager
java
google__guice
extensions/assistedinject/test/com/google/inject/assistedinject/subpkg/SubpackageTestPrivateFallbackOnly.java
{ "start": 3674, "end": 5554 }
interface ____ extends AbstractAssisted.Factory<Public, String> { @Override Public create(String string); Public create(StringBuilder sb); } } @Test public void testPrivateFallbackOnly() throws Exception { // Private fallback only works on JDKs below 17. On 17+ it's disabled. assumeTrue(JAVA_VERSION < 17); setAllowMethodHandleWorkaround(false); Injector injector = Guice.createInjector( new AbstractModule() { @Override protected void configure() { install( new FactoryModuleBuilder().build(ConcreteAssistedWithOverride.Factory.class)); } }); LogRecord record = Iterables.getOnlyElement(logRecords); assertThat(record.getMessage()).contains("Please pass a `MethodHandles.lookup()`"); ConcreteAssistedWithOverride.Factory factory = injector.getInstance(ConcreteAssistedWithOverride.Factory.class); ConcreteAssistedWithOverride unused = factory.create("foo"); AbstractAssisted.Factory<ConcreteAssistedWithOverride, String> factoryAbstract = factory; unused = factoryAbstract.create("foo"); } private static void setAllowPrivateLookupFallback(boolean allowed) throws Exception { Class<?> factoryProvider2 = Class.forName("com.google.inject.assistedinject.FactoryProvider2"); Field field = factoryProvider2.getDeclaredField("allowPrivateLookupFallback"); field.setAccessible(true); field.setBoolean(null, allowed); } private static void setAllowMethodHandleWorkaround(boolean allowed) throws Exception { Class<?> factoryProvider2 = Class.forName("com.google.inject.assistedinject.FactoryProvider2"); Field field = factoryProvider2.getDeclaredField("allowMethodHandleWorkaround"); field.setAccessible(true); field.setBoolean(null, allowed); } }
Factory
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/records/Resource.java
{ "start": 5935, "end": 6567 }
class ____ have support for units - so this function will continue to return * memory but in the units of MB * * @return <em>memory</em> of the resource */ @Public @Stable public long getMemorySize() { throw new NotImplementedException( "This method is implemented by ResourcePBImpl"); } /** * Set <em>memory</em> of the resource. Note - while memory has * never had a unit specified, all YARN configurations have specified memory * in MB. The assumption has been that the daemons and applications are always * using the same units. With the introduction of the ResourceInformation *
we
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/execannotations/ExecutionModelAnnotationsConfig.java
{ "start": 859, "end": 1233 }
enum ____ { /** * Invalid usage of execution model annotations causes build failure. */ FAIL, /** * Invalid usage of execution model annotations causes warning during build. */ WARN, /** * No detection of invalid usage of execution model annotations. */ DISABLED, } }
Mode
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8465RepositoryWithProjectDirTest.java
{ "start": 1125, "end": 1763 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Verify various supported repository URLs. */ @Test void testProjectDir() throws Exception { Path basedir = extractResources("/mng-8465").getAbsoluteFile().toPath(); Verifier verifier = newVerifier(basedir.toString()); verifier.addCliArgument("help:effective-pom"); verifier.execute(); List<String> urls = verifier.loadLogLines().stream() .filter(s -> s.trim().contains("<url>file://")) .toList(); assertEquals(4, urls.size()); } }
MavenITmng8465RepositoryWithProjectDirTest
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/support/AbstractRegexpMethodPointcut.java
{ "start": 1497, "end": 1828 }
class ____ serializable. Subclasses should declare all fields transient; * the {@link #initPatternRepresentation} method will be invoked again on deserialization. * * @author Rod Johnson * @author Juergen Hoeller * @author Rob Harrop * @since 1.1 * @see JdkRegexpMethodPointcut */ @SuppressWarnings("serial") public abstract
is
java
alibaba__fastjson
src/test/java/com/alibaba/json/demo/Forguard.java
{ "start": 118, "end": 2374 }
class ____ extends TestCase { public void test_0() throws Exception { String json = "{\"id\":\"a123\", \"name\":\"wxf\"}"; String value = javaGet(json, "id"); System.out.println(value); } public static String javaGet(String json, String key) { char[] json_chars = json.toCharArray(); char[] key_chars = key.toCharArray(); char[] value_chars = get(json_chars, json_chars.length, key_chars, key_chars.length); return new String(value_chars); } public static char[] get(char[] json, int json_len, char[] key, int key_len) { if (json_len == 0) { return new char[0]; } Parser parser = new Parser(); parser.json_chars = json; parser.json_len = json_len; parser.ch = json[0]; next_token(parser); if (parser.token != Token.LBRACE) { throw new IllegalArgumentException("illegal json"); } next_token(parser); for (;;) { if (parser.token == Token.RBRACE) { break; } if (parser.token != Token.STRING) { throw new IllegalArgumentException("illegal json"); } char[] name_chars = parser.str_chars; int name_len = parser.str_chars_len; next_token(parser); if (parser.token != Token.COLON) { throw new IllegalArgumentException("illegal json"); } next_token(parser); if (parser.token != Token.STRING) { throw new IllegalArgumentException("illegal json"); } if (name_len == key_len) { boolean eq = true; for (int i = 0; i < name_len; ++i) { if (name_chars[i] != key[i]) { eq = false; break; } } if (eq) { return parser.str_chars; } } next_token(parser); if (parser.token == Token.COMMA) { next_token(parser); continue; } } return null; } public static
Forguard
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/aggfunctions/SumAggFunction.java
{ "start": 4003, "end": 4238 }
class ____ extends SumAggFunction { @Override public DataType getResultType() { return DataTypes.TINYINT(); } } /** Built-in Short Sum aggregate function. */ public static
ByteSumAggFunction
java
grpc__grpc-java
inprocess/src/main/java/io/grpc/inprocess/InProcessTransport.java
{ "start": 2938, "end": 12468 }
class ____ implements ServerTransport, ConnectionClientTransport { private static final Logger log = Logger.getLogger(InProcessTransport.class.getName()); static boolean isEnabledSupportTracingMessageSizes = GrpcUtil.getFlag("GRPC_EXPERIMENTAL_SUPPORT_TRACING_MESSAGE_SIZES", false); private final InternalLogId logId; private final SocketAddress address; private final int clientMaxInboundMetadataSize; private final String authority; private final String userAgent; private int serverMaxInboundMetadataSize; private final boolean includeCauseWithStatus; private ObjectPool<ScheduledExecutorService> serverSchedulerPool; private ScheduledExecutorService serverScheduler; private ServerTransportListener serverTransportListener; private Attributes serverStreamAttributes; private ManagedClientTransport.Listener clientTransportListener; // The size is assumed from the sender's side. private final long assumedMessageSize; @GuardedBy("this") private boolean shutdown; @GuardedBy("this") private boolean terminated; @GuardedBy("this") private Status shutdownStatus; @GuardedBy("this") private final Set<InProcessStream> streams = Collections.newSetFromMap( new IdentityHashMap<InProcessStream, Boolean>()); @GuardedBy("this") private List<ServerStreamTracer.Factory> serverStreamTracerFactories; private Attributes attributes; private Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { if (e instanceof Error) { throw new Error(e); } throw new RuntimeException(e); } }; @GuardedBy("this") private final InUseStateAggregator<InProcessStream> inUseState = new InUseStateAggregator<InProcessStream>() { @Override protected void handleInUse() { clientTransportListener.transportInUse(true); } @Override protected void handleNotInUse() { clientTransportListener.transportInUse(false); } }; public InProcessTransport(SocketAddress address, int maxInboundMetadataSize, String authority, String userAgent, Attributes eagAttrs, boolean includeCauseWithStatus, long assumedMessageSize) { this.address = address; this.clientMaxInboundMetadataSize = maxInboundMetadataSize; this.authority = authority; this.userAgent = GrpcUtil.getGrpcUserAgent("inprocess", userAgent); checkNotNull(eagAttrs, "eagAttrs"); this.attributes = Attributes.newBuilder() .set(GrpcAttributes.ATTR_SECURITY_LEVEL, SecurityLevel.PRIVACY_AND_INTEGRITY) .set(GrpcAttributes.ATTR_CLIENT_EAG_ATTRS, eagAttrs) .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, address) .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, address) .build(); logId = InternalLogId.allocate(getClass(), address.toString()); this.includeCauseWithStatus = includeCauseWithStatus; this.assumedMessageSize = assumedMessageSize; } @CheckReturnValue @Override public synchronized Runnable start(ManagedClientTransport.Listener listener) { this.clientTransportListener = listener; InProcessServer server = InProcessServer.findServer(address); if (server != null) { serverMaxInboundMetadataSize = server.getMaxInboundMetadataSize(); serverSchedulerPool = server.getScheduledExecutorServicePool(); serverScheduler = serverSchedulerPool.getObject(); serverStreamTracerFactories = server.getStreamTracerFactories(); // Must be semi-initialized; past this point, can begin receiving requests serverTransportListener = server.register(this); } if (serverTransportListener == null) { shutdownStatus = Status.UNAVAILABLE.withDescription("Could not find server: " + address); final Status localShutdownStatus = shutdownStatus; return new Runnable() { @Override public void run() { synchronized (InProcessTransport.this) { notifyShutdown(localShutdownStatus); notifyTerminated(); } } }; } Attributes serverTransportAttrs = Attributes.newBuilder() .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, address) .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, address) .build(); serverStreamAttributes = serverTransportListener.transportReady(serverTransportAttrs); attributes = clientTransportListener.filterTransport(attributes); clientTransportListener.transportReady(); return null; } @Override public synchronized ClientStream newStream( MethodDescriptor<?, ?> method, Metadata headers, CallOptions callOptions, ClientStreamTracer[] tracers) { StatsTraceContext statsTraceContext = StatsTraceContext.newClientContext(tracers, getAttributes(), headers); if (shutdownStatus != null) { return failedClientStream(statsTraceContext, shutdownStatus); } headers.put(GrpcUtil.USER_AGENT_KEY, userAgent); if (serverMaxInboundMetadataSize != Integer.MAX_VALUE) { int metadataSize = metadataSize(headers); if (metadataSize > serverMaxInboundMetadataSize) { // Other transports would compute a status with: // GrpcUtil.httpStatusToGrpcStatus(431 /* Request Header Fields Too Large */); // However, that isn't handled specially today, so we'd leak HTTP-isms even though we're // in-process. We go ahead and make a Status, which may need to be updated if // statuscodes.md is updated. Status status = Status.RESOURCE_EXHAUSTED.withDescription( String.format( Locale.US, "Request metadata larger than %d: %d", serverMaxInboundMetadataSize, metadataSize)); return failedClientStream(statsTraceContext, status); } } return new InProcessStream(method, headers, callOptions, authority, statsTraceContext) .clientStream; } private ClientStream failedClientStream( final StatsTraceContext statsTraceCtx, final Status status) { return new NoopClientStream() { @Override public void start(ClientStreamListener listener) { statsTraceCtx.clientOutboundHeaders(); statsTraceCtx.streamClosed(status); listener.closed(status, RpcProgress.PROCESSED, new Metadata()); } }; } @Override public synchronized void ping(final PingCallback callback, Executor executor) { if (terminated) { final Status shutdownStatus = this.shutdownStatus; executor.execute(new Runnable() { @Override public void run() { callback.onFailure(shutdownStatus); } }); } else { executor.execute(new Runnable() { @Override public void run() { callback.onSuccess(0); } }); } } @Override public synchronized void shutdown(Status reason) { // Can be called multiple times: once for ManagedClientTransport, once for ServerTransport. if (shutdown) { return; } shutdownStatus = reason; notifyShutdown(reason); if (streams.isEmpty()) { notifyTerminated(); } } @Override public synchronized void shutdown() { shutdown(Status.UNAVAILABLE.withDescription("InProcessTransport shutdown by the server-side")); } @Override public void shutdownNow(Status reason) { checkNotNull(reason, "reason"); List<InProcessStream> streamsCopy; synchronized (this) { shutdown(reason); if (terminated) { return; } streamsCopy = new ArrayList<>(streams); } for (InProcessStream stream : streamsCopy) { stream.clientStream.cancel(reason); } } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("logId", logId.getId()) .add("address", address) .toString(); } @Override public InternalLogId getLogId() { return logId; } @Override public Attributes getAttributes() { return attributes; } @Override public ScheduledExecutorService getScheduledExecutorService() { return serverScheduler; } @Override public ListenableFuture<SocketStats> getStats() { SettableFuture<SocketStats> ret = SettableFuture.create(); ret.set(null); return ret; } private synchronized void notifyShutdown(Status s) { if (shutdown) { return; } shutdown = true; clientTransportListener.transportShutdown(s); } private synchronized void notifyTerminated() { if (terminated) { return; } terminated = true; if (serverScheduler != null) { serverScheduler = serverSchedulerPool.returnObject(serverScheduler); } clientTransportListener.transportTerminated(); if (serverTransportListener != null) { serverTransportListener.transportTerminated(); } } private static int metadataSize(Metadata metadata) { byte[][] serialized = InternalMetadata.serialize(metadata); if (serialized == null) { return 0; } // Calculate based on SETTINGS_MAX_HEADER_LIST_SIZE in RFC 7540 §6.5.2. We could use something // different, but it's "sane." long size = 0; for (int i = 0; i < serialized.length; i += 2) { size += 32 + serialized[i].length + serialized[i + 1].length; } size = Math.min(size, Integer.MAX_VALUE); return (int) size; } private
InProcessTransport
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/PercentilesAggregatorFactory.java
{ "start": 1472, "end": 3991 }
class ____ extends ValuesSourceAggregatorFactory { private final PercentilesAggregatorSupplier aggregatorSupplier; private final double[] percents; private final PercentilesConfig percentilesConfig; private final boolean keyed; static void registerAggregators(ValuesSourceRegistry.Builder builder) { builder.register( PercentilesAggregationBuilder.REGISTRY_KEY, List.of( CoreValuesSourceType.NUMERIC, CoreValuesSourceType.DATE, CoreValuesSourceType.BOOLEAN, TimeSeriesValuesSourceType.COUNTER ), (name, config, context, parent, percents, percentilesConfig, keyed, formatter, metadata) -> percentilesConfig .createPercentilesAggregator(name, config, context, parent, percents, keyed, formatter, metadata), true ); } PercentilesAggregatorFactory( String name, ValuesSourceConfig config, double[] percents, PercentilesConfig percentilesConfig, boolean keyed, AggregationContext context, AggregatorFactory parent, AggregatorFactories.Builder subFactoriesBuilder, Map<String, Object> metadata, PercentilesAggregatorSupplier aggregatorSupplier ) throws IOException { super(name, config, context, parent, subFactoriesBuilder, metadata); this.aggregatorSupplier = aggregatorSupplier; this.percents = percents; this.percentilesConfig = percentilesConfig; this.keyed = keyed; } @Override protected Aggregator createUnmapped(Aggregator parent, Map<String, Object> metadata) throws IOException { final InternalNumericMetricsAggregation.MultiValue empty = percentilesConfig.createEmptyPercentilesAggregator( name, percents, keyed, config.format(), metadata ); final Predicate<String> hasMetric = s -> PercentilesConfig.indexOfKey(percents, Double.parseDouble(s)) >= 0; return new NonCollectingMultiMetricAggregator(name, context, parent, empty, hasMetric, metadata); } @Override protected Aggregator doCreateInternal(Aggregator parent, CardinalityUpperBound bucketCardinality, Map<String, Object> metadata) throws IOException { return aggregatorSupplier.build(name, config, context, parent, percents, percentilesConfig, keyed, config.format(), metadata); } }
PercentilesAggregatorFactory
java
apache__dubbo
dubbo-plugin/dubbo-rest-jaxrs/src/test/java/org/apache/dubbo/rpc/protocol/tri/rest/support/jaxrs/service/ParamConverterProviderImpl.java
{ "start": 1491, "end": 2053 }
class ____ implements ParamConverter<User> { @Override public User fromString(String value) { String[] arr = StringUtils.tokenize(value, ','); User user = new User(); if (arr.length > 1) { user.setId(Long.valueOf(arr[0])); user.setName(arr[1]); } return user; } @Override public String toString(User user) { return "User{" + "id=" + user.getId() + ", name='" + user.getName() + "\"}"; } } }
UserParamConverter
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/lookup/EnrichQuerySourceOperator.java
{ "start": 1609, "end": 7044 }
class ____ extends SourceOperator { private final BlockFactory blockFactory; private final LookupEnrichQueryGenerator queryList; private int queryPosition = -1; private final IndexedByShardId<? extends ShardContext> shardContexts; private final ShardContext shardContext; private final IndexReader indexReader; private final IndexSearcher searcher; private final Warnings warnings; private final int maxPageSize; // using smaller pages enables quick cancellation and reduces sorting costs public static final int DEFAULT_MAX_PAGE_SIZE = 256; public EnrichQuerySourceOperator( BlockFactory blockFactory, int maxPageSize, LookupEnrichQueryGenerator queryList, IndexedByShardId<? extends ShardContext> shardContexts, int shardId, Warnings warnings ) { this.blockFactory = blockFactory; this.maxPageSize = maxPageSize; this.queryList = queryList; this.shardContexts = shardContexts; this.shardContext = shardContexts.get(shardId); this.shardContext.incRef(); this.searcher = shardContext.searcher(); this.indexReader = searcher.getIndexReader(); this.warnings = warnings; } @Override public void finish() {} @Override public boolean isFinished() { return queryPosition >= queryList.getPositionCount(); } @Override public Page getOutput() { int estimatedSize = Math.min(maxPageSize, queryList.getPositionCount() - queryPosition); IntVector.Builder positionsBuilder = null; IntVector.Builder docsBuilder = null; IntVector.Builder segmentsBuilder = null; try { positionsBuilder = blockFactory.newIntVectorBuilder(estimatedSize); docsBuilder = blockFactory.newIntVectorBuilder(estimatedSize); if (indexReader.leaves().size() > 1) { segmentsBuilder = blockFactory.newIntVectorBuilder(estimatedSize); } int totalMatches = 0; do { Query query; try { query = nextQuery(); if (query == null) { assert isFinished(); break; } query = searcher.rewrite(new ConstantScoreQuery(query)); } catch (Exception e) { warnings.registerException(e); continue; } final var weight = searcher.createWeight(query, ScoreMode.COMPLETE_NO_SCORES, 1.0f); if (weight == null) { continue; } for (LeafReaderContext leaf : indexReader.leaves()) { var scorer = weight.bulkScorer(leaf); if (scorer == null) { continue; } final DocCollector collector = new DocCollector(docsBuilder); scorer.score(collector, leaf.reader().getLiveDocs(), 0, DocIdSetIterator.NO_MORE_DOCS); int matches = collector.matches; if (segmentsBuilder != null) { for (int i = 0; i < matches; i++) { segmentsBuilder.appendInt(leaf.ord); } } for (int i = 0; i < matches; i++) { positionsBuilder.appendInt(queryPosition); } totalMatches += matches; } } while (totalMatches < maxPageSize); return buildPage(totalMatches, positionsBuilder, segmentsBuilder, docsBuilder); } catch (IOException e) { throw new UncheckedIOException(e); } finally { Releasables.close(docsBuilder, segmentsBuilder, positionsBuilder); } } Page buildPage(int positions, IntVector.Builder positionsBuilder, IntVector.Builder segmentsBuilder, IntVector.Builder docsBuilder) { IntVector positionsVector = null; IntVector shardsVector = null; IntVector segmentsVector = null; IntVector docsVector = null; Page page = null; try { positionsVector = positionsBuilder.build(); shardsVector = blockFactory.newConstantIntVector(0, positions); if (segmentsBuilder == null) { segmentsVector = blockFactory.newConstantIntVector(0, positions); } else { segmentsVector = segmentsBuilder.build(); } docsVector = docsBuilder.build(); page = new Page( new DocVector(shardContexts, shardsVector, segmentsVector, docsVector, null).asBlock(), positionsVector.asBlock() ); } finally { if (page == null) { Releasables.close(positionsBuilder, segmentsVector, docsBuilder, positionsVector, shardsVector, docsVector); } } return page; } private Query nextQuery() { ++queryPosition; while (isFinished() == false) { Query query = queryList.getQuery(queryPosition); if (query != null) { return query; } ++queryPosition; } return null; } private static
EnrichQuerySourceOperator
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/router/TestRouterMountTableWithoutDefaultNS.java
{ "start": 2888, "end": 11074 }
class ____ { private static StateStoreDFSCluster cluster; private static RouterContext routerContext; private static MountTableResolver mountTable; private static ClientProtocol routerProtocol; private static FileSystem nnFs0; private static FileSystem nnFs1; @BeforeAll public static void globalSetUp() throws Exception { // Build and start a federated cluster cluster = new StateStoreDFSCluster(false, 2); Configuration conf = new RouterConfigBuilder() .stateStore() .admin() .rpc() .build(); conf.setInt(RBFConfigKeys.DFS_ROUTER_ADMIN_MAX_COMPONENT_LENGTH_KEY, 20); conf.setBoolean(RBFConfigKeys.DFS_ROUTER_DEFAULT_NAMESERVICE_ENABLE, false); cluster.addRouterOverrides(conf); cluster.startCluster(); cluster.startRouters(); cluster.waitClusterUp(); // Get the end points nnFs0 = cluster.getNamenode("ns0", null).getFileSystem(); nnFs1 = cluster.getNamenode("ns1", null).getFileSystem(); routerContext = cluster.getRandomRouter(); Router router = routerContext.getRouter(); routerProtocol = routerContext.getClient().getNamenode(); mountTable = (MountTableResolver) router.getSubclusterResolver(); } @AfterAll public static void tearDown() { if (cluster != null) { cluster.stopRouter(routerContext); cluster.shutdown(); cluster = null; } } @AfterEach public void clearMountTable() throws IOException { RouterClient client = routerContext.getAdminClient(); MountTableManager mountTableManager = client.getMountTableManager(); GetMountTableEntriesRequest req1 = GetMountTableEntriesRequest.newInstance("/"); GetMountTableEntriesResponse response = mountTableManager.getMountTableEntries(req1); for (MountTable entry : response.getEntries()) { RemoveMountTableEntryRequest req2 = RemoveMountTableEntryRequest.newInstance(entry.getSourcePath()); mountTableManager.removeMountTableEntry(req2); } } /** * Add a mount table entry to the mount table through the admin API. * @param entry Mount table entry to add. * @return If it was succesfully added. * @throws IOException Problems adding entries. */ private boolean addMountTable(final MountTable entry) throws IOException { RouterClient client = routerContext.getAdminClient(); MountTableManager mountTableManager = client.getMountTableManager(); AddMountTableEntryRequest addRequest = AddMountTableEntryRequest.newInstance(entry); AddMountTableEntryResponse addResponse = mountTableManager.addMountTableEntry(addRequest); // Reload the Router cache mountTable.loadCache(true); return addResponse.getStatus(); } /** * Verify that RBF that disable default nameservice should support * get information about ancestor mount points. */ @Test public void testGetFileInfoWithSubMountPoint() throws IOException { MountTable addEntry = MountTable.newInstance("/testdir/1", Collections.singletonMap("ns0", "/testdir/1")); assertTrue(addMountTable(addEntry)); HdfsFileStatus finfo = routerProtocol.getFileInfo("/testdir"); assertNotNull(finfo); assertEquals("supergroup", finfo.getGroup()); assertTrue(finfo.isDirectory()); } /** * Verify that RBF doesn't support get the file information * with no location and sub mount points. */ @Test public void testGetFileInfoWithoutSubMountPoint() throws Exception { MountTable addEntry = MountTable.newInstance("/testdir/1", Collections.singletonMap("ns0", "/testdir/1")); assertTrue(addMountTable(addEntry)); LambdaTestUtils.intercept(RouterResolveException.class, () -> routerContext.getRouter().getRpcServer().getFileInfo("/testdir2")); } /** * Verify that RBF that disable default nameservice should support * get information about ancestor mount points. */ @Test public void testGetContentSummaryWithSubMountPoint() throws IOException { MountTable addEntry = MountTable.newInstance("/testdir/1/2", Collections.singletonMap("ns0", "/testdir/1/2")); assertTrue(addMountTable(addEntry)); try { writeData(nnFs0, new Path("/testdir/1/2/3"), 10 * 1024 * 1024); RouterRpcServer routerRpcServer = routerContext.getRouterRpcServer(); ContentSummary summaryFromRBF = routerRpcServer.getContentSummary("/testdir"); assertNotNull(summaryFromRBF); assertEquals(1, summaryFromRBF.getFileCount()); assertEquals(10 * 1024 * 1024, summaryFromRBF.getLength()); } finally { nnFs0.delete(new Path("/testdir"), true); } } @Test public void testGetAllLocations() throws IOException { // Add mount table entry. MountTable addEntry = MountTable.newInstance("/testA", Collections.singletonMap("ns0", "/testA")); assertTrue(addMountTable(addEntry)); addEntry = MountTable.newInstance("/testA/testB", Collections.singletonMap("ns1", "/testA/testB")); assertTrue(addMountTable(addEntry)); addEntry = MountTable.newInstance("/testA/testB/testC", Collections.singletonMap("ns2", "/testA/testB/testC")); assertTrue(addMountTable(addEntry)); RouterClientProtocol protocol = routerContext.getRouterRpcServer().getClientProtocolModule(); Map<String, List<RemoteLocation>> locations = protocol.getAllLocations("/testA"); assertEquals(3, locations.size()); } @Test public void testGetLocationsForContentSummary() throws Exception { // Add mount table entry. MountTable addEntry = MountTable.newInstance("/testA/testB", Collections.singletonMap("ns0", "/testA/testB")); assertTrue(addMountTable(addEntry)); addEntry = MountTable.newInstance("/testA/testB/testC", Collections.singletonMap("ns1", "/testA/testB/testC")); assertTrue(addMountTable(addEntry)); RouterClientProtocol protocol = routerContext.getRouterRpcServer().getClientProtocolModule(); List<RemoteLocation> locations = protocol.getLocationsForContentSummary("/testA"); assertEquals(2, locations.size()); for (RemoteLocation location : locations) { String nsId = location.getNameserviceId(); if ("ns0".equals(nsId)) { assertEquals("/testA/testB", location.getDest()); } else if ("ns1".equals(nsId)) { assertEquals("/testA/testB/testC", location.getDest()); } else { fail("Unexpected NS " + nsId); } } LambdaTestUtils.intercept(NoLocationException.class, () -> protocol.getLocationsForContentSummary("/testB")); } @Test public void testGetContentSummary() throws Exception { try { // Add mount table entry. MountTable addEntry = MountTable.newInstance("/testA", Collections.singletonMap("ns0", "/testA")); assertTrue(addMountTable(addEntry)); addEntry = MountTable.newInstance("/testA/testB", Collections.singletonMap("ns0", "/testA/testB")); assertTrue(addMountTable(addEntry)); addEntry = MountTable.newInstance("/testA/testB/testC", Collections.singletonMap("ns1", "/testA/testB/testC")); assertTrue(addMountTable(addEntry)); writeData(nnFs0, new Path("/testA/testB/file1"), 1024 * 1024); writeData(nnFs1, new Path("/testA/testB/testC/file2"), 1024 * 1024); writeData(nnFs1, new Path("/testA/testB/testC/file3"), 1024 * 1024); RouterRpcServer routerRpcServer = routerContext.getRouterRpcServer(); ContentSummary summary = routerRpcServer.getContentSummary("/testA"); assertEquals(3, summary.getFileCount()); assertEquals(1024 * 1024 * 3, summary.getLength()); LambdaTestUtils.intercept(NoLocationException.class, () -> routerRpcServer.getContentSummary("/testB")); } finally { nnFs0.delete(new Path("/testA"), true); nnFs1.delete(new Path("/testA"), true); } } void writeData(FileSystem fs, Path path, int fileLength) throws IOException { try (FSDataOutputStream outputStream = fs.create(path)) { for (int writeSize = 0; writeSize < fileLength; writeSize++) { outputStream.write(writeSize); } } } }
TestRouterMountTableWithoutDefaultNS
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/bytearrays/ByteArrays_assertNotEmpty_Test.java
{ "start": 1539, "end": 2257 }
class ____ extends ByteArraysBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertNotEmpty(someInfo(), null)) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_is_empty() { AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> arrays.assertNotEmpty(info, emptyArray())); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldNotBeEmpty()); } @Test void should_pass_if_actual_is_not_empty() { arrays.assertNotEmpty(someInfo(), arrayOf(8)); } }
ByteArrays_assertNotEmpty_Test
java
resilience4j__resilience4j
resilience4j-spring-boot2/src/main/java/io/github/resilience4j/bulkhead/monitoring/endpoint/BulkheadEndpoint.java
{ "start": 1313, "end": 2174 }
class ____ { private final BulkheadRegistry bulkheadRegistry; private final ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry; public BulkheadEndpoint(BulkheadRegistry bulkheadRegistry, ThreadPoolBulkheadRegistry threadPoolBulkheadRegistry) { this.bulkheadRegistry = bulkheadRegistry; this.threadPoolBulkheadRegistry = threadPoolBulkheadRegistry; } @ReadOperation public BulkheadEndpointResponse getAllBulkheads() { List<String> bulkheads = Stream.concat(bulkheadRegistry.getAllBulkheads().stream() .map(Bulkhead::getName), threadPoolBulkheadRegistry .getAllBulkheads().stream() .map(ThreadPoolBulkhead::getName)) .sorted().collect(Collectors.toList()); return new BulkheadEndpointResponse(bulkheads); } }
BulkheadEndpoint
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/datastreams/GetDataStreamAction.java
{ "start": 7392, "end": 8199 }
enum ____ { ILM("Index Lifecycle Management"), LIFECYCLE("Data stream lifecycle"), UNMANAGED("Unmanaged"); public final String displayValue; ManagedBy(String displayValue) { this.displayValue = displayValue; } } public static final ParseField DATA_STREAMS_FIELD = new ParseField("data_streams"); private static final TransportVersion INTRODUCE_FAILURES_DEFAULT_RETENTION_PATCH = TransportVersion.fromName( "introduce_failures_default_retention" ).nextPatchVersion(); private static final TransportVersion INCLUDE_INDEX_MODE_IN_GET_DATA_STREAM = TransportVersion.fromName( "include_index_mode_in_get_data_stream" ); public static
ManagedBy
java
apache__maven
impl/maven-impl/src/main/java/org/apache/maven/impl/cache/CacheSelector.java
{ "start": 3264, "end": 3421 }
class ____ any of its interfaces matches the type name */ private boolean matchesAnyInterface(Class<?> clazz, String typeName) { // Check the
or
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecLegacyTableSourceScan.java
{ "start": 2969, "end": 9548 }
class ____ extends CommonExecLegacyTableSourceScan implements StreamExecNode<RowData> { public StreamExecLegacyTableSourceScan( ReadableConfig tableConfig, TableSource<?> tableSource, List<String> qualifiedName, RowType outputType, String description) { super( ExecNodeContext.newNodeId(), ExecNodeContext.newContext(StreamExecLegacyTableSourceScan.class), ExecNodeContext.newPersistedConfig( StreamExecLegacyTableSourceScan.class, tableConfig), tableSource, qualifiedName, outputType, description); } @SuppressWarnings("unchecked") @Override protected Transformation<RowData> createConversionTransformationIfNeeded( StreamExecutionEnvironment streamExecEnv, ExecNodeConfig config, ClassLoader classLoader, Transformation<?> sourceTransform, @Nullable RexNode rowtimeExpression) { final RowType outputType = (RowType) getOutputType(); final Transformation<RowData> transformation; final int[] fieldIndexes = computeIndexMapping(true); if (needInternalConversion(fieldIndexes)) { final String extractElement, resetElement; if (ScanUtil.hasTimeAttributeField(fieldIndexes)) { String elementTerm = OperatorCodeGenerator.ELEMENT(); extractElement = String.format("ctx.%s = %s;", elementTerm, elementTerm); resetElement = String.format("ctx.%s = null;", elementTerm); } else { extractElement = ""; resetElement = ""; } final CodeGeneratorContext ctx = new CodeGeneratorContext(config, classLoader) .setOperatorBaseClass(TableStreamOperator.class); // the produced type may not carry the correct precision user defined in DDL, because // it may be converted from legacy type. Fix precision using logical schema from DDL. // Code generation requires the correct precision of input fields. final DataType fixedProducedDataType = TableSourceUtil.fixPrecisionForProducedDataType(tableSource, outputType); transformation = ScanUtil.convertToInternalRow( ctx, (Transformation<Object>) sourceTransform, fieldIndexes, fixedProducedDataType, outputType, qualifiedName, (detailName, simplifyName) -> createFormattedTransformationName( detailName, simplifyName, config), (description) -> createFormattedTransformationDescription(description, config), JavaScalaConversionUtil.toScala(Optional.ofNullable(rowtimeExpression)), extractElement, resetElement); } else { transformation = (Transformation<RowData>) sourceTransform; } final DataStream<RowData> ingestedTable = new DataStream<>(streamExecEnv, transformation); final Optional<RowtimeAttributeDescriptor> rowtimeDesc = JavaScalaConversionUtil.toJava( TableSourceUtil.getRowtimeAttributeDescriptor(tableSource, outputType)); final DataStream<RowData> withWatermarks = rowtimeDesc .map( desc -> { int rowtimeFieldIdx = outputType .getFieldNames() .indexOf(desc.getAttributeName()); WatermarkStrategy strategy = desc.getWatermarkStrategy(); if (strategy instanceof PeriodicWatermarkAssigner) { PeriodicWatermarkAssignerWrapper watermarkGenerator = new PeriodicWatermarkAssignerWrapper( (PeriodicWatermarkAssigner) strategy, rowtimeFieldIdx); return ingestedTable.assignTimestampsAndWatermarks( watermarkGenerator); } else if (strategy instanceof PunctuatedWatermarkAssigner) { PunctuatedWatermarkAssignerWrapper watermarkGenerator = new PunctuatedWatermarkAssignerWrapper( (PunctuatedWatermarkAssigner) strategy, rowtimeFieldIdx, tableSource.getProducedDataType()); return ingestedTable.assignTimestampsAndWatermarks( watermarkGenerator); } else { // The watermarks have already been provided by the // underlying DataStream. return ingestedTable; } }) .orElse(ingestedTable); // No need to generate watermarks if no rowtime // attribute is specified. return withWatermarks.getTransformation(); } @Override protected <IN> Transformation<IN> createInput( StreamExecutionEnvironment env, InputFormat<IN, ? extends InputSplit> format, TypeInformation<IN> typeInfo) { // See StreamExecutionEnvironment.createInput, it is better to deal with checkpoint. // The disadvantage is that streaming not support multi-paths. return env.createInput(format, typeInfo) .name(tableSource.explainSource()) .getTransformation(); } }
StreamExecLegacyTableSourceScan
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/concurrent/UncheckedTimeoutException.java
{ "start": 1034, "end": 1545 }
class ____ extends UncheckedException { private static final long serialVersionUID = 1L; /** * Constructs an instance initialized to the given {@code cause}. * * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value * is permitted, and indicates that the cause is nonexistent or unknown.) */ public UncheckedTimeoutException(final Throwable cause) { super(cause); } }
UncheckedTimeoutException
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1244/SizeMapper.java
{ "start": 464, "end": 677 }
class ____ { private String size; public String getSize() { return size; } public void setSize(String size) { this.size = size; } }
SizeHolder
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/MergedSortedCacheWindowStoreKeyValueIterator.java
{ "start": 1154, "end": 3860 }
class ____ extends AbstractMergedSortedCacheStoreIterator<Windowed<Bytes>, Windowed<Bytes>, byte[], byte[]> { private final StateSerdes<Bytes, byte[]> serdes; private final long windowSize; private final SegmentedCacheFunction cacheFunction; private final StoreKeyToWindowKey storeKeyToWindowKey; private final WindowKeyToBytes windowKeyToBytes; MergedSortedCacheWindowStoreKeyValueIterator( final PeekingKeyValueIterator<Bytes, LRUCacheEntry> filteredCacheIterator, final KeyValueIterator<Windowed<Bytes>, byte[]> underlyingIterator, final StateSerdes<Bytes, byte[]> serdes, final long windowSize, final SegmentedCacheFunction cacheFunction, final boolean forward ) { this(filteredCacheIterator, underlyingIterator, serdes, windowSize, cacheFunction, forward, WindowKeySchema::fromStoreKey, WindowKeySchema::toStoreKeyBinary); } MergedSortedCacheWindowStoreKeyValueIterator( final PeekingKeyValueIterator<Bytes, LRUCacheEntry> filteredCacheIterator, final KeyValueIterator<Windowed<Bytes>, byte[]> underlyingIterator, final StateSerdes<Bytes, byte[]> serdes, final long windowSize, final SegmentedCacheFunction cacheFunction, final boolean forward, final StoreKeyToWindowKey storeKeyToWindowKey, final WindowKeyToBytes windowKeyToBytes ) { super(filteredCacheIterator, underlyingIterator, forward); this.serdes = serdes; this.windowSize = windowSize; this.cacheFunction = cacheFunction; this.storeKeyToWindowKey = storeKeyToWindowKey; this.windowKeyToBytes = windowKeyToBytes; } @Override Windowed<Bytes> deserializeStoreKey(final Windowed<Bytes> key) { return key; } @Override KeyValue<Windowed<Bytes>, byte[]> deserializeStorePair(final KeyValue<Windowed<Bytes>, byte[]> pair) { return pair; } @Override Windowed<Bytes> deserializeCacheKey(final Bytes cacheKey) { final byte[] binaryKey = cacheFunction.key(cacheKey).get(); return storeKeyToWindowKey.toWindowKey(binaryKey, windowSize, serdes.keyDeserializer(), serdes.topic()); } @Override byte[] deserializeCacheValue(final LRUCacheEntry cacheEntry) { return cacheEntry.value(); } @Override int compare(final Bytes cacheKey, final Windowed<Bytes> storeKey) { final Bytes storeKeyBytes = windowKeyToBytes.toBytes(storeKey.key(), storeKey.window().start(), 0); return cacheFunction.compareSegmentedKeys(cacheKey, storeKeyBytes); } @FunctionalInterface
MergedSortedCacheWindowStoreKeyValueIterator
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MustBeClosedCheckerTest.java
{ "start": 6632, "end": 6694 }
class ____ extends Parent {} abstract
ChildDefaultConstructor
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateTriggerTest2.java
{ "start": 1021, "end": 3453 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "CREATE OR REPLACE TRIGGER projects_idt\n" + " BEFORE INSERT ON projects\n" + " FOR EACH ROW\n" + " BEGIN\n" + " IF :new.id IS null THEN\n" + " SELECT projects_seq.nextval INTO :new.id FROM dual;\n" + " END IF;\n" + " END;"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); assertEquals("CREATE OR REPLACE TRIGGER projects_idt\n" + "\tBEFORE INSERT\n" + "\tON projects\n" + "\tFOR EACH ROW\n" + "BEGIN\n" + "\tIF :new.id IS NULL THEN\n" + "\t\tSELECT projects_seq.NEXTVAL\n" + "\t\tINTO :new.id\n" + "\t\tFROM dual;\n" + "\tEND IF;\n" + "END;", SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE)); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("cdc.en_complaint_ipr_stat_fdt0"))); assertEquals(0, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "*"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode"))); } }
OracleCreateTriggerTest2
java
google__auto
common/src/test/java/com/google/auto/common/BasicAnnotationProcessorTest.java
{ "start": 9137, "end": 9815 }
class ____ extends BaseAnnotationProcessor { @Override protected Iterable<? extends Step> steps() { return ImmutableList.of( new Step() { @Override public ImmutableSet<? extends Element> process( ImmutableSetMultimap<String, Element> elementsByAnnotation) { generateClass(processingEnv.getFiler(), "SomeGeneratedClass"); return ImmutableSet.of(); } @Override public ImmutableSet<String> annotations() { return ImmutableSet.of(ENCLOSING_CLASS_NAME + ".GeneratesCode"); } }); } } public @
GeneratesCodeProcessor
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/socket/WebSocketHandler.java
{ "start": 2484, "end": 3461 }
class ____ implements WebSocketHandler { * * &#064;Override * public Mono&lt;Void&gt; handle(WebSocketSession session) { * * Mono&lt;Void&gt; input = session.receive() * .doOnNext(message -&gt; { * // ... * }) * .concatMap(message -&gt; { * // ... * }) * .then(); * * Flux&lt;String&gt; source = ... ; * Mono&lt;Void&gt; output = session.send(source.map(session::textMessage)); * * return input.and(output); * } * } * </pre> * * <p>A {@code WebSocketHandler} must compose the inbound and outbound streams * into a unified flow and return a {@code Mono<Void>} that reflects the * completion of that flow. That means there is no need to check if the * connection is open, since Reactive Streams signals will terminate activity. * The inbound stream receives a completion/error signal, and the outbound * stream receives a cancellation signal. * * @author Rossen Stoyanchev * @since 5.0 */ public
ExampleHandler
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/persister/filter/internal/DynamicFilterAliasGenerator.java
{ "start": 414, "end": 848 }
class ____ implements FilterAliasGenerator { private final String[] tables; private final String rootAlias; public DynamicFilterAliasGenerator(String[] tables, String rootAlias) { this.tables = tables; this.rootAlias = rootAlias; } @Override public String getAlias(String table) { return table == null ? rootAlias : generateTableAlias( rootAlias, getTableId( table, tables ) ); } }
DynamicFilterAliasGenerator
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 151235, "end": 153100 }
class ____ {}"); private static final ImmutableMap<String, String> GENERATED_TYPES = ImmutableMap.of( "foo.baz.GeneratedParent", GENERATED_PARENT, "foo.baz.GeneratedPropertyType", GENERATED_PROPERTY_TYPE); private final AutoValueProcessor autoValueProcessor; private final Expect expect; GeneratedParentProcessor(AutoValueProcessor autoValueProcessor, Expect expect) { this.autoValueProcessor = autoValueProcessor; this.expect = expect; } private boolean generated; @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (!generated) { generated = true; // Check that AutoValueProcessor has already run and deferred the foo.bar.Test type because // we haven't generated its parent yet. expect.that(autoValueProcessor.deferredTypeNames()).contains("foo.bar.Test"); GENERATED_TYPES.forEach( (typeName, source) -> { try { JavaFileObject generated = processingEnv.getFiler().createSourceFile(typeName); try (Writer writer = generated.openWriter()) { writer.write(source); } } catch (IOException e) { throw new UncheckedIOException(e); } }); } return false; } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } } // This is a regression test for the problem described in // https://github.com/google/auto/issues/1087. @Test public void kotlinMetadataAnnotationsAreImplicitlyExcludedFromCopying() { JavaFileObject metadata = JavaFileObjects.forSourceLines( "kotlin.Metadata", "package kotlin;", "", "public @
GeneratedPropertyType
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/Elasticsearch814Codec.java
{ "start": 1437, "end": 5278 }
class ____ extends CodecService.DeduplicateFieldInfosCodec { private final StoredFieldsFormat storedFieldsFormat; private static final PostingsFormat defaultPostingsFormat = new Lucene99PostingsFormat(); private final PostingsFormat postingsFormat = new PerFieldPostingsFormat() { @Override public PostingsFormat getPostingsFormatForField(String field) { return Elasticsearch814Codec.this.getPostingsFormatForField(field); } }; private static final DocValuesFormat defaultDVFormat = new Lucene90DocValuesFormat(); private final DocValuesFormat docValuesFormat = new PerFieldDocValuesFormat() { @Override public DocValuesFormat getDocValuesFormatForField(String field) { return Elasticsearch814Codec.this.getDocValuesFormatForField(field); } }; private static final KnnVectorsFormat defaultKnnVectorsFormat = new Lucene99HnswVectorsFormat(); private final KnnVectorsFormat knnVectorsFormat = new PerFieldKnnVectorsFormat() { @Override public KnnVectorsFormat getKnnVectorsFormatForField(String field) { return Elasticsearch814Codec.this.getKnnVectorsFormatForField(field); } }; private static final Lucene99Codec lucene99Codec = new Lucene99Codec(); /** Public no-arg constructor, needed for SPI loading at read-time. */ public Elasticsearch814Codec() { this(Zstd814StoredFieldsFormat.Mode.BEST_SPEED); } /** * Constructor. Takes a {@link Zstd814StoredFieldsFormat.Mode} that describes whether to optimize for retrieval speed at the expense of * worse space-efficiency or vice-versa. */ public Elasticsearch814Codec(Zstd814StoredFieldsFormat.Mode mode) { super("Elasticsearch814", lucene99Codec); this.storedFieldsFormat = mode.getFormat(); } @Override public StoredFieldsFormat storedFieldsFormat() { return storedFieldsFormat; } @Override public final PostingsFormat postingsFormat() { return postingsFormat; } @Override public final DocValuesFormat docValuesFormat() { return docValuesFormat; } @Override public final KnnVectorsFormat knnVectorsFormat() { return knnVectorsFormat; } /** * Returns the postings format that should be used for writing new segments of <code>field</code>. * * <p>The default implementation always returns "Lucene99". * * <p><b>WARNING:</b> if you subclass, you are responsible for index backwards compatibility: * future version of Lucene are only guaranteed to be able to read the default implementation, */ public PostingsFormat getPostingsFormatForField(String field) { return defaultPostingsFormat; } /** * Returns the docvalues format that should be used for writing new segments of <code>field</code> * . * * <p>The default implementation always returns "Lucene99". * * <p><b>WARNING:</b> if you subclass, you are responsible for index backwards compatibility: * future version of Lucene are only guaranteed to be able to read the default implementation. */ public DocValuesFormat getDocValuesFormatForField(String field) { return defaultDVFormat; } /** * Returns the vectors format that should be used for writing new segments of <code>field</code> * * <p>The default implementation always returns "Lucene95". * * <p><b>WARNING:</b> if you subclass, you are responsible for index backwards compatibility: * future version of Lucene are only guaranteed to be able to read the default implementation. */ public KnnVectorsFormat getKnnVectorsFormatForField(String field) { return defaultKnnVectorsFormat; } }
Elasticsearch814Codec
java
apache__camel
components/camel-jaxb/src/test/java/org/apache/camel/jaxb/SplitterAndExceptionRouteTwistIssueTest.java
{ "start": 1590, "end": 5781 }
class ____ extends CamelTestSupport { @Produce("direct:error") protected ProducerTemplate templateError; @Produce("direct:error2") protected ProducerTemplate templateError2; @EndpointInject("mock:mockReject") protected MockEndpoint mockRejectEndpoint; @EndpointInject("mock:mock_output") protected MockEndpoint mockOutput; @Test public void testErrorHandlingJaxb() throws Exception { String correctExample = "abcdef"; String errorExample = "myerror\u0010"; mockRejectEndpoint.expectedMessageCount(1); mockOutput.expectedMessageCount(4); templateError.sendBody(correctExample); templateError.sendBody(errorExample); templateError.sendBody(correctExample); templateError.sendBody(correctExample); templateError.sendBody(correctExample); mockRejectEndpoint.assertIsSatisfied(); mockOutput.assertIsSatisfied(); } @Test public void testErrorHandlingPlumber() throws Exception { String correctExample = "abcdef"; String errorExample = "myerror\u0010"; mockRejectEndpoint.expectedMessageCount(1); mockOutput.expectedMessageCount(4); templateError2.sendBody(correctExample); templateError2.sendBody(errorExample); templateError2.sendBody(correctExample); templateError2.sendBody(correctExample); templateError2.sendBody(correctExample); mockRejectEndpoint.assertIsSatisfied(); mockOutput.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { errorHandler( deadLetterChannel(mockRejectEndpoint) .useOriginalMessage() .maximumRedeliveries(0) .retryAttemptedLogLevel(LoggingLevel.WARN) .logExhausted(true) .logStackTrace(true) .logRetryStackTrace(true)); from("direct:error") .convertBodyTo(String.class, "UTF-8") .process(new Processor() { @Override public void process(Exchange exchange) { String text = (String) exchange.getIn().getBody(); Twits twits = new Twits(); Twit twit1 = new Twit(); twit1.setText(text); twits.getTwits().add(twit1); exchange.getIn().setBody(twits); } }) .split().xpath("//twits/twit").streaming() .to(mockOutput); from("direct:error2") .convertBodyTo(String.class, "UTF-8") .process(new Processor() { @Override public void process(Exchange exchange) { String text = (String) exchange.getIn().getBody(); StringBuilder twits = new StringBuilder(); twits.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"); twits.append("<twits>"); twits.append("<twit>"); twits.append(text); twits.append("</twit>"); twits.append("</twits>"); exchange.getIn().setBody(twits.toString()); } }) .split().xpath("//twits/twit").streaming() .to(mockOutput); } }; } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "twits" }) @XmlRootElement(name = "twits")
SplitterAndExceptionRouteTwistIssueTest
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/support/ReflectionEnvironmentPostProcessorsFactoryTests.java
{ "start": 7235, "end": 7600 }
class ____ implements EnvironmentPostProcessor { TestBootstrapRegistryEnvironmentPostProcessor(BootstrapRegistry bootstrapRegistry) { assertThat(bootstrapRegistry).isNotNull(); } @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { } } static
TestBootstrapRegistryEnvironmentPostProcessor
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/ClassUtil.java
{ "start": 1042, "end": 1099 }
class ____ { /** * Find a jar that contains a
ClassUtil
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/abilities/source/WatermarkPushDownSpec.java
{ "start": 2411, "end": 2687 }
class ____ {@link SourceAbilitySpec} that can not only serialize/deserialize the watermark * to/from JSON, but also can push the watermark into a {@link SupportsWatermarkPushDown}. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeName("WatermarkPushDown") public final
of