language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase/hadoop-yarn-server-timelineservice-hbase-common/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/common/ColumnPrefix.java
{ "start": 1249, "end": 2578 }
interface ____<T extends BaseTable<T>> { /** * @param qualifierPrefix Column qualifier or prefix of qualifier. * @return a byte array encoding column prefix and qualifier/prefix passed. */ byte[] getColumnPrefixBytes(String qualifierPrefix); /** * @param qualifierPrefix Column qualifier or prefix of qualifier. * @return a byte array encoding column prefix and qualifier/prefix passed. */ byte[] getColumnPrefixBytes(byte[] qualifierPrefix); /** * Get the column prefix in bytes. * @return column prefix in bytes */ byte[] getColumnPrefixInBytes(); /** * Returns column family name(as bytes) associated with this column prefix. * @return a byte array encoding column family for this prefix. */ byte[] getColumnFamilyBytes(); /** * Returns value converter implementation associated with this column prefix. * @return a {@link ValueConverter} implementation. */ ValueConverter getValueConverter(); /** * Return attributed combined with aggregations, if any. * @return an array of Attributes */ Attribute[] getCombinedAttrsWithAggr(Attribute... attributes); /** * Return true if the cell timestamp needs to be supplemented. * @return true if the cell timestamp needs to be supplemented */ boolean supplementCellTimeStamp(); }
ColumnPrefix
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/introspect/POJOPropertiesCollector.java
{ "start": 721, "end": 1552 }
class ____ { /* /********************************************************************** /* Configuration /********************************************************************** */ /** * Configuration settings */ protected final MapperConfig<?> _config; /** * Handler used for name-mangling of getter, mutator (setter/with) methods */ protected final AccessorNamingStrategy _accessorNaming; /** * True if introspection is done for serialization (giving * precedence for serialization annotations), or not (false, deserialization) */ protected final boolean _forSerialization; /** * Type of POJO for which properties are being collected. */ protected final JavaType _type; /** * Low-level introspected
POJOPropertiesCollector
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBeanByNameLookupTestClassScopedExtensionContextIntegrationTests.java
{ "start": 2982, "end": 3753 }
class ____ { @Autowired @Qualifier("field1") ExampleService localField; @MockitoSpyBean("field2") ExampleService nestedField; @Test void fieldHasOverride(ApplicationContext ctx) { assertThat(ctx.getBean("field1")) .isInstanceOf(ExampleService.class) .satisfies(MockitoAssertions::assertIsSpy) .isSameAs(localField); assertThat(localField.greeting()).isEqualTo("bean1"); } @Test void nestedFieldHasOverride(ApplicationContext ctx) { assertThat(ctx.getBean("field2")) .isInstanceOf(ExampleService.class) .satisfies(MockitoAssertions::assertIsSpy) .isSameAs(nestedField); assertThat(nestedField.greeting()).isEqualTo("bean2"); } } @Configuration(proxyBeanMethods = false) static
MockitoSpyBeanNestedTests
java
elastic__elasticsearch
x-pack/plugin/sql/qa/server/security/src/test/java/org/elasticsearch/xpack/sql/qa/security/RestSqlIT.java
{ "start": 903, "end": 2182 }
class ____ extends RestSqlTestCase { static final boolean SSL_ENABLED = Booleans.parseBoolean(System.getProperty("tests.ssl.enabled"), false); static Settings securitySettings() { String token = basicAuthHeaderValue("test_admin", new SecureString("x-pack-test-password".toCharArray())); Settings.Builder builder = Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token); if (SSL_ENABLED) { Path keyStore; try { keyStore = PathUtils.get(RestSqlIT.class.getResource("/test-node.jks").toURI()); } catch (URISyntaxException e) { throw new RuntimeException("exception while reading the store", e); } if (Files.exists(keyStore) == false) { throw new IllegalStateException("Keystore file [" + keyStore + "] does not exist."); } builder.put(ESRestTestCase.TRUSTSTORE_PATH, keyStore).put(ESRestTestCase.TRUSTSTORE_PASSWORD, "keypass"); } return builder.build(); } @Override protected Settings restClientSettings() { return securitySettings(); } @Override protected String getProtocol() { return RestSqlIT.SSL_ENABLED ? "https" : "http"; } }
RestSqlIT
java
apache__camel
components/camel-servlet/src/test/java/org/apache/camel/component/servlet/rest/RestApiMatchUriServletTest.java
{ "start": 1182, "end": 2479 }
class ____ extends ServletCamelRouterTestSupport { @Test public void testApiDocGet() throws Exception { WebRequest req = new GetMethodWebRequest(contextUrl + "/services/api-doc"); req.setHeaderField("Accept", "application/json"); WebResponse response = query(req, false); assertEquals(200, response.getResponseCode()); MockEndpoint.assertIsSatisfied(context); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { restConfiguration().component("servlet") .apiContextPath("/api-doc") .endpointProperty("matchOnUriPrefix", "true") .apiProperty("cors", "true").apiProperty("api.title", "The hello rest thing") .apiProperty("api.version", "1.2.3") .bindingMode(RestBindingMode.auto); // use the rest DSL to define the rest services rest("/users/") .post("new").consumes("application/json").type(UserPojo.class) .to("mock:input"); } }; } }
RestApiMatchUriServletTest
java
apache__logging-log4j2
log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/util/StringParameterParserTest.java
{ "start": 1589, "end": 12355 }
class ____ { @Test void test_empty_string() { testSuccess("", Collections.emptyMap()); } @Test void test_blank_string() { testSuccess("\t", Collections.emptyMap()); } @Test void test_simple_pair() { testSuccess("a=b", Collections.singletonMap("a", Values.stringValue("b"))); } @Test void test_simple_pair_with_whitespace_1() { testSuccess(" a=b", Collections.singletonMap("a", Values.stringValue("b"))); } @Test void test_simple_pair_with_whitespace_2() { testSuccess(" a =b", Collections.singletonMap("a", Values.stringValue("b"))); } @Test void test_simple_pair_with_whitespace_3() { testSuccess(" a = b", Collections.singletonMap("a", Values.stringValue("b"))); } @Test void test_simple_pair_with_whitespace_4() { testSuccess(" a = b ", Collections.singletonMap("a", Values.stringValue("b"))); } @Test void test_null_value_1() { testSuccess("a", Collections.singletonMap("a", Values.nullValue())); } @Test void test_null_value_2() { testSuccess("a,b=c,d=", new LinkedHashMap<String, Value>() { { put("a", Values.nullValue()); put("b", Values.stringValue("c")); put("d", Values.nullValue()); } }); } @Test void test_null_value_3() { testSuccess("a,b=c,d", new LinkedHashMap<String, Value>() { { put("a", Values.nullValue()); put("b", Values.stringValue("c")); put("d", Values.nullValue()); } }); } @Test void test_null_value_4() { testSuccess("a,b=\"c,=\\\"\",d=,e=f", new LinkedHashMap<String, Value>() { { put("a", Values.nullValue()); put("b", Values.doubleQuotedStringValue("c,=\"")); put("d", Values.nullValue()); put("e", Values.stringValue("f")); } }); } @Test void test_two_pairs() { testSuccess("a=b,c=d", new LinkedHashMap<String, Value>() { { put("a", Values.stringValue("b")); put("c", Values.stringValue("d")); } }); } @Test void test_quoted_string_01() { testSuccess("a=\"b\"", Collections.singletonMap("a", Values.doubleQuotedStringValue("b"))); } @Test void test_quoted_string_02() { testSuccess("a=\"b\",c=d", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("b")); put("c", Values.stringValue("d")); } }); } @Test void test_quoted_string_03() { testSuccess("a=b,c=\"d\"", new LinkedHashMap<String, Value>() { { put("a", Values.stringValue("b")); put("c", Values.doubleQuotedStringValue("d")); } }); } @Test void test_quoted_string_04() { testSuccess("a=\"b\",c=\"d\"", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("b")); put("c", Values.doubleQuotedStringValue("d")); } }); } @Test void test_quoted_string_05() { testSuccess("a=\"\\\"b\"", Collections.singletonMap("a", Values.doubleQuotedStringValue("\"b"))); } @Test void test_quoted_string_06() { testSuccess("a=\"\\\"b\\\"\"", Collections.singletonMap("a", Values.doubleQuotedStringValue("\"b\""))); } @Test void test_quoted_string_07() { testSuccess("a=\"\\\"b\",c=d", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b")); put("c", Values.stringValue("d")); } }); } @Test void test_quoted_string_08() { testSuccess("a=\"\\\"b\\\"\",c=d", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b\"")); put("c", Values.stringValue("d")); } }); } @Test void test_quoted_string_09() { testSuccess("a=\"\\\"b,\",c=d", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b,")); put("c", Values.stringValue("d")); } }); } @Test void test_quoted_string_10() { testSuccess("a=\"\\\"b\\\",\",c=d", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b\",")); put("c", Values.stringValue("d")); } }); } @Test void test_quoted_string_11() { testSuccess("a=\"\\\"b\",c=\"d\"", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b")); put("c", Values.doubleQuotedStringValue("d")); } }); } @Test void test_quoted_string_12() { testSuccess("a=\"\\\"b\\\"\",c=\"d\"", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b\"")); put("c", Values.doubleQuotedStringValue("d")); } }); } @Test void test_quoted_string_13() { testSuccess("a=\"\\\"b,\",c=\"\\\"d\"", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b,")); put("c", Values.doubleQuotedStringValue("\"d")); } }); } @Test void test_quoted_string_14() { testSuccess("a=\"\\\"b\\\",\",c=\"\\\"d\\\"\"", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b\",")); put("c", Values.doubleQuotedStringValue("\"d\"")); } }); } @Test void test_quoted_string_15() { testSuccess("a=\"\\\"b\",c=\",d\"", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b")); put("c", Values.doubleQuotedStringValue(",d")); } }); } @Test void test_quoted_string_16() { testSuccess("a=\"\\\"b\\\"\",c=\",d\"", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b\"")); put("c", Values.doubleQuotedStringValue(",d")); } }); } @Test void test_quoted_string_17() { testSuccess("a=\"\\\"b,\",c=\"\\\"d,\"", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b,")); put("c", Values.doubleQuotedStringValue("\"d,")); } }); } @Test void test_quoted_string_18() { testSuccess("a=\"\\\"b\\\",\",c=\"\\\"d\\\",\"", new LinkedHashMap<String, Value>() { { put("a", Values.doubleQuotedStringValue("\"b\",")); put("c", Values.doubleQuotedStringValue("\"d\",")); } }); } private static void testSuccess(final String input, final Map<String, Value> expectedMap) { final Map<String, Value> actualMap = StringParameterParser.parse(input); Assertions.assertThat(actualMap).as("input: %s", input).isEqualTo(expectedMap); } @Test void test_missing_key() { Assertions.assertThatThrownBy(() -> { final String input = ",a=b"; StringParameterParser.parse(input); }) .hasMessageStartingWith("failed to locate key at index 0"); } @Test void test_conflicting_key() { Assertions.assertThatThrownBy(() -> { final String input = "a,a"; StringParameterParser.parse(input); }) .hasMessageStartingWith("conflicting key at index 2"); } @Test void test_prematurely_ending_quoted_string_01() { Assertions.assertThatThrownBy(() -> { final String input = "a,b=\""; StringParameterParser.parse(input); }) .hasMessageStartingWith("failed to locate the end of double-quoted content starting at index 4"); } @Test void test_prematurely_ending_quoted_string_02() { Assertions.assertThatThrownBy(() -> { final String input = "a,b=\"c"; StringParameterParser.parse(input); }) .hasMessageStartingWith("failed to locate the end of double-quoted content starting at index 4"); } @Test void test_prematurely_ending_quoted_string_03() { Assertions.assertThatThrownBy(() -> { final String input = "a,b=\",c"; StringParameterParser.parse(input); }) .hasMessageStartingWith("failed to locate the end of double-quoted content starting at index 4"); } @Test void test_prematurely_ending_quoted_string_04() { Assertions.assertThatThrownBy(() -> { final String input = "a,b=\",c\" x"; StringParameterParser.parse(input); }) .hasMessageStartingWith("was expecting comma at index 9"); } @Test void test_NullValue_toString() { final Map<String, Value> map = StringParameterParser.parse("a"); final NullValue value = (NullValue) map.get("a"); Assertions.assertThat(value.toString()).isEqualTo("null"); } @Test void test_StringValue_toString() { final Map<String, Value> map = StringParameterParser.parse("a=b"); final StringValue value = (StringValue) map.get("a"); Assertions.assertThat(value.toString()).isEqualTo("b"); } @Test void test_DoubleQuotedStringValue_toString() { final Map<String, Value> map = StringParameterParser.parse("a=\"\\\"b\""); final DoubleQuotedStringValue value = (DoubleQuotedStringValue) map.get("a"); Assertions.assertThat(value.toString()).isEqualTo("\"b"); } @Test void test_allowedKeys() { Assertions.assertThatThrownBy(() -> { final String input = "a,b"; final Set<String> allowedKeys = new LinkedHashSet<>(Collections.singletonList("a")); StringParameterParser.parse(input, allowedKeys); }) .hasMessageStartingWith("unknown key \"b\" is found in input: a,b"); } }
StringParameterParserTest
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java
{ "start": 4281, "end": 4359 }
class ____ output a constant single character. */ private static final
to
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/TestXMLUtils.java
{ "start": 1834, "end": 6928 }
class ____ extends AbstractHadoopTestBase { @Test public void testSecureDocumentBuilderFactory() throws Exception { DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader("<root/>"))); assertThat(doc).describedAs("parsed document").isNotNull(); } @Test public void testExternalDtdWithSecureDocumentBuilderFactory() throws Exception { assertThrows(SAXException.class, () -> { DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder(); try (InputStream stream = getResourceStream("/xml/external-dtd.xml")) { Document doc = db.parse(stream); } }); } @Test public void testEntityDtdWithSecureDocumentBuilderFactory() throws Exception { assertThrows(SAXException.class, () -> { DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder(); try (InputStream stream = getResourceStream("/xml/entity-dtd.xml")) { Document doc = db.parse(stream); } }); } @Test public void testSecureSAXParserFactory() throws Exception { SAXParser parser = XMLUtils.newSecureSAXParserFactory().newSAXParser(); parser.parse(new InputSource(new StringReader("<root/>")), new DefaultHandler()); } @Test public void testExternalDtdWithSecureSAXParserFactory() throws Exception { assertThrows(SAXException.class, () -> { SAXParser parser = XMLUtils.newSecureSAXParserFactory().newSAXParser(); try (InputStream stream = getResourceStream("/xml/external-dtd.xml")) { parser.parse(stream, new DefaultHandler()); } }); } @Test public void testEntityDtdWithSecureSAXParserFactory() throws Exception { assertThrows(SAXException.class, () -> { SAXParser parser = XMLUtils.newSecureSAXParserFactory().newSAXParser(); try (InputStream stream = getResourceStream("/xml/entity-dtd.xml")) { parser.parse(stream, new DefaultHandler()); } }); } @Test public void testSecureTransformerFactory() throws Exception { Transformer transformer = XMLUtils.newSecureTransformerFactory().newTransformer(); DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader("<root/>"))); try (StringWriter stringWriter = new StringWriter()) { transformer.transform(new DOMSource(doc), new StreamResult(stringWriter)); assertThat(stringWriter.toString()).contains("<root"); } } @Test public void testExternalDtdWithSecureTransformerFactory() throws Exception { assertThrows(TransformerException.class, () -> { Transformer transformer = XMLUtils.newSecureTransformerFactory().newTransformer(); try ( InputStream stream = getResourceStream("/xml/external-dtd.xml"); StringWriter stringWriter = new StringWriter() ) { transformer.transform(new StreamSource(stream), new StreamResult(stringWriter)); } }); } @Test public void testSecureSAXTransformerFactory() throws Exception { Transformer transformer = XMLUtils.newSecureSAXTransformerFactory().newTransformer(); DocumentBuilder db = XMLUtils.newSecureDocumentBuilderFactory().newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader("<root/>"))); try (StringWriter stringWriter = new StringWriter()) { transformer.transform(new DOMSource(doc), new StreamResult(stringWriter)); assertThat(stringWriter.toString()).contains("<root"); } } @Test public void testExternalDtdWithSecureSAXTransformerFactory() throws Exception { assertThrows(TransformerException.class, () -> { Transformer transformer = XMLUtils.newSecureSAXTransformerFactory().newTransformer(); try ( InputStream stream = getResourceStream("/xml/external-dtd.xml"); StringWriter stringWriter = new StringWriter() ) { transformer.transform(new StreamSource(stream), new StreamResult(stringWriter)); } }); } @Test public void testBestEffortSetAttribute() throws Exception { TransformerFactory factory = TransformerFactory.newInstance(); AtomicBoolean flag1 = new AtomicBoolean(true); XMLUtils.bestEffortSetAttribute(factory, flag1, "unsupportedAttribute false", "abc"); assertFalse(flag1.get(), "unexpected attribute results in return of false?"); AtomicBoolean flag2 = new AtomicBoolean(true); XMLUtils.bestEffortSetAttribute(factory, flag2, XMLConstants.ACCESS_EXTERNAL_DTD, ""); assertTrue(flag2.get(), "expected attribute results in return of true?"); AtomicBoolean flag3 = new AtomicBoolean(false); XMLUtils.bestEffortSetAttribute(factory, flag3, XMLConstants.ACCESS_EXTERNAL_DTD, ""); assertFalse(flag3.get(), "expected attribute results in return of false if input flag is false?"); } private static InputStream getResourceStream(final String filename) { return TestXMLUtils.class.getResourceAsStream(filename); } }
TestXMLUtils
java
grpc__grpc-java
alts/src/main/java/io/grpc/alts/AltsChannelCredentials.java
{ "start": 4300, "end": 4812 }
class ____ implements InternalProtocolNegotiator.ClientFactory { private final Status status; public FailingProtocolNegotiatorFactory(Status status) { this.status = status; } @Override public ProtocolNegotiator newNegotiator() { return new FailingProtocolNegotiator(status); } @Override public int getDefaultPort() { return 443; } } private static final AsciiString SCHEME = AsciiString.of("https"); static final
FailingProtocolNegotiatorFactory
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/ReturnMissingNullableTest.java
{ "start": 35981, "end": 36524 }
class ____ { java.lang.@Nullable String getMessage(boolean b) { return b ? "" : null; } } """) .doTest(); } @Test public void negativeCases_checkNotNullNullableInput() { createCompilationTestHelper() .addSourceLines( "com/google/errorprone/bugpatterns/nullness/NullReturnTest.java", "package com.google.errorprone.bugpatterns.nullness;", "import javax.annotation.Nullable;", "public
LiteralNullReturnTest
java
spring-projects__spring-framework
spring-beans/src/testFixtures/java/org/springframework/beans/testfixture/beans/IndexedTestBean.java
{ "start": 1090, "end": 4167 }
class ____ { private TestBean[] array; private Collection<?> collection; private List list; private Set<? super Object> set; private SortedSet<? super Object> sortedSet; private Map map; private SortedMap sortedMap; private IterableMap iterableMap; private MyTestBeans myTestBeans; public IndexedTestBean() { this(true); } public IndexedTestBean(boolean populate) { if (populate) { populate(); } } @SuppressWarnings("unchecked") public void populate() { TestBean tb0 = new TestBean("name0", 0); TestBean tb1 = new TestBean("name1", 0); TestBean tb2 = new TestBean("name2", 0); TestBean tb3 = new TestBean("name3", 0); TestBean tb4 = new TestBean("name4", 0); TestBean tb5 = new TestBean("name5", 0); TestBean tb6 = new TestBean("name6", 0); TestBean tb7 = new TestBean("name7", 0); TestBean tb8 = new TestBean("name8", 0); TestBean tbA = new TestBean("nameA", 0); TestBean tbB = new TestBean("nameB", 0); TestBean tbC = new TestBean("nameC", 0); TestBean tbX = new TestBean("nameX", 0); TestBean tbY = new TestBean("nameY", 0); TestBean tbZ = new TestBean("nameZ", 0); this.array = new TestBean[] {tb0, tb1}; this.list = new ArrayList<>(); this.list.add(tb2); this.list.add(tb3); this.set = new TreeSet<>(); this.set.add(tb6); this.set.add(tb7); this.map = new HashMap<>(); this.map.put("key1", tb4); this.map.put("key2", tb5); this.map.put("key.3", tb5); List list = new ArrayList(); list.add(tbA); list.add(tbB); this.iterableMap = new IterableMap<>(); this.iterableMap.put("key1", tbC); this.iterableMap.put("key2", list); list = new ArrayList(); list.add(tbX); list.add(tbY); this.map.put("key4", list); this.map.put("key5[foo]", tb8); this.myTestBeans = new MyTestBeans(tbZ); } public TestBean[] getArray() { return array; } public void setArray(TestBean[] array) { this.array = array; } public Collection<?> getCollection() { return collection; } public void setCollection(Collection<?> collection) { this.collection = collection; } public List getList() { return list; } public void setList(List list) { this.list = list; } public Set<?> getSet() { return set; } public void setSet(Set<? super Object> set) { this.set = set; } public SortedSet<? super Object> getSortedSet() { return sortedSet; } public void setSortedSet(SortedSet<? super Object> sortedSet) { this.sortedSet = sortedSet; } public Map getMap() { return map; } public void setMap(Map map) { this.map = map; } public SortedMap getSortedMap() { return sortedMap; } public void setSortedMap(SortedMap sortedMap) { this.sortedMap = sortedMap; } public IterableMap getIterableMap() { return this.iterableMap; } public void setIterableMap(IterableMap iterableMap) { this.iterableMap = iterableMap; } public MyTestBeans getMyTestBeans() { return myTestBeans; } public void setMyTestBeans(MyTestBeans myTestBeans) { this.myTestBeans = myTestBeans; } @SuppressWarnings("serial") public static
IndexedTestBean
java
micronaut-projects__micronaut-core
inject-java/src/main/java/io/micronaut/annotation/processing/visitor/JavaEnumElement.java
{ "start": 1223, "end": 1298 }
interface ____ Java. * * @author graemerocher * @since 1.0 */ @Internal
for
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/AllowOnlyXForwardedHeaderUsingDefaultConfigTest.java
{ "start": 349, "end": 2809 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(ForwardedHandlerInitializer.class) .addAsResource(new StringAsset("quarkus.http.proxy.proxy-address-forwarding=true\n" + "quarkus.http.proxy.enable-forwarded-host=true\n" + "quarkus.http.proxy.enable-forwarded-prefix=true\n" + "quarkus.http.proxy.forwarded-host-header=X-Forwarded-Server"), "application.properties")); @Test public void testWithXForwardedSsl() { assertThat(RestAssured.get("/path").asString()).startsWith("http|"); RestAssured.given() .header("Forwarded", "proto=http;for=backend2:5555;host=somehost2") .header("X-Forwarded-Ssl", "on") .header("X-Forwarded-For", "backend:4444") .header("X-Forwarded-Server", "somehost") .get("/path") .then() .body(Matchers.equalTo("https|somehost|backend:4444|/path|https://somehost/path")); } @Test public void testWithXForwardedProto() { assertThat(RestAssured.get("/path").asString()).startsWith("http|"); RestAssured.given() .header("Forwarded", "proto=http;for=backend2:5555;host=somehost2") .header("X-Forwarded-Proto", "https") .header("X-Forwarded-For", "backend:4444") .header("X-Forwarded-Server", "somehost") .get("/path") .then() .body(Matchers.equalTo("https|somehost|backend:4444|/path|https://somehost/path")); } @Test public void testWithXForwardedProtoAndXForwardedSsl() { assertThat(RestAssured.get("/path").asString()).startsWith("http|"); RestAssured.given() .header("Forwarded", "proto=http;for=backend2:5555;host=somehost2") .header("X-Forwarded-Proto", "https") .header("X-Forwarded-Ssl", "on") .header("X-Forwarded-For", "backend:4444") .header("X-Forwarded-Server", "somehost") .get("/path") .then() .body(Matchers.equalTo("https|somehost|backend:4444|/path|https://somehost/path")); } }
AllowOnlyXForwardedHeaderUsingDefaultConfigTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/tool/schema/SchemaGenerationScriptsActionBadPropertyValueTests.java
{ "start": 875, "end": 1951 }
class ____ implements ServiceRegistryProducer { @Test public void testValueEndingWithSpaceDoesNotCauseExceptionDuringBootstrap(ServiceRegistryScope registryScope) { registryScope.getRegistry(); } @Override public StandardServiceRegistry produceServiceRegistry(StandardServiceRegistryBuilder builder) { try { var dropOutput = File.createTempFile( "drop_script", ".sql" ); var createOutput = File.createTempFile( "create_script", ".sql" ); dropOutput.deleteOnExit(); createOutput.deleteOnExit(); builder.applySetting( "javax.persistence.schema-generation.scripts.action", // note the space... "drop-and-create " ); builder.applySetting( "javax.persistence.schema-generation.scripts.create-target", createOutput.getAbsolutePath() ); builder.applySetting( "javax.persistence.schema-generation.scripts.drop-target", dropOutput.getAbsolutePath() ); } catch (IOException e) { fail( "unable to create temp file" + e ); } return builder.build(); } }
SchemaGenerationScriptsActionBadPropertyValueTests
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java
{ "start": 12472, "end": 12621 }
class ____ extends TestObject { @SuppressWarnings("unused") public String publicField = "foo"; } private static
TestObjectSubclassWithPublicField
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/tree/EsqlNodeSubclassTests.java
{ "start": 6469, "end": 9983 }
class ____<T extends B, B extends Node<B>> extends NodeSubclassTests { private static final String ESQL_CORE_CLASS_PREFIX = "org.elasticsearch.xpack.esql.core"; private static final String ESQL_CORE_JAR_LOCATION_SUBSTRING = "x-pack-esql-core"; private static final String ESQL_CLASS_PREFIX = "org.elasticsearch.xpack.esql"; private static final Predicate<String> CLASSNAME_FILTER = className -> { boolean esqlCore = className.startsWith(ESQL_CORE_CLASS_PREFIX) != false; boolean esqlProper = className.startsWith(ESQL_CLASS_PREFIX) != false; return (esqlCore || esqlProper); }; /** * Scans the {@code .class} files to identify all classes and checks if * they are subclasses of {@link Node}. */ @ParametersFactory(argumentFormatting = "%1s") @SuppressWarnings("rawtypes") public static List<Object[]> nodeSubclasses() throws IOException { return subclassesOf(Node.class, CLASSNAME_FILTER).stream() .filter(c -> testClassFor(c) == null) .map(c -> new Object[] { c }) .toList(); } private static final List<Class<?>> CLASSES_WITH_MIN_TWO_CHILDREN = List.of(Concat.class, CIDRMatch.class, Fork.class, UnionAll.class); // List of classes that are "unresolved" NamedExpression subclasses, therefore not suitable for use with logical/physical plan nodes. private static final List<Class<?>> UNRESOLVED_CLASSES = List.of( UnresolvedAttribute.class, UnresolvedException.class, UnresolvedFunction.class, UnresolvedNamedExpression.class ); private final Class<T> subclass; public EsqlNodeSubclassTests(Class<T> subclass) { this.subclass = subclass; } public void testInfoParameters() throws Exception { Constructor<T> ctor = longestCtor(subclass); Object[] nodeCtorArgs = ctorArgs(ctor); T node = ctor.newInstance(nodeCtorArgs); /* * The count should be the same size as the longest constructor * by convention. If it isn't then we're missing something. */ int expectedCount = ctor.getParameterCount(); /* * Except the first `Location` argument of the ctor is implicit * in the parameters and not included. */ expectedCount -= 1; assertEquals("Wrong number of info parameters for " + subclass.getSimpleName(), expectedCount, info(node).properties().size()); } /** * Test {@code Node.transformPropertiesOnly} * implementation on {@link #subclass} which tests the implementation of * {@code Node.info}. And tests the actual {@link NodeInfo} subclass * implementations in the process. */ public void testTransform() throws Exception { Constructor<T> ctor = longestCtor(subclass); Object[] nodeCtorArgs = ctorArgs(ctor); T node = ctor.newInstance(nodeCtorArgs); Type[] argTypes = ctor.getGenericParameterTypes(); // start at 1 because we can't change Location. for (int changedArgOffset = 1; changedArgOffset < ctor.getParameterCount(); changedArgOffset++) { Object originalArgValue = nodeCtorArgs[changedArgOffset]; Type changedArgType = argTypes[changedArgOffset]; Object changedArgValue = randomValueOtherThanMaxTries( nodeCtorArgs[changedArgOffset], () -> makeArg(changedArgType), // JoinType has only 1 permitted
EsqlNodeSubclassTests
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java
{ "start": 2549, "end": 10823 }
class ____ extends GenericTypeAwareAutowireCandidateResolver { private final Set<Class<? extends Annotation>> qualifierTypes = CollectionUtils.newLinkedHashSet(2); private Class<? extends Annotation> valueAnnotationType = Value.class; /** * Create a new {@code QualifierAnnotationAutowireCandidateResolver} for Spring's * standard {@link Qualifier} annotation. * <p>Also supports JSR-330's {@link jakarta.inject.Qualifier} annotation if available. */ @SuppressWarnings("unchecked") public QualifierAnnotationAutowireCandidateResolver() { this.qualifierTypes.add(Qualifier.class); try { this.qualifierTypes.add((Class<? extends Annotation>) ClassUtils.forName("jakarta.inject.Qualifier", QualifierAnnotationAutowireCandidateResolver.class.getClassLoader())); } catch (ClassNotFoundException ex) { // JSR-330 API (as included in Jakarta EE) not available - simply skip. } } /** * Create a new {@code QualifierAnnotationAutowireCandidateResolver} for the given * qualifier annotation type. * @param qualifierType the qualifier annotation to look for */ public QualifierAnnotationAutowireCandidateResolver(Class<? extends Annotation> qualifierType) { Assert.notNull(qualifierType, "'qualifierType' must not be null"); this.qualifierTypes.add(qualifierType); } /** * Create a new {@code QualifierAnnotationAutowireCandidateResolver} for the given * qualifier annotation types. * @param qualifierTypes the qualifier annotations to look for */ public QualifierAnnotationAutowireCandidateResolver(Set<Class<? extends Annotation>> qualifierTypes) { Assert.notNull(qualifierTypes, "'qualifierTypes' must not be null"); this.qualifierTypes.addAll(qualifierTypes); } /** * Register the given type to be used as a qualifier when autowiring. * <p>This identifies qualifier annotations for direct use (on fields, * method parameters and constructor parameters) as well as meta * annotations that in turn identify actual qualifier annotations. * <p>This implementation only supports annotations as qualifier types. * The default is Spring's {@link Qualifier} annotation which serves * as a qualifier for direct use and also as a meta annotation. * @param qualifierType the annotation type to register */ public void addQualifierType(Class<? extends Annotation> qualifierType) { this.qualifierTypes.add(qualifierType); } /** * Set the 'value' annotation type, to be used on fields, method parameters * and constructor parameters. * <p>The default value annotation type is the Spring-provided * {@link Value} annotation. * <p>This setter property exists so that developers can provide their own * (non-Spring-specific) annotation type to indicate a default value * expression for a specific argument. */ public void setValueAnnotationType(Class<? extends Annotation> valueAnnotationType) { this.valueAnnotationType = valueAnnotationType; } /** * Determine whether the provided bean definition is an autowire candidate. * <p>To be considered a candidate the bean's <em>autowire-candidate</em> * attribute must not have been set to 'false'. Also, if an annotation on * the field or parameter to be autowired is recognized by this bean factory * as a <em>qualifier</em>, the bean must 'match' against the annotation as * well as any attributes it may contain. The bean definition must contain * the same qualifier or match by meta attributes. A "value" attribute will * fall back to match against the bean name or an alias if a qualifier or * attribute does not match. * @see Qualifier */ @Override public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) { if (!super.isAutowireCandidate(bdHolder, descriptor)) { return false; } Boolean checked = checkQualifiers(bdHolder, descriptor.getAnnotations()); if (checked != Boolean.FALSE) { MethodParameter methodParam = descriptor.getMethodParameter(); if (methodParam != null) { Method method = methodParam.getMethod(); if (method == null || void.class == method.getReturnType()) { Boolean methodChecked = checkQualifiers(bdHolder, methodParam.getMethodAnnotations()); if (methodChecked != null && checked == null) { checked = methodChecked; } } } } return (checked == Boolean.TRUE || (checked == null && ((RootBeanDefinition) bdHolder.getBeanDefinition()).isDefaultCandidate())); } /** * Match the given qualifier annotations against the candidate bean definition. * @return {@code false} if a qualifier has been found but not matched, * {@code true} if a qualifier has been found and matched, * {@code null} if no qualifier has been found at all */ protected @Nullable Boolean checkQualifiers(BeanDefinitionHolder bdHolder, Annotation[] annotationsToSearch) { boolean qualifierFound = false; if (!ObjectUtils.isEmpty(annotationsToSearch)) { SimpleTypeConverter typeConverter = new SimpleTypeConverter(); for (Annotation annotation : annotationsToSearch) { Class<? extends Annotation> type = annotation.annotationType(); if (isPlainJavaAnnotation(type)) { continue; } boolean checkMeta = true; boolean fallbackToMeta = false; if (isQualifier(type)) { qualifierFound = true; if (!checkQualifier(bdHolder, annotation, typeConverter)) { fallbackToMeta = true; } else { checkMeta = false; } } if (checkMeta) { boolean foundMeta = false; for (Annotation metaAnn : type.getAnnotations()) { Class<? extends Annotation> metaType = metaAnn.annotationType(); if (isPlainJavaAnnotation(metaType)) { continue; } if (isQualifier(metaType)) { qualifierFound = true; foundMeta = true; // Only accept fallback match if @Qualifier annotation has a value... // Otherwise, it is just a marker for a custom qualifier annotation. if ((fallbackToMeta && ObjectUtils.isEmpty(AnnotationUtils.getValue(metaAnn))) || !checkQualifier(bdHolder, metaAnn, typeConverter)) { return false; } } } if (fallbackToMeta && !foundMeta) { return false; } } } } return (qualifierFound ? true : null); } /** * Check whether the given annotation type is a plain "java." annotation, * typically from {@code java.lang.annotation}. * <p>Aligned with * {@code org.springframework.core.annotation.AnnotationsScanner#hasPlainJavaAnnotationsOnly}. */ private boolean isPlainJavaAnnotation(Class<? extends Annotation> annotationType) { return annotationType.getName().startsWith("java."); } /** * Check whether the given annotation type is a recognized qualifier type. */ protected boolean isQualifier(Class<? extends Annotation> annotationType) { for (Class<? extends Annotation> qualifierType : this.qualifierTypes) { if (annotationType.equals(qualifierType) || annotationType.isAnnotationPresent(qualifierType)) { return true; } } return false; } /** * Match the given qualifier annotation against the candidate bean definition. */ protected boolean checkQualifier( BeanDefinitionHolder bdHolder, Annotation annotation, TypeConverter typeConverter) { Class<? extends Annotation> type = annotation.annotationType(); RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition(); AutowireCandidateQualifier qualifier = bd.getQualifier(type.getName()); if (qualifier == null) { qualifier = bd.getQualifier(ClassUtils.getShortName(type)); } if (qualifier == null) { // First, check annotation on qualified element, if any Annotation targetAnnotation = getQualifiedElementAnnotation(bd, type); // Then, check annotation on factory method, if applicable if (targetAnnotation == null) { targetAnnotation = getFactoryMethodAnnotation(bd, type); } if (targetAnnotation == null) { RootBeanDefinition dbd = getResolvedDecoratedDefinition(bd); if (dbd != null) { targetAnnotation = getFactoryMethodAnnotation(dbd, type); } } if (targetAnnotation == null) { BeanFactory beanFactory = getBeanFactory(); // Look for matching annotation on the target
QualifierAnnotationAutowireCandidateResolver
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/checkpoints/CheckpointStatistics.java
{ "start": 19657, "end": 23286 }
class ____ extends CheckpointStatistics { public static final String FIELD_NAME_EXTERNAL_PATH = "external_path"; public static final String FIELD_NAME_DISCARDED = "discarded"; @JsonProperty(FIELD_NAME_EXTERNAL_PATH) @Nullable private final String externalPath; @JsonProperty(FIELD_NAME_DISCARDED) private final boolean discarded; @JsonCreator public CompletedCheckpointStatistics( @JsonProperty(FIELD_NAME_ID) long id, @JsonProperty(FIELD_NAME_STATUS) CheckpointStatsStatus status, @JsonProperty(FIELD_NAME_IS_SAVEPOINT) boolean savepoint, @JsonProperty(FIELD_NAME_SAVEPOINT_FORMAT) String savepointFormat, @JsonProperty(FIELD_NAME_TRIGGER_TIMESTAMP) long triggerTimestamp, @JsonProperty(FIELD_NAME_LATEST_ACK_TIMESTAMP) long latestAckTimestamp, @JsonProperty(FIELD_NAME_CHECKPOINTED_SIZE) long checkpointedSize, @JsonProperty(FIELD_NAME_STATE_SIZE) long stateSize, @JsonProperty(FIELD_NAME_DURATION) long duration, @JsonProperty(FIELD_NAME_ALIGNMENT_BUFFERED) long alignmentBuffered, @JsonProperty(FIELD_NAME_PROCESSED_DATA) long processedData, @JsonProperty(FIELD_NAME_PERSISTED_DATA) long persistedData, @JsonProperty(FIELD_NAME_NUM_SUBTASKS) int numSubtasks, @JsonProperty(FIELD_NAME_NUM_ACK_SUBTASKS) int numAckSubtasks, @JsonProperty(FIELD_NAME_CHECKPOINT_TYPE) RestAPICheckpointType checkpointType, @JsonDeserialize(keyUsing = JobVertexIDKeyDeserializer.class) @JsonProperty(FIELD_NAME_TASKS) Map<JobVertexID, TaskCheckpointStatistics> checkpointingStatisticsPerTask, @JsonProperty(FIELD_NAME_EXTERNAL_PATH) @Nullable String externalPath, @JsonProperty(FIELD_NAME_DISCARDED) boolean discarded) { super( id, status, savepoint, savepointFormat, triggerTimestamp, latestAckTimestamp, checkpointedSize, stateSize, duration, alignmentBuffered, processedData, persistedData, numSubtasks, numAckSubtasks, checkpointType, checkpointingStatisticsPerTask); this.externalPath = externalPath; this.discarded = discarded; } @Nullable public String getExternalPath() { return externalPath; } public boolean isDiscarded() { return discarded; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } CompletedCheckpointStatistics that = (CompletedCheckpointStatistics) o; return discarded == that.discarded && Objects.equals(externalPath, that.externalPath); } @Override public int hashCode() { return Objects.hash(super.hashCode(), externalPath, discarded); } } /** Statistics for a failed checkpoint. */ public static final
CompletedCheckpointStatistics
java
spring-projects__spring-boot
module/spring-boot-webservices-test/src/test/java/org/springframework/boot/webservices/test/autoconfigure/server/WebServiceServerTypeExcludeFilterTests.java
{ "start": 3967, "end": 4046 }
class ____ { } @WebServiceServerTest(WebService1.class) static
WithNoEndpoints
java
quarkusio__quarkus
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/QuteProcessor.java
{ "start": 20506, "end": 25173 }
class ____ -parameters"); } bindings.put(name, getCheckedTemplateParameterTypeName(type)); parameterNames.add(name); } AnnotationValue requireTypeSafeExpressions = annotation.value(CHECKED_TEMPLATE_REQUIRE_TYPE_SAFE); ret.add(new CheckedTemplateBuildItem(templatePath, fragmentId, bindings, method, null, requireTypeSafeExpressions != null ? requireTypeSafeExpressions.asBoolean() : true)); enhancer.implement(method, templatePath, fragmentId, parameterNames, adaptor); } transformers.produce(new BytecodeTransformerBuildItem(targetClass.name().toString(), enhancer)); } // Find all Java records that implement TemplateInstance and interfaces adapted by CheckedTemplateAdapter List<DotName> recordInterfaceNames = new ArrayList<>(); recordInterfaceNames.add(Names.TEMPLATE_INSTANCE); adaptors.keySet().forEach(recordInterfaceNames::add); for (DotName recordInterfaceName : recordInterfaceNames) { ClassInfo recordInterface = index.getIndex().getClassByName(recordInterfaceName); if (recordInterface == null) { throw new IllegalStateException(recordInterfaceName + " not found in the index"); } Set<String> reservedNames = new HashSet<>(); for (MethodInfo method : recordInterface.methods()) { if (method.isSynthetic() || method.isBridge() || method.parametersCount() != 0) { continue; } reservedNames.add(method.name()); } for (ClassInfo recordClass : index.getIndex().getAllKnownImplementations(recordInterfaceName)) { if (!recordClass.isRecord()) { continue; } MethodInfo canonicalConstructor = recordClass.canonicalRecordConstructor(); AnnotationInstance checkedTemplateAnnotation = recordClass.declaredAnnotation(Names.CHECKED_TEMPLATE); String fragmentId = getCheckedFragmentId(recordClass, checkedTemplateAnnotation); String templatePath = getCheckedTemplatePath(index.getIndex(), checkedTemplateAnnotation, fragmentId, recordClass); String fullPath = templatePath + (fragmentId != null ? "$" + fragmentId : ""); AnnotationTarget checkedTemplate = checkedTemplates.putIfAbsent(fullPath, recordClass); if (checkedTemplate != null) { throw new TemplateException( String.format( "Multiple checked templates exist for the template path %s:\n\t- %s\n\t- %s", fullPath, recordClass.name(), checkedTemplate)); } if (!filePaths.contains(templatePath) && isNotLocatedByCustomTemplateLocator(locatorPatternsBuildItem.getLocationPatterns(), templatePath)) { List<String> startsWith = new ArrayList<>(); for (String filePath : filePaths.getFilePaths()) { if (filePath.startsWith(templatePath) && filePath.charAt(templatePath.length()) == '.') { startsWith.add(filePath); } } if (startsWith.isEmpty()) { throw new TemplateException( "No template matching the path " + templatePath + " could be found for: " + recordClass.name()); } else { throw new TemplateException( startsWith + " match the path " + templatePath + " but the file suffix is not configured via the quarkus.qute.suffixes property"); } } Map<String, String> bindings = new HashMap<>(); List<Type> parameters = canonicalConstructor.parameterTypes(); for (int i = 0; i < parameters.size(); i++) { Type type = parameters.get(i); String name = canonicalConstructor.parameterName(i); if (name == null) { throw new TemplateException("Parameter names not recorded for " + recordClass.name() + ": compile the
with
java
elastic__elasticsearch
x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/LocalStateSecurity.java
{ "start": 2550, "end": 4487 }
class ____ extends TransportXPackInfoAction { @Inject public SecurityTransportXPackInfoAction( TransportService transportService, ActionFilters actionFilters, LicenseService licenseService, NodeClient client ) { super(transportService, actionFilters, licenseService, client); } @Override protected List<ActionType<XPackInfoFeatureResponse>> infoActions() { return Collections.singletonList(XPackInfoFeatureAction.SECURITY); } } @SuppressWarnings("this-escape") public LocalStateSecurity(final Settings settings, final Path configPath) throws Exception { super(settings, configPath); LocalStateSecurity thisVar = this; plugins.add(new IndexLifecycle(settings) { @Override protected XPackLicenseState getLicenseState() { return thisVar.getLicenseState(); } }); plugins.add(new Monitoring(settings) { @Override protected SSLService getSslService() { return thisVar.getSslService(); } @Override protected LicenseService getLicenseService() { return thisVar.getLicenseService(); } @Override protected XPackLicenseState getLicenseState() { return thisVar.getLicenseState(); } }); } @Override protected Class<? extends TransportAction<XPackUsageRequest, XPackUsageResponse>> getUsageAction() { return SecurityTransportXPackUsageAction.class; } @Override protected Class<? extends TransportAction<XPackInfoRequest, XPackInfoResponse>> getInfoAction() { return SecurityTransportXPackInfoAction.class; } public List<Plugin> plugins() { return plugins; } }
SecurityTransportXPackInfoAction
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/OrderComparator.java
{ "start": 1023, "end": 1861 }
class ____ implements Comparator<Class<?>>, Serializable { private static final long serialVersionUID = 1L; private static final Comparator<Class<?>> INSTANCE = new OrderComparator(); /** * Returns a singleton instance of this class. * * @return the singleton for this class. */ public static Comparator<Class<?>> getInstance() { return INSTANCE; } @Override public int compare(final Class<?> lhs, final Class<?> rhs) { final Order lhsOrder = Objects.requireNonNull(lhs, "lhs").getAnnotation(Order.class); final Order rhsOrder = Objects.requireNonNull(rhs, "rhs").getAnnotation(Order.class); if (lhsOrder == null && rhsOrder == null) { // both unannotated means equal priority return 0; } // if only one
OrderComparator
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/runtime/configuration/CharsetConverter.java
{ "start": 461, "end": 1074 }
class ____ implements Converter<Charset>, Serializable { private static final long serialVersionUID = 2320905063828247874L; @Override public Charset convert(String value) { if (value == null) { return null; } String trimmedCharset = value.trim(); if (trimmedCharset.isEmpty()) { return null; } try { return Charset.forName(trimmedCharset); } catch (Exception e) { throw new IllegalArgumentException("Unable to create Charset from: '" + trimmedCharset + "'", e); } } }
CharsetConverter
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/recording/AnnotationProxyProvider.java
{ "start": 3654, "end": 3930 }
interface ____ { String getAnnotationLiteralType(); ClassInfo getAnnotationClass(); AnnotationInstance getAnnotationInstance(); Map<String, Object> getDefaultValues(); Map<String, Object> getValues(); } public
AnnotationProxy
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionUseOriginalMessageStreamTest.java
{ "start": 6089, "end": 6256 }
class ____ extends Exception { public MyDataFormatException(String message) { super(message); } } public static
MyDataFormatException
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/java/ZoneOffsetJavaType.java
{ "start": 653, "end": 2558 }
class ____ implements Comparator<ZoneOffset> { public static final ZoneOffsetComparator INSTANCE = new ZoneOffsetComparator(); public int compare(ZoneOffset o1, ZoneOffset o2) { return o1.getId().compareTo( o2.getId() ); } } public ZoneOffsetJavaType() { super( ZoneOffset.class, ImmutableMutabilityPlan.instance(), ZoneOffsetComparator.INSTANCE ); } @Override public boolean isInstance(Object value) { return value instanceof ZoneOffset; } @Override public boolean useObjectEqualsHashCode() { return true; } public String toString(ZoneOffset value) { return value.getId(); } public ZoneOffset fromString(CharSequence string) { return ZoneOffset.of( string.toString() ); } @Override public JdbcType getRecommendedJdbcType(JdbcTypeIndicators context) { return StringJavaType.INSTANCE.getRecommendedJdbcType( context ); } @Override @SuppressWarnings("unchecked") public <X> X unwrap(ZoneOffset value, Class<X> type, WrapperOptions wrapperOptions) { if ( value == null ) { return null; } if ( ZoneOffset.class.isAssignableFrom( type ) ) { return (X) value; } if ( String.class.isAssignableFrom( type ) ) { return (X) toString( value ); } if ( Integer.class.isAssignableFrom( type ) ) { return (X) Integer.valueOf( value.getTotalSeconds() ); } throw unknownUnwrap( type ); } @Override public <X> ZoneOffset wrap(X value, WrapperOptions wrapperOptions) { if ( value == null ) { return null; } if ( value instanceof ZoneOffset zoneOffset ) { return zoneOffset; } if ( value instanceof CharSequence charSequence ) { return fromString( charSequence ); } if ( value instanceof Integer integer ) { return ZoneOffset.ofTotalSeconds( integer ); } throw unknownWrap( value.getClass() ); } @Override public long getDefaultSqlLength(Dialect dialect, JdbcType jdbcType) { return 6; } }
ZoneOffsetComparator
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/CryptoComponentBuilderFactory.java
{ "start": 1972, "end": 15593 }
interface ____ extends ComponentBuilder<DigitalSignatureComponent> { /** * Sets the JCE name of the Algorithm that should be used for the * signer. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Default: SHA256withRSA * Group: producer * * @param algorithm the value to set * @return the dsl builder */ default CryptoComponentBuilder algorithm(java.lang.String algorithm) { doSetProperty("algorithm", algorithm); return this; } /** * Sets the alias used to query the KeyStore for keys and {link * java.security.cert.Certificate Certificates} to be used in signing * and verifying exchanges. This value can be provided at runtime via * the message header * org.apache.camel.component.crypto.DigitalSignatureConstants#KEYSTORE_ALIAS. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param alias the value to set * @return the dsl builder */ default CryptoComponentBuilder alias(java.lang.String alias) { doSetProperty("alias", alias); return this; } /** * Sets the reference name for a PrivateKey that can be found in the * registry. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param certificateName the value to set * @return the dsl builder */ default CryptoComponentBuilder certificateName(java.lang.String certificateName) { doSetProperty("certificateName", certificateName); return this; } /** * Sets the KeyStore that can contain keys and Certficates for use in * signing and verifying exchanges. A KeyStore is typically used with an * alias, either one supplied in the Route definition or dynamically via * the message header CamelSignatureKeyStoreAlias. If no alias is * supplied and there is only a single entry in the Keystore, then this * single entry will be used. * * The option is a: &lt;code&gt;java.security.KeyStore&lt;/code&gt; * type. * * Group: producer * * @param keystore the value to set * @return the dsl builder */ default CryptoComponentBuilder keystore(java.security.KeyStore keystore) { doSetProperty("keystore", keystore); return this; } /** * Sets the reference name for a Keystore that can be found in the * registry. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param keystoreName the value to set * @return the dsl builder */ default CryptoComponentBuilder keystoreName(java.lang.String keystoreName) { doSetProperty("keystoreName", keystoreName); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default CryptoComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Set the PrivateKey that should be used to sign the exchange. * * The option is a: &lt;code&gt;java.security.PrivateKey&lt;/code&gt; * type. * * Group: producer * * @param privateKey the value to set * @return the dsl builder */ default CryptoComponentBuilder privateKey(java.security.PrivateKey privateKey) { doSetProperty("privateKey", privateKey); return this; } /** * Sets the reference name for a PrivateKey that can be found in the * registry. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param privateKeyName the value to set * @return the dsl builder */ default CryptoComponentBuilder privateKeyName(java.lang.String privateKeyName) { doSetProperty("privateKeyName", privateKeyName); return this; } /** * Set the id of the security provider that provides the configured * Signature algorithm. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param provider the value to set * @return the dsl builder */ default CryptoComponentBuilder provider(java.lang.String provider) { doSetProperty("provider", provider); return this; } /** * references that should be resolved when the context changes. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param publicKeyName the value to set * @return the dsl builder */ default CryptoComponentBuilder publicKeyName(java.lang.String publicKeyName) { doSetProperty("publicKeyName", publicKeyName); return this; } /** * Sets the reference name for a SecureRandom that can be found in the * registry. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param secureRandomName the value to set * @return the dsl builder */ default CryptoComponentBuilder secureRandomName(java.lang.String secureRandomName) { doSetProperty("secureRandomName", secureRandomName); return this; } /** * Set the name of the message header that should be used to store the * base64 encoded signature. This defaults to 'CamelDigitalSignature'. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param signatureHeaderName the value to set * @return the dsl builder */ default CryptoComponentBuilder signatureHeaderName(java.lang.String signatureHeaderName) { doSetProperty("signatureHeaderName", signatureHeaderName); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default CryptoComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * Set the size of the buffer used to read in the Exchange payload data. * * The option is a: &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Default: 2048 * Group: advanced * * @param bufferSize the value to set * @return the dsl builder */ default CryptoComponentBuilder bufferSize(java.lang.Integer bufferSize) { doSetProperty("bufferSize", bufferSize); return this; } /** * Set the Certificate that should be used to verify the signature in * the exchange based on its payload. * * The option is a: * &lt;code&gt;java.security.cert.Certificate&lt;/code&gt; type. * * Group: advanced * * @param certificate the value to set * @return the dsl builder */ default CryptoComponentBuilder certificate(java.security.cert.Certificate certificate) { doSetProperty("certificate", certificate); return this; } /** * Determines if the Signature specific headers be cleared after signing * and verification. Defaults to true, and should only be made otherwise * at your extreme peril as vital private information such as Keys and * passwords may escape if unset. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param clearHeaders the value to set * @return the dsl builder */ default CryptoComponentBuilder clearHeaders(boolean clearHeaders) { doSetProperty("clearHeaders", clearHeaders); return this; } /** * To use the shared DigitalSignatureConfiguration as configuration. * * The option is a: * &lt;code&gt;org.apache.camel.component.crypto.DigitalSignatureConfiguration&lt;/code&gt; type. * * Group: advanced * * @param configuration the value to set * @return the dsl builder */ default CryptoComponentBuilder configuration(org.apache.camel.component.crypto.DigitalSignatureConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * Sets the KeyStore that can contain keys and Certficates for use in * signing and verifying exchanges based on the given * KeyStoreParameters. A KeyStore is typically used with an alias, * either one supplied in the Route definition or dynamically via the * message header CamelSignatureKeyStoreAlias. If no alias is supplied * and there is only a single entry in the Keystore, then this single * entry will be used. * * The option is a: * &lt;code&gt;org.apache.camel.support.jsse.KeyStoreParameters&lt;/code&gt; type. * * Group: advanced * * @param keyStoreParameters the value to set * @return the dsl builder */ default CryptoComponentBuilder keyStoreParameters(org.apache.camel.support.jsse.KeyStoreParameters keyStoreParameters) { doSetProperty("keyStoreParameters", keyStoreParameters); return this; } /** * Set the PublicKey that should be used to verify the signature in the * exchange. * * The option is a: &lt;code&gt;java.security.PublicKey&lt;/code&gt; * type. * * Group: advanced * * @param publicKey the value to set * @return the dsl builder */ default CryptoComponentBuilder publicKey(java.security.PublicKey publicKey) { doSetProperty("publicKey", publicKey); return this; } /** * Set the SecureRandom used to initialize the Signature service. * * The option is a: &lt;code&gt;java.security.SecureRandom&lt;/code&gt; * type. * * Group: advanced * * @param secureRandom the value to set * @return the dsl builder */ default CryptoComponentBuilder secureRandom(java.security.SecureRandom secureRandom) { doSetProperty("secureRandom", secureRandom); return this; } /** * Sets the password used to access an aliased PrivateKey in the * KeyStore. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param password the value to set * @return the dsl builder */ default CryptoComponentBuilder password(java.lang.String password) { doSetProperty("password", password); return this; } }
CryptoComponentBuilder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/StateProvince.java
{ "start": 316, "end": 1504 }
class ____ { private Long id; private String name; private String isoCode; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsoCode() { return isoCode; } public void setIsoCode(String isoCode) { this.isoCode = isoCode; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( !( o instanceof StateProvince ) ) { return false; } StateProvince that = ( StateProvince ) o; if ( isoCode != null ? !isoCode.equals( that.getIsoCode() ) : that.getIsoCode() != null ) { return false; } if ( name != null ? !name.equals( that.getName() ) : that.getName() != null ) { return false; } return true; } @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + ( isoCode != null ? isoCode.hashCode() : 0 ); return result; } @Override public String toString() { return "StateProvince{" + "id=" + id + ", name='" + name + '\'' + ", isoCode='" + isoCode + '\'' + '}'; } }
StateProvince
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/exceptionhandling/ExceptionExpectations.java
{ "start": 821, "end": 10480 }
interface ____ { static ExceptionExpectations jpa() { return new ExceptionExpectations() { @Override public void onConstraintViolationOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); } @Override public void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause(), instanceOf( SQLException.class ) ); } @Override public void onTransientObjectOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransientObjectException.class ) ); } @Override public void onTransientObjectOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( IllegalStateException.class ) ); assertThat( e.getCause(), instanceOf( TransientObjectException.class ) ); } @Override public void onInvalidQueryExecuted(RuntimeException e) { assertThat( e, instanceOf( IllegalArgumentException.class ) ); assertThat( e.getCause(), instanceOf( SyntaxException.class ) ); } @Override public void onUniqueResultWithMultipleResults(RuntimeException e) { assertThat( e, instanceOf( org.hibernate.NonUniqueResultException.class ) ); } @Override public void onGetSingleResultWithMultipleResults(RuntimeException e) { assertThat( e, instanceOf( jakarta.persistence.NonUniqueResultException.class ) ); } @Override public void onGetSingleResultWithNoResults(RuntimeException e) { assertThat( e, instanceOf( NoResultException.class ) ); } @Override public void onStaleObjectMergeAndUpdateFlush(RuntimeException e) { assertThat( e, instanceOf( OptimisticLockException.class ) ); assertThat( e.getCause(), instanceOf( StaleStateException.class ) ); } @Override public void onIdentifierGeneratorFailure(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e, instanceOf( IdentifierGenerationException.class ) ); } @Override public void onTransactionExceptionOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnCommit(RuntimeException e) { assertThat( e, instanceOf( RollbackException.class ) ); assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e.getCause(), instanceOf( TransactionException.class ) ); } @Override public void onExecuteUpdateWithConstraintViolation(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause(), instanceOf( SQLException.class ) ); } }; } static ExceptionExpectations nativePre52() { return new ExceptionExpectations() { @Override public void onConstraintViolationOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e, instanceOf( SQLException.class ) ); } @Override public void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e, instanceOf( SQLException.class ) ); } @Override public void onTransientObjectOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransientObjectException.class ) ); } @Override public void onTransientObjectOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( TransientObjectException.class ) ); } @Override public void onInvalidQueryExecuted(RuntimeException e) { assertThat( e, instanceOf( SemanticException.class ) ); } @Override public void onUniqueResultWithMultipleResults(RuntimeException e) { assertThat( e, instanceOf( org.hibernate.NonUniqueResultException.class ) ); } @Override public void onGetSingleResultWithMultipleResults(RuntimeException e) { assertThat( e, instanceOf( org.hibernate.NonUniqueResultException.class ) ); } @Override public void onGetSingleResultWithNoResults(RuntimeException e) { assertThat( e, instanceOf( NoResultException.class ) ); } @Override public void onStaleObjectMergeAndUpdateFlush(RuntimeException e) { assertThat( e, instanceOf( StaleStateException.class ) ); } @Override public void onIdentifierGeneratorFailure(RuntimeException e) { assertThat( e, instanceOf( IdentifierGenerationException.class ) ); } @Override public void onTransactionExceptionOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnCommit(RuntimeException e) { assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onExecuteUpdateWithConstraintViolation(RuntimeException e) { assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause(), instanceOf( SQLException.class ) ); } }; } static ExceptionExpectations nativePost52() { return new ExceptionExpectations() { @Override public void onConstraintViolationOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause(), instanceOf( SQLException.class ) ); } @Override public void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause(), instanceOf( SQLException.class ) ); } @Override public void onTransientObjectOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransientObjectException.class ) ); } @Override public void onTransientObjectOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( IllegalStateException.class ) ); assertThat( e.getCause(), instanceOf( TransientObjectException.class ) ); } @Override public void onInvalidQueryExecuted(RuntimeException e) { assertThat( e, instanceOf( IllegalArgumentException.class ) ); assertThat( e.getCause(), instanceOf( SyntaxException.class ) ); } @Override public void onUniqueResultWithMultipleResults(RuntimeException e) { assertThat( e, instanceOf( org.hibernate.NonUniqueResultException.class ) ); } @Override public void onGetSingleResultWithMultipleResults(RuntimeException e) { assertThat( e, instanceOf( jakarta.persistence.NonUniqueResultException.class ) ); } @Override public void onGetSingleResultWithNoResults(RuntimeException e) { assertThat( e, instanceOf( NoResultException.class ) ); } @Override public void onStaleObjectMergeAndUpdateFlush(RuntimeException e) { assertThat( e, instanceOf( OptimisticLockException.class ) ); assertThat( e.getCause(), instanceOf( StaleStateException.class ) ); } @Override public void onIdentifierGeneratorFailure(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e, instanceOf( IdentifierGenerationException.class ) ); } @Override public void onTransactionExceptionOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnCommit(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onExecuteUpdateWithConstraintViolation(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause(), instanceOf( SQLException.class ) ); } }; } void onConstraintViolationOnSaveAndSaveOrUpdate(RuntimeException e); void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e); void onTransientObjectOnSaveAndSaveOrUpdate(RuntimeException e); void onTransientObjectOnPersistAndMergeAndFlush(RuntimeException e); void onInvalidQueryExecuted(RuntimeException e); void onUniqueResultWithMultipleResults(RuntimeException e); void onGetSingleResultWithMultipleResults(RuntimeException e); void onGetSingleResultWithNoResults(RuntimeException e); void onStaleObjectMergeAndUpdateFlush(RuntimeException e); void onIdentifierGeneratorFailure(RuntimeException e); void onTransactionExceptionOnSaveAndSaveOrUpdate(RuntimeException e); void onTransactionExceptionOnPersistAndMergeAndFlush(RuntimeException e); void onTransactionExceptionOnCommit(RuntimeException e); void onExecuteUpdateWithConstraintViolation(RuntimeException e); }
ExceptionExpectations
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/serialization/Encoder.java
{ "start": 1244, "end": 1536 }
interface ____<IN> extends Serializable { /** * Writes one element to the bucket file. * * @param element the element to be written. * @param stream the stream to write the element to. */ void encode(IN element, OutputStream stream) throws IOException; }
Encoder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/event/collection/CollectionListeners.java
{ "start": 1465, "end": 1602 }
interface ____ extends Serializable { void addEvent(AbstractCollectionEvent event, Listener listener); } public static abstract
Listener
java
quarkusio__quarkus
extensions/scheduler/deployment/src/test/java/io/quarkus/scheduler/test/inheritance/ScheduledMethodNotInheritedTest.java
{ "start": 1016, "end": 1356 }
class ____ { static final CountDownLatch LATCH = new CountDownLatch(2); static final List<String> JOB_CLASSES = new CopyOnWriteArrayList<>(); @Scheduled(every = "1s", identity = "foo") void everySecond() { JOB_CLASSES.add(getClass().getName()); LATCH.countDown(); } } }
Jobs
java
alibaba__nacos
client/src/test/java/com/alibaba/nacos/client/naming/remote/AbstractNamingClientProxyTest.java
{ "start": 3867, "end": 6953 }
class ____ extends AbstractNamingClientProxy { protected MockNamingClientProxy(SecurityProxy securityProxy) { super(securityProxy); } @Override public void registerService(String serviceName, String groupName, Instance instance) throws NacosException { } @Override public void batchRegisterService(String serviceName, String groupName, List<Instance> instances) throws NacosException { } @Override public void batchDeregisterService(String serviceName, String groupName, List<Instance> instances) throws NacosException { } @Override public void deregisterService(String serviceName, String groupName, Instance instance) throws NacosException { } @Override public void updateInstance(String serviceName, String groupName, Instance instance) throws NacosException { } @Override public ServiceInfo queryInstancesOfService(String serviceName, String groupName, String clusters, boolean healthyOnly) throws NacosException { return null; } @Override public Service queryService(String serviceName, String groupName) throws NacosException { return null; } @Override public void createService(Service service, AbstractSelector selector) throws NacosException { } @Override public boolean deleteService(String serviceName, String groupName) throws NacosException { return false; } @Override public void updateService(Service service, AbstractSelector selector) throws NacosException { } @Override public ListView<String> getServiceList(int pageNo, int pageSize, String groupName, AbstractSelector selector) throws NacosException { return null; } @Override public ServiceInfo subscribe(String serviceName, String groupName, String clusters) throws NacosException { return null; } @Override public void unsubscribe(String serviceName, String groupName, String clusters) throws NacosException { } @Override public boolean isSubscribed(String serviceName, String groupName, String clusters) throws NacosException { return false; } @Override public boolean serverHealthy() { return false; } @Override public void shutdown() throws NacosException { } @Override public void onEvent(ServerListChangeEvent event) { } @Override public Class<? extends Event> subscribeType() { return null; } } }
MockNamingClientProxy
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedTestIntegrationTests.java
{ "start": 86107, "end": 86493 }
enum ____ implements Action { BAR } @ParameterizedTest(quoteTextArguments = false) @MethodSource("someArgumentsMethodSource") @MethodSource("otherArgumentsMethodSource") void testWithRepeatableMethodSource(String argument) { fail(argument); } @MethodSource("someArgumentsMethodSource") @MethodSource("otherArgumentsMethodSource") @Retention(RUNTIME) @
QuickAction
java
elastic__elasticsearch
modules/repository-s3/src/test/java/org/elasticsearch/repositories/s3/S3BlobContainerRetriesTests.java
{ "start": 65275, "end": 66676 }
class ____ extends S3HttpHandler { RejectsUploadPartRequests() { super("bucket"); } @Override public void handle(HttpExchange exchange) throws IOException { if (parseRequest(exchange).isUploadPartRequest()) { exchange.sendResponseHeaders(RestStatus.NOT_FOUND.getStatus(), -1); } else { super.handle(exchange); } } } httpServer.createContext("/", new RejectsUploadPartRequests()); safeAwait( l -> statefulBlobContainer.compareAndExchangeRegister( randomPurpose(), "not_found_register", BytesArray.EMPTY, new BytesArray(new byte[1]), l.map(result -> { assertFalse(result.isPresent()); return null; }) ) ); } public void testCompareAndExchangeWithConcurrentPutObject() throws Exception { final var blobContainerPath = BlobPath.EMPTY.add(getTestName()); final var statefulBlobContainer = createBlobContainer(1, null, null, null, null, null, blobContainerPath); final var objectContentsRequestedLatch = new CountDownLatch(1); @SuppressForbidden(reason = "use a http server")
RejectsUploadPartRequests
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/bug/Issue1994.java
{ "start": 499, "end": 4110 }
class ____ extends TestCase { public void test_for_issue() throws Exception { String sql = "INSERT INTO MKTG_H_EXEC_RESULT_FACT\n" + "(THE_DATE, AREA_ID, SCENE_ID, MKTG_CNT, MKTG_SUC_CNT\n" + ", TASK_CNT, TASK_F_CNT, TASK_F_SUC_CNT, CON_CNT, CON_SUC_CNT)\n" + "SELECT TRUNC(SYSDATE), T1.AREA_ID\n" + ", RTRIM(TO_CHAR(T2.PID))\n" + ", SUM(T1.MKTG_CNT), SUM(T1.MKTG_SUC_CNT)\n" + ", SUM(T1.TASK_CNT), SUM(T1.TASK_F_CNT)\n" + ", SUM(T1.TASK_F_SUC_CNT), SUM(T1.CON_CNT)\n" + ", SUM(T1.CON_SUC_CNT)\n" + "FROM MKTG_H_EXEC_RESULT_FACT T1, (\n" + "SELECT DISTINCT MKTG_PLAN_LVL1_ID AS PID, MKTG_PLAN_LVL4_ID AS SCENE_ID\n" + "FROM DMN_MKTG_PLAN_TYPE\n" + "UNION ALL\n" + "SELECT DISTINCT MKTG_PLAN_LVL2_ID AS PID, MKTG_PLAN_LVL4_ID AS SCENE_ID\n" + "FROM DMN_MKTG_PLAN_TYPE_TWO\n" + "WHERE MKTG_PLAN_LVL2_ID <> MKTG_PLAN_LVL4_ID\n" + "UNION ALL\n" + "SELECT DISTINCT MKTG_PLAN_LVL3_ID AS PID, MKTG_PLAN_LVL4_ID AS SCENE_ID\n" + "FROM DMN_MKTG_PLAN_TYPE\n" + "WHERE MKTG_PLAN_LVL3_ID <> MKTG_PLAN_LVL4_ID\n" + ") T2\n" + "WHERE T1.THE_DATE = TRUNC(SYSDATE)\n" + "AND T1.SCENE_ID = T2.SCENE_ID\n" + "GROUP BY T1.AREA_ID, RTRIM(TO_CHAR(T2.PID))"; List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE); assertEquals(1, stmtList.size()); SQLStatement stmt = stmtList.get(0); System.out.println(stmt); SchemaStatVisitor statVisitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ORACLE); stmt.accept(statVisitor); System.out.println("columns : " + statVisitor.getColumns()); assertTrue(statVisitor.containsColumn("MKTG_H_EXEC_RESULT_FACT", "THE_DATE")); assertTrue(statVisitor.containsColumn("MKTG_H_EXEC_RESULT_FACT", "AREA_ID")); assertTrue(statVisitor.containsColumn("MKTG_H_EXEC_RESULT_FACT", "SCENE_ID")); assertTrue(statVisitor.containsColumn("MKTG_H_EXEC_RESULT_FACT", "MKTG_CNT")); assertTrue(statVisitor.containsColumn("MKTG_H_EXEC_RESULT_FACT", "MKTG_SUC_CNT")); assertTrue(statVisitor.containsColumn("MKTG_H_EXEC_RESULT_FACT", "TASK_CNT")); assertTrue(statVisitor.containsColumn("MKTG_H_EXEC_RESULT_FACT", "TASK_F_CNT")); assertTrue(statVisitor.containsColumn("MKTG_H_EXEC_RESULT_FACT", "TASK_F_SUC_CNT")); assertTrue(statVisitor.containsColumn("MKTG_H_EXEC_RESULT_FACT", "CON_CNT")); assertTrue(statVisitor.containsColumn("MKTG_H_EXEC_RESULT_FACT", "CON_SUC_CNT")); assertTrue(statVisitor.containsColumn("DMN_MKTG_PLAN_TYPE", "MKTG_PLAN_LVL1_ID")); assertTrue(statVisitor.containsColumn("DMN_MKTG_PLAN_TYPE", "MKTG_PLAN_LVL4_ID")); assertTrue(statVisitor.containsColumn("DMN_MKTG_PLAN_TYPE_TWO", "MKTG_PLAN_LVL2_ID")); assertTrue(statVisitor.containsColumn("DMN_MKTG_PLAN_TYPE_TWO", "MKTG_PLAN_LVL4_ID")); assertTrue(statVisitor.containsColumn("DMN_MKTG_PLAN_TYPE", "MKTG_PLAN_LVL3_ID")); OracleInsertStatement insertStmt = (OracleInsertStatement) stmt; OracleSelectQueryBlock queryBlock = (OracleSelectQueryBlock) insertStmt.getQuery().getQueryBlock(); SQLSelectItem selectItem = queryBlock.getSelectList().get(0); assertEquals("TRUNC(SYSDATE)", selectItem.toString()); } }
Issue1994
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/JodaWithDurationAddedLongTest.java
{ "start": 4222, "end": 5400 }
class ____ { // BUG: Diagnostic contains: ZERO.withDurationAdded(Duration.millis(42), 2); private static final Duration A = ZERO.withDurationAdded(42, 2); private static final Duration B = // BUG: Diagnostic contains: ZERO.withDurationAdded(Duration.millis(42), 2); ZERO.withDurationAdded(Duration.millis(42).getMillis(), 2); // BUG: Diagnostic contains: ZERO.plus(Duration.millis(42)); private static final Duration PLUS = ZERO.withDurationAdded(42, 1); // BUG: Diagnostic contains: ZERO; private static final Duration ZEROX = ZERO.withDurationAdded(42, 0); // BUG: Diagnostic contains: ZERO.minus(Duration.millis(42)); private static final Duration MINUS = ZERO.withDurationAdded(42, -1); } """) .doTest(); } @Test public void durationWithDurationAddedLong_insideJodaTime() { helper .addSourceLines( "TestClass.java", """ package org.joda.time; import static org.joda.time.Duration.ZERO; public
TestClass
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/enhanced/SequenceIdTrackingModifiedEntitiesRevisionEntity.java
{ "start": 491, "end": 608 }
class ____ extends SequenceIdTrackingModifiedEntitiesRevisionMapping { }
SequenceIdTrackingModifiedEntitiesRevisionEntity
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/date/DateTest_tz.java
{ "start": 1379, "end": 1428 }
class ____ { public Date value; } }
Model
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/ExtensionRegistrationViaParametersAndFieldsTests.java
{ "start": 28845, "end": 29715 }
class ____<T extends Annotation> implements ParameterResolver { private final Class<T> annotationType; @SuppressWarnings("unchecked") BaseParameterExtension() { Type genericSuperclass = getClass().getGenericSuperclass(); this.annotationType = (Class<T>) ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0]; } @Override public final boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return parameterContext.isAnnotated(this.annotationType) && parameterContext.getParameter().getType() == String.class; } @Override public final Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return "enigma"; } } @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @ExtendWith(ConstructorParameter.Extension.class) @
BaseParameterExtension
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/exceptions/InvalidResourceRequestException.java
{ "start": 1296, "end": 2556 }
class ____ extends YarnException { public static final String LESS_THAN_ZERO_RESOURCE_MESSAGE_TEMPLATE = "Invalid resource request! Cannot allocate containers as " + "requested resource is less than 0! " + "Requested resource type=[%s], " + "Requested resource=%s"; public static final String GREATER_THAN_MAX_RESOURCE_MESSAGE_TEMPLATE = "Invalid resource request! Cannot allocate containers as " + "requested resource is greater than " + "maximum allowed allocation. " + "Requested resource type=[%s], " + "Requested resource=%s, maximum allowed allocation=%s, " + "please note that maximum allowed allocation is calculated " + "by scheduler based on maximum resource of registered " + "NodeManagers, which might be less than configured " + "maximum allocation=%s"; public static final String UNKNOWN_REASON_MESSAGE_TEMPLATE = "Invalid resource request! " + "Cannot allocate containers for an unknown reason! " + "Requested resource type=[%s], Requested resource=%s"; public
InvalidResourceRequestException
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/update/SqmUpdateStatement.java
{ "start": 1927, "end": 10683 }
class ____<T> extends AbstractSqmRestrictedDmlStatement<T> implements SqmDeleteOrUpdateStatement<T>, JpaCriteriaUpdate<T> { private boolean versioned; private SqmSetClause setClause = new SqmSetClause(); public SqmUpdateStatement(NodeBuilder nodeBuilder) { super( SqmQuerySource.HQL, nodeBuilder ); } /** * @deprecated was previously used for HQL. Use {@link SqmUpdateStatement#SqmUpdateStatement(NodeBuilder)} instead */ @Deprecated(forRemoval = true) public SqmUpdateStatement(SqmRoot<T> target, NodeBuilder nodeBuilder) { super( target, SqmQuerySource.HQL, nodeBuilder ); } /** * @deprecated was previously used for Criteria. Use {@link SqmUpdateStatement#SqmUpdateStatement(Class, SqmCriteriaNodeBuilder)} instead. */ @Deprecated(forRemoval = true) public SqmUpdateStatement(SqmRoot<T> target, SqmQuerySource querySource, NodeBuilder nodeBuilder) { super( target, querySource, nodeBuilder ); } public SqmUpdateStatement(Class<T> targetEntity, SqmCriteriaNodeBuilder nodeBuilder) { super( new SqmRoot<>( nodeBuilder.getDomainModel().entity( targetEntity ), "_0", !nodeBuilder.isJpaQueryComplianceEnabled(), nodeBuilder ), SqmQuerySource.CRITERIA, nodeBuilder ); } public SqmUpdateStatement( NodeBuilder builder, SqmQuerySource querySource, @Nullable Set<SqmParameter<?>> parameters, Map<String, SqmCteStatement<?>> cteStatements, SqmRoot<T> target) { this( builder, querySource, parameters, cteStatements, target, false ); } private SqmUpdateStatement( NodeBuilder builder, SqmQuerySource querySource, @Nullable Set<SqmParameter<?>> parameters, Map<String, SqmCteStatement<?>> cteStatements, SqmRoot<T> target, boolean versioned) { super( builder, querySource, parameters, cteStatements, target ); this.versioned = versioned; } @Override public SqmUpdateStatement<T> copy(SqmCopyContext context) { final SqmUpdateStatement<T> existing = context.getCopy( this ); if ( existing != null ) { return existing; } final var newQuerySource = context.getQuerySource(); final SqmUpdateStatement<T> statement = context.registerCopy( this, new SqmUpdateStatement<>( nodeBuilder(), newQuerySource == null ? getQuerySource() : newQuerySource, copyParameters( context ), copyCteStatements( context ), getTarget().copy( context ), versioned ) ); statement.setWhereClause( copyWhereClause( context ) ); statement.setClause = setClause.copy( context ); return statement; } @Override public void validate(@Nullable String hql) { verifyImmutableEntityUpdate( hql ); if ( getSetClause().getAssignments().isEmpty() ) { throw new IllegalArgumentException( "No assignments specified as part of UPDATE criteria" ); } verifyUpdateTypesMatch(); } private void verifyImmutableEntityUpdate(@Nullable String hql) { final EntityPersister persister = nodeBuilder().getMappingMetamodel().getEntityDescriptor( getTarget().getEntityName() ); if ( !persister.isMutable() ) { final String querySpaces = Arrays.toString( persister.getQuerySpaces() ); switch ( nodeBuilder().getImmutableEntityUpdateQueryHandlingMode() ) { case ALLOW : CORE_LOGGER.immutableEntityUpdateQueryAllowed( hql, querySpaces ); break; case WARNING: CORE_LOGGER.immutableEntityUpdateQuery( hql, querySpaces ); break; case EXCEPTION: throw new HibernateException( "The query attempts to update an immutable entity: " + querySpaces + " (set '" + AvailableSettings.IMMUTABLE_ENTITY_UPDATE_QUERY_HANDLING_MODE + "' to suppress)"); } } } private void verifyUpdateTypesMatch() { final List<SqmAssignment<?>> assignments = getSetClause().getAssignments(); for ( int i = 0; i < assignments.size(); i++ ) { final SqmAssignment<?> assignment = assignments.get( i ); final SqmPath<?> targetPath = assignment.getTargetPath(); final SqmExpression<?> expression = assignment.getValue(); assertAssignable( null, targetPath, expression, nodeBuilder() ); } } public SqmSetClause getSetClause() { return setClause; } public void setSetClause(SqmSetClause setClause) { this.setClause = setClause; } @Override public <Y, X extends Y> SqmUpdateStatement<T> set(SingularAttribute<? super T, Y> attribute, @Nullable X value) { final SqmCriteriaNodeBuilder nodeBuilder = (SqmCriteriaNodeBuilder) nodeBuilder(); SqmPath<Y> sqmAttribute = getTarget().get( attribute ); applyAssignment( sqmAttribute, nodeBuilder.value( value, sqmAttribute) ); return this; } @Override public <Y> SqmUpdateStatement<T> set(SingularAttribute<? super T, Y> attribute, Expression<? extends Y> value) { applyAssignment( getTarget().get( attribute ), (SqmExpression<? extends Y>) value ); return this; } @Override public <Y, X extends Y> SqmUpdateStatement<T> set(Path<Y> attribute, @Nullable X value) { final SqmCriteriaNodeBuilder nodeBuilder = (SqmCriteriaNodeBuilder) nodeBuilder(); final SqmPath<Y> sqmAttribute = (SqmPath<Y>) attribute; applyAssignment( sqmAttribute, nodeBuilder.value( value, sqmAttribute ) ); return this; } @Override public <Y> SqmUpdateStatement<T> set(Path<Y> attribute, Expression<? extends Y> value) { applyAssignment( (SqmPath<Y>) attribute, (SqmExpression<? extends Y>) value ); return this; } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public SqmUpdateStatement<T> set(String attributeName, @Nullable Object value) { final SqmPath sqmPath = getTarget().get( attributeName ); final SqmExpression expression; if ( value instanceof SqmExpression ) { expression = (SqmExpression) value; } else { final SqmCriteriaNodeBuilder nodeBuilder = (SqmCriteriaNodeBuilder) nodeBuilder(); expression = nodeBuilder.value( value, sqmPath ); } applyAssignment( sqmPath, expression ); return this; } @Override public boolean isVersioned() { return versioned; } @Override public SqmUpdateStatement<T> versioned() { this.versioned = true; return this; } @Override public SqmUpdateStatement<T> versioned(boolean versioned) { this.versioned = versioned; return this; } @Override public void setTarget(JpaRoot<T> root) { if ( root.getModel() instanceof SqmPolymorphicRootDescriptor<?> ) { throw new SemanticException( String.format( "Target type '%s' is not an entity", root.getModel().getHibernateEntityName() ) ); } super.setTarget( root ); } @Override public SqmUpdateStatement<T> where(@Nullable Expression<Boolean> restriction) { setWhere( restriction ); return this; } @Override public SqmUpdateStatement<T> where(Predicate @Nullable... restrictions) { setWhere( restrictions ); return this; } @Override public <X> X accept(SemanticQueryWalker<X> walker) { return walker.visitUpdateStatement( this ); } @Override public <U> SqmSubQuery<U> subquery(EntityType<U> type) { return new SqmSubQuery<>( this, type, nodeBuilder() ); } public <Y> void applyAssignment(SqmPath<Y> targetPath, SqmExpression<? extends Y> value) { applyAssignment( new SqmAssignment<>( targetPath, value ) ); } public <Y> void applyAssignment(SqmAssignment<Y> assignment) { setClause.addAssignment( assignment ); } @Override public void appendHqlString(StringBuilder hql, SqmRenderContext context) { appendHqlCteString( hql, context ); hql.append( "update " ); if ( versioned ) { hql.append( "versioned " ); } final SqmRoot<T> root = getTarget(); hql.append( root.getEntityName() ); hql.append( ' ' ).append( root.resolveAlias( context ) ); SqmFromClause.appendJoins( root, hql, context ); SqmFromClause.appendTreatJoins( root, hql, context ); setClause.appendHqlString( hql, context ); super.appendHqlString( hql, context ); } @Override public boolean equals(@Nullable Object object) { return object instanceof SqmUpdateStatement<?> that && super.equals( that ) && this.versioned == that.versioned && setClause.equals( that.setClause ); } @Override public int hashCode() { int result = getTarget().hashCode(); result = 31 * result + Boolean.hashCode( versioned ); result = 31 * result + setClause.hashCode(); return result; } @Override public boolean isCompatible(Object object) { return object instanceof SqmUpdateStatement<?> that && super.isCompatible( that ) && this.versioned == that.versioned && setClause.isCompatible( that.setClause ); } @Override public int cacheHashCode() { int result = getTarget().cacheHashCode(); result = 31 * result + Boolean.hashCode( versioned ); result = 31 * result + setClause.cacheHashCode(); return result; } }
SqmUpdateStatement
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/TempSchedulerNode.java
{ "start": 1528, "end": 3919 }
class ____ { private List<RMContainer> runningContainers; private RMContainer reservedContainer; private Resource totalResource; // excluded reserved resource private Resource allocatedResource; // total - allocated private Resource availableResource; // just a shortcut of reservedContainer.getResource. private Resource reservedResource; private NodeId nodeId; public static TempSchedulerNode fromSchedulerNode( FiCaSchedulerNode schedulerNode) { TempSchedulerNode n = new TempSchedulerNode(); n.totalResource = Resources.clone(schedulerNode.getTotalResource()); n.allocatedResource = Resources.clone(schedulerNode.getAllocatedResource()); n.runningContainers = schedulerNode.getCopiedListOfRunningContainers(); n.reservedContainer = schedulerNode.getReservedContainer(); if (n.reservedContainer != null) { n.reservedResource = n.reservedContainer.getReservedResource(); } else { n.reservedResource = Resources.none(); } n.availableResource = Resources.subtract(n.totalResource, n.allocatedResource); n.nodeId = schedulerNode.getNodeID(); return n; } public NodeId getNodeId() { return nodeId; } public List<RMContainer> getRunningContainers() { return runningContainers; } public void setRunningContainers(List<RMContainer> runningContainers) { this.runningContainers = runningContainers; } public RMContainer getReservedContainer() { return reservedContainer; } public void setReservedContainer(RMContainer reservedContainer) { this.reservedContainer = reservedContainer; } public Resource getTotalResource() { return totalResource; } public void setTotalResource(Resource totalResource) { this.totalResource = totalResource; } public Resource getAllocatedResource() { return allocatedResource; } public void setAllocatedResource(Resource allocatedResource) { this.allocatedResource = allocatedResource; } public Resource getAvailableResource() { return availableResource; } public void setAvailableResource(Resource availableResource) { this.availableResource = availableResource; } public Resource getReservedResource() { return reservedResource; } public void setReservedResource(Resource reservedResource) { this.reservedResource = reservedResource; } }
TempSchedulerNode
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/rules/logical/DeduplicateAggs.java
{ "start": 571, "end": 745 }
class ____ extends ReplaceAggregateAggExpressionWithEval implements OptimizerRules.CoordinatorOnly { public DeduplicateAggs() { super(false); } }
DeduplicateAggs
java
elastic__elasticsearch
x-pack/plugin/rank-vectors/src/main/java/org/elasticsearch/xpack/rank/vectors/mapper/RankVectorsFieldMapper.java
{ "start": 7887, "end": 17750 }
class ____ extends SimpleMappedFieldType { private final Element element; private final Integer dims; private final XPackLicenseState licenseState; public RankVectorsFieldType( String name, ElementType elementType, Integer dims, XPackLicenseState licenseState, Map<String, String> meta ) { super(name, IndexType.docValuesOnly(), false, meta); this.element = Element.getElement(elementType); this.dims = dims; this.licenseState = licenseState; } @Override public String typeName() { return CONTENT_TYPE; } @Override public boolean isSearchable() { return false; } @Override public boolean isVectorEmbedding() { return true; } @Override public ValueFetcher valueFetcher(SearchExecutionContext context, String format) { if (format != null) { throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName() + "] doesn't support formats."); } return new ArraySourceValueFetcher(name(), context) { @Override protected Object parseSourceValue(Object value) { List<?> outerList = (List<?>) value; List<Object> vectors = new ArrayList<>(outerList.size()); for (Object o : outerList) { if (o instanceof List<?> innerList) { float[] vector = new float[innerList.size()]; for (int i = 0; i < vector.length; i++) { vector[i] = ((Number) innerList.get(i)).floatValue(); } vectors.add(vector); } else { vectors.add(o); } } return vectors; } }; } @Override public DocValueFormat docValueFormat(String format, ZoneId timeZone) { return DocValueFormat.DENSE_VECTOR; } @Override public boolean isAggregatable() { return false; } @Override public IndexFieldData.Builder fielddataBuilder(FieldDataContext fieldDataContext) { if (RANK_VECTORS_FEATURE.check(licenseState) == false) { throw LicenseUtils.newComplianceException("Rank Vectors"); } return new RankVectorsIndexFieldData.Builder(name(), CoreValuesSourceType.KEYWORD, dims, element.elementType()); } @Override public Query existsQuery(SearchExecutionContext context) { return new FieldExistsQuery(name()); } @Override public Query termQuery(Object value, SearchExecutionContext context) { throw new IllegalArgumentException("Field [" + name() + "] of type [" + typeName() + "] doesn't support term queries"); } int getVectorDimensions() { return dims; } DenseVectorFieldMapper.ElementType getElementType() { return element.elementType(); } } private final IndexVersion indexCreatedVersion; private final XPackLicenseState licenseState; private final boolean isExcludeSourceVectors; private RankVectorsFieldMapper( String simpleName, MappedFieldType fieldType, BuilderParams params, IndexVersion indexCreatedVersion, XPackLicenseState licenseState, boolean isExcludeSourceVectors ) { super(simpleName, fieldType, params); this.indexCreatedVersion = indexCreatedVersion; this.licenseState = licenseState; this.isExcludeSourceVectors = isExcludeSourceVectors; } @Override public RankVectorsFieldType fieldType() { return (RankVectorsFieldType) super.fieldType(); } @Override public boolean parsesArrayValue() { return true; } @Override public void parse(DocumentParserContext context) throws IOException { if (RANK_VECTORS_FEATURE.check(licenseState) == false) { throw LicenseUtils.newComplianceException("Rank Vectors"); } if (context.doc().getByKey(fieldType().name()) != null) { throw new IllegalArgumentException( "Field [" + fullPath() + "] of type [" + typeName() + "] doesn't support indexing multiple values for the same field in the same document" ); } if (XContentParser.Token.VALUE_NULL == context.parser().currentToken()) { return; } if (XContentParser.Token.START_ARRAY != context.parser().currentToken()) { throw new IllegalArgumentException( "Field [" + fullPath() + "] of type [" + typeName() + "] cannot be indexed with a single value" ); } if (fieldType().dims == null) { int currentDims = -1; while (XContentParser.Token.END_ARRAY != context.parser().nextToken()) { int dims = fieldType().element.parseDimensionCount(context); if (currentDims == -1) { currentDims = dims; } else if (currentDims != dims) { throw new IllegalArgumentException( "Field [" + fullPath() + "] of type [" + typeName() + "] cannot be indexed with vectors of different dimensions" ); } } var builder = (Builder) getMergeBuilder(); builder.dimensions(currentDims); Mapper update = builder.build(context.createDynamicMapperBuilderContext()); context.addDynamicMapper(update); return; } int dims = fieldType().dims; Element element = fieldType().element; List<VectorData> vectors = new ArrayList<>(); while (XContentParser.Token.END_ARRAY != context.parser().nextToken()) { VectorData vector = element.parseKnnVector(context, dims, (i, b) -> { if (b) { checkDimensionMatches(i, context); } else { checkDimensionExceeded(i, context); } }, null); vectors.add(vector); } int bufferSize = element.getNumBytes(dims) * vectors.size(); ByteBuffer buffer = ByteBuffer.allocate(bufferSize).order(ByteOrder.LITTLE_ENDIAN); ByteBuffer magnitudeBuffer = ByteBuffer.allocate(vectors.size() * Float.BYTES).order(ByteOrder.LITTLE_ENDIAN); for (VectorData vector : vectors) { vector.addToBuffer(element, buffer); magnitudeBuffer.putFloat((float) Math.sqrt(element.computeSquaredMagnitude(vector))); } String vectorFieldName = fieldType().name(); String vectorMagnitudeFieldName = vectorFieldName + VECTOR_MAGNITUDES_SUFFIX; context.doc().addWithKey(vectorFieldName, new BinaryDocValuesField(vectorFieldName, new BytesRef(buffer.array()))); context.doc() .addWithKey( vectorMagnitudeFieldName, new BinaryDocValuesField(vectorMagnitudeFieldName, new BytesRef(magnitudeBuffer.array())) ); } private void checkDimensionExceeded(int index, DocumentParserContext context) { if (index >= fieldType().dims) { throw new IllegalArgumentException( "The [" + typeName() + "] field [" + fullPath() + "] in doc [" + context.documentDescription() + "] has more dimensions " + "than defined in the mapping [" + fieldType().dims + "]" ); } } private void checkDimensionMatches(int index, DocumentParserContext context) { if (index != fieldType().dims) { throw new IllegalArgumentException( "The [" + typeName() + "] field [" + fullPath() + "] in doc [" + context.documentDescription() + "] has a different number of dimensions " + "[" + index + "] than defined in the mapping [" + fieldType().dims + "]" ); } } @Override protected void parseCreateField(DocumentParserContext context) { throw new AssertionError("parse is implemented directly"); } @Override protected String contentType() { return CONTENT_TYPE; } @Override public FieldMapper.Builder getMergeBuilder() { return new Builder(leafName(), indexCreatedVersion, licenseState, isExcludeSourceVectors).init(this); } @Override protected SyntheticSourceSupport syntheticSourceSupport() { return new SyntheticSourceSupport.Native(DocValuesSyntheticFieldLoader::new); } @Override public SourceLoader.SyntheticVectorsLoader syntheticVectorsLoader() { if (isExcludeSourceVectors) { return new SyntheticVectorsPatchFieldLoader<>( // Recreate the object for each leaf so that different segments can be searched concurrently. DocValuesSyntheticFieldLoader::new, DocValuesSyntheticFieldLoader::copyVectorsAsList ); } return null; } private
RankVectorsFieldType
java
quarkusio__quarkus
extensions/hibernate-search-orm-elasticsearch/runtime/src/main/java/io/quarkus/hibernate/search/orm/elasticsearch/runtime/HibernateSearchElasticsearchBuildTimeConfigManagement.java
{ "start": 175, "end": 511 }
interface ____ { /** * Root path for reindexing endpoints. * This value will be resolved as a path relative to `${quarkus.management.root-path}`. * * @asciidoclet */ @WithDefault("hibernate-search/") String rootPath(); /** * If management
HibernateSearchElasticsearchBuildTimeConfigManagement
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/AbstractSecurityBuilder.java
{ "start": 935, "end": 1826 }
class ____<O> implements SecurityBuilder<O> { private AtomicBoolean building = new AtomicBoolean(); private O object; @Override public final O build() { if (this.building.compareAndSet(false, true)) { this.object = doBuild(); return this.object; } throw new AlreadyBuiltException("This object has already been built"); } /** * Gets the object that was built. If it has not been built yet an Exception is * thrown. * @return the Object that was built */ public final O getObject() { if (!this.building.get()) { throw new IllegalStateException("This object has not been built"); } return this.object; } /** * Subclasses should implement this to perform the build. * @return the object that should be returned by {@link SecurityBuilder#build()}. * @throws Exception if an error occurs */ protected abstract O doBuild(); }
AbstractSecurityBuilder
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/PendingReconstructionBlocks.java
{ "start": 7794, "end": 10527 }
class ____ implements Runnable { @Override public void run() { while (fsRunning) { long period = Math.min(DEFAULT_RECHECK_INTERVAL, timeout); try { pendingReconstructionCheck(); Thread.sleep(period); } catch (InterruptedException ie) { LOG.debug("PendingReconstructionMonitor thread is interrupted.", ie); } } } /** * Iterate through all items and detect timed-out items */ void pendingReconstructionCheck() { synchronized (pendingReconstructions) { Iterator<Map.Entry<BlockInfo, PendingBlockInfo>> iter = pendingReconstructions.entrySet().iterator(); long now = monotonicNow(); LOG.debug("PendingReconstructionMonitor checking Q"); while (iter.hasNext()) { Map.Entry<BlockInfo, PendingBlockInfo> entry = iter.next(); PendingBlockInfo pendingBlock = entry.getValue(); if (now > pendingBlock.getTimeStamp() + timeout) { BlockInfo block = entry.getKey(); synchronized (timedOutItems) { timedOutItems.add(block); } LOG.warn("PendingReconstructionMonitor timed out " + block); NameNode.getNameNodeMetrics().incTimeoutReReplications(); iter.remove(); } } } } } /** * @return timer thread. */ @VisibleForTesting public Daemon getTimerThread() { return timerThread; } /* * Shuts down the pending reconstruction monitor thread. * Waits for the thread to exit. */ void stop() { fsRunning = false; if(timerThread == null) return; timerThread.interrupt(); try { timerThread.join(3000); } catch (InterruptedException ie) { } } /** * Iterate through all items and print them. */ void metaSave(PrintWriter out) { synchronized (pendingReconstructions) { out.println("Metasave: Blocks being reconstructed: " + pendingReconstructions.size()); for (Map.Entry<BlockInfo, PendingBlockInfo> entry : pendingReconstructions.entrySet()) { PendingBlockInfo pendingBlock = entry.getValue(); Block block = entry.getKey(); out.println(block + " StartTime: " + new Time(pendingBlock.timeStamp) + " NumReconstructInProgress: " + pendingBlock.getNumReplicas()); } } } List<DatanodeStorageInfo> getTargets(BlockInfo block) { synchronized (pendingReconstructions) { PendingBlockInfo found = pendingReconstructions.get(block); if (found != null) { return new ArrayList<>(found.targets); } } return null; } }
PendingReconstructionMonitor
java
apache__flink
flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/SubEvent.java
{ "start": 900, "end": 1864 }
class ____ extends Event { private final double volume; public SubEvent(int id, String name, double price, double volume) { super(id, name, price); this.volume = volume; } public double getVolume() { return volume; } @Override public boolean equals(Object obj) { return obj instanceof SubEvent && super.equals(obj) && ((SubEvent) obj).volume == volume; } @Override public int hashCode() { return super.hashCode() + (int) volume; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("SubEvent(") .append(getId()) .append(", ") .append(getName()) .append(", ") .append(getPrice()) .append(", ") .append(getVolume()) .append(")"); return builder.toString(); } }
SubEvent
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointCustomRoutePolicyTest.java
{ "start": 1670, "end": 4252 }
class ____ extends RoutePolicySupport { private final LongAdder invoked = new LongAdder(); private final AtomicBoolean stopped = new AtomicBoolean(); @Override public void onExchangeDone(Route route, Exchange exchange) { invoked.increment(); if (invoked.intValue() >= 2) { try { stopped.set(true); stopConsumer(route.getConsumer()); } catch (Exception e) { handleException(e); } } } @Override public boolean isStopped() { return stopped.get(); } } @Test public void testAsyncEndpoint() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedBodiesReceived("Bye Camel"); getMockEndpoint("mock:before").expectedBodiesReceived("Hello Camel"); getMockEndpoint("mock:after").expectedBodiesReceived("Bye Camel"); String reply = template.requestBody("direct:start", "Hello Camel", String.class); assertEquals("Bye Camel", reply); assertMockEndpointsSatisfied(); assertFalse(beforeThreadName.equalsIgnoreCase(afterThreadName), "Should use different threads"); mock.reset(); mock.expectedMessageCount(1); // we send a 2nd message which should cause it to stop template.sendBody("direct:start", "stop"); mock.assertIsSatisfied(); await().atMost(1, TimeUnit.SECONDS).untilAsserted(() -> assertTrue(policy.isStopped(), "Should be stopped")); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { context.addComponent("async", new MyAsyncComponent()); from("direct:start").routeId("foo").routePolicy(policy).to("mock:before").to("log:before") .process(new Processor() { public void process(Exchange exchange) { beforeThreadName = Thread.currentThread().getName(); } }).to("async:bye:camel").process(new Processor() { public void process(Exchange exchange) { afterThreadName = Thread.currentThread().getName(); } }).to("log:after").to("mock:after").to("mock:result"); } }; } }
MyCustomRoutePolicy
java
apache__camel
tooling/maven/camel-package-maven-plugin/src/main/java/org/apache/camel/maven/packaging/GenerateEndpointUriFactoryMojo.java
{ "start": 1931, "end": 2220 }
class ____ endpoint uri factory generator. */ @Mojo(name = "generate-endpoint-uri-factory", threadSafe = true, defaultPhase = LifecyclePhase.PROCESS_CLASSES, requiresDependencyCollection = ResolutionScope.COMPILE, requiresDependencyResolution = ResolutionScope.COMPILE) public
for
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/EffectivelyPrivateTest.java
{ "start": 1115, "end": 1435 }
class ____ { void f() { var r = new Runnable() { // BUG: Diagnostic contains: public void foo() {} @Override public void run() {} }; }
T
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/inject/guice/AssistedInjectScoping.java
{ "start": 2334, "end": 2887 }
class ____ assisted: * a) If there is a constructor that is annotated with @Inject and that constructor has at least one * parameter that is annotated with @Assisted. b) If there is no @Inject constructor and at least * one constructor is annotated with {@code @AssistedInject}. 2) There is an annotation on the * class, and the annotation is itself annotated with {@code @ScopeAnnotation}. * * @author eaftan@google.com (Eddie Aftandilian) */ @BugPattern( name = "GuiceAssistedInjectScoping", summary = "Scope annotation on implementation
is
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/tck/UnicastProcessorAsPublisherTckTest.java
{ "start": 837, "end": 1863 }
class ____ extends BaseTck<Integer> { public UnicastProcessorAsPublisherTckTest() { super(100); } @Override public Publisher<Integer> createPublisher(final long elements) { final UnicastProcessor<Integer> pp = UnicastProcessor.create(); Schedulers.io().scheduleDirect(new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); while (!pp.hasSubscribers()) { try { Thread.sleep(1); } catch (InterruptedException ex) { return; } if (System.currentTimeMillis() - start > 200) { return; } } for (int i = 0; i < elements; i++) { pp.onNext(i); } pp.onComplete(); } }); return pp; } }
UnicastProcessorAsPublisherTckTest
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/TestInstance.java
{ "start": 2892, "end": 3179 }
class ____ test method is annotated with * {@link Execution @Execution(CONCURRENT)}. * * @since 5.0 * @see Nested @Nested * @see Execution @Execution */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @API(status = STABLE, since = "5.0") public @
or
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/root/ApplicationPathTest.java
{ "start": 378, "end": 847 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(HelloResource.class, HelloApp.class)); @Test public void testResources() { RestAssured.when().get("/hello/world").then().body(Matchers.is("hello world")); RestAssured.when().get("/world").then().statusCode(404); } @Path("world") public static
ApplicationPathTest
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/deployment/src/main/java/io/quarkus/restclient/deployment/RestClientAnnotationProviderBuildItem.java
{ "start": 224, "end": 951 }
class ____ extends MultiBuildItem { private final DotName annotationName; private final Class<?> providerClass; public RestClientAnnotationProviderBuildItem(DotName annotationName, Class<?> providerClass) { this.annotationName = annotationName; this.providerClass = providerClass; } public RestClientAnnotationProviderBuildItem(String annotationName, Class<?> providerClass) { this.annotationName = DotName.createSimple(annotationName); this.providerClass = providerClass; } public DotName getAnnotationName() { return annotationName; } public Class<?> getProviderClass() { return providerClass; } }
RestClientAnnotationProviderBuildItem
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/visitor/MySqlSchemaStatVisitorTest4.java
{ "start": 973, "end": 1998 }
class ____ extends TestCase { public void test_0() throws Exception { String sql = "insert into users (id, name) values(?, ?)"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); statemen.accept(visitor); System.out.println(sql); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(true, visitor.containsTable("users")); assertEquals(2, visitor.getColumns().size()); assertEquals(true, visitor.getColumns().contains(new Column("users", "id"))); assertEquals(true, visitor.getColumns().contains(new Column("users", "name"))); } }
MySqlSchemaStatVisitorTest4
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java
{ "start": 33509, "end": 36250 }
interface ____.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt")); assertThat( expected.getMessage(), containsString( "cause: Duplicate extension org.apache.dubbo.common.extension.duplicated.DuplicatedWithoutOverriddenExt name duplicated")); } finally { // recover the loading strategies ExtensionLoader.setLoadingStrategies( loadingStrategies.toArray(new LoadingStrategy[loadingStrategies.size()])); } } @Test void testDuplicatedImplWithOverriddenStrategy() { List<LoadingStrategy> loadingStrategies = ExtensionLoader.getLoadingStrategies(); ExtensionLoader.setLoadingStrategies( new DubboExternalLoadingStrategyTest(true), new DubboInternalLoadingStrategyTest(true)); ExtensionLoader<DuplicatedOverriddenExt> extensionLoader = getExtensionLoader(DuplicatedOverriddenExt.class); DuplicatedOverriddenExt duplicatedOverriddenExt = extensionLoader.getExtension("duplicated"); assertEquals("DuplicatedOverriddenExt1", duplicatedOverriddenExt.echo()); // recover the loading strategies ExtensionLoader.setLoadingStrategies(loadingStrategies.toArray(new LoadingStrategy[loadingStrategies.size()])); } @Test void testLoadByDubboInternalSPI() { ExtensionLoader<SPI1> extensionLoader = getExtensionLoader(SPI1.class); SPI1 spi1 = extensionLoader.getExtension("1", true); assertNotNull(spi1); ExtensionLoader<SPI2> extensionLoader2 = getExtensionLoader(SPI2.class); SPI2 spi2 = extensionLoader2.getExtension("2", true); assertNotNull(spi2); try { ExtensionLoader<SPI3> extensionLoader3 = getExtensionLoader(SPI3.class); SPI3 spi3 = extensionLoader3.getExtension("3", true); assertNotNull(spi3); } catch (IllegalStateException illegalStateException) { if (!illegalStateException.getMessage().contains("No such extension")) { fail(); } } ExtensionLoader<SPI4> extensionLoader4 = getExtensionLoader(SPI4.class); SPI4 spi4 = extensionLoader4.getExtension("4", true); assertNotNull(spi4); } @Test void isWrapperClass() { assertFalse(getExtensionLoader(Demo.class).isWrapperClass(DemoImpl.class)); assertTrue(getExtensionLoader(Demo.class).isWrapperClass(DemoWrapper.class)); assertTrue(getExtensionLoader(Demo.class).isWrapperClass(DemoWrapper2.class)); } /** * The external {@link LoadingStrategy}, which can set if it supports overriding. */ private static
org
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/a/A20170327_0.java
{ "start": 1721, "end": 2837 }
class ____ implements ObjectDeserializer { @SuppressWarnings("unchecked") public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { ParseContext cxt = parser.getContext(); Object object = parser.parse(fieldName); if (object == null) { return null; } String moneyCentStr = null; if (object instanceof JSONObject) {//历史数据兼容 JSONObject jsonObject = (JSONObject) object; moneyCentStr = jsonObject.getString("cent"); } else if (object instanceof String) { moneyCentStr = (String) object; } else { throw new RuntimeException("money属性反序列化失败,不支持的类型:" + object.getClass().getName()); } if (moneyCentStr.length() != 0) { Money m = new Money(); m.cent = Long.valueOf(moneyCentStr); return (T) m; } return null; } public int getFastMatchToken() { return 0; } } }
MoneyDeserialize
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inject/AssistedInjectAndInjectOnConstructorsTest.java
{ "start": 3012, "end": 3140 }
class ____ { /** Class has a single constructor with no annotation. */ public
AssistedInjectAndInjectOnConstructorsNegativeCases
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/util/ReflectionUtil.java
{ "start": 363, "end": 3806 }
class ____ { /** * Get a field from a given class * * @param clazz clazz * @param name field name * * @return field object */ public static Field getField(Class clazz, String name) { try { Field field = clazz.getDeclaredField( name ); field.setAccessible( true ); return field; } catch (NoSuchFieldException e) { Class superClass = clazz.getSuperclass(); if ( !clazz.equals( superClass ) ) { return getField( superClass, name ); } throw new IllegalArgumentException( "Class " + clazz + " does not contain a " + name + " field", e ); } } /** * Get a field value from a given object * * @param target Object whose field is being read * @param name field name * * @return field object */ public static <T> T getFieldValue(Object target, String name) { try { Field field = target.getClass().getDeclaredField( name ); field.setAccessible( true ); return (T) field.get( target ); } catch (NoSuchFieldException e) { throw new IllegalArgumentException( "Class " + target.getClass() + " does not contain a " + name + " field", e ); } catch (IllegalAccessException e) { throw new IllegalArgumentException( "Cannot set field " + name, e ); } } /** * Set target Object field to a certain value * * @param target Object whose field is being set * @param field Object field to set * @param value the new value for the given field */ public static void setField(Object target, Field field, Object value) { try { field.set( target, value ); } catch (IllegalAccessException e) { throw new IllegalArgumentException( "Field " + field + " could not be set", e ); } } /** * Set target Object field to a certain value * * @param target Object whose field is being set * @param fieldName Object field naem to set * @param value the new value for the given field */ public static void setField(Object target, String fieldName, Object value) { try { Field field = getField( target.getClass(), fieldName ); field.set( target, value ); } catch (IllegalAccessException e) { throw new IllegalArgumentException( "Field " + fieldName + " could not be set", e ); } } /** * Set target Class field to a certain value * * @param target Class whose field is being set * @param fieldName Class field name to set * @param value the new value for the given field */ public static void setStaticField(Class<?> target, String fieldName, Object value) { try { Field field = getField( target, fieldName ); field.set( null, value ); } catch (IllegalAccessException e) { throw new IllegalArgumentException( "Field " + fieldName + " could not be set", e ); } } /** * New target Object instance using the given arguments * * @param constructorSupplier constructor supplier * @param args Constructor arguments * * @return new Object instance */ public static <T> T newInstance(Supplier<Constructor<T>> constructorSupplier, Object... args) { try { Constructor constructor = constructorSupplier.get(); constructor.setAccessible( true ); return (T) constructor.newInstance( args ); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new IllegalArgumentException( "Constructor could not be called", e ); } } /** * New target Object instance using the given Class name * * @param className
ReflectionUtil
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/jdk8/OffseTimeTest.java
{ "start": 168, "end": 564 }
class ____ extends TestCase { public void test_for_issue() throws Exception { VO vo = new VO(); vo.setDate(OffsetTime.now()); String text = JSON.toJSONString(vo); System.out.println(text); VO vo1 = JSON.parseObject(text, VO.class); Assert.assertEquals(vo.getDate(), vo1.getDate()); } public static
OffseTimeTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/plan/physical/EnrichExecSerializationTests.java
{ "start": 683, "end": 3737 }
class ____ extends AbstractPhysicalPlanSerializationTests<EnrichExec> { public static EnrichExec randomEnrichExec(int depth) { Source source = randomSource(); PhysicalPlan child = randomChild(depth); Enrich.Mode mode = randomFrom(Enrich.Mode.values()); String matchType = randomAlphaOfLength(3); NamedExpression matchField = FieldAttributeTests.createFieldAttribute(0, false); String policyName = randomAlphaOfLength(4); String policyMatchField = randomAlphaOfLength(5); Map<String, String> concreteIndices = randomMap(1, 4, () -> Tuple.tuple(randomAlphaOfLength(3), randomAlphaOfLength(5))); List<NamedExpression> enrichFields = randomFieldAttributes(1, 4, false).stream().map(f -> (NamedExpression) f).toList(); return new EnrichExec(source, child, mode, matchType, matchField, policyName, policyMatchField, concreteIndices, enrichFields); } @Override protected EnrichExec createTestInstance() { return randomEnrichExec(0); } @Override protected EnrichExec mutateInstance(EnrichExec instance) throws IOException { PhysicalPlan child = instance.child(); Enrich.Mode mode = instance.mode(); String matchType = instance.matchType(); NamedExpression matchField = instance.matchField(); String policyName = instance.policyName(); String policyMatchField = instance.policyMatchField(); Map<String, String> concreteIndices = instance.concreteIndices(); List<NamedExpression> enrichFields = instance.enrichFields(); switch (between(0, 7)) { case 0 -> child = randomValueOtherThan(child, () -> randomChild(0)); case 1 -> mode = randomValueOtherThan(mode, () -> randomFrom(Enrich.Mode.values())); case 2 -> matchType = randomValueOtherThan(matchType, () -> randomAlphaOfLength(3)); case 3 -> matchField = randomValueOtherThan(matchField, () -> FieldAttributeTests.createFieldAttribute(0, false)); case 4 -> policyName = randomValueOtherThan(policyName, () -> randomAlphaOfLength(4)); case 5 -> policyMatchField = randomValueOtherThan(policyMatchField, () -> randomAlphaOfLength(5)); case 6 -> concreteIndices = randomValueOtherThan( concreteIndices, () -> randomMap(1, 4, () -> Tuple.tuple(randomAlphaOfLength(3), randomAlphaOfLength(5))) ); case 7 -> enrichFields = randomValueOtherThan( enrichFields, () -> randomFieldAttributes(1, 4, false).stream().map(f -> (NamedExpression) f).toList() ); } return new EnrichExec( instance.source(), child, mode, matchType, matchField, policyName, policyMatchField, concreteIndices, enrichFields ); } @Override protected boolean alwaysEmptySource() { return true; } }
EnrichExecSerializationTests
java
junit-team__junit5
junit-platform-suite-engine/src/main/java/org/junit/platform/suite/engine/LifecycleMethodUtils.java
{ "start": 1171, "end": 4260 }
class ____ { private LifecycleMethodUtils() { /* no-op */ } static List<Method> findBeforeSuiteMethods(Class<?> testClass, DiscoveryIssueReporter issueReporter) { return findMethodsAndCheckStaticAndNonPrivate(testClass, BeforeSuite.class, HierarchyTraversalMode.TOP_DOWN, issueReporter); } static List<Method> findAfterSuiteMethods(Class<?> testClass, DiscoveryIssueReporter issueReporter) { return findMethodsAndCheckStaticAndNonPrivate(testClass, AfterSuite.class, HierarchyTraversalMode.BOTTOM_UP, issueReporter); } private static List<Method> findMethodsAndCheckStaticAndNonPrivate(Class<?> testClass, Class<? extends Annotation> annotationType, HierarchyTraversalMode traversalMode, DiscoveryIssueReporter issueReporter) { return findAnnotatedMethods(testClass, annotationType, traversalMode).stream() // .filter(// returnsPrimitiveVoid(annotationType, issueReporter) // .and(isStatic(annotationType, issueReporter)) // .and(isNotPrivate(annotationType, issueReporter)) // .and(hasNoParameters(annotationType, issueReporter)) // .toPredicate()) // .toList(); } private static DiscoveryIssueReporter.Condition<Method> isStatic(Class<? extends Annotation> annotationType, DiscoveryIssueReporter issueReporter) { return issueReporter.createReportingCondition(ModifierSupport::isStatic, method -> { String message = "@%s method '%s' must be static.".formatted(annotationType.getSimpleName(), method.toGenericString()); return createError(message, method); }); } private static DiscoveryIssueReporter.Condition<Method> isNotPrivate(Class<? extends Annotation> annotationType, DiscoveryIssueReporter issueReporter) { return issueReporter.createReportingCondition(ModifierSupport::isNotPrivate, method -> { String message = "@%s method '%s' must not be private.".formatted(annotationType.getSimpleName(), method.toGenericString()); return createError(message, method); }); } private static DiscoveryIssueReporter.Condition<Method> returnsPrimitiveVoid( Class<? extends Annotation> annotationType, DiscoveryIssueReporter issueReporter) { return issueReporter.createReportingCondition(ReflectionUtils::returnsPrimitiveVoid, method -> { String message = "@%s method '%s' must not return a value.".formatted(annotationType.getSimpleName(), method.toGenericString()); return createError(message, method); }); } private static DiscoveryIssueReporter.Condition<Method> hasNoParameters(Class<? extends Annotation> annotationType, DiscoveryIssueReporter issueReporter) { return issueReporter.createReportingCondition(method -> method.getParameterCount() == 0, method -> { String message = "@%s method '%s' must not accept parameters.".formatted(annotationType.getSimpleName(), method.toGenericString()); return createError(message, method); }); } private static DiscoveryIssue createError(String message, Method method) { return DiscoveryIssue.builder(Severity.ERROR, message).source(MethodSource.from(method)).build(); } }
LifecycleMethodUtils
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSPermission.java
{ "start": 39598, "end": 41188 }
class ____ extends PermissionVerifier { private InodeType inodeType; /* initialize */ void set(Path path, InodeType inodeType, short ancestorPermission, short parentPermission, short permission) { this.inodeType = inodeType; super.set(path, ancestorPermission, parentPermission, permission); } /* set if the given path is a file/directory */ void setInodeType(Path path, InodeType inodeType) { this.path = path; this.inodeType = inodeType; setOpPermission(); this.ugi = null; } @Override void setOpPermission() { this.opParentPermission = SEARCH_MASK; switch (inodeType) { case FILE: this.opPermission = 0; break; case DIR: this.opPermission = READ_MASK | SEARCH_MASK; break; default: throw new IllegalArgumentException("Illegal inode type: " + inodeType); } } @Override void call() throws IOException { fs.listStatus(path); } } final ListPermissionVerifier listVerifier = new ListPermissionVerifier(); /* test if the permission checking of list is correct */ private void testList(UserGroupInformation ugi, Path file, Path dir, short ancestorPermission, short parentPermission, short filePermission) throws Exception { listVerifier.set(file, InodeType.FILE, ancestorPermission, parentPermission, filePermission); listVerifier.verifyPermission(ugi); listVerifier.setInodeType(dir, InodeType.DIR); listVerifier.verifyPermission(ugi); } /* A
ListPermissionVerifier
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/visitor/TypeElementQuery.java
{ "start": 958, "end": 2191 }
class ____ the methods. * * @return this query */ static TypeElementQuery onlyMethods() { return DEFAULT.excludeAll().includeMethods(); } /** * Only visit the class. * * @return this query */ static TypeElementQuery onlyClass() { return DEFAULT.excludeAll(); } /** * Include the methods. * * @return this query */ TypeElementQuery includeMethods(); /** * Exclude the methods. * * @return this query */ TypeElementQuery excludeMethods(); /** * Include the constructors. * * @return this query */ TypeElementQuery includeConstructors(); /** * Exclude the constructors. * * @return this query */ TypeElementQuery excludeConstructors(); /** * Include the fields. * * @return this query */ TypeElementQuery includeFields(); /** * Exclude the fields. * * @return this query */ TypeElementQuery excludeFields(); /** * If the unresolved interfaces should be visited. * * @return this query */ TypeElementQuery visitUnresolvedInterfaces(); /** * Include the
and
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/io/stream/RecyclerBytesStreamOutput.java
{ "start": 1342, "end": 9770 }
class ____ extends BytesStream implements Releasable { private ArrayList<Recycler.V<BytesRef>> pages = new ArrayList<>(8); private final Recycler<BytesRef> recycler; private final int pageSize; private int pageIndex = -1; private int currentCapacity = 0; private BytesRef currentBytesRef; private int currentPageOffset; public RecyclerBytesStreamOutput(Recycler<BytesRef> recycler) { this.recycler = recycler; this.pageSize = recycler.pageSize(); this.currentPageOffset = pageSize; // Always start with a page. This is because if we don't have a page, one of the hot write paths would be forced to go through // a slow path. We prefer to only execute that path if we need to expand. ensureCapacityFromPosition(1); nextPage(); } @Override public long position() { return ((long) pageSize * pageIndex) + currentPageOffset; } @Override public void writeByte(byte b) { int currentPageOffset = this.currentPageOffset; if (1 > pageSize - currentPageOffset) { ensureCapacity(1); nextPage(); currentPageOffset = 0; } final BytesRef currentPage = currentBytesRef; final int destOffset = currentPage.offset + currentPageOffset; currentPage.bytes[destOffset] = b; this.currentPageOffset = currentPageOffset + 1; } @Override public void write(byte[] b) throws IOException { writeBytes(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { writeBytes(b, off, len); } @Override public void writeBytes(byte[] b, int offset, int length) { // nothing to copy if (length == 0) { return; } Objects.checkFromIndexSize(offset, length, b.length); int currentPageOffset = this.currentPageOffset; BytesRef currentPage = currentBytesRef; if (length > pageSize - currentPageOffset) { ensureCapacity(length); } int bytesToCopy = length; int srcOff = offset; while (true) { final int toCopyThisLoop = Math.min(pageSize - currentPageOffset, bytesToCopy); final int destOffset = currentPage.offset + currentPageOffset; System.arraycopy(b, srcOff, currentPage.bytes, destOffset, toCopyThisLoop); srcOff += toCopyThisLoop; bytesToCopy -= toCopyThisLoop; if (bytesToCopy > 0) { currentPageOffset = 0; currentPage = pages.get(++pageIndex).v(); } else { currentPageOffset += toCopyThisLoop; break; } } this.currentPageOffset = currentPageOffset; this.currentBytesRef = currentPage; } @Override public void writeVInt(int i) throws IOException { final int currentPageOffset = this.currentPageOffset; final int remainingBytesInPage = pageSize - currentPageOffset; // Single byte values (most common) if ((i & 0xFFFFFF80) == 0) { if (1 > remainingBytesInPage) { super.writeVInt(i); } else { BytesRef currentPage = currentBytesRef; currentPage.bytes[currentPage.offset + currentPageOffset] = (byte) i; this.currentPageOffset = currentPageOffset + 1; } return; } int bytesNeeded = vIntLength(i); if (bytesNeeded > remainingBytesInPage) { super.writeVInt(i); } else { BytesRef currentPage = currentBytesRef; putVInt(i, bytesNeeded, currentPage.bytes, currentPage.offset + currentPageOffset); this.currentPageOffset = currentPageOffset + bytesNeeded; } } public static int vIntLength(int value) { int leadingZeros = Integer.numberOfLeadingZeros(value); if (leadingZeros >= 25) { return 1; } else if (leadingZeros >= 18) { return 2; } else if (leadingZeros >= 11) { return 3; } else if (leadingZeros >= 4) { return 4; } return 5; } private void putVInt(int i, int bytesNeeded, byte[] page, int offset) { if (bytesNeeded == 1) { page[offset] = (byte) i; } else { putMultiByteVInt(page, i, offset); } } @Override public void writeInt(int i) throws IOException { final int currentPageOffset = this.currentPageOffset; if (4 > (pageSize - currentPageOffset)) { super.writeInt(i); } else { BytesRef currentPage = currentBytesRef; ByteUtils.writeIntBE(i, currentPage.bytes, currentPage.offset + currentPageOffset); this.currentPageOffset = currentPageOffset + 4; } } @Override public void writeIntLE(int i) throws IOException { final int currentPageOffset = this.currentPageOffset; if (4 > (pageSize - currentPageOffset)) { super.writeIntLE(i); } else { BytesRef currentPage = currentBytesRef; ByteUtils.writeIntLE(i, currentPage.bytes, currentPage.offset + currentPageOffset); this.currentPageOffset = currentPageOffset + 4; } } @Override public void writeLong(long i) throws IOException { final int currentPageOffset = this.currentPageOffset; if (8 > (pageSize - currentPageOffset)) { super.writeLong(i); } else { BytesRef currentPage = currentBytesRef; ByteUtils.writeLongBE(i, currentPage.bytes, currentPage.offset + currentPageOffset); this.currentPageOffset = currentPageOffset + 8; } } @Override public void writeLongLE(long i) throws IOException { final int currentPageOffset = this.currentPageOffset; if (8 > (pageSize - currentPageOffset)) { super.writeLongLE(i); } else { BytesRef currentPage = currentBytesRef; ByteUtils.writeLongLE(i, currentPage.bytes, currentPage.offset + currentPageOffset); this.currentPageOffset = currentPageOffset + 8; } } @Override public void legacyWriteWithSizePrefix(Writeable writeable) throws IOException { // TODO: do this without copying the bytes from tmp by calling writeBytes and just use the pages in tmp directly through // manipulation of the offsets on the pages after writing to tmp. This will require adjustments to the places in this class // that make assumptions about the page size try (RecyclerBytesStreamOutput tmp = new RecyclerBytesStreamOutput(recycler)) { tmp.setTransportVersion(getTransportVersion()); writeable.writeTo(tmp); int size = tmp.size(); writeVInt(size); int tmpPage = 0; while (size > 0) { final Recycler.V<BytesRef> p = tmp.pages.get(tmpPage); final BytesRef b = p.v(); final int writeSize = Math.min(size, b.length); writeBytes(b.bytes, b.offset, writeSize); tmp.pages.set(tmpPage, null).close(); size -= writeSize; tmpPage++; } } } /** * Attempt to get one page to perform a write directly into the page. The page will only be returned if the requested bytes can fit. * If requested bytes cannot fit, null will be returned. This will advance the current position in the stream. * * @param bytes the number of bytes for the single write * @return a direct page if there is enough space in current page, otherwise null */ public BytesRef tryGetPageForWrite(int bytes) { final int beforePageOffset = this.currentPageOffset; if (bytes <= (pageSize - beforePageOffset)) { BytesRef currentPage = currentBytesRef; BytesRef bytesRef = new BytesRef(currentPage.bytes, currentPage.offset + beforePageOffset, bytes); this.currentPageOffset = beforePageOffset + bytes; return bytesRef; } else { return null; } } // overridden with some code duplication the same way other write methods in this
RecyclerBytesStreamOutput
java
quarkusio__quarkus
extensions/hibernate-search-standalone-elasticsearch/runtime/src/main/java/io/quarkus/hibernate/search/standalone/elasticsearch/runtime/MappingStructure.java
{ "start": 78, "end": 2258 }
enum ____ { // @formatter:off // @formatter:off /** * Entities indexed through Hibernate Search are nodes in an entity graph. * * With this structure: * * An indexed entity is independent of other entities it references through associations, * which *can* be updated independently of the indexed entity; * in particular they may be passed to * {@link org.hibernate.search.mapper.pojo.standalone.work.SearchIndexingPlan#addOrUpdate(Object)}. * * Therefore, when an entity changes, * Hibernate Search may need to resolve other entities to reindex, * which means in particular that associations between entities must be bi-directional: * specifying the inverse side of associations through `@AssociationInverseSide` *is required*, * unless reindexing is disabled for that association through `@IndexingDependency(reindexOnUpdate = ...)`. * * See also link:{hibernate-search-docs-url}#mapping-reindexing-associationinverseside[`@AssociationInverseSide`] * link:{hibernate-search-docs-url}#mapping-reindexing-reindexonupdate[`@IndexingDependency(reindexOnUpdate = ...)`]. * * @asciidoclet */ // @formatter:on GRAPH, /** * Entities indexed through Hibernate Search are the root of a document. * * With this structure: * * An indexed entity "owns" other entities it references through associations, * which *cannot* be updated independently of the indexed entity; * in particular they cannot be passed to * {@link org.hibernate.search.mapper.pojo.standalone.work.SearchIndexingPlan#addOrUpdate(Object)}. * * Therefore, when an entity changes, * Hibernate Search doesn't need to resolve other entities to reindex, * which means in particular that associations between entities can be uni-directional: * specifying the inverse side of associations through `@AssociationInverseSide` *is not required*. * * See also * link:{hibernate-search-docs-url}#mapping-reindexing-associationinverseside[`@AssociationInverseSide`]. * * @asciidoclet */ // @formatter:on DOCUMENT }
MappingStructure
java
apache__flink
flink-filesystems/flink-azure-fs-hadoop/src/main/java/org/apache/flink/fs/azurefs/AzureDataLakeStoreGen2FSFactory.java
{ "start": 987, "end": 1232 }
class ____ extends AbstractAzureFSFactory { @Override public String getScheme() { return "abfs"; } @Override FileSystem createAzureFS() { return new AzureBlobFileSystem(); } }
AzureDataLakeStoreGen2FSFactory
java
quarkusio__quarkus
core/devmode-spi/src/main/java/io/quarkus/dev/testing/GrpcWebSocketProxy.java
{ "start": 1977, "end": 2160 }
interface ____ { void onOpen(int id, Consumer<String> responseConsumer); void newMessage(int id, String content); void onClose(int id); } }
WebSocketListener
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/TruthGetOrDefaultTest.java
{ "start": 1003, "end": 1600 }
class ____ { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(TruthGetOrDefault.class, getClass()); private final BugCheckerRefactoringTestHelper testHelper = BugCheckerRefactoringTestHelper.newInstance(TruthGetOrDefault.class, getClass()); @Test public void positiveCases() { compilationHelper .addSourceLines( "Test.java", """ import static com.google.common.truth.Truth.assertThat; import java.util.HashMap; import java.util.Map;
TruthGetOrDefaultTest
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/CompareCondition.java
{ "start": 695, "end": 6226 }
class ____ extends AbstractCompareCondition { public static final String TYPE = "compare"; private final String path; private final Op op; private final Object value; public CompareCondition(String path, Op op, Object value) { this(path, op, value, null); } CompareCondition(String path, Op op, Object value, Clock clock) { super(TYPE, clock); this.path = path; this.op = op; this.value = value; } public String getPath() { return path; } public Op getOp() { return op; } public Object getValue() { return value; } public static CompareCondition parse(Clock clock, String watchId, XContentParser parser) throws IOException { if (parser.currentToken() != XContentParser.Token.START_OBJECT) { throw new ElasticsearchParseException( "could not parse [{}] condition for watch [{}]. expected an object but found [{}] " + "instead", TYPE, watchId, parser.currentToken() ); } String path = null; Object value = null; Op op = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { path = parser.currentName(); } else if (path == null) { throw new ElasticsearchParseException( "could not parse [{}] condition for watch [{}]. expected a field indicating the " + "compared path, but found [{}] instead", TYPE, watchId, token ); } else if (token == XContentParser.Token.START_OBJECT) { token = parser.nextToken(); if (token != XContentParser.Token.FIELD_NAME) { throw new ElasticsearchParseException( "could not parse [{}] condition for watch [{}]. expected a field indicating the" + " comparison operator, but found [{}] instead", TYPE, watchId, token ); } try { op = Op.resolve(parser.currentName()); } catch (IllegalArgumentException iae) { throw new ElasticsearchParseException( "could not parse [{}] condition for watch [{}]. unknown comparison operator " + "[{}]", TYPE, watchId, parser.currentName() ); } token = parser.nextToken(); if (op.supportsStructures() == false && token.isValue() == false && token != XContentParser.Token.VALUE_NULL) { throw new ElasticsearchParseException( "could not parse [{}] condition for watch [{}]. compared value for [{}] with " + "operation [{}] must either be a numeric, string, boolean or null value, but found [{}] instead", TYPE, watchId, path, op.name().toLowerCase(Locale.ROOT), token ); } value = XContentUtils.readValue(parser, token); token = parser.nextToken(); if (token != XContentParser.Token.END_OBJECT) { throw new ElasticsearchParseException( "could not parse [{}] condition for watch [{}]. expected end of path object, " + "but found [{}] instead", TYPE, watchId, token ); } } else { throw new ElasticsearchParseException( "could not parse [{}] condition for watch [{}]. expected an object for field [{}] " + "but found [{}] instead", TYPE, watchId, path, token ); } } return new CompareCondition(path, op, value, clock); } @Override protected Result doExecute(Map<String, Object> model, Map<String, Object> resolvedValues) { Object configuredValue = resolveConfiguredValue(resolvedValues, model, value); Object resolvedValue = ObjectPath.eval(path, model); resolvedValues.put(path, resolvedValue); return new Result(resolvedValues, TYPE, op.eval(resolvedValue, configuredValue)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CompareCondition condition = (CompareCondition) o; if (Objects.equals(path, condition.path) == false) return false; if (op != condition.op) return false; return Objects.equals(value, condition.value); } @Override public int hashCode() { return Objects.hash(path, op, value); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.startObject().startObject(path).field(op.id(), value).endObject().endObject(); } public
CompareCondition
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnResourceTests.java
{ "start": 1215, "end": 2256 }
class ____ { private final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); @Test @WithResource(name = "schema.sql") void testResourceExists() { this.context.register(BasicConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("foo")).isTrue(); assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test @WithResource(name = "schema.sql") void testResourceExistsWithPlaceholder() { TestPropertyValues.of("schema=schema.sql").applyTo(this.context); this.context.register(PlaceholderConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("foo")).isTrue(); assertThat(this.context.getBean("foo")).isEqualTo("foo"); } @Test void testResourceNotExists() { this.context.register(MissingConfiguration.class); this.context.refresh(); assertThat(this.context.containsBean("foo")).isFalse(); } @Configuration(proxyBeanMethods = false) @ConditionalOnResource(resources = "foo") static
ConditionalOnResourceTests
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/impl/DefaultCamelBeanPostProcessorFieldFirstTest.java
{ "start": 2385, "end": 2938 }
class ____ { // should inject simple types first such as this property @PropertyInject("foo") private String foo; // should inject simple types first such as this property @PropertyInject(value = "number", defaultValue = "123") private Integer number; @BindToRegistry("myCoolBean") public MySerialBean myBean() { MySerialBean myBean = new MySerialBean(); myBean.setId(number); myBean.setName(foo); return myBean; } } }
FooService
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/EnumUtils.java
{ "start": 14845, "end": 15031 }
class ____ value, returning {@code defaultEnum} if not found. * * <p> * This method differs from {@link Enum#valueOf} in that it does not throw an exception for an invalid
and
java
netty__netty
transport/src/main/java/io/netty/channel/ChannelHandlerContext.java
{ "start": 1878, "end": 3567 }
class ____ extends {@link ChannelDuplexHandler} { * * <b>private {@link ChannelHandlerContext} ctx;</b> * * public void beforeAdd({@link ChannelHandlerContext} ctx) { * <b>this.ctx = ctx;</b> * } * * public void login(String username, password) { * ctx.write(new LoginMessage(username, password)); * } * ... * } * </pre> * * <h3>Storing stateful information</h3> * * {@link #attr(AttributeKey)} allow you to * store and access stateful information that is related with a {@link ChannelHandler} / {@link Channel} and its * context. Please refer to {@link ChannelHandler} to learn various recommended * ways to manage stateful information. * * <h3>A handler can have more than one {@link ChannelHandlerContext}</h3> * * Please note that a {@link ChannelHandler} instance can be added to more than * one {@link ChannelPipeline}. It means a single {@link ChannelHandler} * instance can have more than one {@link ChannelHandlerContext} and therefore * the single instance can be invoked with different * {@link ChannelHandlerContext}s if it is added to one or more {@link ChannelPipeline}s more than once. * Also note that a {@link ChannelHandler} that is supposed to be added to multiple {@link ChannelPipeline}s should * be marked as {@link io.netty.channel.ChannelHandler.Sharable}. * * <h3>Additional resources worth reading</h3> * <p> * Please refer to the {@link ChannelHandler}, and * {@link ChannelPipeline} to find out more about inbound and outbound operations, * what fundamental differences they have, how they flow in a pipeline, and how to handle * the operation in your application. */ public
MyHandler
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurationTests.java
{ "start": 23139, "end": 23484 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((requests) -> requests .anyRequest().authenticated()); return http.build(); // @formatter:on } } @Configuration @EnableWebSecurity static
WebSecurityExpressionHandlerDefaultsConfig
java
elastic__elasticsearch
x-pack/plugin/analytics/src/test/java/org/elasticsearch/xpack/analytics/mapper/TDigestFieldBlockLoaderTests.java
{ "start": 1070, "end": 4732 }
class ____ extends BlockLoaderTestCase { public TDigestFieldBlockLoaderTests(Params params) { super(TDigestFieldMapper.CONTENT_TYPE, List.of(DATA_SOURCE_HANDLER), params); } @Override protected Collection<? extends Plugin> getPlugins() { return List.of(new AnalyticsPlugin()); } @Before public void setup() { assumeTrue("Only when exponential_histogram feature flag is enabled", TDigestFieldMapper.TDIGEST_FIELD_MAPPER.isEnabled()); } private static DataSourceHandler DATA_SOURCE_HANDLER = new DataSourceHandler() { @Override public DataSourceResponse.ObjectArrayGenerator handle(DataSourceRequest.ObjectArrayGenerator request) { // tdigest does not support multiple values in a document so we can't have object arrays return new DataSourceResponse.ObjectArrayGenerator(Optional::empty); } @Override public DataSourceResponse.LeafMappingParametersGenerator handle(DataSourceRequest.LeafMappingParametersGenerator request) { if (request.fieldType().equals(TDigestFieldMapper.CONTENT_TYPE) == false) { return null; } return new DataSourceResponse.LeafMappingParametersGenerator(() -> { var map = new HashMap<String, Object>(); if (ESTestCase.randomBoolean()) { map.put("ignore_malformed", ESTestCase.randomBoolean()); map.put("compression", randomDoubleBetween(1.0, 1000.0, true)); map.put("digest_type", randomFrom(TDigestState.Type.values())); } return map; }); } @Override public DataSourceResponse.FieldDataGenerator handle(DataSourceRequest.FieldDataGenerator request) { if (request.fieldType().equals(TDigestFieldMapper.CONTENT_TYPE) == false) { return null; } return new DataSourceResponse.FieldDataGenerator( mapping -> TDigestFieldMapperTests.generateRandomFieldValues(randomIntBetween(1, 1_000)) ); } }; @Override public void testBlockLoaderOfMultiField() throws IOException { // Multi fields are not supported } @Override protected Object expected(Map<String, Object> fieldMapping, Object value, TestContext testContext) { Map<String, Object> valueAsMap = Types.forciblyCast(value); List<Double> centroids = Types.forciblyCast(valueAsMap.get("centroids")); List<Long> counts = Types.forciblyCast(valueAsMap.get("counts")); BytesStreamOutput streamOutput = new BytesStreamOutput(); long totalCount = 0; // TODO - refactor this, it's duplicated from the parser for (int i = 0; i < centroids.size(); i++) { long count = counts.get(i); totalCount += count; // we do not add elements with count == 0 try { if (count > 0) { streamOutput.writeVLong(count); streamOutput.writeDouble(centroids.get(i)); } } catch (IOException e) { throw new RuntimeException(e); } } long finalTotalCount = totalCount; return Map.of( "min", valueAsMap.get("min"), "max", valueAsMap.get("max"), "sum", valueAsMap.get("sum"), "value_count", finalTotalCount, "encoded_digest", streamOutput.bytes().toBytesRef() ); } }
TDigestFieldBlockLoaderTests
java
apache__dubbo
dubbo-rpc/dubbo-rpc-api/src/test/java/org/apache/dubbo/rpc/filter/AccessLogFilterTest.java
{ "start": 1647, "end": 4821 }
class ____ { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger("mock.dubbo.access.log"); AccessLogFilter accessLogFilter = new AccessLogFilter(); // TODO how to assert thread action @Test @SuppressWarnings("unchecked") public void testDefault() throws NoSuchFieldException, IllegalAccessException { URL url = URL.valueOf("test://test:11/test?accesslog=true&group=dubbo&version=1.1"); Invoker<AccessLogFilterTest> invoker = new MyInvoker<AccessLogFilterTest>(url); Invocation invocation = new MockInvocation(); Field field = AccessLogFilter.class.getDeclaredField("logEntries"); field.setAccessible(true); assertTrue(((Map) field.get(accessLogFilter)).isEmpty()); accessLogFilter.invoke(invoker, invocation); Map<String, Queue<AccessLogData>> logs = (Map<String, Queue<AccessLogData>>) field.get(accessLogFilter); assertFalse(logs.isEmpty()); assertFalse(logs.get("true").isEmpty()); AccessLogData log = logs.get("true").iterator().next(); assertEquals("org.apache.dubbo.rpc.support.DemoService", log.getServiceName()); } @Test void testCustom() { DubboAppender.doStart(); ErrorTypeAwareLogger originalLogger = AccessLogFilter.logger; long originalInterval = AccessLogFilter.getInterval(); AccessLogFilter.setInterval(500); AccessLogFilter.logger = logger; AccessLogFilter customAccessLogFilter = new AccessLogFilter(); try { URL url = URL.valueOf("test://test:11/test?accesslog=custom-access.log"); Invoker<AccessLogFilterTest> invoker = new MyInvoker<>(url); Invocation invocation = new MockInvocation(); customAccessLogFilter.invoke(invoker, invocation); sleep(); assertEquals(1, LogUtil.findMessage("Change of accesslog file path not allowed")); } finally { customAccessLogFilter.destroy(); DubboAppender.clear(); AccessLogFilter.logger = originalLogger; AccessLogFilter.setInterval(originalInterval); } AccessLogFilter.setInterval(500); AccessLogFilter.logger = logger; AccessLogFilter customAccessLogFilter2 = new AccessLogFilter(); try { URL url2 = URL.valueOf("test://test:11/test?accesslog=custom-access.log&accesslog.fixed.path=false"); Invoker<AccessLogFilterTest> invoker = new MyInvoker<>(url2); Invocation invocation = new MockInvocation(); customAccessLogFilter2.invoke(invoker, invocation); sleep(); assertEquals(1, LogUtil.findMessage("Accesslog file path changed to")); } finally { customAccessLogFilter2.destroy(); DubboAppender.clear(); AccessLogFilter.logger = originalLogger; AccessLogFilter.setInterval(originalInterval); } } private void sleep() { try { Thread.sleep(600); } catch (InterruptedException e) { e.printStackTrace(); } } }
AccessLogFilterTest
java
apache__flink
flink-end-to-end-tests/flink-stream-state-ttl-test/src/main/java/org/apache/flink/streaming/tests/verify/TtlValueStateVerifier.java
{ "start": 1217, "end": 2454 }
class ____ extends AbstractTtlStateVerifier< ValueStateDescriptor<String>, ValueState<String>, String, String, String> { TtlValueStateVerifier() { super( new ValueStateDescriptor<>( TtlValueStateVerifier.class.getSimpleName(), StringSerializer.INSTANCE)); } @Override @Nonnull State createState(FunctionInitializationContext context) { return context.getKeyedStateStore().getState(stateDesc); } @Nonnull public String generateRandomUpdate() { return randomString(); } @Override String getInternal(@Nonnull ValueState<String> state) throws Exception { return state.value(); } @Override void updateInternal(@Nonnull ValueState<String> state, String update) throws Exception { state.update(update); } @Override String expected(@Nonnull List<ValueWithTs<String>> updates, long currentTimestamp) { if (updates.isEmpty()) { return null; } ValueWithTs<String> lastUpdate = updates.get(updates.size() - 1); return expired(lastUpdate.getTimestamp(), currentTimestamp) ? null : lastUpdate.getValue(); } }
TtlValueStateVerifier
java
apache__hadoop
hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/Nfs3FileAttributes.java
{ "start": 1064, "end": 1969 }
class ____ { private int type; private int mode; private int nlink; private int uid; private int gid; private long size; private long used; private Specdata3 rdev; private long fsid; private long fileId; private NfsTime atime; private NfsTime mtime; private NfsTime ctime; /* * The interpretation of the two words depends on the type of file system * object. For a block special (NF3BLK) or character special (NF3CHR) file, * specdata1 and specdata2 are the major and minor device numbers, * respectively. (This is obviously a UNIX-specific interpretation.) For all * other file types, these two elements should either be set to 0 or the * values should be agreed upon by the client and server. If the client and * server do not agree upon the values, the client should treat these fields * as if they are set to 0. */ public static
Nfs3FileAttributes
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/aot/nativex/RuntimeHintsWriter.java
{ "start": 1215, "end": 2448 }
class ____ { public void write(BasicJsonWriter writer, RuntimeHints hints) { Map<String, Object> document = new LinkedHashMap<>(); String springVersion = SpringVersion.getVersion(); if (springVersion != null) { document.put("comment", "Spring Framework " + springVersion); } List<Map<String, Object>> reflection = new ReflectionHintsAttributes().reflection(hints); if (!reflection.isEmpty()) { document.put("reflection", reflection); } List<Map<String, Object>> jni = new ReflectionHintsAttributes().jni(hints); if (!jni.isEmpty()) { document.put("jni", jni); } List<Map<String, Object>> resourceHints = new ResourceHintsAttributes().resources(hints.resources()); if (!resourceHints.isEmpty()) { document.put("resources", resourceHints); } List<Map<String, Object>> resourceBundles = new ResourceHintsAttributes().resourceBundles(hints.resources()); if (!resourceBundles.isEmpty()) { document.put("bundles", resourceBundles); } List<Map<String, Object>> serialization = new SerializationHintsAttributes().toAttributes(hints.serialization()); if (!serialization.isEmpty()) { document.put("serialization", serialization); } writer.writeObject(document); } }
RuntimeHintsWriter
java
apache__flink
flink-test-utils-parent/flink-test-utils/src/main/java/org/apache/flink/streaming/util/FiniteTestSource.java
{ "start": 1458, "end": 1612 }
class ____ written to test the Bulk Writers used by the StreamingFileSink. */ @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") public
was
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodesFactory.java
{ "start": 2091, "end": 2312 }
class ____ (for example, from the "/WEB-INF/classes" directory). */ public static final String SQL_ERROR_CODE_OVERRIDE_PATH = "sql-error-codes.xml"; /** * The name of default SQL error code files, loading from the
path
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDiskError.java
{ "start": 2775, "end": 9461 }
class ____ { private FileSystem fs; private MiniDFSCluster cluster; private Configuration conf; @BeforeEach public void setUp() throws Exception { conf = new HdfsConfiguration(); conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 512L); conf.setTimeDuration( DFSConfigKeys.DFS_DATANODE_DISK_CHECK_MIN_GAP_KEY, 0, TimeUnit.MILLISECONDS); cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); fs = cluster.getFileSystem(); } @AfterEach public void tearDown() throws Exception { if (cluster != null) { cluster.shutdown(); cluster = null; } } /** * Test to check that a DN goes down when all its volumes have failed. */ @Test public void testShutdown() throws Exception { if (System.getProperty("os.name").startsWith("Windows")) { /** * This test depends on OS not allowing file creations on a directory * that does not have write permissions for the user. Apparently it is * not the case on Windows (at least under Cygwin), and possibly AIX. * This is disabled on Windows. */ return; } // Bring up two more datanodes cluster.startDataNodes(conf, 2, true, null, null); cluster.waitActive(); final int dnIndex = 0; String bpid = cluster.getNamesystem().getBlockPoolId(); File storageDir = cluster.getInstanceStorageDir(dnIndex, 0); File dir1 = MiniDFSCluster.getRbwDir(storageDir, bpid); storageDir = cluster.getInstanceStorageDir(dnIndex, 1); File dir2 = MiniDFSCluster.getRbwDir(storageDir, bpid); try { // make the data directory of the first datanode to be readonly assertTrue(dir1.setReadOnly(), "Couldn't chmod local vol"); assertTrue(dir2.setReadOnly(), "Couldn't chmod local vol"); // create files and make sure that first datanode will be down DataNode dn = cluster.getDataNodes().get(dnIndex); for (int i=0; dn.isDatanodeUp(); i++) { Path fileName = new Path("/test.txt"+i); DFSTestUtil.createFile(fs, fileName, 1024, (short)2, 1L); DFSTestUtil.waitReplication(fs, fileName, (short)2); fs.delete(fileName, true); } } finally { // restore its old permission FileUtil.setWritable(dir1, true); FileUtil.setWritable(dir2, true); } } /** * Test that when there is a failure replicating a block the temporary * and meta files are cleaned up and subsequent replication succeeds. */ @Test public void testReplicationError() throws Exception { // create a file of replication factor of 1 final Path fileName = new Path("/test.txt"); final int fileLen = 1; DFSTestUtil.createFile(fs, fileName, 1, (short)1, 1L); DFSTestUtil.waitReplication(fs, fileName, (short)1); // get the block belonged to the created file LocatedBlocks blocks = NameNodeAdapter.getBlockLocations( cluster.getNameNode(), fileName.toString(), 0, (long)fileLen); assertEquals(blocks.locatedBlockCount(), 1, "Should only find 1 block"); LocatedBlock block = blocks.get(0); // bring up a second datanode cluster.startDataNodes(conf, 1, true, null, null); cluster.waitActive(); final int sndNode = 1; DataNode datanode = cluster.getDataNodes().get(sndNode); FsDatasetTestUtils utils = cluster.getFsDatasetTestUtils(datanode); // replicate the block to the second datanode InetSocketAddress target = datanode.getXferAddress(); Socket s = new Socket(target.getAddress(), target.getPort()); // write the header. DataOutputStream out = new DataOutputStream(s.getOutputStream()); DataChecksum checksum = DataChecksum.newDataChecksum( DataChecksum.Type.CRC32, 512); new Sender(out).writeBlock(block.getBlock(), StorageType.DEFAULT, BlockTokenSecretManager.DUMMY_TOKEN, "", DatanodeInfo.EMPTY_ARRAY, StorageType.EMPTY_ARRAY, null, BlockConstructionStage.PIPELINE_SETUP_CREATE, 1, 0L, 0L, 0L, checksum, CachingStrategy.newDefaultStrategy(), false, false, null, null, new String[0]); out.flush(); // close the connection before sending the content of the block out.close(); // the temporary block & meta files should be deleted String bpid = cluster.getNamesystem().getBlockPoolId(); while (utils.getStoredReplicas(bpid).hasNext()) { Thread.sleep(100); } // then increase the file's replication factor fs.setReplication(fileName, (short)2); // replication should succeed DFSTestUtil.waitReplication(fs, fileName, (short)1); // clean up the file fs.delete(fileName, false); } /** * Check that the permissions of the local DN directories are as expected. */ @Test public void testLocalDirs() throws Exception { Configuration conf = new Configuration(); final String permStr = conf.get( DFSConfigKeys.DFS_DATANODE_DATA_DIR_PERMISSION_KEY); FsPermission expected = new FsPermission(permStr); // Check permissions on directories in 'dfs.datanode.data.dir' FileSystem localFS = FileSystem.getLocal(conf); for (DataNode dn : cluster.getDataNodes()) { try (FsDatasetSpi.FsVolumeReferences volumes = dn.getFSDataset().getFsVolumeReferences()) { for (FsVolumeSpi vol : volumes) { Path dataDir = new Path(vol.getStorageLocation().getNormalizedUri()); FsPermission actual = localFS.getFileStatus(dataDir).getPermission(); assertEquals(expected, actual, "Permission for dir: " + dataDir + ", is " + actual + ", while expected is " + expected); } } } } /** * Checks whether {@link DataNode#checkDiskErrorAsync()} is being called or not. * Before refactoring the code the above function was not getting called * @throws IOException, InterruptedException */ @Test @Timeout(value = 60) public void testcheckDiskError() throws Exception { if(cluster.getDataNodes().size() <= 0) { cluster.startDataNodes(conf, 1, true, null, null); cluster.waitActive(); } DataNode dataNode = cluster.getDataNodes().get(0); //checking for disk error final long lastCheckTimestamp = dataNode.getLastDiskErrorCheck(); dataNode.checkDiskError(); GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { return dataNode.getLastDiskErrorCheck() > lastCheckTimestamp; } }, 100, 60000); } @Test public void testDataTransferWhenBytesPerChecksumIsZero() throws IOException { DataNode dn0 = cluster.getDataNodes().get(0); // Make a mock blockScanner
TestDiskError
java
spring-projects__spring-boot
module/spring-boot-micrometer-metrics/src/main/java/org/springframework/boot/micrometer/metrics/export/prometheus/PrometheusPushGatewayManager.java
{ "start": 4384, "end": 4757 }
class ____ extends ThreadPoolTaskScheduler { PushGatewayTaskScheduler() { setPoolSize(1); setDaemon(true); setThreadGroupName("prometheus-push-gateway"); } @Override public ScheduledExecutorService getScheduledExecutor() throws IllegalStateException { return Executors.newSingleThreadScheduledExecutor(this::newThread); } } }
PushGatewayTaskScheduler
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schema/PostgreSQLSchemaGenerationTest.java
{ "start": 901, "end": 1014 }
class ____ extends BaseSchemaGeneratorTest { @Test public void testPostgres() { } }
PostgreSQLSchemaGenerationTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/mixins/TestMixinDeserForCreators.java
{ "start": 2486, "end": 4773 }
class ____ { // with and without <Long, String> @JsonCreator static TestMixinDeserForCreators.Pair2020 with(@JsonProperty("value0") Object value0, @JsonProperty("value1") Object value1) { // body does not matter, only signature return null; } } /* /********************************************************** /* Unit tests /********************************************************** */ @Test public void testForConstructor() throws IOException { ObjectMapper mapper = jsonMapperBuilder() .addMixIn(BaseClassWithPrivateCtor.class, MixInForPrivate.class) .build(); BaseClassWithPrivateCtor result = mapper.readValue("\"?\"", BaseClassWithPrivateCtor.class); assertEquals("?...", result._a); } @Test public void testForFactoryAndCtor() throws IOException { BaseClass result; // First: test default behavior: should use constructor result = new ObjectMapper().readValue("\"string\"", BaseClass.class); assertEquals("string...", result._a); // Then with simple mix-in: should change to use the factory method ObjectMapper mapper = jsonMapperBuilder() .addMixIn(BaseClass.class, MixIn.class) .build(); result = mapper.readValue("\"string\"", BaseClass.class); assertEquals("stringX", result._a); } @Test public void testFactoryDelegateMixIn() throws IOException { ObjectMapper mapper = jsonMapperBuilder() .addMixIn(StringWrapper.class, StringWrapperMixIn.class) .build(); StringWrapper result = mapper.readValue("\"a\"", StringWrapper.class); assertEquals("a", result._value); } // [databind#2020] @Test public void testFactoryPropertyMixin() throws Exception { ObjectMapper mapper = jsonMapperBuilder() .addMixIn(Pair2020.class, MyPairMixIn8.class) .build(); String doc = a2q( "{'value0' : 456, 'value1' : 789}"); Pair2020 pair2 = mapper.readValue(doc, Pair2020.class); assertEquals(456, pair2.x); assertEquals(789, pair2.y); } }
MyPairMixIn8
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/bindings/repeatable/RepeatableInterceptorBindingWithNonbindingAttributeTest.java
{ "start": 1199, "end": 2789 }
class ____ { @RegisterExtension public ArcTestContainer container = new ArcTestContainer(MyBinding.class, MyBinding.List.class, MethodInterceptedBean.class, IncrementingInterceptor.class); @BeforeEach public void setUp() { IncrementingInterceptor.AROUND_CONSTRUCT.set(false); IncrementingInterceptor.POST_CONSTRUCT.set(false); IncrementingInterceptor.PRE_DESTROY.set(false); } @Test public void methodLevelInterceptor() { MethodInterceptedBean bean = Arc.container().instance(MethodInterceptedBean.class).get(); assertEquals(11, bean.foo()); assertEquals(21, bean.foobar()); assertEquals(31, bean.foobaz()); assertEquals(41, bean.foobarbaz()); assertEquals(50, bean.nonannotated()); // the instance is created lazily (the bean is @ApplicationScoped), // so the around construct interceptor is also called lazily, // when the first method call is made on the client proxy assertTrue(IncrementingInterceptor.AROUND_CONSTRUCT.get()); // post-construct and pre-destroy interceptors aren't called, // because there are no class-level interceptor bindings assertFalse(IncrementingInterceptor.POST_CONSTRUCT.get()); assertFalse(IncrementingInterceptor.PRE_DESTROY.get()); } @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR }) @Retention(RetentionPolicy.RUNTIME) @Repeatable(MyBinding.List.class) @InterceptorBinding @
RepeatableInterceptorBindingWithNonbindingAttributeTest
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/writing/OptionalFactories.java
{ "start": 8132, "end": 11499 }
class ____ { /** Whether the factory is a {@code Provider} or a {@code Producer}. */ abstract FrameworkType frameworkType(); /** What kind of {@code Optional} is returned. */ abstract OptionalKind optionalKind(); /** The kind of request satisfied by the value of the {@code Optional}. */ abstract RequestKind valueKind(); /** The type variable for the factory class. */ XTypeName typeVariable() { return XTypeNames.getTypeVariableName("T"); } /** The type contained by the {@code Optional}. */ XTypeName valueType() { return requestTypeName(valueKind(), typeVariable()); } /** The type provided or produced by the factory. */ XTypeName optionalType() { return optionalKind().of(valueType()); } /** The type of the factory. */ XTypeName factoryType() { return frameworkType().frameworkClassOf(optionalType()); } /** The type of the delegate provider or producer. */ XTypeName delegateType() { return frameworkType().frameworkClassOf(typeVariable()); } /** Returns the superclass the generated factory should have, if any. */ Optional<XTypeName> superclass() { switch (frameworkType()) { case PRODUCER_NODE: // TODO(cgdecker): This probably isn't a big issue for now, but it's possible this // shouldn't be an AbstractProducer: // - As AbstractProducer, it'll only call the delegate's get() method once and then cache // that result (essentially) rather than calling the delegate's get() method each time // its get() method is called (which was what it did before the cancellation change). // - It's not 100% clear to me whether the view-creation methods should return a view of // the same view created by the delegate or if they should just return their own views. return Optional.of(abstractProducerOf(optionalType())); default: return Optional.empty(); } } /** Returns the superinterface the generated factory should have, if any. */ Optional<XTypeName> superinterface() { switch (frameworkType()) { case PROVIDER: return Optional.of(factoryType()); default: return Optional.empty(); } } /** Returns the name of the factory method to generate. */ String factoryMethodName() { switch (frameworkType()) { case PROVIDER: return "get"; case PRODUCER_NODE: return "compute"; } throw new AssertionError(frameworkType()); } /** The name of the factory class. */ String factoryClassName() { return new StringBuilder("Present") .append(UPPER_UNDERSCORE.to(UPPER_CAMEL, optionalKind().name())) .append(UPPER_UNDERSCORE.to(UPPER_CAMEL, valueKind().toString())) .append(frameworkType().frameworkClassName().getSimpleName()) .toString(); } private static PresentFactorySpec of(OptionalBinding binding) { return new AutoValue_OptionalFactories_PresentFactorySpec( FrameworkType.forBindingType(binding.bindingType()), OptionalType.from(binding.key()).kind(), getOnlyElement(binding.dependencies()).kind()); } } /** * Returns an expression for an instance of a nested
PresentFactorySpec
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metadata/Record.java
{ "start": 724, "end": 935 }
class ____ { @Id @GeneratedValue String id; String text; LocalDateTime timestamp; Record() {} public Record(String text, LocalDateTime timestamp) { this.text = text; this.timestamp = timestamp; } }
Record
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ComparingThisWithNullTest.java
{ "start": 1953, "end": 2349 }
class ____ { void f() { // BUG: Diagnostic contains: ComparingThisWithNull if (this != null) { String x = "Test"; } } } """) .doTest(); } @Test public void nullIsNotThis() { helper .addSourceLines( "Test.java", """
Test
java
dropwizard__dropwizard
dropwizard-jersey/src/main/java/io/dropwizard/jersey/validation/ParamValueExtractor.java
{ "start": 532, "end": 983 }
class ____ implements ValueExtractor<AbstractParam<@ExtractedValue ?>> { static final ValueExtractorDescriptor DESCRIPTOR = new ValueExtractorDescriptor(new ParamValueExtractor()); private ParamValueExtractor() { } @Override public void extractValues(AbstractParam<?> originalValue, ValueExtractor.ValueReceiver receiver) { receiver.value(null, originalValue == null ? null : originalValue.get()); } }
ParamValueExtractor
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/core/Local.java
{ "start": 704, "end": 981 }
class ____ { private Type type; private int index; public Local(int index, Type type) { this.type = type; this.index = index; } public int getIndex() { return index; } public Type getType() { return type; } }
Local
java
redisson__redisson
redisson/src/main/java/org/redisson/cluster/ClusterPartition.java
{ "start": 909, "end": 4789 }
enum ____ {MASTER, SLAVE} private Type type = Type.MASTER; private final String nodeId; private boolean masterFail; private RedisURI masterAddress; private final Set<RedisURI> slaveAddresses = Collections.newSetFromMap(new ConcurrentHashMap<>()); private final Set<RedisURI> failedSlaves = Collections.newSetFromMap(new ConcurrentHashMap<>()); private BitSet slots; private Set<ClusterSlotRange> slotRanges = Collections.emptySet(); private ClusterPartition parent; private int references; private long time = System.currentTimeMillis(); public ClusterPartition(String nodeId) { super(); this.nodeId = nodeId; } public ClusterPartition getParent() { return parent; } public void setParent(ClusterPartition parent) { this.parent = parent; } public void setType(Type type) { this.type = type; } public Type getType() { return type; } public String getNodeId() { return nodeId; } public void setMasterFail(boolean masterFail) { this.masterFail = masterFail; } public boolean isMasterFail() { return masterFail; } public void updateSlotRanges(Set<ClusterSlotRange> ranges, BitSet slots) { this.slotRanges = ranges; this.slots = slots; } public void setSlotRanges(Set<ClusterSlotRange> ranges) { slots = new BitSet(MAX_SLOT); for (ClusterSlotRange clusterSlotRange : ranges) { slots.set(clusterSlotRange.getStartSlot(), clusterSlotRange.getEndSlot() + 1); } slotRanges = ranges; } public Set<ClusterSlotRange> getSlotRanges() { return Collections.unmodifiableSet(slotRanges); } public Iterable<Integer> getSlots() { return slots.stream()::iterator; } public BitSet slots() { return slots; } public BitSet copySlots() { return (BitSet) slots.clone(); } public boolean hasSlot(int slot) { return slots.get(slot); } public int getSlotsAmount() { return slots.cardinality(); } public RedisURI getMasterAddress() { return masterAddress; } public void setMasterAddress(RedisURI masterAddress) { this.masterAddress = masterAddress; } public void addFailedSlaveAddress(RedisURI address) { failedSlaves.add(address); } public Set<RedisURI> getFailedSlaveAddresses() { return Collections.unmodifiableSet(failedSlaves); } public void removeFailedSlaveAddress(RedisURI uri) { failedSlaves.remove(uri); } public void addSlaveAddress(RedisURI address) { slaveAddresses.add(address); } public Set<RedisURI> getSlaveAddresses() { return Collections.unmodifiableSet(slaveAddresses); } public void removeSlaveAddress(RedisURI uri) { slaveAddresses.remove(uri); failedSlaves.remove(uri); } public void incReference() { references++; } public int decReference() { return --references; } public long getTime() { return time; } @Override public int hashCode() { return Objects.hash(nodeId); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ClusterPartition that = (ClusterPartition) o; return Objects.equals(nodeId, that.nodeId); } @Override public String toString() { return "ClusterPartition [nodeId=" + nodeId + ", masterFail=" + masterFail + ", masterAddress=" + masterAddress + ", slaveAddresses=" + slaveAddresses + ", failedSlaves=" + failedSlaves + ", slotRanges=" + slotRanges + "]"; } }
Type
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverter.java
{ "start": 1739, "end": 4976 }
class ____ implements AuthenticationConverter { private final RelyingPartyRegistrationResolver relyingPartyRegistrationResolver; private Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository; private boolean shouldConvertGetRequests = true; /** * Constructs a {@link Saml2AuthenticationTokenConverter} given a strategy for * resolving {@link RelyingPartyRegistration}s * @param relyingPartyRegistrationResolver the strategy for resolving * {@link RelyingPartyRegistration}s */ public Saml2AuthenticationTokenConverter(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { Assert.notNull(relyingPartyRegistrationResolver, "relyingPartyRegistrationResolver cannot be null"); this.relyingPartyRegistrationResolver = relyingPartyRegistrationResolver; this.authenticationRequestRepository = new HttpSessionSaml2AuthenticationRequestRepository(); } @Override public Saml2AuthenticationToken convert(HttpServletRequest request) { AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository .loadAuthenticationRequest(request); String relyingPartyRegistrationId = (authenticationRequest != null) ? authenticationRequest.getRelyingPartyRegistrationId() : null; RelyingPartyRegistration relyingPartyRegistration = this.relyingPartyRegistrationResolver.resolve(request, relyingPartyRegistrationId); if (relyingPartyRegistration == null) { return null; } String saml2Response = decode(request); if (saml2Response == null) { return null; } return new Saml2AuthenticationToken(relyingPartyRegistration, saml2Response, authenticationRequest); } /** * Use the given {@link Saml2AuthenticationRequestRepository} to load authentication * request. * @param authenticationRequestRepository the * {@link Saml2AuthenticationRequestRepository} to use * @since 5.6 */ public void setAuthenticationRequestRepository( Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) { Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null"); this.authenticationRequestRepository = authenticationRequestRepository; } /** * Use the given {@code shouldConvertGetRequests} to convert {@code GET} requests. * Default is {@code true}. * @param shouldConvertGetRequests the {@code shouldConvertGetRequests} to use * @since 7.0 */ public void setShouldConvertGetRequests(boolean shouldConvertGetRequests) { this.shouldConvertGetRequests = shouldConvertGetRequests; } private String decode(HttpServletRequest request) { String encoded = request.getParameter(Saml2ParameterNames.SAML_RESPONSE); if (encoded == null) { return null; } boolean isGet = HttpMethod.GET.matches(request.getMethod()); if (!this.shouldConvertGetRequests && isGet) { return null; } Saml2Utils.DecodingConfigurer decoding = Saml2Utils.withEncoded(encoded).requireBase64(true).inflate(isGet); try { return decoding.decode(); } catch (Exception ex) { throw new Saml2AuthenticationException(Saml2Error.invalidResponse(ex.getMessage()), ex); } } }
Saml2AuthenticationTokenConverter
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/TestContextAnnotationUtils.java
{ "start": 23341, "end": 25281 }
class ____<T extends Annotation> { private final Class<?> rootDeclaringClass; private final Class<?> declaringClass; private final T annotation; AnnotationDescriptor(Class<?> rootDeclaringClass, T annotation) { this(rootDeclaringClass, rootDeclaringClass, annotation); } @SuppressWarnings("unchecked") AnnotationDescriptor(Class<?> rootDeclaringClass, Class<?> declaringClass, T annotation) { Assert.notNull(rootDeclaringClass, "'rootDeclaringClass' must not be null"); Assert.notNull(declaringClass, "'declaringClass' must not be null"); Assert.notNull(annotation, "Annotation must not be null"); this.rootDeclaringClass = rootDeclaringClass; this.declaringClass = declaringClass; T mergedAnnotation = (T) AnnotatedElementUtils.findMergedAnnotation( rootDeclaringClass, annotation.annotationType()); Assert.state(mergedAnnotation != null, () -> "Failed to find merged annotation for " + annotation); this.annotation = mergedAnnotation; } public Class<?> getRootDeclaringClass() { return this.rootDeclaringClass; } public Class<?> getDeclaringClass() { return this.declaringClass; } /** * Get the merged annotation for this descriptor. */ public T getAnnotation() { return this.annotation; } @SuppressWarnings("unchecked") Class<T> getAnnotationType() { return (Class<T>) this.annotation.annotationType(); } /** * Find the next {@link AnnotationDescriptor} for the specified annotation * type in the hierarchy above the {@linkplain #getRootDeclaringClass() * root declaring class} of this descriptor. * <p>If a corresponding annotation is found in the superclass hierarchy * of the root declaring class, that will be returned. Otherwise, an * attempt will be made to find a corresponding annotation in the * {@linkplain Class#getEnclosingClass() enclosing class} hierarchy of * the root declaring
AnnotationDescriptor
java
micronaut-projects__micronaut-core
http-client-core/src/main/java/io/micronaut/http/client/interceptor/HttpClientIntroductionAdvice.java
{ "start": 4929, "end": 34544 }
class ____ set up things like Headers, Cookies, Parameters for Clients. * * @param clientFactory The client factory * @param jsonMediaTypeCodec The JSON media type codec * @param transformers transformation classes * @param binderRegistry The client binder registry * @param conversionService The bean conversion context */ public HttpClientIntroductionAdvice( HttpClientRegistry<?> clientFactory, JsonMediaTypeCodec jsonMediaTypeCodec, List<ReactiveClientResultTransformer> transformers, HttpClientBinderRegistry binderRegistry, ConversionService conversionService) { this.clientFactory = clientFactory; this.jsonMediaTypeCodec = jsonMediaTypeCodec; this.transformers = transformers != null ? transformers : Collections.emptyList(); this.binderRegistry = binderRegistry; this.conversionService = conversionService; } /** * Interceptor to apply headers, cookies, parameter and body arguments. * * @param context The context * @return httpClient or future */ @Nullable @Override public Object intercept(MethodInvocationContext<Object, Object> context) { if (!context.hasStereotype(Client.class)) { throw new IllegalStateException("Client advice called from type that is not annotated with @Client: " + context); } final AnnotationMetadata annotationMetadata = context.getAnnotationMetadata(); Class<?> declaringType = context.getDeclaringType(); if (Closeable.class == declaringType || AutoCloseable.class == declaringType) { clientFactory.disposeClient(annotationMetadata); return null; } Optional<Class<? extends Annotation>> httpMethodMapping = context.getAnnotationTypeByStereotype(HttpMethodMapping.class); HttpClient httpClient = clientFactory.getClient(annotationMetadata); if (httpMethodMapping.isPresent() && context.hasStereotype(HttpMethodMapping.class) && httpClient != null) { AnnotationValue<HttpMethodMapping> mapping = context.getAnnotation(HttpMethodMapping.class); String uri = mapping.getRequiredValue(String.class); if (StringUtils.isEmpty(uri)) { uri = "/" + context.getMethodName(); } Class<? extends Annotation> annotationType = httpMethodMapping.get(); HttpMethod httpMethod = HttpMethod.parse(annotationType.getSimpleName().toUpperCase(Locale.ENGLISH)); String httpMethodName = context.stringValue(CustomHttpMethod.class, "method").orElse(httpMethod.name()); InterceptedMethod interceptedMethod = InterceptedMethod.of(context, conversionService); Argument<?> errorType = annotationMetadata.classValue(Client.class, "errorType") .map(errorClass -> Argument.of(errorClass)).orElse(HttpClient.DEFAULT_ERROR_TYPE); ReturnType<?> returnType = context.getReturnType(); try { Argument<?> valueType = interceptedMethod.returnTypeValue(); Class<?> reactiveValueType = valueType.getType(); return switch (interceptedMethod.resultType()) { case PUBLISHER -> handlePublisher(context, returnType, reactiveValueType, httpMethod, httpMethodName, uri, interceptedMethod, annotationMetadata, httpClient, errorType, valueType, declaringType); case COMPLETION_STAGE -> handleCompletionStage(context, httpMethod, httpMethodName, uri, interceptedMethod, annotationMetadata, httpClient, returnType, errorType, valueType, reactiveValueType, declaringType); case SYNCHRONOUS -> handleSynchronous(context, returnType, httpClient, httpMethod, httpMethodName, uri, interceptedMethod, annotationMetadata, errorType, declaringType); }; } catch (Exception e) { return interceptedMethod.handleException(e); } } // try other introduction advice return context.proceed(); } @Nullable private Object handleSynchronous(MethodInvocationContext<Object, Object> context, ReturnType<?> returnType, HttpClient httpClient, HttpMethod httpMethod, String httpMethodName, String uriToBind, InterceptedMethod interceptedMethod, AnnotationMetadata annotationMetadata, Argument<?> errorType, Class<?> declaringType) { Class<?> javaReturnType = returnType.getType(); BlockingHttpClient blockingHttpClient = httpClient.toBlocking(); RequestBinderResult binderResult = bindRequest(context, httpMethod, httpMethodName, uriToBind, interceptedMethod, annotationMetadata); String clientName = declaringType.getName(); if (binderResult.isError()) { return binderResult.errorResult; } MutableHttpRequest<?> request = binderResult.request; if (void.class == javaReturnType || httpMethod == HttpMethod.HEAD) { request.getHeaders().remove(HttpHeaders.ACCEPT); } if (HttpResponse.class.isAssignableFrom(javaReturnType)) { return handleBlockingCall( clientName, javaReturnType, () -> blockingHttpClient.exchange(request, returnType.asArgument().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT), errorType )); } else if (void.class == javaReturnType) { return handleBlockingCall(clientName, javaReturnType, () -> blockingHttpClient.exchange(request, null, errorType)); } else { return handleBlockingCall(clientName, javaReturnType, () -> blockingHttpClient.retrieve(request, returnType.asArgument(), errorType)); } } private Object handleCompletionStage(MethodInvocationContext<Object, Object> context, HttpMethod httpMethod, String httpMethodName, String uriToBind, InterceptedMethod interceptedMethod, AnnotationMetadata annotationMetadata, HttpClient httpClient, ReturnType<?> returnType, Argument<?> errorType, Argument<?> valueType, Class<?> reactiveValueType, Class<?> declaringType) { Publisher<RequestBinderResult> csRequestPublisher = Mono.fromCallable(() -> bindRequest(context, httpMethod, httpMethodName, uriToBind, interceptedMethod, annotationMetadata)); Publisher<?> csPublisher = httpClientResponsePublisher(httpClient, csRequestPublisher, returnType, errorType, valueType); CompletableFuture<Object> future = new CompletableFuture<>(); csPublisher.subscribe(new CompletionAwareSubscriber<Object>() { Object message; Subscription subscription; @Override protected void doOnSubscribe(Subscription subscription) { this.subscription = subscription; subscription.request(Long.MAX_VALUE); } @Override protected void doOnNext(Object message) { if (Void.class != reactiveValueType) { this.message = message; } // we only want the first item subscription.cancel(); doOnComplete(); } @Override protected void doOnError(Throwable t) { if (LOG.isDebugEnabled()) { LOG.debug("Client [{}] received HTTP error response: {}", declaringType.getName(), t.getMessage(), t); } if (t instanceof HttpClientResponseException e) { if (e.code() == HttpStatus.NOT_FOUND.getCode()) { if (reactiveValueType == Optional.class) { future.complete(Optional.empty()); } else if (HttpResponse.class.isAssignableFrom(reactiveValueType)) { future.complete(e.getResponse()); } else { future.complete(null); } return; } } future.completeExceptionally(t); } @Override protected void doOnComplete() { // can be called twice future.complete(message); } }); return interceptedMethod.handleResult(future); } private Object handlePublisher(MethodInvocationContext<Object, Object> context, ReturnType<?> returnType, Class<?> reactiveValueType, HttpMethod httpMethod, String httpMethodName, String uriToBind, InterceptedMethod interceptedMethod, AnnotationMetadata annotationMetadata, HttpClient httpClient, Argument<?> errorType, Argument<?> valueType, Class<?> declaringType) { boolean isSingle = returnType.isSingleResult() || returnType.isCompletable() || HttpResponse.class.isAssignableFrom(reactiveValueType) || HttpStatus.class == reactiveValueType; Publisher<RequestBinderResult> requestPublisher = Mono.fromCallable(() -> bindRequest(context, httpMethod, httpMethodName, uriToBind, interceptedMethod, annotationMetadata)); Publisher<?> publisher; if (!isSingle && httpClient instanceof StreamingHttpClient client) { publisher = httpClientResponseStreamingPublisher(client, context, requestPublisher, errorType, valueType); } else { publisher = httpClientResponsePublisher(httpClient, requestPublisher, returnType, errorType, valueType); } if (LOG.isDebugEnabled()) { publisher = Flux.from(publisher).doOnError(t -> LOG.debug("Client [{}] received HTTP error response: {}", declaringType.getName(), t.getMessage(), t) ); } Object finalPublisher = interceptedMethod.handleResult(publisher); for (ReactiveClientResultTransformer transformer : transformers) { finalPublisher = transformer.transform(finalPublisher); } return finalPublisher; } @NonNull private RequestBinderResult bindRequest(MethodInvocationContext<Object, Object> context, HttpMethod httpMethod, String httpMethodName, String uri, InterceptedMethod interceptedMethod, AnnotationMetadata annotationMetadata) { MutableHttpRequest<?> request = HttpRequest.create(httpMethod, "", httpMethodName); UriMatchTemplate uriTemplate = UriMatchTemplate.of(""); if (!(uri.length() == 1 && uri.charAt(0) == '/')) { uriTemplate = uriTemplate.nest(uri); } Map<String, Object> pathParams = new HashMap<>(); Map<String, List<String>> queryParams = new LinkedHashMap<>(); ClientRequestUriContext uriContext = new ClientRequestUriContext(uriTemplate, pathParams, queryParams); List<Argument<?>> bodyArguments = new ArrayList<>(); List<String> uriVariables = uriTemplate.getVariableNames(); Map<String, MutableArgumentValue<?>> parameters = context.getParameters(); ClientArgumentRequestBinder<Object> defaultBinder = buildDefaultBinder(pathParams, bodyArguments); // Apply all the method binders List<Class<? extends Annotation>> methodBinderTypes = context.getAnnotationTypesByStereotype(Bindable.class); // @Version is not a bindable, so it needs to looked for separately methodBinderTypes.addAll(context.getAnnotationTypesByStereotype(Version.class)); if (!CollectionUtils.isEmpty(methodBinderTypes)) { for (Class<? extends Annotation> binderType : methodBinderTypes) { binderRegistry.findAnnotatedBinder(binderType).ifPresent(b -> b.bind(context, uriContext, request)); } } // Apply all the argument binders Optional<Object> bindingErrorResult = bindArguments(context, parameters, defaultBinder, uriContext, request, interceptedMethod); if (bindingErrorResult.isPresent()) { return RequestBinderResult.withErrorResult(bindingErrorResult.get()); } Object body = bindRequestBody(request, bodyArguments, parameters); bindPathParams(uriVariables, pathParams, body); if (!HttpMethod.permitsRequestBody(httpMethod)) { // If a binder set the body and the method does not permit it, reset to null request.body(null); body = null; } uri = uriTemplate.expand(pathParams); // Remove all the pathParams that have already been used. // Other path parameters are added to query uriVariables.forEach(pathParams::remove); addParametersToQuery(pathParams, uriContext); // The original query can be added by getting it from the request.getUri() and appending request.uri(URI.create(appendQuery(uri, uriContext.getQueryParameters()))); final MediaType[] acceptTypes; Collection<MediaType> accept = request.accept(); var definitionType = annotationMetadata.enumValue(Client.class, "definitionType", Client.DefinitionType.class) .orElse(Client.DefinitionType.CLIENT); if (accept.isEmpty()) { String[] consumesMediaType = context.stringValues(definitionType.isClient() ? Consumes.class : Produces.class); if (ArrayUtils.isEmpty(consumesMediaType)) { acceptTypes = DEFAULT_ACCEPT_TYPES; } else { acceptTypes = MediaType.of(consumesMediaType); } request.accept(acceptTypes); } if (body != null && request.getContentType().isEmpty()) { MediaType[] contentTypes = MediaType.of(context.stringValues(definitionType.isClient() ? Produces.class : Consumes.class)); if (ArrayUtils.isEmpty(contentTypes)) { contentTypes = DEFAULT_ACCEPT_TYPES; } if (ArrayUtils.isNotEmpty(contentTypes)) { request.contentType(contentTypes[0]); } } ClientAttributes.setInvocationContext(request, context); // Set the URI template used to make the request for tracing purposes BasicHttpAttributes.setUriTemplate(request, resolveTemplate(annotationMetadata, uriTemplate.toString())); return RequestBinderResult.withRequest(request); } private void bindPathParams(List<String> uriVariables, Map<String, Object> pathParams, Object body) { boolean variableSatisfied = uriVariables.isEmpty() || pathParams.keySet().containsAll(uriVariables); if (body != null && !variableSatisfied) { if (body instanceof Map<?, ?> map) { for (Map.Entry<?, ?> entry : map.entrySet()) { String k = entry.getKey().toString(); Object v = entry.getValue(); if (v != null) { pathParams.putIfAbsent(k, v); } } } else if (!Publishers.isConvertibleToPublisher(body)) { BeanMap<Object> beanMap = BeanMap.of(body); for (Map.Entry<String, Object> entry : beanMap.entrySet()) { String k = entry.getKey(); Object v = entry.getValue(); if (v != null) { pathParams.putIfAbsent(k, v); } } } } } @Nullable private Object bindRequestBody(MutableHttpRequest<?> request, List<Argument<?>> bodyArguments, Map<String, MutableArgumentValue<?>> parameters) { Object body = request.getBody().orElse(null); if (body == null && !bodyArguments.isEmpty()) { Map<String, Object> bodyMap = new LinkedHashMap<>(); for (Argument<?> bodyArgument : bodyArguments) { String argumentName = bodyArgument.getName(); MutableArgumentValue<?> value = parameters.get(argumentName); if (bodyArgument.getAnnotationMetadata().hasStereotype(Format.class)) { conversionService.convert(value.getValue(), ConversionContext.STRING.with(bodyArgument.getAnnotationMetadata())) .ifPresent(v -> bodyMap.put(argumentName, v)); } else { bodyMap.put(argumentName, value.getValue()); } } body = bodyMap; request.body(body); } return body; } @NonNull private ClientArgumentRequestBinder<Object> buildDefaultBinder(Map<String, Object> pathParams, List<Argument<?>> bodyArguments) { return (ctx, uriCtx, value, req) -> { Argument<?> argument = ctx.getArgument(); if (uriCtx.getUriTemplate().getVariableNames().contains(argument.getName())) { String name = argument.getAnnotationMetadata().stringValue(Bindable.class) .orElse(argument.getName()); // Convert and put as path param if (argument.getAnnotationMetadata().hasStereotype(Format.class)) { conversionService.convert(value, ConversionContext.STRING.with(argument.getAnnotationMetadata())) .ifPresent(v -> pathParams.put(name, v)); } else { pathParams.put(name, value); } } else { bodyArguments.add(ctx.getArgument()); } }; } @NonNull private Optional<Object> bindArguments(MethodInvocationContext<Object, Object> context, Map<String, MutableArgumentValue<?>> parameters, ClientArgumentRequestBinder<Object> defaultBinder, ClientRequestUriContext uriContext, MutableHttpRequest<?> request, InterceptedMethod interceptedMethod) { Optional<Object> bindingErrorResult = Optional.empty(); Argument<?>[] arguments = context.getArguments(); for (Argument<?> argument : arguments) { Object definedValue = getValue(argument, context, parameters); if (definedValue != null) { final ClientArgumentRequestBinder<Object> binder = (ClientArgumentRequestBinder<Object>) binderRegistry .findArgumentBinder((Argument<Object>) argument) .orElse(defaultBinder); ArgumentConversionContext conversionContext = ConversionContext.of(argument); binder.bind(conversionContext, uriContext, definedValue, request); if (conversionContext.hasErrors()) { return conversionContext.getLastError().map(e -> interceptedMethod.handleException(new ConversionErrorException(argument, e))); } } } return bindingErrorResult; } private Publisher<?> httpClientResponsePublisher(HttpClient httpClient, Publisher<RequestBinderResult> requestPublisher, ReturnType<?> returnType, Argument<?> errorType, Argument<?> reactiveValueArgument) { Flux<RequestBinderResult> requestFlux = Flux.from(requestPublisher); return requestFlux.filter(result -> !result.isError).map(RequestBinderResult::request).flatMap(request -> { Class<?> argumentType = reactiveValueArgument.getType(); if (Void.class == argumentType || returnType.isVoid()) { request.getHeaders().remove(HttpHeaders.ACCEPT); return httpClient.retrieve(request, Argument.VOID, errorType); } else { if (HttpResponse.class.isAssignableFrom(argumentType)) { return httpClient.exchange(request, reactiveValueArgument, errorType); } return httpClient.retrieve(request, reactiveValueArgument, errorType); } }).switchIfEmpty(requestFlux.mapNotNull(RequestBinderResult::errorResult)); } private Publisher<?> httpClientResponseStreamingPublisher(StreamingHttpClient streamingHttpClient, MethodInvocationContext<Object, Object> context, Publisher<RequestBinderResult> requestPublisher, Argument<?> errorType, Argument<?> reactiveValueArgument) { Flux<RequestBinderResult> requestFlux = Flux.from(requestPublisher); return requestFlux.filter(result -> !result.isError()).map(RequestBinderResult::request).flatMap(request -> { Class<?> reactiveValueType = reactiveValueArgument.getType(); if (Void.class == reactiveValueType) { request.getHeaders().remove(HttpHeaders.ACCEPT); } Collection<MediaType> acceptTypes = request.accept(); if (streamingHttpClient instanceof SseClient sseClient && acceptTypes.contains(MediaType.TEXT_EVENT_STREAM_TYPE)) { if (reactiveValueArgument.getType() == Event.class) { return sseClient.eventStream( request, reactiveValueArgument.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT), errorType ); } return Publishers.map(sseClient.eventStream(request, reactiveValueArgument, errorType), Event::getData); } else { if (isJsonParsedMediaType(acceptTypes)) { return streamingHttpClient.jsonStream(request, reactiveValueArgument, errorType); } else { Publisher<ByteBuffer<?>> byteBufferPublisher = streamingHttpClient.dataStream(request, errorType); if (reactiveValueType == ByteBuffer.class) { return byteBufferPublisher; } else { if (conversionService.canConvert(ByteBuffer.class, reactiveValueType)) { // It would be nice if we could capture the TypeConverter here return Publishers.map(byteBufferPublisher, value -> conversionService.convert(value, reactiveValueType).get()); } else { return Flux.error(new ConfigurationException("Cannot create the generated HTTP client's " + "required return type, since no TypeConverter from ByteBuffer to " + reactiveValueType + " is registered")); } } } } }).switchIfEmpty(requestFlux.mapNotNull(RequestBinderResult::errorResult)); } private Object getValue(Argument argument, MethodInvocationContext<?, ?> context, Map<String, MutableArgumentValue<?>> parameters) { String argumentName = argument.getName(); MutableArgumentValue<?> value = parameters.get(argumentName); Object definedValue = value.getValue(); if (definedValue == null) { definedValue = argument.getAnnotationMetadata().stringValue(Bindable.class, "defaultValue").orElse(null); } if (definedValue == null && !argument.isNullable()) { throw new IllegalArgumentException( ("Argument [%s] is null. Null values are not allowed to be passed to client methods (%s). Add a supported Nullable " + "annotation type if that is the desired behaviour").formatted(argument.getName(), context.getExecutableMethod().toString()) ); } if (definedValue instanceof Optional optional) { return optional.orElse(null); } else { return definedValue; } } private Object handleBlockingCall(String clientName, Class returnType, Supplier<Object> supplier) { try { if (void.class == returnType) { supplier.get(); return null; } else { return supplier.get(); } } catch (RuntimeException t) { if (LOG.isDebugEnabled()) { LOG.debug("Client [{}] received HTTP error response: {}", clientName, t.getMessage(), t); } if (t instanceof HttpClientResponseException exception && exception.code() == HttpStatus.NOT_FOUND.getCode()) { if (returnType == Optional.class) { return Optional.empty(); } else if (HttpResponse.class.isAssignableFrom(returnType)) { return exception.getResponse(); } return null; } else { throw t; } } } private boolean isJsonParsedMediaType(Collection<MediaType> acceptTypes) { return acceptTypes.stream().anyMatch(mediaType -> mediaType.equals(MediaType.APPLICATION_JSON_STREAM_TYPE) || mediaType.getExtension().equals(MediaType.EXTENSION_JSON) || jsonMediaTypeCodec.getMediaTypes().contains(mediaType) ); } /** * Resolve the template for the client annotation. * * @param annotationMetadata client annotation reference * @param templateString template to be applied * @return resolved template contents */ private String resolveTemplate(AnnotationMetadata annotationMetadata, String templateString) { String path = annotationMetadata.stringValue(Client.class, "path").orElse(null); if (StringUtils.isNotEmpty(path)) { return path + templateString; } else { String value = getClientId(annotationMetadata); if (StringUtils.isNotEmpty(value) && value.startsWith("/")) { return value + templateString; } return templateString; } } private String getClientId(AnnotationMetadata clientAnn) { return clientAnn.stringValue(Client.class).orElse(null); } private void addParametersToQuery(Map<String, Object> parameters, ClientRequestUriContext uriContext) { for (Map.Entry<String, Object> entry: parameters.entrySet()) { conversionService.convert(entry.getValue(), ConversionContext.STRING).ifPresent(v -> { conversionService.convert(entry.getKey(), ConversionContext.STRING).ifPresent(k -> { uriContext.addQueryParameter(k, v); }); }); } } private String appendQuery(String uri, Map<String, List<String>> queryParams) { if (!queryParams.isEmpty()) { final UriBuilder builder = UriBuilder.of(uri); for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) { builder.queryParam(entry.getKey(), entry.getValue().toArray()); } return builder.toString(); } return uri; } private record RequestBinderResult( @Nullable MutableHttpRequest<?> request, @Nullable Object errorResult, boolean isError ) { static RequestBinderResult withRequest(@NonNull MutableHttpRequest<?> request) { Objects.requireNonNull(request, "Bound HTTP request must not be null"); return new RequestBinderResult(request, null, false); } static RequestBinderResult withErrorResult(@Nullable Object errorResult) { return new RequestBinderResult(null, errorResult, true); } } }
to
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/api/AsyncCloseable.java
{ "start": 320, "end": 758 }
interface ____ extends io.lettuce.core.internal.AsyncCloseable { /** * Requests to close this object and releases any system resources associated with it. If the object is already closed then * invoking this method has no effect. * <p> * Calls to this method return a {@link CompletableFuture} that is notified with the outcome of the close request. */ CompletableFuture<Void> closeAsync(); }
AsyncCloseable