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__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/config/configcenter/AbstractDynamicConfigurationFactoryTest.java
{ "start": 1235, "end": 1844 }
class ____ { private AbstractDynamicConfigurationFactory factory; @BeforeEach public void init() { factory = new AbstractDynamicConfigurationFactory() { @Override protected DynamicConfiguration createDynamicConfiguration(URL url) { return new NopDynamicConfiguration(url); } }; } @Test void testGetDynamicConfiguration() { URL url = URL.valueOf("nop://127.0.0.1"); assertEquals(factory.getDynamicConfiguration(url), factory.getDynamicConfiguration(url)); } }
AbstractDynamicConfigurationFactoryTest
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/extension/ExecutableInvoker.java
{ "start": 804, "end": 2291 }
interface ____ { /** * Invoke the supplied {@code static} method with dynamic parameter resolution. * * @param method the method to invoke and resolve parameters for * @see #invoke(Method, Object) */ default @Nullable Object invoke(Method method) { return invoke(method, null); } /** * Invoke the supplied method with dynamic parameter resolution. * * @param method the method to invoke and resolve parameters for * @param target the target on which the executable will be invoked; * can be {@code null} for {@code static} methods */ @Nullable Object invoke(Method method, @Nullable Object target); /** * Invoke the supplied top-level constructor with dynamic parameter resolution. * * @param constructor the constructor to invoke and resolve parameters for * @see #invoke(Constructor, Object) */ default <T> T invoke(Constructor<T> constructor) { return invoke(constructor, null); } /** * Invoke the supplied constructor with the supplied outer instance and * dynamic parameter resolution. * * <p>Use this method when invoking the constructor for an <em>inner</em> class. * * @param constructor the constructor to invoke and resolve parameters for * @param outerInstance the outer instance to supply as the first argument * to the constructor; must be {@code null} for top-level classes * or {@code static} nested classes */ <T> T invoke(Constructor<T> constructor, @Nullable Object outerInstance); }
ExecutableInvoker
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest101_geometry.java
{ "start": 329, "end": 978 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "CREATE TABLE geom (g GEOMETRY NOT NULL);"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals(1, stmt.getTableElementList().size()); assertEquals("CREATE TABLE geom (\n" + "\tg GEOMETRY NOT NULL\n" + ");", stmt.toString()); } }
MySqlCreateTableTest101_geometry
java
alibaba__nacos
client-basic/src/main/java/com/alibaba/nacos/client/auth/ram/identify/CredentialService.java
{ "start": 950, "end": 3612 }
class ____ implements SpasCredentialLoader { private static final Logger LOGGER = LoggerFactory.getLogger(CredentialService.class); private static final ConcurrentHashMap<String, CredentialService> INSTANCES = new ConcurrentHashMap<>(); private final String appName; private Credentials credentials = new Credentials(); private final CredentialWatcher watcher; private CredentialListener listener; private CredentialService(String appName) { if (appName == null) { String value = NacosClientProperties.PROTOTYPE.getProperty(IdentifyConstants.PROJECT_NAME_PROPERTY); if (StringUtils.isNotEmpty(value)) { appName = value; } } this.appName = appName; watcher = new CredentialWatcher(appName, this); } public static CredentialService getInstance() { return getInstance(null); } public static CredentialService getInstance(String appName) { String key = appName != null ? appName : IdentifyConstants.NO_APP_NAME; return INSTANCES.computeIfAbsent(key, k -> new CredentialService(appName)); } public static CredentialService freeInstance() { return freeInstance(null); } /** * Free instance. * * @param appName app name * @return {@link CredentialService} */ public static CredentialService freeInstance(String appName) { String key = appName != null ? appName : IdentifyConstants.NO_APP_NAME; CredentialService instance = INSTANCES.remove(key); if (instance != null) { instance.free(); } return instance; } /** * Free service. */ public void free() { if (watcher != null) { watcher.stop(); } LOGGER.info("[{}] {} is freed", appName, this.getClass().getSimpleName()); } @Override public Credentials getCredential() { return credentials; } public void setCredential(Credentials credential) { boolean changed = !(credentials == credential || (credentials != null && credentials.identical(credential))); credentials = credential; if (changed && listener != null) { listener.onUpdateCredential(); } } public void setStaticCredential(Credentials credential) { if (watcher != null) { watcher.stop(); } setCredential(credential); } public void registerCredentialListener(CredentialListener listener) { this.listener = listener; } }
CredentialService
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/service/ConfigOperationService.java
{ "start": 2690, "end": 16218 }
class ____ { private ConfigInfoPersistService configInfoPersistService; private ConfigInfoGrayPersistService configInfoGrayPersistService; private ConfigMigrateService configMigrateService; private static final Logger LOGGER = LoggerFactory.getLogger(ConfigOperationService.class); public ConfigOperationService(ConfigInfoPersistService configInfoPersistService, ConfigInfoGrayPersistService configInfoGrayPersistService, ConfigMigrateService configMigrateService) { this.configInfoPersistService = configInfoPersistService; this.configInfoGrayPersistService = configInfoGrayPersistService; this.configMigrateService = configMigrateService; } /** * Adds or updates non-aggregated data. * * @throws NacosException NacosException. */ @SuppressWarnings("PMD.MethodTooLongRule") public Boolean publishConfig(ConfigForm configForm, ConfigRequestInfo configRequestInfo, String encryptedDataKey) throws NacosException { Map<String, Object> configAdvanceInfo = getConfigAdvanceInfo(configForm); ParamUtils.checkParam(configAdvanceInfo); configForm.setEncryptedDataKey(encryptedDataKey); ConfigInfo configInfo = new ConfigInfo(configForm.getDataId(), configForm.getGroup(), configForm.getNamespaceId(), configForm.getAppName(), configForm.getContent()); //set old md5 if (StringUtils.isNotBlank(configRequestInfo.getCasMd5())) { configInfo.setMd5(configRequestInfo.getCasMd5()); } configInfo.setType(configForm.getType()); configInfo.setEncryptedDataKey(encryptedDataKey); //beta publish if (StringUtils.isNotBlank(configRequestInfo.getBetaIps())) { configForm.setGrayName(BetaGrayRule.TYPE_BETA); configForm.setGrayRuleExp(configRequestInfo.getBetaIps()); configForm.setGrayVersion(BetaGrayRule.VERSION); configMigrateService.persistBeta(configForm, configInfo, configRequestInfo); configForm.setGrayPriority(Integer.MAX_VALUE); configMigrateService.publishConfigGrayMigrate(BetaGrayRule.TYPE_BETA, configForm, configRequestInfo); publishConfigGray(BetaGrayRule.TYPE_BETA, configForm, configRequestInfo); return Boolean.TRUE; } // tag publish if (StringUtils.isNotBlank(configForm.getTag())) { configForm.setGrayName(TagGrayRule.TYPE_TAG + "_" + configForm.getTag()); configForm.setGrayRuleExp(configForm.getTag()); configForm.setGrayVersion(TagGrayRule.VERSION); configForm.setGrayPriority(Integer.MAX_VALUE - 1); configMigrateService.persistTagv1(configForm, configInfo, configRequestInfo); configMigrateService.publishConfigGrayMigrate(TagGrayRule.TYPE_TAG, configForm, configRequestInfo); publishConfigGray(TagGrayRule.TYPE_TAG, configForm, configRequestInfo); return Boolean.TRUE; } ConfigOperateResult configOperateResult; configMigrateService.publishConfigMigrate(configForm, configRequestInfo, configForm.getEncryptedDataKey()); //formal publish if (StringUtils.isNotBlank(configRequestInfo.getCasMd5())) { configOperateResult = configInfoPersistService.insertOrUpdateCas(configRequestInfo.getSrcIp(), configForm.getSrcUser(), configInfo, configAdvanceInfo); if (!configOperateResult.isSuccess()) { LOGGER.warn( "[cas-publish-config-fail] srcIp = {}, dataId= {}, casMd5 = {}, msg = server md5 may have changed.", configRequestInfo.getSrcIp(), configForm.getDataId(), configRequestInfo.getCasMd5()); throw new NacosApiException(HttpStatus.INTERNAL_SERVER_ERROR.value(), ErrorCode.RESOURCE_CONFLICT, "Cas publish fail, server md5 may have changed."); } } else { if (configRequestInfo.getUpdateForExist()) { configOperateResult = configInfoPersistService.insertOrUpdate(configRequestInfo.getSrcIp(), configForm.getSrcUser(), configInfo, configAdvanceInfo); } else { try { configOperateResult = configInfoPersistService.addConfigInfo(configRequestInfo.getSrcIp(), configForm.getSrcUser(), configInfo, configAdvanceInfo); } catch (DataIntegrityViolationException ive) { configOperateResult = new ConfigOperateResult(false); } } } if (!configOperateResult.isSuccess()) { LOGGER.warn("[publish-config-failed] config already exists. dataId: {}, group: {}, namespaceId: {}", configForm.getDataId(), configForm.getGroup(), configForm.getNamespaceId()); throw new ConfigAlreadyExistsException( String.format("config already exist, dataId: %s, group: %s, namespaceId: %s", configForm.getDataId(), configForm.getGroup(), configForm.getNamespaceId())); } ConfigChangePublisher.notifyConfigChange( new ConfigDataChangeEvent(configForm.getDataId(), configForm.getGroup(), configForm.getNamespaceId(), configOperateResult.getLastModified())); if (ConfigTagUtil.isIstio(configForm.getConfigTags())) { ConfigChangePublisher.notifyConfigChange( new IstioConfigChangeEvent(configForm.getDataId(), configForm.getGroup(), configForm.getNamespaceId(), configOperateResult.getLastModified(), configForm.getContent(), ConfigTagUtil.getIstioType(configForm.getConfigTags()))); } ConfigTraceService.logPersistenceEvent(configForm.getDataId(), configForm.getGroup(), configForm.getNamespaceId(), configRequestInfo.getRequestIpApp(), configOperateResult.getLastModified(), InetUtils.getSelfIP(), ConfigTraceService.PERSISTENCE_EVENT, ConfigTraceService.PERSISTENCE_TYPE_PUB, configForm.getContent()); return true; } /** * publish gray config tag v2. * * @param configForm ConfigForm * @param configRequestInfo ConfigRequestInfo * @return boolean * @throws NacosException NacosException. * @date 2024/2/5 */ private Boolean publishConfigGray(String grayType, ConfigForm configForm, ConfigRequestInfo configRequestInfo) throws NacosException { Map<String, Object> configAdvanceInfo = getConfigAdvanceInfo(configForm); ParamUtils.checkParam(configAdvanceInfo); ConfigGrayPersistInfo localConfigGrayPersistInfo = new ConfigGrayPersistInfo(grayType, configForm.getGrayVersion(), configForm.getGrayRuleExp(), configForm.getGrayPriority()); GrayRule grayRuleStruct = GrayRuleManager.constructGrayRule(localConfigGrayPersistInfo); if (grayRuleStruct == null) { throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.CONFIG_GRAY_VERSION_INVALID, ErrorCode.CONFIG_GRAY_VERSION_INVALID.getMsg()); } if (!grayRuleStruct.isValid()) { throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.CONFIG_GRAY_RULE_FORMAT_INVALID, ErrorCode.CONFIG_GRAY_RULE_FORMAT_INVALID.getMsg()); } //version count check. if (checkGrayVersionOverMaxCount(configForm.getDataId(), configForm.getGroup(), configForm.getNamespaceId(), configForm.getGrayName())) { throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.CONFIG_GRAY_OVER_MAX_VERSION_COUNT, "gray config version is over max count :" + getMaxGrayVersionCount()); } ConfigInfo configInfo = new ConfigInfo(configForm.getDataId(), configForm.getGroup(), configForm.getNamespaceId(), configForm.getAppName(), configForm.getContent()); configInfo.setType(configForm.getType()); configInfo.setEncryptedDataKey(configForm.getEncryptedDataKey()); ConfigOperateResult configOperateResult; if (StringUtils.isNotBlank(configRequestInfo.getCasMd5())) { configOperateResult = configInfoGrayPersistService.insertOrUpdateGrayCas(configInfo, configForm.getGrayName(), GrayRuleManager.serializeConfigGrayPersistInfo(localConfigGrayPersistInfo), configRequestInfo.getSrcIp(), configForm.getSrcUser()); if (!configOperateResult.isSuccess()) { LOGGER.warn( "[cas-publish-gray-config-fail] srcIp = {}, dataId= {}, casMd5 = {}, grayName = {}, msg = server md5 may have changed.", configRequestInfo.getSrcIp(), configForm.getDataId(), configRequestInfo.getCasMd5(), configForm.getGrayName()); throw new NacosApiException(HttpStatus.INTERNAL_SERVER_ERROR.value(), ErrorCode.RESOURCE_CONFLICT, "Cas publish gray config fail, server md5 may have changed."); } } else { configOperateResult = configInfoGrayPersistService.insertOrUpdateGray(configInfo, configForm.getGrayName(), GrayRuleManager.serializeConfigGrayPersistInfo(localConfigGrayPersistInfo), configRequestInfo.getSrcIp(), configForm.getSrcUser()); } ConfigChangePublisher.notifyConfigChange( new ConfigDataChangeEvent(configForm.getDataId(), configForm.getGroup(), configForm.getNamespaceId(), configForm.getGrayName(), configOperateResult.getLastModified())); String eventType = ConfigTraceService.PERSISTENCE_EVENT + "-" + configForm.getGrayName(); ConfigTraceService.logPersistenceEvent(configForm.getDataId(), configForm.getGroup(), configForm.getNamespaceId(), configRequestInfo.getRequestIpApp(), configOperateResult.getLastModified(), InetUtils.getSelfIP(), eventType, ConfigTraceService.PERSISTENCE_TYPE_PUB, configForm.getContent()); return true; } private boolean checkGrayVersionOverMaxCount(String dataId, String group, String tenant, String grayName) { List<String> configInfoGrays = configInfoGrayPersistService.findConfigInfoGrays(dataId, group, tenant); if (configInfoGrays == null || configInfoGrays.isEmpty()) { return false; } else { if (configInfoGrays.contains(grayName)) { return false; } return configInfoGrays.size() >= getMaxGrayVersionCount(); } } private static final int DEFAULT_MAX_GRAY_VERSION_COUNT = 10; private int getMaxGrayVersionCount() { String value = EnvUtil.getProperty("nacos.config.gray.version.max.count", ""); return NumberUtils.isDigits(value) ? NumberUtils.toInt(value) : DEFAULT_MAX_GRAY_VERSION_COUNT; } /** * Synchronously delete all pre-aggregation data under a dataId. */ public Boolean deleteConfig(String dataId, String group, String namespaceId, String grayName, String clientIp, String srcUser, String srcType) { String persistEvent = ConfigTraceService.PERSISTENCE_EVENT; if (StringUtils.isBlank(grayName)) { configInfoPersistService.removeConfigInfo(dataId, group, namespaceId, clientIp, srcUser); configMigrateService.removeConfigInfoMigrate(dataId, group, namespaceId, clientIp, srcUser); } else { persistEvent = ConfigTraceService.PERSISTENCE_EVENT + "-" + grayName; configInfoGrayPersistService.removeConfigInfoGray(dataId, group, namespaceId, grayName, clientIp, srcUser); configMigrateService.deleteConfigGrayV1(dataId, group, namespaceId, grayName, clientIp, srcUser); configMigrateService.removeConfigInfoGrayMigrate(dataId, group, namespaceId, grayName, clientIp, srcUser); } final Timestamp time = TimeUtils.getCurrentTime(); ConfigTraceService.logPersistenceEvent(dataId, group, namespaceId, null, time.getTime(), clientIp, persistEvent, ConfigTraceService.PERSISTENCE_TYPE_REMOVE, null); ConfigChangePublisher.notifyConfigChange( new ConfigDataChangeEvent(dataId, group, namespaceId, grayName, time.getTime())); return true; } public Map<String, Object> getConfigAdvanceInfo(ConfigForm configForm) { Map<String, Object> configAdvanceInfo = new HashMap<>(10); MapUtil.putIfValNoNull(configAdvanceInfo, "config_tags", configForm.getConfigTags()); MapUtil.putIfValNoNull(configAdvanceInfo, "desc", configForm.getDesc()); MapUtil.putIfValNoNull(configAdvanceInfo, "use", configForm.getUse()); MapUtil.putIfValNoNull(configAdvanceInfo, "effect", configForm.getEffect()); MapUtil.putIfValNoNull(configAdvanceInfo, "type", configForm.getType()); MapUtil.putIfValNoNull(configAdvanceInfo, "schema", configForm.getSchema()); return configAdvanceInfo; } }
ConfigOperationService
java
apache__camel
components/camel-fop/src/main/java/org/apache/camel/component/fop/FopEndpoint.java
{ "start": 1651, "end": 4674 }
class ____ extends DefaultEndpoint { @UriPath @Metadata(required = true) private FopOutputType outputType; @UriParam @Metadata(supportFileReference = true) private String userConfigURL; @UriParam private FopFactory fopFactory; public FopEndpoint(String uri, FopComponent component, FopOutputType outputType) { super(uri, component); this.outputType = outputType; } @Override public boolean isRemote() { return false; } @Override public Producer createProducer() throws Exception { return new FopProducer(this, fopFactory, outputType.getFormatExtended()); } @Override public Consumer createConsumer(Processor processor) throws Exception { throw new UnsupportedOperationException("Consumer not supported for FOP endpoint"); } public FopOutputType getOutputType() { return outputType; } /** * The primary output format is PDF but other output formats are also supported. */ public void setOutputType(FopOutputType outputType) { this.outputType = outputType; } public String getUserConfigURL() { return userConfigURL; } /** * The location of a configuration file which can be loaded from classpath or file system. */ public void setUserConfigURL(String userConfigURL) { this.userConfigURL = userConfigURL; } public FopFactory getFopFactory() { return fopFactory; } /** * Allows to use a custom configured or implementation of org.apache.fop.apps.FopFactory. */ public void setFopFactory(FopFactory fopFactory) { this.fopFactory = fopFactory; } @Override protected void doInit() throws Exception { super.doInit(); if (fopFactory == null && userConfigURL == null) { fopFactory = FopFactory.newInstance(new URI("./")); } else if (fopFactory != null && userConfigURL != null) { throw new FopConfigException( "More than one configuration. " + "You can configure fop either by config file or by supplying FopFactory but not both."); } else if (fopFactory == null && userConfigURL != null) { if (ResourceHelper.isClasspathUri(userConfigURL)) { InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), userConfigURL); fopFactory = FopFactory.newInstance(new URI(userConfigURL), is); } } } @Override protected void doStart() throws Exception { super.doStart(); if (fopFactory == null && userConfigURL != null) { if (!ResourceHelper.isClasspathUri(userConfigURL)) { InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), userConfigURL); fopFactory = FopFactory.newInstance(new URI(userConfigURL), is); } } } }
FopEndpoint
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/sql/partition/SQLServerPartitionedTableTest.java
{ "start": 1387, "end": 1911 }
class ____ { @Test void test(EntityManagerFactoryScope scope) { scope.inTransaction( session -> { Partitioned partitioned = new Partitioned(); partitioned.id = 1L; partitioned.pid = 500L; session.persist( partitioned ); } ); scope.inTransaction( session -> { Partitioned partitioned = session.find( Partitioned.class, 1L ); assertNotNull( partitioned ); partitioned.text = "updated"; } ); } @Entity @Table(name = "msparts", options = "on partScheme(pid)") static
SQLServerPartitionedTableTest
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringRouteWithConstantFieldFromExchangeFailTest.java
{ "start": 1063, "end": 1409 }
class ____ extends RouteWithConstantFieldFromExchangeFailTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/RouteWithConstantFieldFromExchangeFailTest.xml"); } }
SpringRouteWithConstantFieldFromExchangeFailTest
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/util/GeneratedClass.java
{ "start": 67, "end": 305 }
class ____ { final String name; final byte[] data; public GeneratedClass(String name, byte[] data) { if (name.endsWith(".class")) { throw new RuntimeException("resource name specified instead of
GeneratedClass
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DefaultLocaleTest.java
{ "start": 15039, "end": 17180 }
class ____ {", " void f(Locale locale, File file, OutputStream os) throws Exception {", " // BUG: Diagnostic contains: new Formatter(Locale.getDefault(FORMAT));", " new Formatter();", " // BUG: Diagnostic contains: new Formatter(new StringBuilder()," + " Locale.getDefault(FORMAT));", " new Formatter(new StringBuilder());", " // BUG: Diagnostic matches: NoFix", " new Formatter(\"filename\");", " // BUG: Diagnostic contains: new Formatter(\"filename\", \"utf8\"," + " Locale.getDefault(FORMAT));", " new Formatter(\"filename\", \"utf8\");", " // BUG: Diagnostic matches: NoFix", " new Formatter(file);", " // BUG: Diagnostic contains: new Formatter(file, \"utf8\"," + " Locale.getDefault(FORMAT));", " new Formatter(file, \"utf8\");", " // BUG: Diagnostic matches: NoFix", " new Formatter(System.out);", " // BUG: Diagnostic matches: NoFix", " new Formatter(os);", " // BUG: Diagnostic contains: new Formatter(os, \"utf8\"," + " Locale.getDefault(FORMAT));", " new Formatter(os, \"utf8\");", // negative " new Formatter(locale);", " new Formatter(new StringBuilder(), locale);", " new Formatter(\"filename\", \"utf8\", locale);", " new Formatter(\"filename\", UTF_8, locale);", " new Formatter(file, \"utf8\", locale);", " new Formatter(file, UTF_8, locale);", " new Formatter(os, \"utf8\", locale);", " new Formatter(os, UTF_8, locale);", " }", "}") .expectErrorMessage("NoFix", not(containsPattern("Did you mean"))) .doTest(); } @Test public void refactoringAddLocaleImport() { refactoringTest() .addInputLines( "Test.java", """ import java.text.*;
Test
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/results/internal/complete/CompleteResultBuilderBasicModelPart.java
{ "start": 893, "end": 3755 }
class ____ implements CompleteResultBuilderBasicValued, ModelPartReferenceBasic { private final NavigablePath navigablePath; private final BasicValuedModelPart modelPart; private final String columnAlias; public CompleteResultBuilderBasicModelPart( NavigablePath navigablePath, BasicValuedModelPart modelPart, String columnAlias) { this.navigablePath = navigablePath; this.modelPart = modelPart; this.columnAlias = columnAlias; } @Override public Class<?> getJavaType() { return modelPart.getExpressibleJavaType().getJavaTypeClass(); } @Override public NavigablePath getNavigablePath() { return navigablePath; } @Override public BasicValuedModelPart getReferencedPart() { return modelPart; } @Override public ResultBuilder cacheKeyInstance() { return this; } @Override public BasicResult<?> buildResult( JdbcValuesMetadata jdbcResultsMetadata, int resultPosition, DomainResultCreationState domainResultCreationState) { final DomainResultCreationStateImpl creationStateImpl = impl( domainResultCreationState ); final TableReference tableReference = tableReference( creationStateImpl ); final SqlSelection sqlSelection = sqlSelection( jdbcResultsMetadata, creationStateImpl, tableReference ); return new BasicResult<>( sqlSelection.getValuesArrayPosition(), columnAlias, modelPart.getJdbcMapping(), navigablePath, false, !sqlSelection.isVirtual() ); } private SqlSelection sqlSelection( JdbcValuesMetadata jdbcResultsMetadata, DomainResultCreationStateImpl creationStateImpl, TableReference tableReference) { return creationStateImpl.resolveSqlSelection( ResultsHelper.resolveSqlExpression( creationStateImpl, jdbcResultsMetadata, tableReference, modelPart, columnAlias ), modelPart.getJdbcMapping().getJdbcJavaType(), null, creationStateImpl.getSessionFactory().getTypeConfiguration() ); } private TableReference tableReference(DomainResultCreationStateImpl creationStateImpl) { return creationStateImpl.getFromClauseAccess() .getTableGroup( navigablePath.getParent() ) .resolveTableReference( navigablePath, modelPart, modelPart.getContainingTableExpression() ); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } final CompleteResultBuilderBasicModelPart that = (CompleteResultBuilderBasicModelPart) o; return navigablePath.equals( that.navigablePath ) && modelPart.equals( that.modelPart ) && columnAlias.equals( that.columnAlias ); } @Override public int hashCode() { int result = navigablePath.hashCode(); result = 31 * result + modelPart.hashCode(); result = 31 * result + columnAlias.hashCode(); return result; } }
CompleteResultBuilderBasicModelPart
java
apache__camel
components/camel-ldap/src/test/java/org/apache/camel/component/ldap/LdapRouteManualIT.java
{ "start": 2614, "end": 8308 }
class ____ extends AbstractLdapTestUnit { private CamelContext camel; private ProducerTemplate template; private int port; @BeforeEach public void setup() throws Exception { // you can assign port number in the @CreateTransport annotation port = super.getLdapServer().getPort(); LdapContext ctx = getWiredContext(ldapServer); SimpleRegistry reg = new SimpleRegistry(); reg.bind("localhost:" + port, ctx); camel = new DefaultCamelContext(reg); template = camel.createProducerTemplate(); } @AfterEach public void tearDown() { camel.stop(); } @Test public void testLdapRouteStandard() throws Exception { camel.addRoutes(createRouteBuilder("ldap:localhost:" + port + "?base=ou=system")); camel.start(); // START SNIPPET: invoke Endpoint endpoint = camel.getEndpoint("direct:start"); Exchange exchange = endpoint.createExchange(); // then we set the LDAP filter on the in body exchange.getIn().setBody("(!(ou=test1))"); // now we send the exchange to the endpoint, and receives the response from Camel Exchange out = template.send(endpoint, exchange); Collection<SearchResult> searchResults = defaultLdapModuleOutAssertions(out); assertFalse(contains("uid=test1,ou=test,ou=system", searchResults)); assertTrue(contains("uid=test2,ou=test,ou=system", searchResults)); assertTrue(contains("uid=testNoOU,ou=test,ou=system", searchResults)); assertTrue(contains("uid=tcruise,ou=actors,ou=system", searchResults)); // START SNIPPET: invoke } @Test public void testLdapRouteWithPaging() throws Exception { camel.addRoutes(createRouteBuilder("ldap:localhost:" + port + "?base=ou=system&pageSize=5")); camel.start(); Endpoint endpoint = camel.getEndpoint("direct:start"); Exchange exchange = endpoint.createExchange(); // then we set the LDAP filter on the in body exchange.getIn().setBody("(objectClass=*)"); // now we send the exchange to the endpoint, and receives the response from Camel Exchange out = template.send(endpoint, exchange); Collection<SearchResult> searchResults = defaultLdapModuleOutAssertions(out); assertEquals(16, searchResults.size()); } @Test public void testLdapRouteReturnedAttributes() throws Exception { // LDAP servers behave differently when it comes to what attributes are returned // by default (Apache Directory server returns all attributes by default) // Using the returnedAttributes parameter this behavior can be controlled camel.addRoutes(createRouteBuilder("ldap:localhost:" + port + "?base=ou=system&returnedAttributes=uid,cn")); camel.start(); Endpoint endpoint = camel.getEndpoint("direct:start"); Exchange exchange = endpoint.createExchange(); // then we set the LDAP filter on the in body exchange.getIn().setBody("(uid=tcruise)"); // now we send the exchange to the endpoint, and receives the response from Camel Exchange out = template.send(endpoint, exchange); Collection<SearchResult> searchResults = defaultLdapModuleOutAssertions(out); assertEquals(1, searchResults.size()); assertTrue(contains("uid=tcruise,ou=actors,ou=system", searchResults)); Attributes theOneResultAtts = searchResults.iterator().next().getAttributes(); assertEquals("tcruise", theOneResultAtts.get("uid").get()); assertEquals("Tom Cruise", theOneResultAtts.get("cn").get()); // make sure this att is NOT returned anymore assertNull(theOneResultAtts.get("sn")); } @Test public void testLdapRoutePreserveHeader() throws Exception { camel.addRoutes(createRouteBuilder("ldap:localhost:" + port + "?base=ou=system")); camel.start(); Exchange out = template.request("direct:start", exchange -> { exchange.getIn().setBody("(!(ou=test1))"); exchange.getIn().setHeader("ldapTest", "Camel"); }); Collection<SearchResult> searchResults = defaultLdapModuleOutAssertions(out); assertFalse(contains("uid=test1,ou=test,ou=system", searchResults)); assertTrue(contains("uid=test2,ou=test,ou=system", searchResults)); assertTrue(contains("uid=testNoOU,ou=test,ou=system", searchResults)); assertTrue(contains("uid=tcruise,ou=actors,ou=system", searchResults)); assertEquals("Camel", out.getMessage().getHeader("ldapTest")); } @SuppressWarnings("unchecked") private Collection<SearchResult> defaultLdapModuleOutAssertions(Exchange out) { // assertions of the response assertNotNull(out); assertNotNull(out.getMessage()); Collection<SearchResult> data = out.getMessage().getBody(Collection.class); assertNotNull(data, "out body could not be converted to a Collection - was: " + out.getMessage().getBody()); return data; } protected boolean contains(String dn, Collection<SearchResult> results) { for (SearchResult result : results) { if (result.getNameInNamespace().equals(dn)) { return true; } } return false; } protected RouteBuilder createRouteBuilder(final String ldapEndpointUrl) { return new RouteBuilder() { // START SNIPPET: route public void configure() { from("direct:start").to(ldapEndpointUrl); } // END SNIPPET: route }; } }
LdapRouteManualIT
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java
{ "start": 1420, "end": 3080 }
class ____ { private ClassPathXmlApplicationContext ctx; private ITestBean testBean1; private ITestBean testBean3; private CounterAspect counterAspect; @BeforeEach void setup() { this.ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass()); counterAspect = (CounterAspect) ctx.getBean("counterAspect"); testBean1 = (ITestBean) ctx.getBean("testBean1"); testBean3 = (ITestBean) ctx.getBean("testBean3"); } @AfterEach void tearDown() { this.ctx.close(); } @Test void matchingBeanName() { boolean condition = testBean1 instanceof Advised; assertThat(condition).as("Expected a proxy").isTrue(); // Call two methods to test for SPR-3953-like condition testBean1.setAge(20); testBean1.setName(""); assertThat(counterAspect.count).isEqualTo(2); } @Test void nonMatchingBeanName() { boolean condition = testBean3 instanceof Advised; assertThat(condition).as("Didn't expect a proxy").isFalse(); testBean3.setAge(20); assertThat(counterAspect.count).isEqualTo(0); } @Test void programmaticProxyCreation() { ITestBean testBean = new TestBean(); AspectJProxyFactory factory = new AspectJProxyFactory(); factory.setTarget(testBean); CounterAspect myCounterAspect = new CounterAspect(); factory.addAspect(myCounterAspect); ITestBean proxyTestBean = factory.getProxy(); boolean condition = proxyTestBean instanceof Advised; assertThat(condition).as("Expected a proxy").isTrue(); proxyTestBean.setAge(20); assertThat(myCounterAspect.count).as("Programmatically created proxy shouldn't match bean()").isEqualTo(0); } } @Aspect
BeanNamePointcutAtAspectTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/BiDirectionalAssociationHandler.java
{ "start": 1600, "end": 12000 }
class ____ implements Implementation { static Implementation wrap( TypeDescription managedCtClass, ByteBuddyEnhancementContext enhancementContext, AnnotatedFieldDescription persistentField, Implementation implementation) { if ( !enhancementContext.doBiDirectionalAssociationManagement() ) { return implementation; } TypeDescription targetEntity = getTargetEntityClass( managedCtClass, persistentField ); if ( targetEntity == null ) { return implementation; } String mappedBy = getMappedBy( persistentField, targetEntity, enhancementContext ); String bidirectionalAttributeName; if ( mappedBy == null ) { bidirectionalAttributeName = getMappedByManyToMany( persistentField, targetEntity, enhancementContext ); } else { bidirectionalAttributeName = mappedBy; } if ( bidirectionalAttributeName == null || bidirectionalAttributeName.isEmpty() ) { if ( ENHANCEMENT_LOGGER.isInfoEnabled() ) { ENHANCEMENT_LOGGER.bidirectionalNotManagedCouldNotFindTargetField( managedCtClass.getName(), persistentField.getName(), targetEntity.getCanonicalName() ); } return implementation; } TypeDescription targetType = FieldLocator.ForClassHierarchy.Factory.INSTANCE.make( targetEntity ) .locate( bidirectionalAttributeName ) .getField() .asDefined() .getType() .asErasure(); if ( persistentField.hasAnnotation( OneToOne.class ) ) { implementation = Advice.withCustomMapping() .bind( // We need to make the fieldValue writable for one-to-one to avoid stack overflows // when unsetting the inverse field new Advice.OffsetMapping.ForField.Resolved.Factory<>( CodeTemplates.FieldValue.class, persistentField.getFieldDescription(), false, Assigner.Typing.DYNAMIC ) ) .bind( CodeTemplates.InverseSide.class, mappedBy != null ) .to( CodeTemplates.OneToOneHandler.class ) .wrap( implementation ); } if ( persistentField.hasAnnotation( OneToMany.class ) ) { implementation = Advice.withCustomMapping() .bind( CodeTemplates.FieldValue.class, persistentField.getFieldDescription() ) .bind( CodeTemplates.InverseSide.class, mappedBy != null ) .to( persistentField.getType().asErasure().isAssignableTo( Map.class ) ? CodeTemplates.OneToManyOnMapHandler.class : CodeTemplates.OneToManyOnCollectionHandler.class ) .wrap( implementation ); } if ( persistentField.hasAnnotation( ManyToOne.class ) ) { implementation = Advice.withCustomMapping() .bind( CodeTemplates.FieldValue.class, persistentField.getFieldDescription() ) .bind( CodeTemplates.BidirectionalAttribute.class, bidirectionalAttributeName ) .to( CodeTemplates.ManyToOneHandler.class ) .wrap( implementation ); } if ( persistentField.hasAnnotation( ManyToMany.class ) ) { if ( persistentField.getType().asErasure().isAssignableTo( Map.class ) || targetType.isAssignableTo( Map.class ) ) { if ( ENHANCEMENT_LOGGER.isInfoEnabled() ) { ENHANCEMENT_LOGGER.manyToManyInMapNotSupported( managedCtClass.getName(), persistentField.getName() ); } return implementation; } implementation = Advice.withCustomMapping() .bind( CodeTemplates.FieldValue.class, persistentField.getFieldDescription() ) .bind( CodeTemplates.InverseSide.class, mappedBy != null ) .bind( CodeTemplates.BidirectionalAttribute.class, bidirectionalAttributeName ) .to( CodeTemplates.ManyToManyHandler.class ) .wrap( implementation ); } return new BiDirectionalAssociationHandler( implementation, managedCtClass, persistentField, targetEntity, targetType, bidirectionalAttributeName ); } public static TypeDescription getTargetEntityClass(TypeDescription managedCtClass, AnnotatedFieldDescription persistentField) { try { AnnotationDescription.Loadable<OneToOne> oto = persistentField.getAnnotation( OneToOne.class ); AnnotationDescription.Loadable<OneToMany> otm = persistentField.getAnnotation( OneToMany.class ); AnnotationDescription.Loadable<ManyToOne> mto = persistentField.getAnnotation( ManyToOne.class ); AnnotationDescription.Loadable<ManyToMany> mtm = persistentField.getAnnotation( ManyToMany.class ); final AnnotationValue<?, ?> targetClass; if ( oto != null ) { targetClass = oto.getValue( new MethodDescription.ForLoadedMethod( OneToOne.class.getDeclaredMethod( "targetEntity" ) ) ); } else if ( otm != null ) { targetClass = otm.getValue( new MethodDescription.ForLoadedMethod( OneToMany.class.getDeclaredMethod( "targetEntity" ) ) ); } else if ( mto != null ) { targetClass = mto.getValue( new MethodDescription.ForLoadedMethod( ManyToOne.class.getDeclaredMethod( "targetEntity" ) ) ); } else if ( mtm != null ) { targetClass = mtm.getValue( new MethodDescription.ForLoadedMethod( ManyToMany.class.getDeclaredMethod( "targetEntity" ) ) ); } else { if ( ENHANCEMENT_LOGGER.isInfoEnabled() ) { ENHANCEMENT_LOGGER.bidirectionalNotManagedCouldNotFindTargetType( managedCtClass.getName(), persistentField.getName() ); } return null; } if ( !targetClass.resolve( TypeDescription.class ).represents( void.class ) ) { return targetClass.resolve( TypeDescription.class ); } } catch (NoSuchMethodException ignored) { } return entityType( target( persistentField ) ); } private static TypeDescription.Generic target(AnnotatedFieldDescription persistentField) { AnnotationDescription.Loadable<Access> access = persistentField.getDeclaringType().asErasure().getDeclaredAnnotations().ofType( Access.class ); if ( access != null && access.load().value() == AccessType.FIELD ) { return persistentField.getType(); } else { Optional<MethodDescription> getter = persistentField.getGetter(); if ( getter.isPresent() ) { return getter.get().getReturnType(); } else { return persistentField.getType(); } } } private static String getMappedBy(AnnotatedFieldDescription target, TypeDescription targetEntity, ByteBuddyEnhancementContext context) { final String mappedBy = getMappedByFromAnnotation( target ); if ( mappedBy == null || mappedBy.isEmpty() ) { return null; } else { // HHH-13446 - mappedBy from annotation may not be a valid bidirectional association, verify by calling isValidMappedBy() return isValidMappedBy( target, targetEntity, mappedBy, context ) ? mappedBy : null; } } private static boolean isValidMappedBy(AnnotatedFieldDescription persistentField, TypeDescription targetEntity, String mappedBy, ByteBuddyEnhancementContext context) { try { FieldDescription f = FieldLocator.ForClassHierarchy.Factory.INSTANCE.make( targetEntity ).locate( mappedBy ).getField(); AnnotatedFieldDescription annotatedF = new AnnotatedFieldDescription( context, f ); return context.isPersistentField( annotatedF ) && persistentField.getDeclaringType().asErasure().isAssignableTo( entityType( f.getType() ) ); } catch ( IllegalStateException e ) { return false; } } private static String getMappedByFromAnnotation(AnnotatedFieldDescription target) { try { AnnotationDescription.Loadable<OneToOne> oto = target.getAnnotation( OneToOne.class ); if ( oto != null ) { return oto.getValue( new MethodDescription.ForLoadedMethod( OneToOne.class.getDeclaredMethod( "mappedBy" ) ) ).resolve( String.class ); } AnnotationDescription.Loadable<OneToMany> otm = target.getAnnotation( OneToMany.class ); if ( otm != null ) { return otm.getValue( new MethodDescription.ForLoadedMethod( OneToMany.class.getDeclaredMethod( "mappedBy" ) ) ).resolve( String.class ); } AnnotationDescription.Loadable<ManyToMany> mtm = target.getAnnotation( ManyToMany.class ); if ( mtm != null ) { return mtm.getValue( new MethodDescription.ForLoadedMethod( ManyToMany.class.getDeclaredMethod( "mappedBy" ) ) ).resolve( String.class ); } } catch (NoSuchMethodException ignored) { } return null; } private static String getMappedByManyToMany(AnnotatedFieldDescription target, TypeDescription targetEntity, ByteBuddyEnhancementContext context) { for ( FieldDescription f : targetEntity.getDeclaredFields() ) { AnnotatedFieldDescription annotatedF = new AnnotatedFieldDescription( context, f ); if ( context.isPersistentField( annotatedF ) && target.getName().equals( getMappedBy( annotatedF, entityType( annotatedF.getType() ), context ) ) && target.getDeclaringType().asErasure().isAssignableTo( entityType( annotatedF.getType() ) ) ) { if ( ENHANCEMENT_LOGGER.isTraceEnabled() ) { ENHANCEMENT_LOGGER.tracef( "mappedBy association for field [%s#%s] is [%s#%s]", target.getDeclaringType().asErasure().getName(), target.getName(), targetEntity.getName(), f.getName() ); } return f.getName(); } } return null; } private static TypeDescription entityType(TypeDescription.Generic type) { if ( type.getSort().isParameterized() ) { if ( type.asErasure().isAssignableTo( Collection.class ) ) { return type.getTypeArguments().get( 0 ).asErasure(); } if ( type.asErasure().isAssignableTo( Map.class ) ) { return type.getTypeArguments().get( 1 ).asErasure(); } } return type.asErasure(); } private final Implementation delegate; private final TypeDescription entity; private final AnnotatedFieldDescription field; private final TypeDescription targetEntity; private final TypeDescription targetType; private final String bidirectionalAttributeName; private BiDirectionalAssociationHandler( Implementation delegate, TypeDescription entity, AnnotatedFieldDescription field, TypeDescription targetEntity, TypeDescription targetType, String bidirectionalAttributeName) { this.delegate = delegate; this.entity = entity; this.field = field; this.targetEntity = targetEntity; this.targetType = targetType; this.bidirectionalAttributeName = bidirectionalAttributeName; } @Override public ByteCodeAppender appender(Target implementationTarget) { return new WrappingAppender( delegate.appender( implementationTarget ) ); } @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { return delegate.prepare( instrumentedType ); } private
BiDirectionalAssociationHandler
java
apache__camel
core/camel-core-processor/src/main/java/org/apache/camel/processor/StreamCachingProcessor.java
{ "start": 1150, "end": 2342 }
class ____ extends BaseProcessorSupport implements Traceable, IdAware, RouteIdAware { private String id; private String routeId; @Override public boolean process(Exchange exchange, AsyncCallback callback) { try { Object body = exchange.getIn().getBody(); if (!(body instanceof StreamCache)) { StreamCache streamCache = exchange.getContext().getTypeConverter() .convertTo(StreamCache.class, exchange, body); if (streamCache != null) { exchange.getIn().setBody(streamCache); } } } catch (Exception e) { exchange.setException(e); } callback.done(true); return true; } @Override public String getTraceLabel() { return "cache"; } @Override public void setId(String id) { this.id = id; } @Override public String getId() { return id; } @Override public String getRouteId() { return routeId; } @Override public void setRouteId(String routeId) { this.routeId = routeId; } }
StreamCachingProcessor
java
netty__netty
transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketMultipleConnectTest.java
{ "start": 1061, "end": 2240 }
class ____ extends SocketMultipleConnectTest { @Override protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() { List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> factories = new ArrayList<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>>(); for (TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap> comboFactory : EpollSocketTestPermutation.INSTANCE.socketWithFastOpen()) { EventLoopGroup group = comboFactory.newClientInstance().config().group(); if (group instanceof IoEventLoopGroup && ((IoEventLoopGroup) group).isIoType(NioIoHandler.class)) { factories.add(comboFactory); } if (group instanceof IoEventLoopGroup) { IoEventLoopGroup ioGroup = (IoEventLoopGroup) group; if (ioGroup.isIoType(NioIoHandler.class) || ioGroup.isIoType(EpollIoHandler.class)) { factories.add(comboFactory); } } } return factories; } }
EpollSocketMultipleConnectTest
java
google__guava
guava-tests/test/com/google/common/collect/MultimapsCollectionTest.java
{ "start": 8357, "end": 12312 }
class ____ extends TestEntriesGenerator implements TestListGenerator<Entry<String, Integer>> { @Override public List<Entry<String, Integer>> create(Object... elements) { return (List<Entry<String, Integer>>) super.create(elements); } } public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(transformSuite()); suite.addTest(filterSuite()); suite.addTest( ListMultimapTestSuiteBuilder.using( new TestStringListMultimapGenerator() { @Override protected ListMultimap<String, String> create(Entry<String, String>[] entries) { ListMultimap<String, String> multimap = synchronizedListMultimap(ArrayListMultimap.<String, String>create()); for (Entry<String, String> entry : entries) { multimap.put(entry.getKey(), entry.getValue()); } return multimap; } }) .named("synchronized ArrayListMultimap") .withFeatures( MapFeature.ALLOWS_NULL_KEYS, MapFeature.ALLOWS_NULL_VALUES, MapFeature.ALLOWS_ANY_NULL_QUERIES, MapFeature.GENERAL_PURPOSE, MapFeature.FAILS_FAST_ON_CONCURRENT_MODIFICATION, CollectionFeature.SUPPORTS_ITERATOR_REMOVE, CollectionSize.ANY) .createTestSuite()); suite.addTest( SetTestSuiteBuilder.using( new TestStringSetGenerator() { @Override protected Set<String> create(String[] elements) { PopulatableMapAsMultimap<Integer, String> multimap = PopulatableMapAsMultimap.create(); populateMultimapForGet(multimap, elements); return multimap.build().get(3); } }) .named("Multimaps.forMap.get") .withFeatures(FOR_MAP_FEATURES_ONE) .createTestSuite()); suite.addTest( SetTestSuiteBuilder.using( new TestStringSetGenerator() { @Override protected Set<String> create(String[] elements) { PopulatableMapAsMultimap<String, Integer> multimap = PopulatableMapAsMultimap.create(); populateMultimapForKeySet(multimap, elements); return multimap.build().keySet(); } }) .named("Multimaps.forMap.keySet") .withFeatures(FOR_MAP_FEATURES_ANY) .createTestSuite()); // TODO: use collection testers on Multimaps.forMap.values suite.addTest( MultisetTestSuiteBuilder.using( new TestStringMultisetGenerator() { @Override protected Multiset<String> create(String[] elements) { PopulatableMapAsMultimap<String, Integer> multimap = PopulatableMapAsMultimap.create(); populateMultimapForKeys(multimap, elements); return multimap.build().keys(); } }) .named("Multimaps.forMap.keys") .withFeatures(FOR_MAP_FEATURES_ANY) .suppressing(getCountDuplicateInitializingMethods()) .suppressing(getSetCountDuplicateInitializingMethods()) .suppressing(getIteratorDuplicateInitializingMethods()) .suppressing(getRemoveDuplicateInitializingMethods()) .suppressing(getForEachEntryDuplicateInitializingMethods()) .suppressing(getElementSetDuplicateInitializingMethods()) .createTestSuite()); // TODO: use collection testers on Multimaps.forMap.entries return suite; } abstract static
TestEntriesListGenerator
java
micronaut-projects__micronaut-core
http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/BodyArgumentTest.java
{ "start": 1384, "end": 2148 }
class ____ { public static final String SPEC_NAME = "BodyArgumentTest"; /** * @see <a href="https://github.com/micronaut-projects/micronaut-aws/issues/1164">micronaut-aws #1164</a> */ @Test void testBodyArguments() throws IOException { asserts(SPEC_NAME, HttpRequest.POST("/body-arguments-test/getA", "{\"a\":\"A\",\"b\":\"B\"}").header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN), (server, request) -> AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder() .status(HttpStatus.OK) .body("A") .build())); } @Controller("/body-arguments-test") @Requires(property = "spec.name", value = SPEC_NAME) static
BodyArgumentTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocalDateJavaType.java
{ "start": 825, "end": 4906 }
class ____ extends AbstractTemporalJavaType<LocalDate> { /** * Singleton access */ public static final LocalDateJavaType INSTANCE = new LocalDateJavaType(); public LocalDateJavaType() { super( LocalDate.class, ImmutableMutabilityPlan.instance() ); } @Override public boolean isInstance(Object value) { return value instanceof LocalDate; } @Override public TemporalType getPrecision() { return TemporalType.DATE; } @Override public JdbcType getRecommendedJdbcType(JdbcTypeIndicators context) { return context.isPreferJavaTimeJdbcTypesEnabled() ? context.getJdbcType( SqlTypes.LOCAL_DATE ) : context.getJdbcType( Types.DATE ); } @Override protected <X> TemporalJavaType<X> forDatePrecision(TypeConfiguration typeConfiguration) { //noinspection unchecked return (TemporalJavaType<X>) this; } @Override public boolean useObjectEqualsHashCode() { return true; } @Override public String toString(LocalDate value) { return DateTimeFormatter.ISO_LOCAL_DATE.format( value ); } @Override public LocalDate fromString(CharSequence string) { return LocalDate.from( DateTimeFormatter.ISO_LOCAL_DATE.parse( string ) ); } @Override @SuppressWarnings("unchecked") public <X> X unwrap(LocalDate value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } if ( LocalDate.class.isAssignableFrom( type ) ) { return (X) value; } if ( java.sql.Date.class.isAssignableFrom( type ) ) { return (X) java.sql.Date.valueOf( value ); } final LocalDateTime localDateTime = value.atStartOfDay(); if ( Timestamp.class.isAssignableFrom( type ) ) { /* * Workaround for HHH-13266 (JDK-8061577). * We could have done Timestamp.from( localDateTime.atZone( ZoneId.systemDefault() ).toInstant() ), * but on top of being more complex than the line below, it won't always work. * Timestamp.from() assumes the number of milliseconds since the epoch * means the same thing in Timestamp and Instant, but it doesn't, in particular before 1900. */ return (X) Timestamp.valueOf( localDateTime ); } final var zonedDateTime = localDateTime.atZone( ZoneId.systemDefault() ); if ( Calendar.class.isAssignableFrom( type ) ) { return (X) GregorianCalendar.from( zonedDateTime ); } final var instant = zonedDateTime.toInstant(); if ( Date.class.equals( type ) ) { return (X) Date.from( instant ); } if ( Long.class.isAssignableFrom( type ) ) { return (X) Long.valueOf( instant.toEpochMilli() ); } throw unknownUnwrap( type ); } @Override public <X> LocalDate wrap(X value, WrapperOptions options) { if ( value == null ) { return null; } if (value instanceof LocalDate localDate) { return localDate; } if (value instanceof Timestamp timestamp) { /* * Workaround for HHH-13266 (JDK-8061577). * We used to do LocalDateTime.ofInstant( ts.toInstant(), ZoneId.systemDefault() ).toLocalDate(), * but on top of being more complex than the line below, it won't always work. * ts.toInstant() assumes the number of milliseconds since the epoch * means the same thing in Timestamp and Instant, but it doesn't, in particular before 1900. */ return timestamp.toLocalDateTime().toLocalDate(); } if (value instanceof Long longValue) { final var instant = Instant.ofEpochMilli( longValue ); return LocalDateTime.ofInstant( instant, ZoneId.systemDefault() ).toLocalDate(); } if (value instanceof Calendar calendar) { return LocalDateTime.ofInstant( calendar.toInstant(), calendar.getTimeZone().toZoneId() ).toLocalDate(); } if (value instanceof Date date) { if (value instanceof java.sql.Date sqlDate) { return sqlDate.toLocalDate(); } else { return Instant.ofEpochMilli( date.getTime() ).atZone( ZoneId.systemDefault() ).toLocalDate(); } } throw unknownWrap( value.getClass() ); } @Override public boolean isWider(JavaType<?> javaType) { return switch ( javaType.getTypeName() ) { case "java.sql.Date" -> true; default -> false; }; } }
LocalDateJavaType
java
apache__flink
flink-dstl/flink-dstl-dfs/src/test/java/org/apache/flink/changelog/fs/TestingStateChangeUploader.java
{ "start": 1410, "end": 3670 }
class ____ implements StateChangeUploader { private final Collection<StateChangeSet> uploaded = new CopyOnWriteArrayList<>(); private final List<UploadTask> tasks; private boolean closed; TestingStateChangeUploader() { tasks = new CopyOnWriteArrayList<>(); } @Override public void close() { this.closed = true; } @Override public UploadTasksResult upload(Collection<UploadTask> tasks) throws IOException { for (UploadTask uploadTask : tasks) { this.uploaded.addAll(uploadTask.changeSets); this.tasks.add(uploadTask); } return new UploadTasksResult(emptyMap(), new ByteStreamStateHandle("", new byte[0])); } public Collection<StateChangeSet> getUploaded() { return uploaded; } public boolean isClosed() { return closed; } public void reset() { uploaded.clear(); tasks.clear(); } public void failUpload(RuntimeException exception) { tasks.forEach(t -> t.fail(exception)); } public void completeUpload() { tasks.forEach( t -> t.complete( uploaded.stream() .map( changeSet -> new UploadResult( asBytesHandle(changeSet), 0L, changeSet.getSequenceNumber(), changeSet.getSize())) .collect(toList()))); } private StreamStateHandle asBytesHandle(StateChangeSet changeSet) { byte[] bytes = new byte[(int) changeSet.getSize()]; int offset = 0; for (StateChange change : changeSet.getChanges()) { for (int i = 0; i < change.getChange().length; i++) { bytes[offset++] = change.getChange()[i]; } } return new ByteStreamStateHandle("", bytes); } }
TestingStateChangeUploader
java
greenrobot__greendao
DaoGenerator/src/org/greenrobot/greendao/generator/Entity.java
{ "start": 1079, "end": 1697 }
class ____ an entity: a Java data object mapped to a data base table. A new entity is added to a {@link Schema} * by the method {@link Schema#addEntity(String)} (there is no public constructor for {@link Entity} itself). <br/> * <br/> Use the various addXXX methods to add entity properties, indexes, and relations to other entities (addToOne, * addToMany).<br/> <br/> There are further configuration possibilities: <ul> <li>{@link * Entity#implementsInterface(String...)} and {@link #implementsSerializable()} to specify interfaces the entity will * implement</li> <li>{@link #setSuperclass(String)} to specify a
for
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/action/DeletingVisitorTest.java
{ "start": 1772, "end": 6527 }
class ____ extends DeletingVisitor { List<Path> deleted = new ArrayList<>(); public DeletingVisitorHelper( final Path basePath, final List<? extends PathCondition> pathFilters, final boolean testMode) { super(basePath, pathFilters, testMode); } @Override protected void delete(final Path file) { deleted.add(file); // overrides and stores path instead of deleting } } @Test void testAcceptedFilesAreDeleted() throws IOException { final Path base = Paths.get("/a/b/c"); final FixedCondition ACCEPT_ALL = new FixedCondition(true); final DeletingVisitorHelper visitor = new DeletingVisitorHelper(base, Collections.singletonList(ACCEPT_ALL), false); final Path any = Paths.get("/a/b/c/any"); visitor.visitFile(any, null); assertTrue(visitor.deleted.contains(any)); } @Test void testRejectedFilesAreNotDeleted() throws IOException { final Path base = Paths.get("/a/b/c"); final FixedCondition REJECT_ALL = new FixedCondition(false); final DeletingVisitorHelper visitor = new DeletingVisitorHelper(base, Collections.singletonList(REJECT_ALL), false); final Path any = Paths.get("/a/b/c/any"); visitor.visitFile(any, null); assertFalse(visitor.deleted.contains(any)); } @Test void testAllFiltersMustAcceptOrFileIsNotDeleted() throws IOException { final Path base = Paths.get("/a/b/c"); final FixedCondition ACCEPT_ALL = new FixedCondition(true); final FixedCondition REJECT_ALL = new FixedCondition(false); final List<? extends PathCondition> filters = Arrays.asList(ACCEPT_ALL, ACCEPT_ALL, REJECT_ALL); final DeletingVisitorHelper visitor = new DeletingVisitorHelper(base, filters, false); final Path any = Paths.get("/a/b/c/any"); visitor.visitFile(any, null); assertFalse(visitor.deleted.contains(any)); } @Test void testIfAllFiltersAcceptFileIsDeleted() throws IOException { final Path base = Paths.get("/a/b/c"); final FixedCondition ACCEPT_ALL = new FixedCondition(true); final List<? extends PathCondition> filters = Arrays.asList(ACCEPT_ALL, ACCEPT_ALL, ACCEPT_ALL); final DeletingVisitorHelper visitor = new DeletingVisitorHelper(base, filters, false); final Path any = Paths.get("/a/b/c/any"); visitor.visitFile(any, null); assertTrue(visitor.deleted.contains(any)); } @Test void testInTestModeFileIsNotDeletedEvenIfAllFiltersAccept() throws IOException { final Path base = Paths.get("/a/b/c"); final FixedCondition ACCEPT_ALL = new FixedCondition(true); final List<? extends PathCondition> filters = Arrays.asList(ACCEPT_ALL, ACCEPT_ALL, ACCEPT_ALL); final DeletingVisitorHelper visitor = new DeletingVisitorHelper(base, filters, true); final Path any = Paths.get("/a/b/c/any"); visitor.visitFile(any, null); assertFalse(visitor.deleted.contains(any)); } @Test void testVisitFileRelativizesAgainstBase() throws IOException { final PathCondition filter = new PathCondition() { @Override public boolean accept(final Path baseDir, final Path relativePath, final BasicFileAttributes attrs) { final Path expected = Paths.get("relative"); assertEquals(expected, relativePath); return true; } @Override public void beforeFileTreeWalk() {} }; final Path base = Paths.get("/a/b/c"); final DeletingVisitorHelper visitor = new DeletingVisitorHelper(base, Collections.singletonList(filter), false); final Path child = Paths.get("/a/b/c/relative"); visitor.visitFile(child, null); } @Test void testNoSuchFileFailure() throws IOException { final DeletingVisitorHelper visitor = new DeletingVisitorHelper(Paths.get("/a/b/c"), Collections.emptyList(), true); assertEquals( FileVisitResult.CONTINUE, visitor.visitFileFailed(Paths.get("doesNotExist"), new NoSuchFileException("doesNotExist"))); } @Test void testIOException() { final DeletingVisitorHelper visitor = new DeletingVisitorHelper(Paths.get("/a/b/c"), Collections.emptyList(), true); final IOException exception = new IOException(); try { visitor.visitFileFailed(Paths.get("doesNotExist"), exception); fail(); } catch (IOException e) { assertSame(exception, e); } } }
DeletingVisitorHelper
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/deployment/src/test/java/io/quarkus/restclient/ft/AsyncRestClientFallbackTest.java
{ "start": 1568, "end": 1767 }
interface ____ { @Asynchronous @Fallback(MyFallback.class) @GET @Path("/test") CompletionStage<String> ping(); } @Path("/test") public static
Client
java
quarkusio__quarkus
integration-tests/main/src/test/java/io/quarkus/it/main/QuarkusTestNestedITCase.java
{ "start": 5848, "end": 6522 }
class ____ { @BeforeEach void beforeEach() { COUNT_BEFORE_EACH.incrementAndGet(); } @Test void testOne() { assertEquals(1, COUNT_BEFORE_ALL.get(), "COUNT_BEFORE_ALL"); assertEquals(3, COUNT_BEFORE_EACH.get(), "COUNT_BEFORE_EACH"); assertEquals(1, COUNT_TEST.getAndIncrement(), "COUNT_TEST"); assertEquals(1, COUNT_AFTER_EACH.get(), "COUNT_AFTER_EACH"); assertEquals(0, COUNT_AFTER_ALL.get(), "COUNT_AFTER_ALL"); } @AfterEach void afterEach() { COUNT_AFTER_EACH.incrementAndGet(); } @Nested
SecondNested
java
spring-projects__spring-boot
module/spring-boot-health/src/test/java/org/springframework/boot/health/contributor/ReactiveHealthContributorsTests.java
{ "start": 1218, "end": 3064 }
class ____ { @Test void iteratorAdaptsStream() { Entry e1 = new Entry("e1", mock(ReactiveHealthIndicator.class)); Entry e2 = new Entry("e2", mock(ReactiveHealthIndicator.class)); ReactiveHealthContributors contributors = new ReactiveHealthContributors() { @Override public Stream<Entry> stream() { return Stream.of(e1, e2); } @Override public @Nullable ReactiveHealthContributor getContributor(String name) { return null; } }; assertThat(contributors).containsExactly(e1, e2); } @Test void asHealthContributorsReturnsAdapter() { ReactiveHealthContributors contributors = mock(ReactiveHealthContributors.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS)); assertThat(contributors.asHealthContributors()).isInstanceOf(ReactiveHealthContributorsAdapter.class); } @Test void ofCreateComposite() { ReactiveHealthContributors c = mock(ReactiveHealthContributors.class); assertThat(ReactiveHealthContributors.of(c)).isInstanceOf(CompositeReactiveHealthContributors.class); } @Test void adaptWhenNullReturnsNull() { assertThat(ReactiveHealthContributors.adapt(null)).isNull(); } @Test void adaptReturnsAdapter() { HealthContributors c = mock(HealthContributors.class); assertThat(ReactiveHealthContributors.adapt(c)).isInstanceOf(HealthContributorsAdapter.class); } @Test void createEntryWhenNameIsEmptyThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Entry("", mock(ReactiveHealthIndicator.class))) .withMessage("'name' must not be empty"); } @Test @SuppressWarnings("NullAway") // Test null check void createEntryWhenContributorIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new Entry("test", null)) .withMessage("'contributor' must not be null"); } }
ReactiveHealthContributorsTests
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-nativetask/src/test/java/org/apache/hadoop/mapred/nativetask/testutil/ResultVerifier.java
{ "start": 1326, "end": 5717 }
class ____ { /** * verify the result * * @param sample the path to correct results * @param source the path to the results from the native implementation */ public static boolean verify(String sample, String source) throws Exception { FSDataInputStream sourcein = null; FSDataInputStream samplein = null; final Configuration conf = new Configuration(); final FileSystem fs = FileSystem.get(conf); final Path hdfssource = new Path(source); final Path[] sourcepaths = FileUtil.stat2Paths(fs.listStatus(hdfssource)); final Path hdfssample = new Path(sample); final Path[] samplepaths = FileUtil.stat2Paths(fs.listStatus(hdfssample)); if (sourcepaths == null) { throw new Exception("source file can not be found"); } if (samplepaths == null) { throw new Exception("sample file can not be found"); } if (sourcepaths.length != samplepaths.length) { return false; } for (int i = 0; i < sourcepaths.length; i++) { final Path sourcepath = sourcepaths[i]; // op result file start with "part-r" like part-r-00000 if (!sourcepath.getName().startsWith("part-r")) { continue; } Path samplepath = null; for (int j = 0; j < samplepaths.length; j++) { if (samplepaths[i].getName().equals(sourcepath.getName())) { samplepath = samplepaths[i]; break; } } if (samplepath == null) { throw new Exception("cound not find file " + samplepaths[0].getParent() + "/" + sourcepath.getName() + " , as sourcepaths has such file"); } // compare try { if (fs.exists(sourcepath) && fs.exists(samplepath)) { sourcein = fs.open(sourcepath); samplein = fs.open(samplepath); } else { System.err.println("result file not found:" + sourcepath + " or " + samplepath); return false; } CRC32 sourcecrc, samplecrc; samplecrc = new CRC32(); sourcecrc = new CRC32(); final byte[] bufin = new byte[1 << 16]; int readnum = 0; int totalRead = 0; while (samplein.available() > 0) { readnum = samplein.read(bufin); totalRead += readnum; samplecrc.update(bufin, 0, readnum); } if (0 == totalRead) { throw new Exception("source " + sample + " is empty file"); } totalRead = 0; while (sourcein.available() > 0) { readnum = sourcein.read(bufin); totalRead += readnum; sourcecrc.update(bufin, 0, readnum); } if (0 == totalRead) { throw new Exception("source " + sample + " is empty file"); } if (samplecrc.getValue() == sourcecrc.getValue()) { ; } else { return false; } } catch (final IOException e) { throw new Exception("verify exception :", e); } finally { try { if (samplein != null) { samplein.close(); } if (sourcein != null) { sourcein.close(); } } catch (final IOException e) { e.printStackTrace(); } } } return true; } public static void verifyCounters(Job normalJob, Job nativeJob, boolean hasCombiner) throws IOException { Counters normalCounters = normalJob.getCounters(); Counters nativeCounters = nativeJob.getCounters(); assertEquals(normalCounters.findCounter(TaskCounter.MAP_OUTPUT_RECORDS).getValue(), nativeCounters.findCounter(TaskCounter.MAP_OUTPUT_RECORDS).getValue(), "Counter MAP_OUTPUT_RECORDS should be equal"); assertEquals(normalCounters.findCounter(TaskCounter.REDUCE_INPUT_GROUPS).getValue(), nativeCounters.findCounter(TaskCounter.REDUCE_INPUT_GROUPS).getValue(), "Counter REDUCE_INPUT_GROUPS should be equal"); if (!hasCombiner) { assertEquals(normalCounters.findCounter(TaskCounter.REDUCE_INPUT_RECORDS).getValue(), nativeCounters.findCounter(TaskCounter.REDUCE_INPUT_RECORDS).getValue(), "Counter REDUCE_INPUT_RECORDS should be equal"); } } public static void verifyCounters(Job normalJob, Job nativeJob) throws IOException { verifyCounters(normalJob, nativeJob, false); } }
ResultVerifier
java
google__guava
android/guava/src/com/google/common/hash/LittleEndianByteArray.java
{ "start": 5151, "end": 5323 }
class ____, and the outer * class's static initializer can fall back on a non-Unsafe version. */ @SuppressWarnings("SunApi") // b/345822163 @VisibleForTesting
fails
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Aws2SnsComponentBuilderFactory.java
{ "start": 1375, "end": 1909 }
interface ____ { /** * AWS Simple Notification System (SNS) (camel-aws2-sns) * Send messages to AWS Simple Notification Topic. * * Category: cloud,messaging,mobile * Since: 3.1 * Maven coordinates: org.apache.camel:camel-aws2-sns * * @return the dsl builder */ static Aws2SnsComponentBuilder aws2Sns() { return new Aws2SnsComponentBuilderImpl(); } /** * Builder for the AWS Simple Notification System (SNS) component. */
Aws2SnsComponentBuilderFactory
java
apache__camel
components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/KafkaManualCommitFactory.java
{ "start": 1196, "end": 1312 }
class ____ the Camel exchange related payload, such as the exchange itself, the consumer, thread ID, etc */
for
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsTests.java
{ "start": 15583, "end": 15726 }
class ____ { ClassWithOneCustomConstructor(String str) { } } @SuppressWarnings("unused") private static
ClassWithOneCustomConstructor
java
spring-projects__spring-boot
module/spring-boot-data-elasticsearch/src/test/java/org/springframework/boot/data/elasticsearch/autoconfigure/DataElasticsearchAutoConfigurationTests.java
{ "start": 6507, "end": 6781 }
class ____ { @Bean ReactiveElasticsearchTemplate reactiveElasticsearchTemplate() { return mock(ReactiveElasticsearchTemplate.class); } } @Configuration(proxyBeanMethods = false) @TestAutoConfigurationPackage(City.class) static
CustomReactiveElasticsearchTemplate
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/action/EqlSearchResponse.java
{ "start": 19782, "end": 20069 }
class ____ implements Writeable, ToXContentFragment { public static final Hits EMPTY = new Hits(null, null, null); private final List<Event> events; private final List<Sequence> sequences; private final TotalHits totalHits; private static final
Hits
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/ModelAndView.java
{ "start": 983, "end": 1711 }
class ____ holds * both to make it possible for a controller to return both model * and view in a single return value. * * <p>Represents a model and view returned by a handler, to be resolved * by a DispatcherServlet. The view can take the form of a String * view name which will need to be resolved by a ViewResolver object; * alternatively a View object can be specified directly. The model * is a Map, allowing the use of multiple objects keyed by name. * * @author Rod Johnson * @author Juergen Hoeller * @author Rob Harrop * @author Rossen Stoyanchev * @see DispatcherServlet * @see ViewResolver * @see HandlerAdapter#handle * @see org.springframework.web.servlet.mvc.Controller#handleRequest */ public
merely
java
apache__avro
lang/java/avro/src/main/java/org/apache/avro/io/Encoder.java
{ "start": 1992, "end": 11137 }
class ____ stateful.) * * @throws AvroTypeException If this is a stateful writer and a null is not * expected */ public abstract void writeNull() throws IOException; /** * Write a boolean value. * * @throws AvroTypeException If this is a stateful writer and a boolean is not * expected */ public abstract void writeBoolean(boolean b) throws IOException; /** * Writes a 32-bit integer. * * @throws AvroTypeException If this is a stateful writer and an integer is not * expected */ public abstract void writeInt(int n) throws IOException; /** * Write a 64-bit integer. * * @throws AvroTypeException If this is a stateful writer and a long is not * expected */ public abstract void writeLong(long n) throws IOException; /** * Write a float. * * @throws IOException * @throws AvroTypeException If this is a stateful writer and a float is not * expected */ public abstract void writeFloat(float f) throws IOException; /** * Write a double. * * @throws AvroTypeException If this is a stateful writer and a double is not * expected */ public abstract void writeDouble(double d) throws IOException; /** * Write a Unicode character string. * * @throws AvroTypeException If this is a stateful writer and a char-string is * not expected */ public abstract void writeString(Utf8 utf8) throws IOException; /** * Write a Unicode character string. The default implementation converts the * String to a {@link org.apache.avro.util.Utf8}. Some Encoder implementations * may want to do something different as a performance optimization. * * @throws AvroTypeException If this is a stateful writer and a char-string is * not expected */ public void writeString(String str) throws IOException { writeString(new Utf8(str)); } /** * Write a Unicode character string. If the CharSequence is an * {@link org.apache.avro.util.Utf8} it writes this directly, otherwise the * CharSequence is converted to a String via toString() and written. * * @throws AvroTypeException If this is a stateful writer and a char-string is * not expected */ public void writeString(CharSequence charSequence) throws IOException { if (charSequence instanceof Utf8) writeString((Utf8) charSequence); else writeString(charSequence.toString()); } /** * Write a byte string. * * @throws AvroTypeException If this is a stateful writer and a byte-string is * not expected */ public abstract void writeBytes(ByteBuffer bytes) throws IOException; /** * Write a byte string. * * @throws AvroTypeException If this is a stateful writer and a byte-string is * not expected */ public abstract void writeBytes(byte[] bytes, int start, int len) throws IOException; /** * Writes a byte string. Equivalent to * <tt>writeBytes(bytes, 0, bytes.length)</tt> * * @throws IOException * @throws AvroTypeException If this is a stateful writer and a byte-string is * not expected */ public void writeBytes(byte[] bytes) throws IOException { writeBytes(bytes, 0, bytes.length); } /** * Writes a fixed size binary object. * * @param bytes The contents to write * @param start The position within <tt>bytes</tt> where the contents start. * @param len The number of bytes to write. * @throws AvroTypeException If this is a stateful writer and a byte-string is * not expected * @throws IOException */ public abstract void writeFixed(byte[] bytes, int start, int len) throws IOException; /** * A shorthand for <tt>writeFixed(bytes, 0, bytes.length)</tt> * * @param bytes the data */ public void writeFixed(byte[] bytes) throws IOException { writeFixed(bytes, 0, bytes.length); } /** Writes a fixed from a ByteBuffer. */ public void writeFixed(ByteBuffer bytes) throws IOException { int pos = bytes.position(); int len = bytes.limit() - pos; if (bytes.hasArray()) { writeFixed(bytes.array(), bytes.arrayOffset() + pos, len); } else { byte[] b = new byte[len]; bytes.duplicate().get(b, 0, len); writeFixed(b, 0, len); } } /** * Writes an enumeration. * * @param e the enumeration to write * @throws AvroTypeException If this is a stateful writer and an enumeration is * not expected or the <tt>e</tt> is out of range. * @throws IOException */ public abstract void writeEnum(int e) throws IOException; /** * Call this method to start writing an array. * * When starting to serialize an array, call {@link #writeArrayStart}. Then, * before writing any data for any item call {@link #setItemCount} followed by a * sequence of {@link #startItem()} and the item itself. The number of * {@link #startItem()} should match the number specified in * {@link #setItemCount}. When actually writing the data of the item, you can * call any {@link Encoder} method (e.g., {@link #writeLong}). When all items of * the array have been written, call {@link #writeArrayEnd}. * * As an example, let's say you want to write an array of records, the record * consisting of a Long field and a Boolean field. Your code would look * something like this: * * <pre> * out.writeArrayStart(); * out.setItemCount(list.size()); * for (Record r : list) { * out.startItem(); * out.writeLong(r.longField); * out.writeBoolean(r.boolField); * } * out.writeArrayEnd(); * </pre> * * @throws AvroTypeException If this is a stateful writer and an array is not * expected */ public abstract void writeArrayStart() throws IOException; /** * Call this method before writing a batch of items in an array or a map. Then * for each item, call {@link #startItem()} followed by any of the other write * methods of {@link Encoder}. The number of calls to {@link #startItem()} must * be equal to the count specified in {@link #setItemCount}. Once a batch is * completed you can start another batch with {@link #setItemCount}. * * @param itemCount The number of {@link #startItem()} calls to follow. * @throws IOException */ public abstract void setItemCount(long itemCount) throws IOException; /** * Start a new item of an array or map. See {@link #writeArrayStart} for usage * information. * * @throws AvroTypeException If called outside an array or map context */ public abstract void startItem() throws IOException; /** * Call this method to finish writing an array. See {@link #writeArrayStart} for * usage information. * * @throws AvroTypeException If items written does not match count provided to * {@link #writeArrayStart} * @throws AvroTypeException If not currently inside an array */ public abstract void writeArrayEnd() throws IOException; /** * Call this to start a new map. See {@link #writeArrayStart} for details on * usage. * * As an example of usage, let's say you want to write a map of records, the * record consisting of a Long field and a Boolean field. Your code would look * something like this: * * <pre> * out.writeMapStart(); * out.setItemCount(list.size()); * for (Map.Entry<String, Record> entry : map.entrySet()) { * out.startItem(); * out.writeString(entry.getKey()); * out.writeLong(entry.getValue().longField); * out.writeBoolean(entry.getValue().boolField); * } * out.writeMapEnd(); * </pre> * * @throws AvroTypeException If this is a stateful writer and a map is not * expected */ public abstract void writeMapStart() throws IOException; /** * Call this method to terminate the inner-most, currently-opened map. See * {@link #writeArrayStart} for more details. * * @throws AvroTypeException If items written does not match count provided to * {@link #writeMapStart} * @throws AvroTypeException If not currently inside a map */ public abstract void writeMapEnd() throws IOException; /** * Call this method to write the tag of a union. * * As an example of usage, let's say you want to write a union, whose second * branch is a record consisting of a Long field and a Boolean field. Your code * would look something like this: * * <pre> * out.writeIndex(1); * out.writeLong(record.longField); * out.writeBoolean(record.boolField); * </pre> * * @throws AvroTypeException If this is a stateful writer and a map is not * expected */ public abstract void writeIndex(int unionIndex) throws IOException; }
is
java
elastic__elasticsearch
x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/saml/sp/WildcardServiceProviderResolver.java
{ "start": 10537, "end": 10623 }
interface ____ { ParseField SERVICES = new ParseField("services"); } }
Fields
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/inference/results/SparseEmbeddingResultsTests.java
{ "start": 901, "end": 8828 }
class ____ extends AbstractWireSerializingTestCase<SparseEmbeddingResults> { public static SparseEmbeddingResults createRandomResults() { int numEmbeddings = randomIntBetween(1, 10); int numTokens = randomIntBetween(0, 20); return createRandomResults(numEmbeddings, numTokens); } public static SparseEmbeddingResults createRandomResults(int numEmbeddings, int numTokens) { List<SparseEmbeddingResults.Embedding> embeddings = new ArrayList<>(numEmbeddings); for (int i = 0; i < numEmbeddings; i++) { embeddings.add(createRandomEmbedding(numTokens)); } return new SparseEmbeddingResults(embeddings); } public static SparseEmbeddingResults createRandomResults(List<String> input) { List<SparseEmbeddingResults.Embedding> embeddings = new ArrayList<>(input.size()); for (String s : input) { int numTokens = Strings.tokenizeToStringArray(s, " ").length; embeddings.add(createRandomEmbedding(numTokens)); } return new SparseEmbeddingResults(embeddings); } private static SparseEmbeddingResults.Embedding createRandomEmbedding(int numTokens) { List<WeightedToken> tokenList = new ArrayList<>(numTokens); for (int i = 0; i < numTokens; i++) { tokenList.add(new WeightedToken(Integer.toString(i), (float) randomDoubleBetween(0.0, 5.0, false))); } return new SparseEmbeddingResults.Embedding(tokenList, randomBoolean()); } @Override protected Writeable.Reader<SparseEmbeddingResults> instanceReader() { return SparseEmbeddingResults::new; } @Override protected SparseEmbeddingResults createTestInstance() { return createRandomResults(); } @Override protected SparseEmbeddingResults mutateInstance(SparseEmbeddingResults instance) throws IOException { // if true we reduce the embeddings list by a random amount, if false we add an embedding to the list if (randomBoolean()) { // -1 to remove at least one item from the list int end = randomInt(instance.embeddings().size() - 1); return new SparseEmbeddingResults(instance.embeddings().subList(0, end)); } else { List<SparseEmbeddingResults.Embedding> embeddings = new ArrayList<>(instance.embeddings()); embeddings.add(createRandomEmbedding(randomIntBetween(0, 20))); return new SparseEmbeddingResults(embeddings); } } public void testToXContent_CreatesTheRightFormatForASingleEmbedding() throws IOException { var entity = createSparseResult(List.of(createEmbedding(List.of(new WeightedToken("token", 0.1F)), false))); assertThat(entity.asMap(), is(buildExpectationSparseEmbeddings(List.of(new EmbeddingExpectation(Map.of("token", 0.1F), false))))); String xContentResult = Strings.toString(entity, true, true); assertThat(xContentResult, is(""" { "sparse_embedding" : [ { "is_truncated" : false, "embedding" : { "token" : 0.1 } } ] }""")); } public void testToXContent_CreatesTheRightFormatForMultipleEmbeddings() throws IOException { var entity = createSparseResult( List.of( new SparseEmbeddingResults.Embedding(List.of(new WeightedToken("token", 0.1F), new WeightedToken("token2", 0.2F)), false), new SparseEmbeddingResults.Embedding(List.of(new WeightedToken("token3", 0.3F), new WeightedToken("token4", 0.4F)), false) ) ); assertThat( entity.asMap(), is( buildExpectationSparseEmbeddings( List.of( new EmbeddingExpectation(Map.of("token", 0.1F, "token2", 0.2F), false), new EmbeddingExpectation(Map.of("token3", 0.3F, "token4", 0.4F), false) ) ) ) ); String xContentResult = Strings.toString(entity, true, true); assertThat(xContentResult, is(""" { "sparse_embedding" : [ { "is_truncated" : false, "embedding" : { "token" : 0.1, "token2" : 0.2 } }, { "is_truncated" : false, "embedding" : { "token3" : 0.3, "token4" : 0.4 } } ] }""")); } public void testTransformToCoordinationFormat() { var results = createSparseResult( List.of( createEmbedding(List.of(new WeightedToken("token", 0.1F)), false), createEmbedding(List.of(new WeightedToken("token2", 0.2F)), true) ) ).transformToCoordinationFormat(); assertThat( results, is( List.of( new TextExpansionResults(DEFAULT_RESULTS_FIELD, List.of(new WeightedToken("token", 0.1F)), false), new TextExpansionResults(DEFAULT_RESULTS_FIELD, List.of(new WeightedToken("token2", 0.2F)), true) ) ) ); } public void testEmbeddingMerge() { SparseEmbeddingResults.Embedding embedding1 = new SparseEmbeddingResults.Embedding( List.of( new WeightedToken("this", 1.0f), new WeightedToken("is", 0.8f), new WeightedToken("the", 0.6f), new WeightedToken("first", 0.4f), new WeightedToken("embedding", 0.2f) ), true ); SparseEmbeddingResults.Embedding embedding2 = new SparseEmbeddingResults.Embedding( List.of( new WeightedToken("this", 0.95f), new WeightedToken("is", 0.85f), new WeightedToken("another", 0.65f), new WeightedToken("embedding", 0.15f) ), false ); assertThat( embedding1.merge(embedding2), equalTo( new SparseEmbeddingResults.Embedding( List.of( new WeightedToken("this", 1.0f), new WeightedToken("is", 0.85f), new WeightedToken("another", 0.65f), new WeightedToken("the", 0.6f), new WeightedToken("first", 0.4f), new WeightedToken("embedding", 0.2f) ), true ) ) ); } public record EmbeddingExpectation(Map<String, Float> tokens, boolean isTruncated) {} public static Map<String, Object> buildExpectationSparseEmbeddings(List<EmbeddingExpectation> embeddings) { return Map.of( SparseEmbeddingResults.SPARSE_EMBEDDING, embeddings.stream() .map( embedding -> Map.of( EmbeddingResults.EMBEDDING, embedding.tokens, SparseEmbeddingResults.Embedding.IS_TRUNCATED, embedding.isTruncated ) ) .toList() ); } public static SparseEmbeddingResults createSparseResult(List<SparseEmbeddingResults.Embedding> embeddings) { return new SparseEmbeddingResults(embeddings); } public static SparseEmbeddingResults.Embedding createEmbedding(List<WeightedToken> tokensList, boolean isTruncated) { return new SparseEmbeddingResults.Embedding(tokensList, isTruncated); } }
SparseEmbeddingResultsTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cascade/circle/CascadeManagedAndTransientTest.java
{ "start": 2254, "end": 5855 }
class ____ { @AfterEach public void cleanupTest(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testAttachedChildInMerge(SessionFactoryScope scope) { fillInitialData( scope ); scope.inTransaction( session -> { Route route = session.createQuery( "FROM Route WHERE name = :name", Route.class ) .setParameter( "name", "Route 1" ) .uniqueResult(); Node n2 = session.createQuery( "FROM Node WHERE name = :name", Node.class ) .setParameter( "name", "Node 2" ) .uniqueResult(); Node n3 = session.createQuery( "FROM Node WHERE name = :name", Node.class ) .setParameter( "name", "Node 3" ) .uniqueResult(); Vehicle vehicle = new Vehicle(); vehicle.setName( "Bus" ); vehicle.setRoute( route ); Transport $2to3 = new Transport(); $2to3.setName( "Transport 2 -> 3" ); $2to3.setPickupNode( n2 ); n2.getPickupTransports().add( $2to3 ); $2to3.setDeliveryNode( n3 ); n3.getDeliveryTransports().add( $2to3 ); $2to3.setVehicle( vehicle ); vehicle.setTransports( Set.of( $2to3 ) ); // Try to save graph of transient entities (vehicle, transport) which contains attached entities (node2, node3) Vehicle managedVehicle = (Vehicle) session.merge( vehicle ); checkNewVehicle( managedVehicle ); session.flush(); session.clear(); assertEquals( 3, session.createQuery( "FROM Transport", Transport.class ).list().size() ); assertEquals( 2, session.createQuery( "FROM Vehicle", Vehicle.class ).list().size() ); assertEquals( 4, session.createQuery( "FROM Node", Node.class ).list().size() ); Vehicle newVehicle = session.createQuery( "FROM Vehicle WHERE name = :name", Vehicle.class ) .setParameter( "name", "Bus" ) .uniqueResult(); checkNewVehicle( newVehicle ); } ); } private void checkNewVehicle(Vehicle newVehicle) { assertEquals( "Bus", newVehicle.getName() ); assertEquals( 1, newVehicle.getTransports().size() ); Transport t = (Transport) newVehicle.getTransports().iterator().next(); assertEquals( "Transport 2 -> 3", t.getName() ); assertEquals( "Node 2", t.getPickupNode().getName() ); assertEquals( "Node 3", t.getDeliveryNode().getName() ); } private void fillInitialData(SessionFactoryScope scope) { Tour tour = new Tour(); tour.setName( "Tour 1" ); Route route = new Route(); route.setName( "Route 1" ); ArrayList<Node> nodes = new ArrayList<Node>(); for ( int i = 0; i < 4; i++ ) { Node n = new Node(); n.setName( "Node " + i ); n.setTour( tour ); n.setRoute( route ); nodes.add( n ); } tour.setNodes( new HashSet<>( nodes ) ); route.setNodes( new HashSet<>( Arrays.asList( nodes.get( 0 ), nodes.get( 1 ), nodes.get( 2 ) ) ) ); Vehicle vehicle = new Vehicle(); vehicle.setName( "Car" ); route.setVehicles( Set.of( vehicle ) ); vehicle.setRoute( route ); Transport $0to1 = new Transport(); $0to1.setName( "Transport 0 -> 1" ); $0to1.setPickupNode( nodes.get( 0 ) ); $0to1.setDeliveryNode( nodes.get( 1 ) ); $0to1.setVehicle( vehicle ); Transport $1to2 = new Transport(); $1to2.setName( "Transport 1 -> 2" ); $1to2.setPickupNode( nodes.get( 1 ) ); $1to2.setDeliveryNode( nodes.get( 2 ) ); $1to2.setVehicle( vehicle ); vehicle.setTransports( new HashSet<>( Arrays.asList( $0to1, $1to2 ) ) ); scope.inTransaction( session -> session.persist( tour ) ); } @Entity(name = "Route") @Table(name = "HB_Route") public static
CascadeManagedAndTransientTest
java
resilience4j__resilience4j
resilience4j-feign/src/test/java/io/github/resilience4j/feign/Resilience4jFeignFallbackFactoryTest.java
{ "start": 1441, "end": 3075 }
class ____ { @ClassRule public static final WireMockClassRule WIRE_MOCK_RULE = new WireMockClassRule(8080); private static final String MOCK_URL = "http://localhost:8080/"; @Rule public WireMockClassRule instanceRule = WIRE_MOCK_RULE; private static TestService buildTestService(Function<Exception, ?> fallbackSupplier) { FeignDecorators decorators = FeignDecorators.builder() .withFallbackFactory(fallbackSupplier) .build(); return Feign.builder() .addCapability(Resilience4jFeign.capability(decorators)) .target(TestService.class, MOCK_URL); } private static void setupStub(int responseCode) { stubFor(get(urlPathEqualTo("/greeting")) .willReturn(aResponse() .withStatus(responseCode) .withHeader("Content-Type", "text/plain") .withBody("Hello, world!"))); } @Test public void should_successfully_get_a_response() { setupStub(200); TestService testService = buildTestService(e -> "my fallback"); String result = testService.greeting(); assertThat(result).isEqualTo("Hello, world!"); verify(1, getRequestedFor(urlPathEqualTo("/greeting"))); } @Test public void should_lazily_fail_on_invalid_fallback() { TestService testService = buildTestService(e -> "my fallback"); Throwable throwable = catchThrowable(testService::greeting); assertThat(throwable).isNotNull() .hasMessageContaining( "Cannot use the fallback [
Resilience4jFeignFallbackFactoryTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDatanodeDeath.java
{ "start": 1729, "end": 1805 }
class ____ that pipelines survive data node death and recovery. */ public
tests
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/TestStringCollectionGenerator.java
{ "start": 990, "end": 1711 }
class ____ implements TestCollectionGenerator<String> { @Override public SampleElements<String> samples() { return new Strings(); } @Override public Collection<String> create(Object... elements) { String[] array = new String[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (String) e; } return create(array); } protected abstract Collection<String> create(String[] elements); @Override public String[] createArray(int length) { return new String[length]; } /** Returns the original element list, unchanged. */ @Override public List<String> order(List<String> insertionOrder) { return insertionOrder; } }
TestStringCollectionGenerator
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/model/BindingGraph.java
{ "start": 17068, "end": 17748 }
interface ____ extends Node { /** The component represented by this node. */ @Override ComponentPath componentPath(); /** * Returns {@code true} if the component is a {@code @Subcomponent} or * {@code @ProductionSubcomponent}. */ boolean isSubcomponent(); /** * Returns {@code true} if the component is a real component, or {@code false} if it is a * fictional component based on a module. */ boolean isRealComponent(); /** The entry points on this component. */ ImmutableSet<DependencyRequest> entryPoints(); /** The scopes declared on this component. */ ImmutableSet<Scope> scopes(); } }
ComponentNode
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/impl/RouterStoreImpl.java
{ "start": 2090, "end": 3782 }
class ____ extends RouterStore { public RouterStoreImpl(StateStoreDriver driver) { super(driver); } @Override public GetRouterRegistrationResponse getRouterRegistration( GetRouterRegistrationRequest request) throws IOException { final RouterState partial = RouterState.newInstance(); partial.setAddress(request.getRouterId()); final Query<RouterState> query = new Query<RouterState>(partial); RouterState record = getDriver().get(getRecordClass(), query); if (record != null) { overrideExpiredRecord(record); } GetRouterRegistrationResponse response = GetRouterRegistrationResponse.newInstance(); response.setRouter(record); return response; } @Override public GetRouterRegistrationsResponse getRouterRegistrations( GetRouterRegistrationsRequest request) throws IOException { // Get all values from the cache QueryResult<RouterState> recordsAndTimeStamp = getCachedRecordsAndTimeStamp(); List<RouterState> records = recordsAndTimeStamp.getRecords(); long timestamp = recordsAndTimeStamp.getTimestamp(); // Generate response GetRouterRegistrationsResponse response = GetRouterRegistrationsResponse.newInstance(); response.setRouters(records); response.setTimestamp(timestamp); return response; } @Override public RouterHeartbeatResponse routerHeartbeat(RouterHeartbeatRequest request) throws IOException { RouterState record = request.getRouter(); boolean status = getDriver().put(record, true, false); RouterHeartbeatResponse response = RouterHeartbeatResponse.newInstance(status); return response; } }
RouterStoreImpl
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/JavaEitherSerializerSnapshot.java
{ "start": 1251, "end": 2802 }
class ____<L, R> extends CompositeTypeSerializerSnapshot<Either<L, R>, EitherSerializer<L, R>> { private static final int CURRENT_VERSION = 1; /** Constructor for read instantiation. */ public JavaEitherSerializerSnapshot() {} /** Constructor to create the snapshot for writing. */ public JavaEitherSerializerSnapshot(EitherSerializer<L, R> eitherSerializer) { super(eitherSerializer); } @Override protected int getCurrentOuterSnapshotVersion() { return CURRENT_VERSION; } @Override public TypeSerializerSchemaCompatibility<Either<L, R>> resolveSchemaCompatibility( TypeSerializerSnapshot<Either<L, R>> oldSerializerSnapshot) { return super.resolveSchemaCompatibility(oldSerializerSnapshot); } @Override protected EitherSerializer<L, R> createOuterSerializerWithNestedSerializers( TypeSerializer<?>[] nestedSerializers) { @SuppressWarnings("unchecked") TypeSerializer<L> leftSerializer = (TypeSerializer<L>) nestedSerializers[0]; @SuppressWarnings("unchecked") TypeSerializer<R> rightSerializer = (TypeSerializer<R>) nestedSerializers[1]; return new EitherSerializer<>(leftSerializer, rightSerializer); } @Override protected TypeSerializer<?>[] getNestedSerializers(EitherSerializer<L, R> outerSerializer) { return new TypeSerializer<?>[] { outerSerializer.getLeftSerializer(), outerSerializer.getRightSerializer() }; } }
JavaEitherSerializerSnapshot
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/autodetect/UpdateParams.java
{ "start": 4076, "end": 5698 }
class ____ { private String jobId; private ModelPlotConfig modelPlotConfig; private PerPartitionCategorizationConfig perPartitionCategorizationConfig; private List<JobUpdate.DetectorUpdate> detectorUpdates; private MlFilter filter; private boolean updateScheduledEvents; public Builder(String jobId) { this.jobId = Objects.requireNonNull(jobId); } public Builder modelPlotConfig(ModelPlotConfig modelPlotConfig) { this.modelPlotConfig = modelPlotConfig; return this; } public Builder perPartitionCategorizationConfig(PerPartitionCategorizationConfig perPartitionCategorizationConfig) { this.perPartitionCategorizationConfig = perPartitionCategorizationConfig; return this; } public Builder detectorUpdates(List<JobUpdate.DetectorUpdate> detectorUpdates) { this.detectorUpdates = detectorUpdates; return this; } public Builder filter(MlFilter filter) { this.filter = filter; return this; } public Builder updateScheduledEvents(boolean updateScheduledEvents) { this.updateScheduledEvents = updateScheduledEvents; return this; } public UpdateParams build() { return new UpdateParams( jobId, modelPlotConfig, perPartitionCategorizationConfig, detectorUpdates, filter, updateScheduledEvents ); } } }
Builder
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RouterFunctions.java
{ "start": 50528, "end": 51383 }
class ____<T extends ServerResponse> extends AbstractRouterFunction<T> { private final RouterFunction<T> first; private final RouterFunction<T> second; public SameComposedRouterFunction(RouterFunction<T> first, RouterFunction<T> second) { this.first = first; this.second = second; } @Override public Mono<HandlerFunction<T>> route(ServerRequest request) { return Flux.concat(this.first.route(request), Mono.defer(() -> this.second.route(request))) .next(); } @Override public void accept(Visitor visitor) { this.first.accept(visitor); this.second.accept(visitor); } } /** * A composed routing function that first invokes one function, * and then invokes another function (of a different response type) * if this route had {@linkplain Mono#empty() no result}. */ static final
SameComposedRouterFunction
java
netty__netty
resolver-dns/src/main/java/io/netty/resolver/dns/DnsQueryContextManager.java
{ "start": 6526, "end": 7670 }
class ____ { private final DnsQueryIdSpace idSpace = new DnsQueryIdSpace(); // We increment on every usage so start with -1, this will ensure we start with 0 as first id. private final IntObjectMap<DnsQueryContext> map = new IntObjectHashMap<DnsQueryContext>(); synchronized int add(DnsQueryContext ctx) { int id = idSpace.nextId(); if (id == -1) { // -1 means that we couldn't reserve an id to use. In this case return early and not store the // context in the map. return -1; } DnsQueryContext oldCtx = map.put(id, ctx); assert oldCtx == null; return id; } synchronized DnsQueryContext get(int id) { return map.get(id); } synchronized DnsQueryContext remove(int id) { DnsQueryContext result = map.remove(id); if (result != null) { idSpace.pushId(id); } assert result != null : "DnsQueryContext not found, id: " + id; return result; } } }
DnsQueryContextMap
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/functions/co/BroadcastProcessFunction.java
{ "start": 2397, "end": 5193 }
class ____<IN1, IN2, OUT> extends BaseBroadcastProcessFunction { private static final long serialVersionUID = 8352559162119034453L; /** * This method is called for each element in the (non-broadcast) {@link * org.apache.flink.streaming.api.datastream.DataStream data stream}. * * <p>This function can output zero or more elements using the {@link Collector} parameter, * query the current processing/event time, and also query and update the local keyed state. * Finally, it has <b>read-only</b> access to the broadcast state. The context is only valid * during the invocation of this method, do not store it. * * @param value The stream element. * @param ctx A {@link ReadOnlyContext} that allows querying the timestamp of the element, * querying the current processing/event time and updating the broadcast state. The context * is only valid during the invocation of this method, do not store it. * @param out The collector to emit resulting elements to * @throws Exception The function may throw exceptions which cause the streaming program to fail * and go into recovery. */ public abstract void processElement( final IN1 value, final ReadOnlyContext ctx, final Collector<OUT> out) throws Exception; /** * This method is called for each element in the {@link * org.apache.flink.streaming.api.datastream.BroadcastStream broadcast stream}. * * <p>This function can output zero or more elements using the {@link Collector} parameter, * query the current processing/event time, and also query and update the internal {@link * org.apache.flink.api.common.state.BroadcastState broadcast state}. These can be done through * the provided {@link Context}. The context is only valid during the invocation of this method, * do not store it. * * @param value The stream element. * @param ctx A {@link Context} that allows querying the timestamp of the element, querying the * current processing/event time and updating the broadcast state. The context is only valid * during the invocation of this method, do not store it. * @param out The collector to emit resulting elements to * @throws Exception The function may throw exceptions which cause the streaming program to fail * and go into recovery. */ public abstract void processBroadcastElement( final IN2 value, final Context ctx, final Collector<OUT> out) throws Exception; /** * A {@link BaseBroadcastProcessFunction.Context context} available to the broadcast side of a * {@link org.apache.flink.streaming.api.datastream.BroadcastConnectedStream}. */ public abstract
BroadcastProcessFunction
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/system/OutputCaptureRuleTests.java
{ "start": 894, "end": 2072 }
class ____ { @Rule public OutputCaptureRule output = new OutputCaptureRule(); @Test public void toStringShouldReturnAllCapturedOutput() { System.out.println("Hello World"); assertThat(this.output.toString()).contains("Hello World"); } @Test public void getAllShouldReturnAllCapturedOutput() { System.out.println("Hello World"); System.err.println("Hello Error"); assertThat(this.output.getAll()).contains("Hello World", "Hello Error"); } @Test public void getOutShouldOnlyReturnOutputCapturedFromSystemOut() { System.out.println("Hello World"); System.err.println("Hello Error"); assertThat(this.output.getOut()).contains("Hello World"); assertThat(this.output.getOut()).doesNotContain("Hello Error"); } @Test public void getErrShouldOnlyReturnOutputCapturedFromSystemErr() { System.out.println("Hello World"); System.err.println("Hello Error"); assertThat(this.output.getErr()).contains("Hello Error"); assertThat(this.output.getErr()).doesNotContain("Hello World"); } @Test public void captureShouldBeAssertable() { System.out.println("Hello World"); assertThat(this.output).contains("Hello World"); } }
OutputCaptureRuleTests
java
apache__kafka
test-common/test-common-runtime/src/test/java/org/apache/kafka/common/test/junit/ClusterTestExtensionsUnitTest.java
{ "start": 1237, "end": 3036 }
class ____ { static List<ClusterConfig> cfgEmpty() { return List.of(); } @SuppressWarnings({"unchecked", "rawtypes"}) private ExtensionContext buildExtensionContext(String methodName) throws Exception { ExtensionContext extensionContext = mock(ExtensionContext.class); Class clazz = ClusterTestExtensionsUnitTest.class; Method method = clazz.getDeclaredMethod(methodName); when(extensionContext.getRequiredTestClass()).thenReturn(clazz); when(extensionContext.getRequiredTestMethod()).thenReturn(method); return extensionContext; } @Test void testProcessClusterTemplate() throws Exception { ClusterTestExtensions ext = new ClusterTestExtensions(); ExtensionContext context = buildExtensionContext("cfgEmpty"); ClusterTemplate annot = mock(ClusterTemplate.class); when(annot.value()).thenReturn("").thenReturn(" ").thenReturn("cfgEmpty"); Assertions.assertEquals( "ClusterTemplate value can't be empty string.", Assertions.assertThrows(IllegalStateException.class, () -> ext.processClusterTemplate(context, annot) ).getMessage() ); Assertions.assertEquals( "ClusterTemplate value can't be empty string.", Assertions.assertThrows(IllegalStateException.class, () -> ext.processClusterTemplate(context, annot) ).getMessage() ); Assertions.assertEquals( "ClusterConfig generator method should provide at least one config", Assertions.assertThrows(IllegalStateException.class, () -> ext.processClusterTemplate(context, annot) ).getMessage() ); } }
ClusterTestExtensionsUnitTest
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/codec/AbstractJacksonEncoder.java
{ "start": 2715, "end": 13999 }
class ____<T extends ObjectMapper> extends JacksonCodecSupport<T> implements HttpMessageEncoder<Object> { private static final byte[] NEWLINE_SEPARATOR = {'\n'}; private static final byte[] EMPTY_BYTES = new byte[0]; private static final Map<String, JsonEncoding> ENCODINGS; static { ENCODINGS = CollectionUtils.newHashMap(JsonEncoding.values().length); for (JsonEncoding encoding : JsonEncoding.values()) { ENCODINGS.put(encoding.getJavaName(), encoding); } ENCODINGS.put("US-ASCII", JsonEncoding.UTF8); } private final List<MediaType> streamingMediaTypes = new ArrayList<>(1); /** * Construct a new instance with the provided {@link MapperBuilder builder} * customized with the {@link tools.jackson.databind.JacksonModule}s found * by {@link MapperBuilder#findModules(ClassLoader)} and {@link MimeType}s. */ protected AbstractJacksonEncoder(MapperBuilder<T, ?> builder, MimeType... mimeTypes) { super(builder, mimeTypes); } /** * Construct a new instance with the provided {@link ObjectMapper} and {@link MimeType}s. */ protected AbstractJacksonEncoder(T mapper, MimeType... mimeTypes) { super(mapper, mimeTypes); } /** * Configure "streaming" media types for which flushing should be performed * automatically vs at the end of the stream. */ public void setStreamingMediaTypes(List<MediaType> mediaTypes) { this.streamingMediaTypes.clear(); this.streamingMediaTypes.addAll(mediaTypes); } @Override @SuppressWarnings("removal") public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) { if (!supportsMimeType(mimeType)) { return false; } if (mimeType != null && mimeType.getCharset() != null) { Charset charset = mimeType.getCharset(); if (!ENCODINGS.containsKey(charset.name())) { return false; } } if (this.mapperRegistrations != null && selectMapper(elementType, mimeType) == null) { return false; } Class<?> elementClass = elementType.toClass(); if (MappingJacksonValue.class.isAssignableFrom(elementClass)) { throw new UnsupportedOperationException("MappingJacksonValue is not supported, use hints instead"); } return !ServerSentEvent.class.isAssignableFrom(elementClass); } @Override public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory, ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { Assert.notNull(inputStream, "'inputStream' must not be null"); Assert.notNull(bufferFactory, "'bufferFactory' must not be null"); Assert.notNull(elementType, "'elementType' must not be null"); return Flux.deferContextual(contextView -> { Map<String, Object> hintsToUse = contextView.isEmpty() ? hints : Hints.merge(hints, ContextView.class.getName(), contextView); if (inputStream instanceof Mono) { return Mono.from(inputStream) .map(value -> encodeValue(value, bufferFactory, elementType, mimeType, hintsToUse)) .flux(); } try { T mapper = selectMapper(elementType, mimeType); if (mapper == null) { throw new IllegalStateException("No ObjectMapper for " + elementType); } ObjectWriter writer = createObjectWriter(mapper, elementType, mimeType, hintsToUse); ByteArrayBuilder byteBuilder = new ByteArrayBuilder(writer.generatorFactory()._getBufferRecycler()); JsonEncoding encoding = getJsonEncoding(mimeType); JsonGenerator generator = mapper.createGenerator(byteBuilder, encoding); SequenceWriter sequenceWriter = writer.writeValues(generator); byte[] separator = getStreamingMediaTypeSeparator(mimeType); Flux<DataBuffer> dataBufferFlux; if (separator != null) { dataBufferFlux = Flux.from(inputStream).map(value -> encodeStreamingValue( value, bufferFactory, hintsToUse, sequenceWriter, byteBuilder, EMPTY_BYTES, separator)); } else { JsonArrayJoinHelper helper = new JsonArrayJoinHelper(); // Do not prepend JSON array prefix until first signal is known, onNext vs onError // Keeps response not committed for error handling dataBufferFlux = Flux.from(inputStream) .map(value -> { byte[] prefix = helper.getPrefix(); byte[] delimiter = helper.getDelimiter(); DataBuffer dataBuffer = encodeStreamingValue( value, bufferFactory, hintsToUse, sequenceWriter, byteBuilder, delimiter, EMPTY_BYTES); return (prefix.length > 0 ? bufferFactory.join(List.of(bufferFactory.wrap(prefix), dataBuffer)) : dataBuffer); }) .switchIfEmpty(Mono.fromCallable(() -> bufferFactory.wrap(helper.getPrefix()))) .concatWith(Mono.fromCallable(() -> bufferFactory.wrap(helper.getSuffix()))); } return dataBufferFlux .doOnNext(dataBuffer -> Hints.touchDataBuffer(dataBuffer, hintsToUse, logger)) .doAfterTerminate(() -> { try { generator.close(); byteBuilder.release(); } catch (JacksonIOException ex) { logger.error("Could not close Encoder resources", ex); } }); } catch (JacksonIOException ex) { return Flux.error(ex); } }); } @Override public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory, ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { T mapper = selectMapper(valueType, mimeType); if (mapper == null) { throw new IllegalStateException("No ObjectMapper for " + valueType); } ObjectWriter writer = createObjectWriter(mapper, valueType, mimeType, hints); ByteArrayBuilder byteBuilder = new ByteArrayBuilder(writer.generatorFactory()._getBufferRecycler()); try { JsonEncoding encoding = getJsonEncoding(mimeType); logValue(hints, value); try (JsonGenerator generator = writer.createGenerator(byteBuilder, encoding)) { writer.writeValue(generator, value); generator.flush(); } catch (InvalidDefinitionException ex) { throw new CodecException("Type definition error: " + ex.getType(), ex); } catch (JacksonException ex) { throw new EncodingException("JSON encoding error: " + ex.getOriginalMessage(), ex); } byte[] bytes = byteBuilder.toByteArray(); DataBuffer buffer = bufferFactory.allocateBuffer(bytes.length); buffer.write(bytes); Hints.touchDataBuffer(buffer, hints, logger); return buffer; } finally { byteBuilder.release(); } } private DataBuffer encodeStreamingValue( Object value, DataBufferFactory bufferFactory, @Nullable Map<String, Object> hints, SequenceWriter sequenceWriter, ByteArrayBuilder byteArrayBuilder, byte[] prefix, byte[] suffix) { logValue(hints, value); try { sequenceWriter.write(value); sequenceWriter.flush(); } catch (InvalidDefinitionException ex) { throw new CodecException("Type definition error: " + ex.getType(), ex); } catch (JacksonException ex) { throw new EncodingException("JSON encoding error: " + ex.getOriginalMessage(), ex); } byte[] bytes = byteArrayBuilder.toByteArray(); byteArrayBuilder.reset(); int offset; int length; if (bytes.length > 0 && bytes[0] == ' ') { // SequenceWriter writes an unnecessary space in between values offset = 1; length = bytes.length - 1; } else { offset = 0; length = bytes.length; } DataBuffer buffer = bufferFactory.allocateBuffer(length + prefix.length + suffix.length); if (prefix.length != 0) { buffer.write(prefix); } buffer.write(bytes, offset, length); if (suffix.length != 0) { buffer.write(suffix); } Hints.touchDataBuffer(buffer, hints, logger); return buffer; } private void logValue(@Nullable Map<String, Object> hints, Object value) { if (!Hints.isLoggingSuppressed(hints)) { LogFormatUtils.traceDebug(logger, traceOn -> { String formatted = LogFormatUtils.formatValue(value, !traceOn); return Hints.getLogPrefix(hints) + "Encoding [" + formatted + "]"; }); } } private ObjectWriter createObjectWriter( T mapper, ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) { JavaType javaType = getJavaType(valueType.getType(), null); Class<?> jsonView = null; FilterProvider filters = null; if (hints != null) { jsonView = (Class<?>) hints.get(JacksonCodecSupport.JSON_VIEW_HINT); filters = (FilterProvider) hints.get(FILTER_PROVIDER_HINT); } ObjectWriter writer = (jsonView != null ? mapper.writerWithView(jsonView) : mapper.writer()); if (filters != null) { writer = writer.with(filters); } if (javaType.isContainerType()) { writer = writer.forType(javaType); } return customizeWriter(writer, mimeType, valueType, hints); } /** * Subclasses can use this method to customize the {@link ObjectWriter} used * for writing values. * @param writer the writer instance to customize * @param mimeType the selected MIME type * @param elementType the type of element values to write * @param hints a map with serialization hints; the Reactor Context, when * available, may be accessed under the key * {@code ContextView.class.getName()} * @return the customized {@code ObjectWriter} to use */ protected ObjectWriter customizeWriter(ObjectWriter writer, @Nullable MimeType mimeType, ResolvableType elementType, @Nullable Map<String, Object> hints) { return writer; } /** * Return the separator to use for the given mime type. * <p>By default, this method returns new line {@code "\n"} if the given * mime type is one of the configured {@link #setStreamingMediaTypes(List) * streaming} mime types. */ protected byte @Nullable [] getStreamingMediaTypeSeparator(@Nullable MimeType mimeType) { for (MediaType streamingMediaType : this.streamingMediaTypes) { if (streamingMediaType.isCompatibleWith(mimeType)) { return NEWLINE_SEPARATOR; } } return null; } /** * Determine the JSON encoding to use for the given mime type. * @param mimeType the mime type as requested by the caller * @return the JSON encoding to use (never {@code null}) */ protected JsonEncoding getJsonEncoding(@Nullable MimeType mimeType) { if (mimeType != null && mimeType.getCharset() != null) { Charset charset = mimeType.getCharset(); JsonEncoding result = ENCODINGS.get(charset.name()); if (result != null) { return result; } } return JsonEncoding.UTF8; } // HttpMessageEncoder @Override public List<MimeType> getEncodableMimeTypes() { return getMimeTypes(); } @Override public List<MimeType> getEncodableMimeTypes(ResolvableType elementType) { return getMimeTypes(elementType); } @Override public List<MediaType> getStreamingMediaTypes() { return Collections.unmodifiableList(this.streamingMediaTypes); } @Override public Map<String, Object> getEncodeHints(@Nullable ResolvableType actualType, ResolvableType elementType, @Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) { return (actualType != null ? getHints(actualType) : Hints.none()); } // JacksonCodecSupport @Override protected <A extends Annotation> @Nullable A getAnnotation(MethodParameter parameter, Class<A> annotType) { return parameter.getMethodAnnotation(annotType); } private static
AbstractJacksonEncoder
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/tofix/ExternalTypeCustomResolver1288Test.java
{ "start": 1275, "end": 1384 }
class ____ extends DatabindTestUtil { // [databind#1288] public static
ExternalTypeCustomResolver1288Test
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ext/javatime/deser/key/ZonedDateTimeKeyDeserializerTest.java
{ "start": 385, "end": 2377 }
class ____ extends DateTimeTestBase { private final ObjectMapper MAPPER = newMapper(); private final TypeReference<Map<ZonedDateTime, String>> MAP_TYPE_REF = new TypeReference<Map<ZonedDateTime, String>>() {}; @Test public void Instant_style_can_be_deserialized() throws Exception { Map<ZonedDateTime, String> map = MAPPER.readValue(getMap("2015-07-24T12:23:34.184Z"), MAP_TYPE_REF); Map.Entry<ZonedDateTime, String> entry = map.entrySet().iterator().next(); assertEquals("2015-07-24T12:23:34.184Z", entry.getKey().toString()); } @Test public void ZonedDateTime_with_zone_name_can_be_deserialized() throws Exception { Map<ZonedDateTime, String> map = MAPPER.readValue(getMap("2015-07-24T12:23:34.184Z[UTC]"), MAP_TYPE_REF); Map.Entry<ZonedDateTime, String> entry = map.entrySet().iterator().next(); assertEquals("2015-07-24T12:23:34.184Z[UTC]", entry.getKey().toString()); } // NOTE: Java 9+ test @Test public void ZonedDateTime_with_place_name_can_be_deserialized() throws Exception { Map<ZonedDateTime, String> map = MAPPER.readValue(getMap("2015-07-24T12:23:34.184Z[Europe/London]"), MAP_TYPE_REF); Map.Entry<ZonedDateTime, String> entry = map.entrySet().iterator().next(); assertEquals("2015-07-24T13:23:34.184+01:00[Europe/London]", entry.getKey().toString()); } @Test public void ZonedDateTime_with_offset_can_be_deserialized() throws Exception { Map<ZonedDateTime, String> map = MAPPER.readValue(getMap("2015-07-24T12:23:34.184+02:00"), MAP_TYPE_REF); Map.Entry<ZonedDateTime, String> entry = map.entrySet().iterator().next(); assertEquals("2015-07-24T12:23:34.184+02:00", entry.getKey().toString()); } private static String getMap(String input) { return "{\"" + input + "\": \"This is a string\"}"; } }
ZonedDateTimeKeyDeserializerTest
java
apache__kafka
storage/src/test/java/org/apache/kafka/server/log/remote/metadata/storage/TopicBasedRemoteLogMetadataManagerTest.java
{ "start": 2828, "end": 21852 }
class ____ { private static final int SEG_SIZE = 1048576; private final ClusterInstance clusterInstance; private final RemotePartitionMetadataStore spyRemotePartitionMetadataEventHandler = spy(new RemotePartitionMetadataStore()); private final Time time = Time.SYSTEM; private TopicBasedRemoteLogMetadataManager remoteLogMetadataManager; TopicBasedRemoteLogMetadataManagerTest(ClusterInstance clusterInstance) { this.clusterInstance = clusterInstance; } private TopicBasedRemoteLogMetadataManager topicBasedRlmm() { if (remoteLogMetadataManager == null) remoteLogMetadataManager = RemoteLogMetadataManagerTestUtils.builder() .bootstrapServers(clusterInstance.bootstrapServers()) .remotePartitionMetadataStore(() -> spyRemotePartitionMetadataEventHandler) .build(); return remoteLogMetadataManager; } @AfterEach public void teardown() throws IOException { if (remoteLogMetadataManager != null) remoteLogMetadataManager.close(); } @ClusterTest public void testDoesTopicExist() throws ExecutionException, InterruptedException { try (Admin admin = clusterInstance.admin()) { String topic = "test-topic-exist"; admin.createTopics(List.of(new NewTopic(topic, 1, (short) 1))).all().get(); clusterInstance.waitTopicCreation(topic, 1); boolean doesTopicExist = topicBasedRlmm().doesTopicExist(admin, topic); assertTrue(doesTopicExist); } } @ClusterTest public void testTopicDoesNotExist() throws ExecutionException, InterruptedException { try (Admin admin = clusterInstance.admin()) { String topic = "dummy-test-topic"; boolean doesTopicExist = topicBasedRlmm().doesTopicExist(admin, topic); assertFalse(doesTopicExist); } } @SuppressWarnings("unchecked") @ClusterTest public void testDoesTopicExistWithAdminClientExecutionError() throws ExecutionException, InterruptedException { // Create a mock Admin client that throws an ExecutionException (not UnknownTopicOrPartitionException) Admin mockAdmin = mock(Admin.class); DescribeTopicsResult mockDescribeTopicsResult = mock(DescribeTopicsResult.class); KafkaFuture<TopicDescription> mockFuture = mock(KafkaFuture.class); String topic = "test-topic"; // Set up the mock to throw a RuntimeException wrapped in ExecutionException when(mockAdmin.describeTopics(anySet())).thenReturn(mockDescribeTopicsResult); when(mockDescribeTopicsResult.topicNameValues()).thenReturn(Map.of(topic, mockFuture)); when(mockFuture.get()).thenThrow(new ExecutionException("Admin client connection error", new RuntimeException("Connection failed"))); // The method should re-throw the ExecutionException since it's not an UnknownTopicOrPartitionException TopicBasedRemoteLogMetadataManager rlmm = topicBasedRlmm(); assertThrows(ExecutionException.class, () -> rlmm.doesTopicExist(mockAdmin, topic)); } @ClusterTest public void testWithNoAssignedPartitions() { // This test checks simple lifecycle of TopicBasedRemoteLogMetadataManager with out assigning any leader/follower partitions. // This should close successfully releasing the resources. topicBasedRlmm(); } @ClusterTest public void testNewPartitionUpdates() throws Exception { // Create topics. String leaderTopic = "new-leader"; String followerTopic = "new-follower"; try (Admin admin = clusterInstance.admin()) { // Set broker id 0 as the first entry which is taken as the leader. admin.createTopics(List.of(new NewTopic(leaderTopic, Map.of(0, List.of(0, 1, 2))))).all().get(); clusterInstance.waitTopicCreation(leaderTopic, 1); admin.createTopics(List.of(new NewTopic(followerTopic, Map.of(0, List.of(1, 2, 0))))).all().get(); clusterInstance.waitTopicCreation(followerTopic, 1); } final TopicIdPartition newLeaderTopicIdPartition = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition(leaderTopic, 0)); final TopicIdPartition newFollowerTopicIdPartition = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition(followerTopic, 0)); CountDownLatch initializationLatch = new CountDownLatch(2); doAnswer(invocationOnMock -> { Object result = invocationOnMock.callRealMethod(); initializationLatch.countDown(); return result; }).when(spyRemotePartitionMetadataEventHandler).markInitialized(any()); CountDownLatch handleRemoteLogSegmentMetadataLatch = new CountDownLatch(2); doAnswer(invocationOnMock -> { Object result = invocationOnMock.callRealMethod(); handleRemoteLogSegmentMetadataLatch.countDown(); return result; }).when(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(any()); // Add segments for these partitions but an exception is received as they have not yet been subscribed. // These messages would have been published to the respective metadata topic partitions but the ConsumerManager // has not yet been subscribing as they are not yet registered. RemoteLogSegmentMetadata leaderSegmentMetadata = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(newLeaderTopicIdPartition, Uuid.randomUuid()), 0, 100, -1L, 0, time.milliseconds(), SEG_SIZE, Map.of(0, 0L)); assertThrows(Exception.class, () -> topicBasedRlmm().addRemoteLogSegmentMetadata(leaderSegmentMetadata).get()); RemoteLogSegmentMetadata followerSegmentMetadata = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(newFollowerTopicIdPartition, Uuid.randomUuid()), 0, 100, -1L, 0, time.milliseconds(), SEG_SIZE, Map.of(0, 0L)); assertThrows(Exception.class, () -> topicBasedRlmm().addRemoteLogSegmentMetadata(followerSegmentMetadata).get()); // `listRemoteLogSegments` will receive an exception as these topic partitions are not yet registered. assertThrows(RemoteResourceNotFoundException.class, () -> topicBasedRlmm().listRemoteLogSegments(newLeaderTopicIdPartition)); assertThrows(RemoteResourceNotFoundException.class, () -> topicBasedRlmm().listRemoteLogSegments(newFollowerTopicIdPartition)); assertFalse(topicBasedRlmm().isReady(newLeaderTopicIdPartition)); assertFalse(topicBasedRlmm().isReady(newFollowerTopicIdPartition)); topicBasedRlmm().onPartitionLeadershipChanges(Set.of(newLeaderTopicIdPartition), Set.of(newFollowerTopicIdPartition)); // RemoteLogSegmentMetadata events are already published, and topicBasedRlmm's consumer manager will start // fetching those events and build the cache. assertTrue(initializationLatch.await(30_000, TimeUnit.MILLISECONDS)); assertTrue(handleRemoteLogSegmentMetadataLatch.await(30_000, TimeUnit.MILLISECONDS)); verify(spyRemotePartitionMetadataEventHandler).markInitialized(newLeaderTopicIdPartition); verify(spyRemotePartitionMetadataEventHandler).markInitialized(newFollowerTopicIdPartition); verify(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(leaderSegmentMetadata); verify(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(followerSegmentMetadata); assertTrue(topicBasedRlmm().listRemoteLogSegments(newLeaderTopicIdPartition).hasNext()); assertTrue(topicBasedRlmm().listRemoteLogSegments(newFollowerTopicIdPartition).hasNext()); assertTrue(topicBasedRlmm().isReady(newLeaderTopicIdPartition)); assertTrue(topicBasedRlmm().isReady(newFollowerTopicIdPartition)); } @ClusterTest public void testRemoteLogSizeCalculationForUnknownTopicIdPartitionThrows() { TopicIdPartition topicIdPartition = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("singleton", 0)); assertThrows(RemoteResourceNotFoundException.class, () -> topicBasedRlmm().remoteLogSize(topicIdPartition, 0)); } @ClusterTest public void testRemoteLogSizeCalculationWithSegmentsOfTheSameEpoch() throws RemoteStorageException, InterruptedException { TopicIdPartition topicIdPartition = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("singleton", 0)); TopicBasedRemoteLogMetadataManager topicBasedRemoteLogMetadataManager = topicBasedRlmm(); CountDownLatch initializationLatch = new CountDownLatch(1); doAnswer(invocationOnMock -> { Object result = invocationOnMock.callRealMethod(); initializationLatch.countDown(); return result; }).when(spyRemotePartitionMetadataEventHandler).markInitialized(any()); CountDownLatch handleRemoteLogSegmentMetadataLatch = new CountDownLatch(3); doAnswer(invocationOnMock -> { Object result = invocationOnMock.callRealMethod(); handleRemoteLogSegmentMetadataLatch.countDown(); return result; }).when(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(any()); RemoteLogSegmentMetadata firstSegmentMetadata = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(topicIdPartition, Uuid.randomUuid()), 0, 100, -1L, 0, time.milliseconds(), SEG_SIZE, Map.of(0, 0L)); RemoteLogSegmentMetadata secondSegmentMetadata = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(topicIdPartition, Uuid.randomUuid()), 100, 200, -1L, 0, time.milliseconds(), SEG_SIZE * 2, Map.of(0, 0L)); RemoteLogSegmentMetadata thirdSegmentMetadata = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(topicIdPartition, Uuid.randomUuid()), 200, 300, -1L, 0, time.milliseconds(), SEG_SIZE * 3, Map.of(0, 0L)); topicBasedRemoteLogMetadataManager.addRemoteLogSegmentMetadata(firstSegmentMetadata); topicBasedRemoteLogMetadataManager.addRemoteLogSegmentMetadata(secondSegmentMetadata); topicBasedRemoteLogMetadataManager.addRemoteLogSegmentMetadata(thirdSegmentMetadata); topicBasedRemoteLogMetadataManager.onPartitionLeadershipChanges(Set.of(topicIdPartition), Set.of()); // RemoteLogSegmentMetadata events are already published, and topicBasedRlmm's consumer manager will start // fetching those events and build the cache. assertTrue(initializationLatch.await(30_000, TimeUnit.MILLISECONDS)); assertTrue(handleRemoteLogSegmentMetadataLatch.await(30_000, TimeUnit.MILLISECONDS)); verify(spyRemotePartitionMetadataEventHandler).markInitialized(topicIdPartition); verify(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(firstSegmentMetadata); verify(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(secondSegmentMetadata); verify(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(thirdSegmentMetadata); Long remoteLogSize = topicBasedRemoteLogMetadataManager.remoteLogSize(topicIdPartition, 0); assertEquals(SEG_SIZE * 6, remoteLogSize); } @ClusterTest public void testRemoteLogSizeCalculationWithSegmentsOfDifferentEpochs() throws RemoteStorageException, InterruptedException { TopicIdPartition topicIdPartition = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("singleton", 0)); TopicBasedRemoteLogMetadataManager topicBasedRemoteLogMetadataManager = topicBasedRlmm(); CountDownLatch initializationLatch = new CountDownLatch(1); doAnswer(invocationOnMock -> { Object result = invocationOnMock.callRealMethod(); initializationLatch.countDown(); return result; }).when(spyRemotePartitionMetadataEventHandler).markInitialized(any()); CountDownLatch handleRemoteLogSegmentMetadataLatch = new CountDownLatch(3); doAnswer(invocationOnMock -> { Object result = invocationOnMock.callRealMethod(); handleRemoteLogSegmentMetadataLatch.countDown(); return result; }).when(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(any()); RemoteLogSegmentMetadata firstSegmentMetadata = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(topicIdPartition, Uuid.randomUuid()), 0, 100, -1L, 0, time.milliseconds(), SEG_SIZE, Map.of(0, 0L)); RemoteLogSegmentMetadata secondSegmentMetadata = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(topicIdPartition, Uuid.randomUuid()), 100, 200, -1L, 0, time.milliseconds(), SEG_SIZE * 2, Map.of(1, 100L)); RemoteLogSegmentMetadata thirdSegmentMetadata = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(topicIdPartition, Uuid.randomUuid()), 200, 300, -1L, 0, time.milliseconds(), SEG_SIZE * 3, Map.of(2, 200L)); topicBasedRemoteLogMetadataManager.addRemoteLogSegmentMetadata(firstSegmentMetadata); topicBasedRemoteLogMetadataManager.addRemoteLogSegmentMetadata(secondSegmentMetadata); topicBasedRemoteLogMetadataManager.addRemoteLogSegmentMetadata(thirdSegmentMetadata); topicBasedRemoteLogMetadataManager.onPartitionLeadershipChanges(Set.of(topicIdPartition), Set.of()); // RemoteLogSegmentMetadata events are already published, and topicBasedRlmm's consumer manager will start // fetching those events and build the cache. assertTrue(initializationLatch.await(30_000, TimeUnit.MILLISECONDS)); assertTrue(handleRemoteLogSegmentMetadataLatch.await(30_000, TimeUnit.MILLISECONDS)); verify(spyRemotePartitionMetadataEventHandler).markInitialized(topicIdPartition); verify(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(firstSegmentMetadata); verify(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(secondSegmentMetadata); verify(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(thirdSegmentMetadata); assertEquals(SEG_SIZE, topicBasedRemoteLogMetadataManager.remoteLogSize(topicIdPartition, 0)); assertEquals(SEG_SIZE * 2, topicBasedRemoteLogMetadataManager.remoteLogSize(topicIdPartition, 1)); assertEquals(SEG_SIZE * 3, topicBasedRemoteLogMetadataManager.remoteLogSize(topicIdPartition, 2)); } @ClusterTest public void testRemoteLogSizeCalculationWithSegmentsHavingNonExistentEpochs() throws RemoteStorageException, InterruptedException { TopicIdPartition topicIdPartition = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("singleton", 0)); TopicBasedRemoteLogMetadataManager topicBasedRemoteLogMetadataManager = topicBasedRlmm(); CountDownLatch initializationLatch = new CountDownLatch(1); doAnswer(invocationOnMock -> { Object result = invocationOnMock.callRealMethod(); initializationLatch.countDown(); return result; }).when(spyRemotePartitionMetadataEventHandler).markInitialized(any()); CountDownLatch handleRemoteLogSegmentMetadataLatch = new CountDownLatch(2); doAnswer(invocationOnMock -> { Object result = invocationOnMock.callRealMethod(); handleRemoteLogSegmentMetadataLatch.countDown(); return result; }).when(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(any()); RemoteLogSegmentMetadata firstSegmentMetadata = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(topicIdPartition, Uuid.randomUuid()), 0, 100, -1L, 0, time.milliseconds(), SEG_SIZE, Map.of(0, 0L)); RemoteLogSegmentMetadata secondSegmentMetadata = new RemoteLogSegmentMetadata(new RemoteLogSegmentId(topicIdPartition, Uuid.randomUuid()), 100, 200, -1L, 0, time.milliseconds(), SEG_SIZE * 2, Map.of(1, 100L)); topicBasedRemoteLogMetadataManager.addRemoteLogSegmentMetadata(firstSegmentMetadata); topicBasedRemoteLogMetadataManager.addRemoteLogSegmentMetadata(secondSegmentMetadata); topicBasedRemoteLogMetadataManager.onPartitionLeadershipChanges(Set.of(topicIdPartition), Set.of()); // RemoteLogSegmentMetadata events are already published, and topicBasedRlmm's consumer manager will start // fetching those events and build the cache. assertTrue(initializationLatch.await(30_000, TimeUnit.MILLISECONDS)); assertTrue(handleRemoteLogSegmentMetadataLatch.await(30_000, TimeUnit.MILLISECONDS)); verify(spyRemotePartitionMetadataEventHandler).markInitialized(topicIdPartition); verify(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(firstSegmentMetadata); verify(spyRemotePartitionMetadataEventHandler).handleRemoteLogSegmentMetadata(secondSegmentMetadata); assertEquals(0, topicBasedRemoteLogMetadataManager.remoteLogSize(topicIdPartition, 9001)); } @ClusterTest public void testInitializationFailure() throws IOException, InterruptedException { // Set up a custom exit procedure for testing final AtomicBoolean exitCalled = new AtomicBoolean(false); final AtomicInteger exitCode = new AtomicInteger(-1); // Set custom exit procedure that won't actually exit the process Exit.setExitProcedure((statusCode, message) -> { exitCalled.set(true); exitCode.set(statusCode); }); try (TopicBasedRemoteLogMetadataManager rlmm = new TopicBasedRemoteLogMetadataManager()) { // configure rlmm without bootstrap servers, so it will fail to initialize admin client. Map<String, Object> configs = Map.of( TopicBasedRemoteLogMetadataManagerConfig.LOG_DIR, TestUtils.tempDirectory("rlmm_segs_").getAbsolutePath(), TopicBasedRemoteLogMetadataManagerConfig.BROKER_ID, 0 ); rlmm.configure(configs); rlmm.onBrokerReady(); // Wait for initialization failure and exit procedure to be called TestUtils.waitForCondition(() -> exitCalled.get(), "Exit procedure should be called due to initialization failure"); // Verify exit code assertEquals(1, exitCode.get(), "Exit code should be 1"); } finally { // Restore default exit procedure Exit.resetExitProcedure(); } } }
TopicBasedRemoteLogMetadataManagerTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2356/Issue2356Mapper.java
{ "start": 388, "end": 497 }
interface ____ { Issue2356Mapper INSTANCE = Mappers.getMapper( Issue2356Mapper.class );
Issue2356Mapper
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/JpaMetamodelEntityInformationIntegrationTests.java
{ "start": 10746, "end": 10923 }
class ____ implements Serializable { Long id; Long feedRunId; } @MappedSuperclass @IdClass(BaseIdClass.class) @Access(AccessType.FIELD) public static abstract
BaseIdClass
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/transaction/managed/ManagedTransactionWithDataSourceTest.java
{ "start": 1337, "end": 3372 }
class ____ extends ManagedTransactionBase { @Mock private DataSource dataSource; @Mock private Connection connection; private Transaction transaction; @BeforeEach void setup() { this.transaction = new ManagedTransaction(dataSource, TransactionIsolationLevel.READ_COMMITTED, true); } @Override @Test void shouldGetConnection() throws SQLException { when(dataSource.getConnection()).thenReturn(connection); Connection result = transaction.getConnection(); assertEquals(connection, result); verify(connection).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); } @Test @Override void shouldNotCommitWhetherConnectionIsAutoCommit() throws SQLException { when(dataSource.getConnection()).thenReturn(connection); transaction.getConnection(); transaction.commit(); verify(connection, never()).commit(); verify(connection, never()).getAutoCommit(); } @Test @Override void shouldNotRollbackWhetherConnectionIsAutoCommit() throws SQLException { when(dataSource.getConnection()).thenReturn(connection); transaction.getConnection(); transaction.rollback(); verify(connection, never()).rollback(); verify(connection, never()).getAutoCommit(); } @Test @Override void shouldCloseWhenSetCloseConnectionIsTrue() throws SQLException { when(dataSource.getConnection()).thenReturn(connection); transaction.getConnection(); transaction.close(); verify(connection).close(); } @Test @Override void shouldNotCloseWhenSetCloseConnectionIsFalse() throws SQLException { transaction = new ManagedTransaction(dataSource, TransactionIsolationLevel.READ_COMMITTED, false); when(dataSource.getConnection()).thenReturn(connection); transaction.getConnection(); transaction.close(); verify(connection, never()).close(); } @Test @Override void shouldReturnNullWhenGetTimeout() throws SQLException { assertNull(transaction.getTimeout()); } }
ManagedTransactionWithDataSourceTest
java
quarkusio__quarkus
integration-tests/oidc-wiremock/src/main/java/io/quarkus/it/keycloak/TenantEcho2Resource.java
{ "start": 444, "end": 1857 }
class ____ { @Inject RoutingContext routingContext; @Inject SecurityIdentity identity; @Path("/hr") @Tenant("hr") @GET @Produces(MediaType.TEXT_PLAIN) public String getHrTenant() { return getTenant(); } @Path("/hr-jax-rs-perm-check") @Tenant("hr") @GET @Produces(MediaType.TEXT_PLAIN) public String getHrTenantJaxRsPermCheck() { return getTenant(); } @Path("/hr-classic-perm-check") @Tenant("hr") @GET @Produces(MediaType.TEXT_PLAIN) public String getHrTenantClassicPermCheck() { return getTenant(); } @Path("/hr-classic-and-jaxrs-perm-check") @Tenant("hr") @GET @Produces(MediaType.TEXT_PLAIN) public String getHrTenantClassicAndJaxRsPermCheck() { return getTenant(); } @Path("/default") @GET @Produces(MediaType.TEXT_PLAIN) public String getDefaultTenant() { return getTenant(); } private String getTenant() { return OidcUtils.TENANT_ID_ATTRIBUTE + "=" + routingContext.get(OidcUtils.TENANT_ID_ATTRIBUTE) + ", static.tenant.id=" + routingContext.get("static.tenant.id") + ", name=" + identity.getPrincipal().getName() + ", " + OidcUtils.TENANT_ID_SET_BY_ANNOTATION + "=" + routingContext.get(OidcUtils.TENANT_ID_SET_BY_ANNOTATION); } }
TenantEcho2Resource
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/MySqlDeleteTest_1.java
{ "start": 1052, "end": 2805 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "DELETE FROM a1, a2 USING t1 AS a1 INNER JOIN t2 AS a2 WHERE a1.id=a2.id;"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); assertEquals("DELETE FROM a1, a2\n" + "USING t1 a1\n" + "\tINNER JOIN t2 a2\n" + "WHERE a1.id = a2.id;", SQLUtils.toMySqlString(stmt)); assertEquals("delete from a1, a2\n" + "using t1 a1\n" + "\tinner join t2 a2\n" + "where a1.id = a2.id;", SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); assertEquals(1, statementList.size()); System.out.println(stmt.toString()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(2, visitor.getTables().size()); assertEquals(2, visitor.getColumns().size()); assertEquals(2, visitor.getConditions().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("t1"))); assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2"))); assertTrue(visitor.getColumns().contains(new Column("t1", "id"))); assertTrue(visitor.getColumns().contains(new Column("t2", "id"))); } }
MySqlDeleteTest_1
java
google__guava
android/guava/src/com/google/common/graph/Traverser.java
{ "start": 14606, "end": 19542 }
class ____<N> { final SuccessorsFunction<N> successorFunction; Traversal(SuccessorsFunction<N> successorFunction) { this.successorFunction = successorFunction; } static <N> Traversal<N> inGraph(SuccessorsFunction<N> graph) { Set<N> visited = new HashSet<>(); return new Traversal<N>(graph) { @Override @Nullable N visitNext(Deque<Iterator<? extends N>> horizon) { Iterator<? extends N> top = horizon.getFirst(); while (top.hasNext()) { N element = top.next(); // requireNonNull is safe because horizon contains only graph nodes. /* * TODO(cpovirk): Replace these two statements with one (`N element = * requireNonNull(top.next())`) once our checker supports it. * * (The problem is likely * https://github.com/jspecify/jspecify-reference-checker/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecAnnotatedTypeFactory.java#L896) */ requireNonNull(element); if (visited.add(element)) { return element; } } horizon.removeFirst(); return null; } }; } static <N> Traversal<N> inTree(SuccessorsFunction<N> tree) { return new Traversal<N>(tree) { @Override @Nullable N visitNext(Deque<Iterator<? extends N>> horizon) { Iterator<? extends N> top = horizon.getFirst(); if (top.hasNext()) { return checkNotNull(top.next()); } horizon.removeFirst(); return null; } }; } final Iterator<N> breadthFirst(Iterator<? extends N> startNodes) { return topDown(startNodes, InsertionOrder.BACK); } final Iterator<N> preOrder(Iterator<? extends N> startNodes) { return topDown(startNodes, InsertionOrder.FRONT); } /** * In top-down traversal, an ancestor node is always traversed before any of its descendant * nodes. The traversal order among descendant nodes (particularly aunts and nieces) are * determined by the {@code InsertionOrder} parameter: nieces are placed at the FRONT before * aunts for pre-order; while in BFS they are placed at the BACK after aunts. */ private Iterator<N> topDown(Iterator<? extends N> startNodes, InsertionOrder order) { Deque<Iterator<? extends N>> horizon = new ArrayDeque<>(); horizon.add(startNodes); return new AbstractIterator<N>() { @Override protected @Nullable N computeNext() { do { N next = visitNext(horizon); if (next != null) { Iterator<? extends N> successors = successorFunction.successors(next).iterator(); if (successors.hasNext()) { // BFS: horizon.addLast(successors) // Pre-order: horizon.addFirst(successors) order.insertInto(horizon, successors); } return next; } } while (!horizon.isEmpty()); return endOfData(); } }; } final Iterator<N> postOrder(Iterator<? extends N> startNodes) { Deque<N> ancestorStack = new ArrayDeque<>(); Deque<Iterator<? extends N>> horizon = new ArrayDeque<>(); horizon.add(startNodes); return new AbstractIterator<N>() { @Override protected @Nullable N computeNext() { for (N next = visitNext(horizon); next != null; next = visitNext(horizon)) { Iterator<? extends N> successors = successorFunction.successors(next).iterator(); if (!successors.hasNext()) { return next; } horizon.addFirst(successors); ancestorStack.push(next); } // TODO(b/192579700): Use a ternary once it no longer confuses our nullness checker. if (!ancestorStack.isEmpty()) { return ancestorStack.pop(); } return endOfData(); } }; } /** * Visits the next node from the top iterator of {@code horizon} and returns the visited node. * Null is returned to indicate reaching the end of the top iterator. * * <p>For example, if horizon is {@code [[a, b], [c, d], [e]]}, {@code visitNext()} will return * {@code [a, b, null, c, d, null, e, null]} sequentially, encoding the topological structure. * (Note, however, that the callers of {@code visitNext()} often insert additional iterators * into {@code horizon} between calls to {@code visitNext()}. This causes them to receive * additional values interleaved with those shown above.) */ abstract @Nullable N visitNext(Deque<Iterator<? extends N>> horizon); } /** Poor man's method reference for {@code Deque::addFirst} and {@code Deque::addLast}. */ private
Traversal
java
grpc__grpc-java
android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/XdsUpdateHealthServiceGrpc.java
{ "start": 252, "end": 7137 }
class ____ { private XdsUpdateHealthServiceGrpc() {} public static final java.lang.String SERVICE_NAME = "grpc.testing.XdsUpdateHealthService"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getSetServingMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "SetServing", requestType = io.grpc.testing.integration.EmptyProtos.Empty.class, responseType = io.grpc.testing.integration.EmptyProtos.Empty.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getSetServingMethod() { io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getSetServingMethod; if ((getSetServingMethod = XdsUpdateHealthServiceGrpc.getSetServingMethod) == null) { synchronized (XdsUpdateHealthServiceGrpc.class) { if ((getSetServingMethod = XdsUpdateHealthServiceGrpc.getSetServingMethod) == null) { XdsUpdateHealthServiceGrpc.getSetServingMethod = getSetServingMethod = io.grpc.MethodDescriptor.<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "SetServing")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller( io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller( io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance())) .build(); } } } return getSetServingMethod; } private static volatile io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getSetNotServingMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "SetNotServing", requestType = io.grpc.testing.integration.EmptyProtos.Empty.class, responseType = io.grpc.testing.integration.EmptyProtos.Empty.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getSetNotServingMethod() { io.grpc.MethodDescriptor<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty> getSetNotServingMethod; if ((getSetNotServingMethod = XdsUpdateHealthServiceGrpc.getSetNotServingMethod) == null) { synchronized (XdsUpdateHealthServiceGrpc.class) { if ((getSetNotServingMethod = XdsUpdateHealthServiceGrpc.getSetNotServingMethod) == null) { XdsUpdateHealthServiceGrpc.getSetNotServingMethod = getSetNotServingMethod = io.grpc.MethodDescriptor.<io.grpc.testing.integration.EmptyProtos.Empty, io.grpc.testing.integration.EmptyProtos.Empty>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "SetNotServing")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller( io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller( io.grpc.testing.integration.EmptyProtos.Empty.getDefaultInstance())) .build(); } } } return getSetNotServingMethod; } /** * Creates a new async stub that supports all call types for the service */ public static XdsUpdateHealthServiceStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceStub> factory = new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceStub>() { @java.lang.Override public XdsUpdateHealthServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new XdsUpdateHealthServiceStub(channel, callOptions); } }; return XdsUpdateHealthServiceStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports all types of calls on the service */ public static XdsUpdateHealthServiceBlockingV2Stub newBlockingV2Stub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingV2Stub> factory = new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingV2Stub>() { @java.lang.Override public XdsUpdateHealthServiceBlockingV2Stub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new XdsUpdateHealthServiceBlockingV2Stub(channel, callOptions); } }; return XdsUpdateHealthServiceBlockingV2Stub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static XdsUpdateHealthServiceBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceBlockingStub>() { @java.lang.Override public XdsUpdateHealthServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new XdsUpdateHealthServiceBlockingStub(channel, callOptions); } }; return XdsUpdateHealthServiceBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static XdsUpdateHealthServiceFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<XdsUpdateHealthServiceFutureStub>() { @java.lang.Override public XdsUpdateHealthServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new XdsUpdateHealthServiceFutureStub(channel, callOptions); } }; return XdsUpdateHealthServiceFutureStub.newStub(factory, channel); } /** * <pre> * A service to remotely control health status of an xDS test server. * </pre> */ public
XdsUpdateHealthServiceGrpc
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/TestContextBootstrapper.java
{ "start": 3072, "end": 4207 }
class ____ the {@link BootstrapContext} associated with this * bootstrapper. * <p>Implementations must take the following into account when building the * merged configuration: * <ul> * <li>Context hierarchies declared via {@link ContextHierarchy @ContextHierarchy} * and {@link ContextConfiguration @ContextConfiguration}</li> * <li>Active bean definition profiles declared via {@link ActiveProfiles @ActiveProfiles}</li> * <li>{@linkplain org.springframework.context.ApplicationContextInitializer * Context initializers} declared via {@link ContextConfiguration#initializers}</li> * <li>Test property sources declared via {@link TestPropertySource @TestPropertySource}</li> * </ul> * <p>Consult the Javadoc for the aforementioned annotations for details on * the required semantics. * <p>Note that the implementation of {@link #buildTestContext()} should * typically delegate to this method when constructing the {@code TestContext}. * <p>When determining which {@link ContextLoader} to use for a given test * class, the following algorithm should be used: * <ol> * <li>If a {@code ContextLoader}
in
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/intarray/IntArrayAssert_contains_at_Index_Test.java
{ "start": 996, "end": 1377 }
class ____ extends IntArrayAssertBaseTest { private final Index index = someIndex(); @Override protected IntArrayAssert invoke_api_method() { return assertions.contains(8, index); } @Override protected void verify_internal_effects() { verify(arrays).assertContains(getInfo(assertions), getActual(assertions), 8, index); } }
IntArrayAssert_contains_at_Index_Test
java
spring-projects__spring-boot
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/logging/LoggersEndpoint.java
{ "start": 7244, "end": 7661 }
class ____ extends LoggerLevelsDescriptor { private final String effectiveLevel; public SingleLoggerLevelsDescriptor(LoggerConfiguration configuration) { super(configuration.getLevelConfiguration(ConfigurationScope.DIRECT)); this.effectiveLevel = configuration.getLevelConfiguration().getName(); } public String getEffectiveLevel() { return this.effectiveLevel; } } }
SingleLoggerLevelsDescriptor
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapred/TestCounters.java
{ "start": 2065, "end": 2524 }
enum ____ {TEST1, TEST2}; private static final long MAX_VALUE = 10; private static final Logger LOG = LoggerFactory.getLogger(TestCounters.class); static final Enum<?> FRAMEWORK_COUNTER = TaskCounter.CPU_MILLISECONDS; static final long FRAMEWORK_COUNTER_VALUE = 8; static final String FS_SCHEME = "HDFS"; static final FileSystemCounter FS_COUNTER = FileSystemCounter.BYTES_READ; static final long FS_COUNTER_VALUE = 10; // Generates
myCounters
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/ClassReader.java
{ "start": 166577, "end": 167336 }
class ____ or * adapters.</i> * * @param offset the start offset of an unsigned short value in this {@link ClassReader}, whose * value is the index of a CONSTANT_Class entry in class's constant pool table. * @param charBuffer the buffer to be used to read the item. This buffer must be sufficiently * large. It is not automatically resized. * @return the String corresponding to the specified CONSTANT_Class entry. */ public String readClass(final int offset, final char[] charBuffer) { return readStringish(offset, charBuffer); } /** * Reads a CONSTANT_Module constant pool entry in this {@link ClassReader}. <i>This method is * intended for {@link Attribute} sub classes, and is normally not needed by
generators
java
hibernate__hibernate-orm
hibernate-jcache/src/test/java/org/hibernate/orm/test/jcache/HibernateCacheTest.java
{ "start": 1377, "end": 8317 }
class ____ extends BaseFunctionalTest { @Test public void testQueryCacheInvalidation() { Session s = sessionFactory().openSession(); Transaction t = s.beginTransaction(); Item i = new Item(); i.setName( "widget" ); i.setDescription( "A really top-quality, full-featured widget." ); s.persist( i ); t.commit(); s.close(); CacheRegionStatistics slcs = sessionFactory() .getStatistics() .getDomainDataRegionStatistics( Item.class.getName() ); assertThat( slcs.getPutCount(), equalTo( 1L ) ); assertTrue( sessionFactory().getCache().containsEntity( Item.class, i.getId() ) ); s = sessionFactory().openSession(); t = s.beginTransaction(); i = s.find( Item.class, i.getId() ); assertThat( slcs.getHitCount(), equalTo( 1L ) ); assertThat( slcs.getMissCount(), equalTo( 0L ) ); i.setDescription( "A bog standard item" ); t.commit(); s.close(); assertThat( slcs.getPutCount(), equalTo( 2L ) ); assertTrue( sessionFactory().getCache().containsEntity( Item.class, i.getId() ) ); final DomainDataRegionTemplate region = (DomainDataRegionTemplate) sessionFactory().getMappingMetamodel() .getEntityDescriptor( Item.class ) .getCacheAccessStrategy() .getRegion(); final Object fromCache = region.getCacheStorageAccess().getFromCache( region.getEffectiveKeysFactory().createEntityKey( i.getId(), sessionFactory().getMappingMetamodel().getEntityDescriptor( Item.class ), sessionFactory(), null ), (SharedSessionContractImplementor) s ); assertNotNull( fromCache ); ExtraAssertions.assertTyping( AbstractReadWriteAccess.Item.class, fromCache ); // assertThat( (String) map.get( "description" ), equalTo( "A bog standard item" ) ); // assertThat( (String) map.get( "name" ), equalTo( "widget" ) ); // cleanup s = sessionFactory().openSession(); t = s.beginTransaction(); s.remove( i ); t.commit(); s.close(); } // @Test // public void testEmptySecondLevelCacheEntry() throws Exception { // sessionFactory().getCache().evictEntityRegion( Item.class.getName() ); // Statistics stats = sessionFactory().getStatistics(); // stats.clear(); // CacheRegionStatistics statistics = stats.getDomainDataRegionStatistics( Item.class.getName() ); // Map cacheEntries = statistics.getEntries(); // assertThat( cacheEntries.size(), equalTo( 0 ) ); // } @Test public void testStaleWritesLeaveCacheConsistent() { Session s = sessionFactory().openSession(); Transaction txn = s.beginTransaction(); VersionedItem item = new VersionedItem(); item.setName( "steve" ); item.setDescription( "steve's item" ); s.persist( item ); txn.commit(); s.close(); // manually revert the version property item.setVersion( item.getVersion() - 1 ); try { s = sessionFactory().openSession(); txn = s.beginTransaction(); s.merge( item ); txn.commit(); s.close(); fail( "expected stale write to fail" ); } catch ( Throwable expected ) { // expected behavior here if ( txn != null ) { try { txn.rollback(); } catch ( Throwable ignore ) { } } if ( expected instanceof AssertionError ) { throw (AssertionError) expected; } } finally { if ( s != null && s.isOpen() ) { try { s.close(); } catch ( Throwable ignore ) { } } } // // check the version value in the cache... // CacheRegionStatistics slcs = sessionFactory().getStatistics() // .getDomainDataRegionStatistics( VersionedItem.class.getName() ); // assertNotNull(slcs); // final Map entries = slcs.getEntries(); // Object entry = entries.get( item.getId() ); // Long cachedVersionValue; // if ( entry instanceof SoftLock ) { // //FIXME don't know what to test here // //cachedVersionValue = new Long( ( (ReadWriteCache.Lock) entry).getUnlockTimestamp() ); // } // else { // cachedVersionValue = (Long) ( (Map) entry ).get( "_version" ); // assertThat( initialVersion, equalTo( cachedVersionValue ) ); // } final DomainDataRegionTemplate region = (DomainDataRegionTemplate) sessionFactory().getMappingMetamodel() .getEntityDescriptor( Item.class ) .getCacheAccessStrategy() .getRegion(); final Object fromCache = region.getCacheStorageAccess().getFromCache( region.getEffectiveKeysFactory().createEntityKey( item.getId(), sessionFactory().getMappingMetamodel().getEntityDescriptor( Item.class ), sessionFactory(), null ), (SharedSessionContractImplementor) s ); assertTrue( fromCache == null || fromCache instanceof SoftLock ); // cleanup s = sessionFactory().openSession(); txn = s.beginTransaction(); item = s.getReference( VersionedItem.class, item.getId() ); s.remove( item ); txn.commit(); s.close(); } @Test public void testGeneralUsage() { EventManager mgr = new EventManager( sessionFactory() ); Statistics stats = sessionFactory().getStatistics(); // create 3 persons Steve, Orion, Tim Person stevePerson = new Person(); stevePerson.setFirstname( "Steve" ); stevePerson.setLastname( "Harris" ); Long steveId = mgr.createAndStorePerson( stevePerson ); mgr.addEmailToPerson( steveId, "steve@tc.com" ); mgr.addEmailToPerson( steveId, "sharrif@tc.com" ); mgr.addTalismanToPerson( steveId, "rabbit foot" ); mgr.addTalismanToPerson( steveId, "john de conqueror" ); PhoneNumber p1 = new PhoneNumber(); p1.setNumberType( "Office" ); p1.setPhone( 111111 ); mgr.addPhoneNumberToPerson( steveId, p1 ); PhoneNumber p2 = new PhoneNumber(); p2.setNumberType( "Home" ); p2.setPhone( 222222 ); mgr.addPhoneNumberToPerson( steveId, p2 ); Person orionPerson = new Person(); orionPerson.setFirstname( "Orion" ); orionPerson.setLastname( "Letizi" ); Long orionId = mgr.createAndStorePerson( orionPerson ); mgr.addEmailToPerson( orionId, "orion@tc.com" ); mgr.addTalismanToPerson( orionId, "voodoo doll" ); Long timId = mgr.createAndStorePerson( "Tim", "Teck" ); mgr.addEmailToPerson( timId, "teck@tc.com" ); mgr.addTalismanToPerson( timId, "magic decoder ring" ); Long engMeetingId = mgr.createAndStoreEvent( "Eng Meeting", stevePerson, new Date() ); mgr.addPersonToEvent( steveId, engMeetingId ); mgr.addPersonToEvent( orionId, engMeetingId ); mgr.addPersonToEvent( timId, engMeetingId ); Long docMeetingId = mgr.createAndStoreEvent( "Doc Meeting", orionPerson, new Date() ); mgr.addPersonToEvent( steveId, docMeetingId ); mgr.addPersonToEvent( orionId, docMeetingId ); for ( Event event : (List<Event>) mgr.listEvents() ) { mgr.listEmailsOfEvent( event.getId() ); } QueryStatistics queryStats = stats.getQueryStatistics( "from Event" ); assertThat( "Cache Miss Count", queryStats.getCacheMissCount(), equalTo( 1L ) ); assertThat( "Cache Hit Count", queryStats.getCacheHitCount(), equalTo( 0L ) ); assertThat( "Cache Put Count", queryStats.getCachePutCount(), equalTo( 1L ) ); } }
HibernateCacheTest
java
elastic__elasticsearch
modules/rank-eval/src/main/java/org/elasticsearch/index/rankeval/EvaluationMetric.java
{ "start": 1163, "end": 3932 }
interface ____ extends ToXContentObject, NamedWriteable { /** * Evaluates a single ranking evaluation case. * * @param taskId * an identifier of the query for which the search ranking is * evaluated * @param hits * the search result hits * @param ratedDocs * the documents that contain the document rating for this query case * @return an {@link EvalQueryQuality} instance that contains the metric score * with respect to the provided search hits and ratings */ EvalQueryQuality evaluate(String taskId, SearchHit[] hits, List<RatedDocument> ratedDocs); /** * Joins hits with rated documents using the joint _index/_id document key. */ static List<RatedSearchHit> joinHitsWithRatings(SearchHit[] hits, List<RatedDocument> ratedDocs) { Map<DocumentKey, RatedDocument> ratedDocumentMap = ratedDocs.stream() .collect(Collectors.toMap(RatedDocument::getKey, item -> item)); List<RatedSearchHit> ratedSearchHits = new ArrayList<>(hits.length); for (SearchHit hit : hits) { DocumentKey key = new DocumentKey(hit.getIndex(), hit.getId()); RatedDocument ratedDoc = ratedDocumentMap.get(key); if (ratedDoc != null) { ratedSearchHits.add(new RatedSearchHit(hit, OptionalInt.of(ratedDoc.getRating()))); } else { ratedSearchHits.add(new RatedSearchHit(hit, OptionalInt.empty())); } } return ratedSearchHits; } /** * Filter {@link RatedSearchHit}s that do not have a rating. */ static List<DocumentKey> filterUnratedDocuments(List<RatedSearchHit> ratedHits) { return ratedHits.stream() .filter(hit -> hit.getRating().isPresent() == false) .map(hit -> new DocumentKey(hit.getSearchHit().getIndex(), hit.getSearchHit().getId())) .collect(Collectors.toList()); } /** * Combine several {@link EvalQueryQuality} results into the overall evaluation score. * This defaults to averaging over the partial results, but can be overwritten to obtain a different behavior. */ default double combine(Collection<EvalQueryQuality> partialResults) { return partialResults.stream().mapToDouble(EvalQueryQuality::metricScore).sum() / partialResults.size(); } /** * Metrics can define a size of the search hits windows they want to retrieve by overwriting * this method. The default implementation returns an empty optional. * @return the number of search hits this metrics requests */ default OptionalInt forcedSearchSize() { return OptionalInt.empty(); } }
EvaluationMetric
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/manytomany/unidirectional/BasicUniSet.java
{ "start": 968, "end": 5397 }
class ____ { private Integer ed1_id; private Integer ed2_id; private Integer ing1_id; private Integer ing2_id; @BeforeClassTemplate public void initData(EntityManagerFactoryScope scope) { // Revision 1 scope.inTransaction( em -> { StrTestEntity ed1 = new StrTestEntity( "data_ed_1" ); StrTestEntity ed2 = new StrTestEntity( "data_ed_2" ); SetUniEntity ing1 = new SetUniEntity( 3, "data_ing_1" ); SetUniEntity ing2 = new SetUniEntity( 4, "data_ing_2" ); em.persist( ed1 ); em.persist( ed2 ); em.persist( ing1 ); em.persist( ing2 ); ed1_id = ed1.getId(); ed2_id = ed2.getId(); ing1_id = ing1.getId(); ing2_id = ing2.getId(); } ); // Revision 2 scope.inTransaction( em -> { SetUniEntity ing1 = em.find( SetUniEntity.class, ing1_id ); SetUniEntity ing2 = em.find( SetUniEntity.class, ing2_id ); StrTestEntity ed1 = em.find( StrTestEntity.class, ed1_id ); StrTestEntity ed2 = em.find( StrTestEntity.class, ed2_id ); ing1.setReferences( new HashSet<StrTestEntity>() ); ing1.getReferences().add( ed1 ); ing2.setReferences( new HashSet<StrTestEntity>() ); ing2.getReferences().add( ed1 ); ing2.getReferences().add( ed2 ); } ); // Revision 3 scope.inTransaction( em -> { SetUniEntity ing1 = em.find( SetUniEntity.class, ing1_id ); StrTestEntity ed2 = em.find( StrTestEntity.class, ed2_id ); ing1.getReferences().add( ed2 ); } ); // Revision 4 scope.inTransaction( em -> { SetUniEntity ing1 = em.find( SetUniEntity.class, ing1_id ); StrTestEntity ed1 = em.find( StrTestEntity.class, ed1_id ); ing1.getReferences().remove( ed1 ); } ); // Revision 5 scope.inTransaction( em -> { SetUniEntity ing1 = em.find( SetUniEntity.class, ing1_id ); ing1.setReferences( null ); } ); } @Test public void testRevisionsCounts(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); assertEquals( Arrays.asList( 1 ), auditReader.getRevisions( StrTestEntity.class, ed1_id ) ); assertEquals( Arrays.asList( 1 ), auditReader.getRevisions( StrTestEntity.class, ed2_id ) ); assertEquals( Arrays.asList( 1, 2, 3, 4, 5 ), auditReader.getRevisions( SetUniEntity.class, ing1_id ) ); assertEquals( Arrays.asList( 1, 2 ), auditReader.getRevisions( SetUniEntity.class, ing2_id ) ); } ); } @Test public void testHistoryOfEdIng1(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); StrTestEntity ed1 = em.find( StrTestEntity.class, ed1_id ); StrTestEntity ed2 = em.find( StrTestEntity.class, ed2_id ); SetUniEntity rev1 = auditReader.find( SetUniEntity.class, ing1_id, 1 ); SetUniEntity rev2 = auditReader.find( SetUniEntity.class, ing1_id, 2 ); SetUniEntity rev3 = auditReader.find( SetUniEntity.class, ing1_id, 3 ); SetUniEntity rev4 = auditReader.find( SetUniEntity.class, ing1_id, 4 ); SetUniEntity rev5 = auditReader.find( SetUniEntity.class, ing1_id, 5 ); assertEquals( Collections.EMPTY_SET, rev1.getReferences() ); assertEquals( TestTools.makeSet( ed1 ), rev2.getReferences() ); assertEquals( TestTools.makeSet( ed1, ed2 ), rev3.getReferences() ); assertEquals( TestTools.makeSet( ed2 ), rev4.getReferences() ); assertEquals( Collections.EMPTY_SET, rev5.getReferences() ); } ); } @Test public void testHistoryOfEdIng2(EntityManagerFactoryScope scope) { scope.inEntityManager( em -> { final var auditReader = AuditReaderFactory.get( em ); StrTestEntity ed1 = em.find( StrTestEntity.class, ed1_id ); StrTestEntity ed2 = em.find( StrTestEntity.class, ed2_id ); SetUniEntity rev1 = auditReader.find( SetUniEntity.class, ing2_id, 1 ); SetUniEntity rev2 = auditReader.find( SetUniEntity.class, ing2_id, 2 ); SetUniEntity rev3 = auditReader.find( SetUniEntity.class, ing2_id, 3 ); SetUniEntity rev4 = auditReader.find( SetUniEntity.class, ing2_id, 4 ); SetUniEntity rev5 = auditReader.find( SetUniEntity.class, ing2_id, 5 ); assertEquals( Collections.EMPTY_SET, rev1.getReferences() ); assertEquals( TestTools.makeSet( ed1, ed2 ), rev2.getReferences() ); assertEquals( TestTools.makeSet( ed1, ed2 ), rev3.getReferences() ); assertEquals( TestTools.makeSet( ed1, ed2 ), rev4.getReferences() ); assertEquals( TestTools.makeSet( ed1, ed2 ), rev5.getReferences() ); } ); } }
BasicUniSet
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/cookie/Cookie.java
{ "start": 796, "end": 4332 }
interface ____ extends Comparable<Cookie> { /** * Constant for undefined MaxAge attribute value. */ long UNDEFINED_MAX_AGE = Long.MIN_VALUE; /** * Returns the name of this {@link Cookie}. * * @return The name of this {@link Cookie} */ String name(); /** * Returns the value of this {@link Cookie}. * * @return The value of this {@link Cookie} */ String value(); /** * Sets the value of this {@link Cookie}. * * @param value The value to set */ void setValue(String value); /** * Returns true if the raw value of this {@link Cookie}, * was wrapped with double quotes in original Set-Cookie header. * * @return If the value of this {@link Cookie} is to be wrapped */ boolean wrap(); /** * Sets true if the value of this {@link Cookie} * is to be wrapped with double quotes. * * @param wrap true if wrap */ void setWrap(boolean wrap); /** * Returns the domain of this {@link Cookie}. * * @return The domain of this {@link Cookie} */ String domain(); /** * Sets the domain of this {@link Cookie}. * * @param domain The domain to use */ void setDomain(String domain); /** * Returns the path of this {@link Cookie}. * * @return The {@link Cookie}'s path */ String path(); /** * Sets the path of this {@link Cookie}. * * @param path The path to use for this {@link Cookie} */ void setPath(String path); /** * Returns the maximum age of this {@link Cookie} in seconds or {@link Cookie#UNDEFINED_MAX_AGE} if unspecified * * @return The maximum age of this {@link Cookie} */ long maxAge(); /** * Sets the maximum age of this {@link Cookie} in seconds. * If an age of {@code 0} is specified, this {@link Cookie} will be * automatically removed by browser because it will expire immediately. * If {@link Cookie#UNDEFINED_MAX_AGE} is specified, this {@link Cookie} will be removed when the * browser is closed. * * @param maxAge The maximum age of this {@link Cookie} in seconds */ void setMaxAge(long maxAge); /** * Checks to see if this {@link Cookie} is secure * * @return True if this {@link Cookie} is secure, otherwise false */ boolean isSecure(); /** * Sets the security getStatus of this {@link Cookie} * * @param secure True if this {@link Cookie} is to be secure, otherwise false */ void setSecure(boolean secure); /** * Checks to see if this {@link Cookie} can only be accessed via HTTP. * If this returns true, the {@link Cookie} cannot be accessed through * client side script - But only if the browser supports it. * For more information, please look <a href="https://owasp.org/www-community/HttpOnly">here</a> * * @return True if this {@link Cookie} is HTTP-only or false if it isn't */ boolean isHttpOnly(); /** * Determines if this {@link Cookie} is HTTP only. * If set to true, this {@link Cookie} cannot be accessed by a client * side script. However, this works only if the browser supports it. * For information, please look * <a href="https://owasp.org/www-community/HttpOnly">here</a>. * * @param httpOnly True if the {@link Cookie} is HTTP only, otherwise false. */ void setHttpOnly(boolean httpOnly); }
Cookie
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/namesuggestion/SuggestMostSimilarNameTest.java
{ "start": 955, "end": 4217 }
class ____ { @ProcessorTest @WithClasses({ PersonAgeMapper.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = PersonAgeMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 19, message = "No property named \"agee\" exists in source parameter(s). Did you mean \"age\"?") } ) public void testAgeSuggestion() { } @ProcessorTest @WithClasses({ PersonNameMapper.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = PersonNameMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 19, message = "Unknown property \"fulName\" in result type Person. Did you mean \"fullName\"?") } ) public void testNameSuggestion() { } @ProcessorTest @WithClasses({ PersonGarageWrongTargetMapper.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = PersonGarageWrongTargetMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 19, message = "Unknown property \"colour\" in type Garage for target name \"garage.colour.rgb\". " + "Did you mean \"garage.color\"?"), @Diagnostic(type = PersonGarageWrongTargetMapper.class, kind = javax.tools.Diagnostic.Kind.WARNING, line = 20, messageRegExp = "Unmapped target properties: \"fullName, fullAge\"\\."), @Diagnostic(type = PersonGarageWrongTargetMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 22, message = "Unknown property \"colour\" in type Garage for target name \"garage.colour\". " + "Did you mean \"garage.color\"?"), @Diagnostic(type = PersonGarageWrongTargetMapper.class, kind = javax.tools.Diagnostic.Kind.WARNING, line = 23, messageRegExp = "Unmapped target properties: \"fullName, fullAge\"\\."), } ) public void testGarageTargetSuggestion() { } @ProcessorTest @WithClasses({ PersonGarageWrongSourceMapper.class }) @ExpectedCompilationOutcome( value = CompilationResult.FAILED, diagnostics = { @Diagnostic(type = PersonGarageWrongSourceMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 21, message = "No property named \"garage.colour.rgb\" exists in source parameter(s). Did you mean " + "\"garage.color\"?"), @Diagnostic(type = PersonGarageWrongSourceMapper.class, kind = javax.tools.Diagnostic.Kind.ERROR, line = 28, message = "No property named \"garage.colour\" exists in source parameter(s). Did you mean \"garage" + ".color\"?") } ) public void testGarageSourceSuggestion() { } }
SuggestMostSimilarNameTest
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/writing/ComponentWrapperImplementation.java
{ "start": 1979, "end": 4259 }
class ____ implements GeneratedImplementation { private final BindingGraph graph; private final XClassName name; private final UniqueNameSet componentClassNames = new UniqueNameSet(); private final ListMultimap<FieldSpecKind, XPropertySpec> fieldSpecsMap = MultimapBuilder.enumKeys(FieldSpecKind.class).arrayListValues().build(); private final ListMultimap<MethodSpecKind, XFunSpec> methodSpecsMap = MultimapBuilder.enumKeys(MethodSpecKind.class).arrayListValues().build(); private final ListMultimap<TypeSpecKind, XTypeSpec> typeSpecsMap = MultimapBuilder.enumKeys(TypeSpecKind.class).arrayListValues().build(); private final List<Supplier<XTypeSpec>> typeSuppliers = new ArrayList<>(); @Inject ComponentWrapperImplementation(@TopLevel BindingGraph graph) { this.graph = graph; this.name = ComponentNames.getTopLevelClassName(graph.componentDescriptor()); } @Override public XClassName name() { return name; } @Override public String getUniqueClassName(String name) { return componentClassNames.getUniqueName(name); } @Override public void addField(FieldSpecKind fieldKind, XPropertySpec fieldSpec) { fieldSpecsMap.put(fieldKind, fieldSpec); } @Override public void addMethod(MethodSpecKind methodKind, XFunSpec methodSpec) { methodSpecsMap.put(methodKind, methodSpec); } @Override public void addType(TypeSpecKind typeKind, XTypeSpec typeSpec) { typeSpecsMap.put(typeKind, typeSpec); } @Override public void addTypeSupplier(Supplier<XTypeSpec> typeSpecSupplier) { typeSuppliers.add(typeSpecSupplier); } @Override public XTypeSpec generate() { XTypeSpecs.Builder builder = classBuilder(getTopLevelClassName(graph.componentDescriptor())).addModifiers(FINAL); if (graph.componentTypeElement().isPublic()) { builder.addModifiers(PUBLIC); } fieldSpecsMap.asMap().values().forEach(builder::addProperties); methodSpecsMap.asMap().values().forEach(builder::addFunctions); typeSpecsMap.asMap().values().forEach(builder::addTypes); typeSuppliers.stream().map(Supplier::get).forEach(builder::addType); return builder.addFunction(constructorBuilder().addModifiers(PRIVATE).build()).build(); } }
ComponentWrapperImplementation
java
apache__kafka
connect/runtime/src/test/java/org/apache/kafka/connect/runtime/WorkerTaskTest.java
{ "start": 2573, "end": 11648 }
class ____ { private static final Map<String, String> TASK_PROPS = new HashMap<>(); static { TASK_PROPS.put(TaskConfig.TASK_CLASS_CONFIG, TestSinkTask.class.getName()); } private static final TaskConfig TASK_CONFIG = new TaskConfig(TASK_PROPS); @Mock private TaskStatus.Listener statusListener; @Mock private ClassLoader loader; @Mock private StatusBackingStore statusBackingStore; private ConnectMetrics metrics; @Mock private ErrorHandlingMetrics errorHandlingMetrics; @Mock private RetryWithToleranceOperator<Object> retryWithToleranceOperator; @Mock private TransformationChain<Object, SourceRecord> transformationChain; @Mock private Supplier<List<ErrorReporter<Object>>> errorReportersSupplier; @BeforeEach public void setup() { metrics = new MockConnectMetrics(); } @AfterEach public void tearDown() { if (metrics != null) metrics.stop(); } @Test public void standardStartup() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask<Object, SourceRecord> workerTask = new TestWorkerTask(taskId, statusListener, TargetState.STARTED, loader, metrics, errorHandlingMetrics, retryWithToleranceOperator, transformationChain, errorReportersSupplier, Time.SYSTEM, statusBackingStore); workerTask.initialize(TASK_CONFIG); workerTask.run(); workerTask.stop(); workerTask.awaitStop(1000L); verify(statusListener).onStartup(taskId); verify(statusListener).onShutdown(taskId); } @Test public void stopBeforeStarting() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask<Object, SourceRecord> workerTask = new TestWorkerTask(taskId, statusListener, TargetState.STARTED, loader, metrics, errorHandlingMetrics, retryWithToleranceOperator, transformationChain, errorReportersSupplier, Time.SYSTEM, statusBackingStore) { @Override public void initializeAndStart() { fail("This method is expected to not be invoked"); } @Override public void execute() { fail("This method is expected to not be invoked"); } }; workerTask.initialize(TASK_CONFIG); workerTask.stop(); workerTask.awaitStop(1000L); // now run should not do anything workerTask.run(); } @Test public void cancelBeforeStopping() throws Exception { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); final CountDownLatch stopped = new CountDownLatch(1); WorkerTask<Object, SourceRecord> workerTask = new TestWorkerTask(taskId, statusListener, TargetState.STARTED, loader, metrics, errorHandlingMetrics, retryWithToleranceOperator, transformationChain, errorReportersSupplier, Time.SYSTEM, statusBackingStore) { @Override public void execute() { try { stopped.await(); } catch (InterruptedException e) { fail("Unexpected interrupt"); } } // Trigger task shutdown immediately after start. The task will block in its execute() method // until the stopped latch is counted down (i.e. it doesn't actually stop after stop is triggered). @Override public void initializeAndStart() { stop(); } }; workerTask.initialize(TASK_CONFIG); Thread t = new Thread(workerTask); t.start(); workerTask.cancel(); stopped.countDown(); t.join(); verify(statusListener).onStartup(taskId); // there should be no other status updates, including shutdown verifyNoMoreInteractions(statusListener); } @Test public void testErrorReportersConfigured() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask<Object, SourceRecord> workerTask = new TestWorkerTask(taskId, statusListener, TargetState.STARTED, loader, metrics, errorHandlingMetrics, retryWithToleranceOperator, transformationChain, errorReportersSupplier, Time.SYSTEM, statusBackingStore); List<ErrorReporter<Object>> errorReporters = new ArrayList<>(); when(errorReportersSupplier.get()).thenReturn(errorReporters); workerTask.doStart(); verify(retryWithToleranceOperator).reporters(errorReporters); } @Test public void testErrorReporterConfigurationExceptionPropagation() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask<Object, SourceRecord> workerTask = new TestWorkerTask(taskId, statusListener, TargetState.STARTED, loader, metrics, errorHandlingMetrics, retryWithToleranceOperator, transformationChain, errorReportersSupplier, Time.SYSTEM, statusBackingStore); when(errorReportersSupplier.get()).thenThrow(new ConnectException("Failed to create error reporters")); assertThrows(ConnectException.class, workerTask::doStart); } @Test public void testCloseClosesManagedResources() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask<Object, SourceRecord> workerTask = new TestWorkerTask(taskId, statusListener, TargetState.STARTED, loader, metrics, errorHandlingMetrics, retryWithToleranceOperator, transformationChain, errorReportersSupplier, Time.SYSTEM, statusBackingStore); workerTask.doClose(); verify(retryWithToleranceOperator).close(); verify(transformationChain).close(); } @Test public void testCloseClosesManagedResourcesIfSubclassThrows() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); WorkerTask<Object, SourceRecord> workerTask = new TestWorkerTask(taskId, statusListener, TargetState.STARTED, loader, metrics, errorHandlingMetrics, retryWithToleranceOperator, transformationChain, errorReportersSupplier, Time.SYSTEM, statusBackingStore) { @Override protected void close() { throw new ConnectException("Failure during close"); } }; assertThrows(ConnectException.class, workerTask::doClose); verify(retryWithToleranceOperator).close(); verify(transformationChain).close(); } @Test public void updateMetricsOnListenerEventsForStartupPauseResumeAndShutdown() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); ConnectMetrics metrics = new MockConnectMetrics(); TaskMetricsGroup group = new TaskMetricsGroup(taskId, metrics, statusListener); group.onStartup(taskId); assertRunningMetric(group); group.onPause(taskId); assertPausedMetric(group); group.onResume(taskId); assertRunningMetric(group); group.onShutdown(taskId); assertStoppedMetric(group); verify(statusListener).onStartup(taskId); verify(statusListener).onPause(taskId); verify(statusListener).onResume(taskId); verify(statusListener).onShutdown(taskId); } @Test public void updateMetricsOnListenerEventsForStartupPauseResumeAndFailure() { ConnectorTaskId taskId = new ConnectorTaskId("foo", 0); MockConnectMetrics metrics = new MockConnectMetrics(); MockTime time = metrics.time(); ConnectException error = new ConnectException("error"); TaskMetricsGroup group = new TaskMetricsGroup(taskId, metrics, statusListener); time.sleep(1000L); group.onStartup(taskId); assertRunningMetric(group); time.sleep(2000L); group.onPause(taskId); assertPausedMetric(group); time.sleep(3000L); group.onResume(taskId); assertRunningMetric(group); time.sleep(4000L); group.onPause(taskId); assertPausedMetric(group); time.sleep(5000L); group.onResume(taskId); assertRunningMetric(group); time.sleep(6000L); group.onFailure(taskId, error); assertFailedMetric(group); time.sleep(7000L); group.onShutdown(taskId); assertStoppedMetric(group); verify(statusListener).onStartup(taskId); verify(statusListener, times(2)).onPause(taskId); verify(statusListener, times(2)).onResume(taskId); verify(statusListener).onFailure(taskId, error); verify(statusListener).onShutdown(taskId); long totalTime = 27000L; double pauseTimeRatio = (double) (3000L + 5000L) / totalTime; double runningTimeRatio = (double) (2000L + 4000L + 6000L) / totalTime; assertEquals(pauseTimeRatio, metrics.currentMetricValueAsDouble(group.metricGroup(), "pause-ratio"), 0.000001d); assertEquals(runningTimeRatio, metrics.currentMetricValueAsDouble(group.metricGroup(), "running-ratio"), 0.000001d); } private abstract static
WorkerTaskTest
java
apache__camel
components/camel-bindy/src/main/java/org/apache/camel/dataformat/bindy/format/factories/BytePatternFormatFactory.java
{ "start": 1119, "end": 1733 }
class ____ extends AbstractFormatFactory { { supportedClasses.add(byte.class); supportedClasses.add(Byte.class); } @Override public boolean canBuild(FormattingOptions formattingOptions) { return super.canBuild(formattingOptions) && ObjectHelper.isNotEmpty(formattingOptions.getPattern()); } @Override public Format<?> build(FormattingOptions formattingOptions) { return new BytePatternFormat( formattingOptions.getPattern(), formattingOptions.getLocale()); } private static
BytePatternFormatFactory
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/Route.java
{ "start": 1817, "end": 12363 }
interface ____ extends RuntimeConfiguration { String ID_PROPERTY = "id"; String CUSTOM_ID_PROPERTY = "customId"; String PARENT_PROPERTY = "parent"; String GROUP_PROPERTY = "group"; String NODE_PREFIX_ID_PROPERTY = "nodePrefixId"; String REST_PROPERTY = "rest"; String TEMPLATE_PROPERTY = "template"; String KAMELET_PROPERTY = "kamelet"; String DESCRIPTION_PROPERTY = "description"; String NOTE_PROPERTY = "note"; String CONFIGURATION_ID_PROPERTY = "configurationId"; String SUPERVISED = "supervised"; /** * Gets the route id * * @return the route id */ String getId(); /** * Gets the node prefix id */ String getNodePrefixId(); /** * Whether the route id is custom assigned or auto assigned * * @return true if custom id, false if auto assigned id */ boolean isCustomId(); /** * Whether this route is a Rest DSL route. */ boolean isCreatedByRestDsl(); /** * Whether this route was created from a route template (or a Kamelet). */ boolean isCreatedByRouteTemplate(); /** * Whether this route was created from a Kamelet. */ boolean isCreatedByKamelet(); /** * Gets the route group * * @return the route group */ String getGroup(); /** * Gets the uptime in a human-readable format * * @return the uptime in days/hours/minutes */ String getUptime(); /** * Gets the uptime in milliseconds * * @return the uptime in milliseconds */ long getUptimeMillis(); /** * Gets the inbound {@link Consumer} * * @return the inbound consumer */ Consumer getConsumer(); /** * Gets the {@link Processor} * * @return the processor */ Processor getProcessor(); /** * Sets the {@link Processor} */ void setProcessor(Processor processor); /** * Whether or not the route supports suspension (suspend and resume) * * @return <tt>true</tt> if this route supports suspension */ boolean supportsSuspension(); /** * This property map is used to associate information about the route. * * @return properties */ Map<String, Object> getProperties(); /** * Gets the route description (if any has been configured). * <p/> * The description is configured using the {@link #DESCRIPTION_PROPERTY} as key in the {@link #getProperties()}. * * @return the description, or <tt>null</tt> if no description has been configured. */ String getDescription(); /** * Gets the route note (if any has been configured). * <p/> * The note is configured using the {@link #NOTE_PROPERTY} as key in the {@link #getProperties()}. * * @return the note, or <tt>null</tt> if no note has been configured. */ String getNote(); /** * Gets the route configuration id(s) the route has been applied with. Multiple ids is separated by comma. * <p/> * The configuration ids is configured using the {@link #CONFIGURATION_ID_PROPERTY} as key in the * {@link #getProperties()}. * * @return the configuration, or <tt>null</tt> if no configuration has been configured. */ String getConfigurationId(); /** * Gets the source resource that this route is located from * * @return the source, or null if this route is not loaded from a resource */ Resource getSourceResource(); /** * The source:line-number where the route input is located in the source code */ String getSourceLocation(); /** * The source:line-number in short format that can be used for logging or summary purposes. */ String getSourceLocationShort(); /** * Gets the camel context * * @return the camel context */ CamelContext getCamelContext(); /** * Gets the input endpoint for this route. * * @return the endpoint */ Endpoint getEndpoint(); /** * A strategy callback allowing special initialization when services are initializing. * * @throws Exception is thrown in case of error */ void initializeServices() throws Exception; /** * Returns the services for this particular route * * @return the services */ List<Service> getServices(); /** * Adds a service to this route * * @param service the service */ void addService(Service service); /** * Adds a service to this route * * @param service the service * @param forceStop whether to force stopping the service when the route stops */ void addService(Service service, boolean forceStop); /** * Returns a navigator to navigate this route by navigating all the {@link Processor}s. * * @return a navigator for {@link Processor}. */ Navigate<Processor> navigate(); /** * Returns a list of all the {@link Processor}s from this route that has id's matching the pattern * * @param pattern the pattern to match by ids * @return a list of {@link Processor}, is never <tt>null</tt>. */ List<Processor> filter(String pattern); /** * Callback preparing the route to be started, by warming up the route. */ void warmUp(); /** * Gets the last error that happened during changing the route lifecycle, i.e. such as when an exception was thrown * during starting the route. * <p/> * This is only errors for route lifecycle changes, it is not exceptions thrown during routing exchanges by the * Camel routing engine. * * @return the error or <tt>null</tt> if no error */ RouteError getLastError(); /** * Sets the last error that happened during changing the route lifecycle, i.e. such as when an exception was thrown * during starting the route. * <p/> * This is only errors for route lifecycle changes, it is not exceptions thrown during routing exchanges by the * Camel routing engine. * * @param error the error */ void setLastError(RouteError error); /** * Gets the route startup order */ Integer getStartupOrder(); /** * Sets the route startup order */ void setStartupOrder(Integer startupOrder); /** * Gets the {@link RouteController} for this route. * * @return the route controller, */ RouteController getRouteController(); /** * Sets the {@link RouteController} for this route. * * @param controller the RouteController */ void setRouteController(RouteController controller); /** * Sets whether the route should automatically start when Camel starts. * <p/> * Default is <tt>true</tt> to always start up. * * @param autoStartup whether to start up automatically. */ void setAutoStartup(Boolean autoStartup); /** * Gets whether the route should automatically start when Camel starts. * <p/> * Default is <tt>true</tt> to always start up. * * @return <tt>true</tt> if route should automatically start */ Boolean isAutoStartup(); /** * Gets the route id */ String getRouteId(); /** * Gets the route description */ String getRouteDescription(); /** * Gets the route note */ String getRouteNote(); /** * Get the route type. * * Important: is null after the route has been created. * * @return the route type during creation of the route, is null after the route has been created. */ NamedNode getRoute(); /** * Clears the route model when its no longer needed. */ void clearRouteModel(); // // CREATION TIME // /** * This method retrieves the event driven Processors on this route context. */ List<Processor> getEventDrivenProcessors(); /** * This method retrieves the InterceptStrategy instances this route context. * * @return the strategy */ List<InterceptStrategy> getInterceptStrategies(); /** * Sets a special intercept strategy for management. * <p/> * Is by default used to correlate managed performance counters with processors when the runtime route is being * constructed * * @param interceptStrategy the managed intercept strategy */ void setManagementInterceptStrategy(ManagementInterceptStrategy interceptStrategy); /** * Gets the special managed intercept strategy if any * * @return the managed intercept strategy, or <tt>null</tt> if not managed */ ManagementInterceptStrategy getManagementInterceptStrategy(); /** * Gets the route policy List * * @return the route policy list if any */ List<RoutePolicy> getRoutePolicyList(); // called at completion time void setErrorHandlerFactory(ErrorHandlerFactory errorHandlerFactory); // called at runtime ErrorHandlerFactory getErrorHandlerFactory(); // called at runtime Collection<Processor> getOnCompletions(); // called at completion time void setOnCompletion(String onCompletionId, Processor processor); // called at runtime Collection<Processor> getOnExceptions(); // called at runtime Processor getOnException(String onExceptionId); // called at completion time void setOnException(String onExceptionId, Processor processor); /** * Adds error handler for the given exception type * * @param factory the error handler factory * @param exception the exception to handle */ void addErrorHandler(ErrorHandlerFactory factory, NamedNode exception); /** * Gets the error handlers * * @param factory the error handler factory */ Set<NamedNode> getErrorHandlers(ErrorHandlerFactory factory); /** * Link the error handlers from a factory to another * * @param source the source factory * @param target the target factory */ void addErrorHandlerFactoryReference(ErrorHandlerFactory source, ErrorHandlerFactory target); /** * Sets the resume strategy for the route */ void setResumeStrategy(ResumeStrategy resumeStrategy); /** * Sets the consumer listener for the route */ void setConsumerListener(ConsumerListener<?, ?> consumerListener); }
Route
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2700/Issue2752.java
{ "start": 585, "end": 999 }
class ____ extends TestCase { public void test_for_issue() { Pageable pageRequest = new PageRequest(0, 10, new Sort(new Sort.Order("id, desc"))); SerializeConfig config = new SerializeConfig(); config.register(new MyModule()); String result = JSON.toJSONString(pageRequest, config); assertTrue(result.indexOf("\"property\":\"id, desc\"") != -1); } public
Issue2752
java
spring-projects__spring-boot
module/spring-boot-data-redis/src/main/java/org/springframework/boot/data/redis/autoconfigure/LettuceClientOptionsBuilderCustomizer.java
{ "start": 873, "end": 1267 }
interface ____ can be implemented by beans wishing to customize the * {@link Builder} to fine-tune its auto-configuration before it creates the * {@link ClientOptions} of the {@link LettuceClientConfiguration}. To customize the * entire configuration, use {@link LettuceClientConfigurationBuilderCustomizer} instead. * * @author Soohyun Lim * @since 4.0.0 */ @FunctionalInterface public
that
java
apache__dubbo
dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/integration/RegistryProtocol.java
{ "start": 36157, "end": 37095 }
class ____<T> implements Exporter<T> { private Exporter<T> exporter; public DestroyableExporter(Exporter<T> exporter) { this.exporter = exporter; } @Override public Invoker<T> getInvoker() { return exporter.getInvoker(); } @Override public void unexport() { exporter.unexport(); } @Override public void register() { exporter.register(); } @Override public void unregister() { exporter.unregister(); } } /** * Reexport: the exporter destroy problem in protocol * 1.Ensure that the exporter returned by registry protocol can be normal destroyed * 2.No need to re-register to the registry after notify * 3.The invoker passed by the export method , would better to be the invoker of exporter */ private
DestroyableExporter
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/config/provider/FileConfigProviderTest.java
{ "start": 1700, "end": 4351 }
class ____ { private FileConfigProvider configProvider; @TempDir private File parent; private String dir; private String dirFile; private String siblingDir; private String siblingDirFile; @BeforeEach public void setup() throws IOException { configProvider = new TestFileConfigProvider(); configProvider.configure(Collections.emptyMap()); dir = Files.createDirectory(Paths.get(parent.toString(), "dir")).toString(); dirFile = Files.createFile(Paths.get(dir, "dirFile")).toString(); siblingDir = Files.createDirectory(Paths.get(parent.toString(), "siblingDir")).toString(); siblingDirFile = Files.createFile(Paths.get(siblingDir, "siblingDirFile")).toString(); } @Test public void testGetAllKeysAtPath() { ConfigData configData = configProvider.get("dummy"); Map<String, String> result = new HashMap<>(); result.put("testKey", "testResult"); result.put("testKey2", "testResult2"); assertEquals(result, configData.data()); assertNull(configData.ttl()); } @Test public void testGetOneKeyAtPath() { ConfigData configData = configProvider.get("dummy", Collections.singleton("testKey")); Map<String, String> result = new HashMap<>(); result.put("testKey", "testResult"); assertEquals(result, configData.data()); assertNull(configData.ttl()); } @Test public void testEmptyPath() { ConfigData configData = configProvider.get("", Collections.singleton("testKey")); assertTrue(configData.data().isEmpty()); assertNull(configData.ttl()); } @Test public void testEmptyPathWithKey() { ConfigData configData = configProvider.get(""); assertTrue(configData.data().isEmpty()); assertNull(configData.ttl()); } @Test public void testNullPath() { ConfigData configData = configProvider.get(null); assertTrue(configData.data().isEmpty()); assertNull(configData.ttl()); } @Test public void testNullPathWithKey() { ConfigData configData = configProvider.get(null, Collections.singleton("testKey")); assertTrue(configData.data().isEmpty()); assertNull(configData.ttl()); } @Test public void testServiceLoaderDiscovery() { ServiceLoader<ConfigProvider> serviceLoader = ServiceLoader.load(ConfigProvider.class); assertTrue(StreamSupport.stream(serviceLoader.spliterator(), false).anyMatch(configProvider -> configProvider instanceof FileConfigProvider)); } public static
FileConfigProviderTest
java
apache__camel
components/camel-zookeeper/src/main/java/org/apache/camel/component/zookeeper/operations/DeleteOperation.java
{ "start": 1190, "end": 2410 }
class ____ extends ZooKeeperOperation<Boolean> { private int version = -1; public DeleteOperation(ZooKeeper connection, String node) { super(connection, node); } @Override public OperationResult<Boolean> getResult() { try { connection.delete(node, version); if (LOG.isDebugEnabled()) { if (LOG.isTraceEnabled()) { LOG.trace(format("Set data of node '%s'", node)); } else { LOG.debug(format("Set data of node '%s'", node)); } } return new OperationResult<>(true, null, true); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return new OperationResult<>(e); } catch (Exception e) { return new OperationResult<>(e); } } public void setVersion(int version) { this.version = version; } @Override public ZooKeeperOperation<?> createCopy() throws Exception { DeleteOperation copy = (DeleteOperation) super.createCopy(); copy.version = -1; // set the version to -1 for 'any version' return copy; } }
DeleteOperation
java
apache__avro
lang/java/thrift/src/test/java/org/apache/avro/thrift/test/Test.java
{ "start": 65177, "end": 65363 }
class ____ implements org.apache.thrift.scheme.SchemeFactory { public TestTupleScheme getScheme() { return new TestTupleScheme(); } } private static
TestTupleSchemeFactory
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/BoundsChecksForInputTest.java
{ "start": 417, "end": 529 }
interface ____ { void call(byte[] data, int offset, int len) throws Exception; }
ByteBackedCreation
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/shell/XAttrCommands.java
{ "start": 1803, "end": 4929 }
class ____ extends FsCommand { public static final String NAME = GET_FATTR; public static final String USAGE = "[-R] {-n name | -d} [-e en] <path>"; public static final String DESCRIPTION = "Displays the extended attribute names and values (if any) for a " + "file or directory.\n" + "-R: Recursively list the attributes for all files and directories.\n" + "-n name: Dump the named extended attribute value.\n" + "-d: Dump all extended attribute values associated with pathname.\n" + "-e <encoding>: Encode values after retrieving them." + "Valid encodings are \"text\", \"hex\", and \"base64\". " + "Values encoded as text strings are enclosed in double quotes (\")," + " and values encoded as hexadecimal and base64 are prefixed with " + "0x and 0s, respectively.\n" + "<path>: The file or directory.\n"; private String name = null; private boolean dump = false; private XAttrCodec encoding = XAttrCodec.TEXT; @Override protected void processOptions(LinkedList<String> args) throws IOException { name = StringUtils.popOptionWithArgument("-n", args); String en = StringUtils.popOptionWithArgument("-e", args); if (en != null) { try { encoding = XAttrCodec.valueOf(StringUtils.toUpperCase(en)); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "Invalid/unsupported encoding option specified: " + en); } Preconditions.checkArgument(encoding != null, "Invalid/unsupported encoding option specified: " + en); } boolean r = StringUtils.popOption("-R", args); setRecursive(r); dump = StringUtils.popOption("-d", args); if (!dump && name == null) { throw new HadoopIllegalArgumentException( "Must specify '-n name' or '-d' option."); } if (args.isEmpty()) { throw new HadoopIllegalArgumentException("<path> is missing."); } if (args.size() > 1) { throw new HadoopIllegalArgumentException("Too many arguments."); } } @Override protected void processPath(PathData item) throws IOException { out.println("# file: " + item); if (dump) { Map<String, byte[]> xattrs = item.fs.getXAttrs(item.path); if (xattrs != null) { Iterator<Entry<String, byte[]>> iter = xattrs.entrySet().iterator(); while(iter.hasNext()) { Entry<String, byte[]> entry = iter.next(); printXAttr(entry.getKey(), entry.getValue()); } } } else { byte[] value = item.fs.getXAttr(item.path, name); printXAttr(name, value); } } private void printXAttr(String name, byte[] value) throws IOException{ if (value != null) { if (value.length != 0) { out.println(name + "=" + XAttrCodec.encodeValue(value, encoding)); } else { out.println(name); } } } } /** * Implements the '-setfattr' command for the FsShell. */ public static
GetfattrCommand
java
micronaut-projects__micronaut-core
test-suite/src/main/java/example/micronaut/inject/visitor/AnnotatingVisitor.java
{ "start": 1131, "end": 2488 }
class ____ implements TypeElementVisitor<Version, Version> { public static final String ANN_NAME = TestAnn.class.getName(); @Override public void visitClass(ClassElement element, VisitorContext context) { context.info("Annotating type", element); element.annotate(TestAnn.class, (builder) -> builder.value("class")); } @NonNull @Override public VisitorKind getVisitorKind() { return VisitorKind.ISOLATING; } @Override public void visitMethod(MethodElement element, VisitorContext context) { context.info("Annotating method", element); element.annotate(TestAnn.class, (builder) -> builder.value("method")); } @Override public void visitConstructor(ConstructorElement element, VisitorContext context) { context.info("Annotating constructor", element); element.annotate(TestAnn.class, (builder) -> builder.value("constructor")); } @Override public void visitField(FieldElement element, VisitorContext context) { context.info("Annotating field", element); // test using name element.annotate(TestAnn.class.getName(), (builder) -> builder.value("field")); } @Override public void visitEnumConstant(EnumConstantElement element, VisitorContext context) { context.info("Annotating
AnnotatingVisitor
java
spring-projects__spring-security
oauth2/oauth2-core/src/test/java/org/springframework/security/oauth2/core/DefaultOAuth2AuthenticatedPrincipalTests.java
{ "start": 1163, "end": 3030 }
class ____ { String name = "test-subject"; Map<String, Object> attributes = Collections.singletonMap("sub", this.name); Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("SCOPE_read"); @Test public void constructorWhenAttributesIsNullOrEmptyThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultOAuth2AuthenticatedPrincipal(null, this.authorities)); assertThatIllegalArgumentException() .isThrownBy(() -> new DefaultOAuth2AuthenticatedPrincipal(Collections.emptyMap(), this.authorities)); } @Test public void constructorWhenAuthoritiesIsNullOrEmptyThenNoAuthorities() { Collection<? extends GrantedAuthority> authorities = new DefaultOAuth2AuthenticatedPrincipal(this.attributes, null) .getAuthorities(); assertThat(authorities).isEmpty(); authorities = new DefaultOAuth2AuthenticatedPrincipal(this.attributes, Collections.emptyList()) .getAuthorities(); assertThat(authorities).isEmpty(); } @Test public void constructorWhenNameIsNullThenFallsbackToSubAttribute() { OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(null, this.attributes, this.authorities); assertThat(principal.getName()).isEqualTo(this.attributes.get("sub")); } @Test public void getNameWhenInConstructorThenReturns() { OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal("other-subject", this.attributes, this.authorities); assertThat(principal.getName()).isEqualTo("other-subject"); } @Test public void getAttributeWhenGivenKeyThenReturnsValue() { OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(this.attributes, this.authorities); assertThat((String) principal.getAttribute("sub")).isEqualTo("test-subject"); } }
DefaultOAuth2AuthenticatedPrincipalTests
java
apache__spark
sql/catalyst/src/test/java/org/apache/spark/sql/connector/catalog/CatalogLoadingSuite.java
{ "start": 8083, "end": 8362 }
class ____ implements CatalogPlugin { // no public constructor private AccessErrorCatalogPlugin() { } @Override public void initialize(String name, CaseInsensitiveStringMap options) { } @Override public String name() { return null; } }
AccessErrorCatalogPlugin
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/apikey/BaseBulkUpdateApiKeyRequest.java
{ "start": 695, "end": 2764 }
class ____ extends BaseUpdateApiKeyRequest { private final List<String> ids; public BaseBulkUpdateApiKeyRequest( final List<String> ids, @Nullable final List<RoleDescriptor> roleDescriptors, @Nullable final Map<String, Object> metadata, @Nullable final TimeValue expiration, @Nullable final CertificateIdentity certificateIdentity ) { super(roleDescriptors, metadata, expiration, certificateIdentity); this.ids = Objects.requireNonNull(ids, "API key IDs must not be null"); } @Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (ids.isEmpty()) { validationException = addValidationError("Field [ids] cannot be empty", validationException); } if (getCertificateIdentity() != null && ids.size() > 1) { validationException = addValidationError( "Certificate identity can only be updated for a single API key at a time. Found [" + ids.size() + "] API key IDs in the request.", validationException ); } return validationException; } public List<String> getIds() { return ids; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass() || super.equals(o)) return false; BaseBulkUpdateApiKeyRequest that = (BaseBulkUpdateApiKeyRequest) o; return Objects.equals(getIds(), that.getIds()) && Objects.equals(metadata, that.metadata) && Objects.equals(expiration, that.expiration) && Objects.equals(roleDescriptors, that.roleDescriptors) && Objects.equals(certificateIdentity, that.certificateIdentity); } @Override public int hashCode() { return Objects.hash(getIds(), expiration, metadata, roleDescriptors, certificateIdentity); } }
BaseBulkUpdateApiKeyRequest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryQualifierTest.java
{ "start": 2149, "end": 2484 }
class ____ { void foo() { // BUG: Diagnostic contains: @Qual int x; } } """) .doTest(); } @Test public void parameterOnNonInjectionPointMethod() { helper .addSourceLines( "Test.java", """
Test
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/SecurityFiles.java
{ "start": 1124, "end": 4546 }
class ____ { private SecurityFiles() {} /** * Atomically writes to the specified file a line per entry in the specified map using the specified transform to convert each entry to * a line. The writing is done atomically in the following sense: first the lines are written to a temporary file and if the writing * succeeds then the temporary file is moved to the specified path, replacing the file if it exists. If a failure occurs, any existing * file is preserved, and the temporary file is cleaned up. * * @param <K> the key type of the map entries * @param <V> the value type of the map entries * @param path the path * @param map the map whose entries to transform into lines * @param transform the transform to convert each map entry to a line */ public static <K, V> void writeFileAtomically(final Path path, final Map<K, V> map, final Function<Map.Entry<K, V>, String> transform) { Path tempFile = null; try { tempFile = Files.createTempFile(path.getParent(), path.getFileName().toString(), "tmp"); try (Writer writer = Files.newBufferedWriter(tempFile, StandardCharsets.UTF_8, CREATE, TRUNCATE_EXISTING, WRITE)) { for (final Map.Entry<K, V> entry : map.entrySet()) { final StringBuilder sb = new StringBuilder(); final String line = sb.append(transform.apply(entry)).append(System.lineSeparator()).toString(); writer.write(line); } } // get original permissions if (Files.exists(path)) { boolean supportsPosixAttributes = Environment.getFileStore(path).supportsFileAttributeView(PosixFileAttributeView.class); if (supportsPosixAttributes) { setPosixAttributesOnTempFile(path, tempFile); } } try { Files.move(tempFile, path, REPLACE_EXISTING, ATOMIC_MOVE); } catch (final AtomicMoveNotSupportedException e) { Files.move(tempFile, path, REPLACE_EXISTING); } } catch (final IOException e) { throw new UncheckedIOException(String.format(Locale.ROOT, "could not write file [%s]", path.toAbsolutePath()), e); } finally { // we are ignoring exceptions here, so we do not need handle whether or not tempFile was initialized nor if the file exists IOUtils.deleteFilesIgnoringExceptions(tempFile); } } static void setPosixAttributesOnTempFile(Path path, Path tempFile) throws IOException { PosixFileAttributes attributes = Files.getFileAttributeView(path, PosixFileAttributeView.class).readAttributes(); PosixFileAttributeView tempFileView = Files.getFileAttributeView(tempFile, PosixFileAttributeView.class); tempFileView.setPermissions(attributes.permissions()); // Make an attempt to set the username and group to match. If it fails, silently ignore the failure as the user // will be notified by the FileAttributeChecker that the ownership has changed and needs to be corrected try { tempFileView.setOwner(attributes.owner()); } catch (Exception e) {} try { tempFileView.setGroup(attributes.group()); } catch (Exception e) {} } }
SecurityFiles
java
google__dagger
javatests/dagger/internal/codegen/ComponentProcessorTest.java
{ "start": 74479, "end": 74958 }
class ____ {", "", " @Inject", " public Foo(GeneratedInjectType param) {}", "", " @Inject", " public void init() {}", "}"); Source component = CompilerTests.javaSource( "test.TestComponent", "package test;", "", "import dagger.Component;", "import java.util.Set;", "", "@Component", "
Foo
java
google__guava
android/guava/src/com/google/common/io/Resources.java
{ "start": 6290, "end": 7569 }
class ____ that loaded * this class ({@code Resources}) will be used instead. * * @throws IllegalArgumentException if the resource is not found */ @CanIgnoreReturnValue // being used to check if a resource exists // TODO(cgdecker): maybe add a better way to check if a resource exists // e.g. Optional<URL> tryGetResource or boolean resourceExists public static URL getResource(String resourceName) { ClassLoader loader = MoreObjects.firstNonNull( Thread.currentThread().getContextClassLoader(), Resources.class.getClassLoader()); URL url = loader.getResource(resourceName); checkArgument(url != null, "resource %s not found.", resourceName); return url; } /** * Given a {@code resourceName} that is relative to {@code contextClass}, returns a {@code URL} * pointing to the named resource. * * @throws IllegalArgumentException if the resource is not found */ @CanIgnoreReturnValue // being used to check if a resource exists public static URL getResource(Class<?> contextClass, String resourceName) { URL url = contextClass.getResource(resourceName); checkArgument( url != null, "resource %s relative to %s not found.", resourceName, contextClass.getName()); return url; } }
loader
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/json/jackson/HybridJacksonPool.java
{ "start": 7713, "end": 8897 }
class ____ { private final int mask; XorShiftThreadProbe(int mask) { this.mask = mask; } public int index() { return probe() & mask; } private int probe() { // Multiplicative Fibonacci hashing implementation // 0x9e3779b9 is the integral part of the Golden Ratio's fractional part 0.61803398875… (sqrt(5)-1)/2 // multiplied by 2^32, which has the best possible scattering properties. int probe = (int) ((Thread.currentThread().getId() * 0x9e3779b9) & Integer.MAX_VALUE); // xorshift probe ^= probe << 13; probe ^= probe >>> 17; probe ^= probe << 5; return probe; } } private static final int MAX_POW2 = 1 << 30; private static int roundToPowerOfTwo(final int value) { if (value > MAX_POW2) { throw new IllegalArgumentException( "There is no larger power of 2 int for value:" + value + " since it exceeds 2^31."); } if (value < 0) { throw new IllegalArgumentException("Given value:" + value + ". Expecting value >= 0."); } final int nextPow2 = 1 << (32 - Integer.numberOfLeadingZeros(value - 1)); return nextPow2; } }
XorShiftThreadProbe
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest62.java
{ "start": 893, "end": 2863 }
class ____ extends TestCase { public void test_true() throws Exception { WallProvider provider = new MySqlWallProvider(); provider.getConfig().setSchemaCheck(true); assertTrue(provider.checkValid(// "select temp.*, u.CanComment, u.CanBeShared, u.CanForward, COALESCE(b.UserID,0) as isBlocked" + " , COALESCE(f.UserID,0) as Followed, COALESCE(ff.UserID,0) as IsFollowed" + " , COALESCE(ul.UserID,0) as liked, COALESCE(fff.UserID,0) as RIsFollowed " + "from (select 294765 as UserID, 0 as RUserID, 7785977 as PicID " + " union all select 294765 as UserID, 0 as RUserID, 7780341 as PicID) temp " + "left join Users as u on u.UserID = temp.UserID " + "left join BlockUser as b on b.UserID = temp.UserID and b.BlockUserID = 294765 " + "left join Fans as f on f.FansID = temp.UserID and f.UserID = 294765 " + "left join Fans as ff ON ff.FansID = 294765 and ff.UserID = temp.UserID " + "left join Fans as fff ON fff.FansID = 294765 and fff.UserID = temp.RUserID " + "left join UserLikes as ul on ul.PicID = temp.PicID and ul.UserID = 294765")); assertEquals(4, provider.getTableStats().size()); } public void test_false() throws Exception { WallProvider provider = new MySqlWallProvider(); provider.getConfig().setSchemaCheck(true); provider.getConfig().setSelectUnionCheck(true); String sql = "SELECT 1, 2, 3" + " UNION ALL SELECT a from tt where c=1" + " UNION ALL SELECT 2 FROM dual --"; assertFalse(provider.checkValid(sql)); sql = "SELECT a from t where c=1 UNION ALL SELECT 2 FROM dual --"; assertFalse(provider.checkValid(sql)); } }
MySqlWallTest62
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestCorruptionWithFailover.java
{ "start": 1460, "end": 3625 }
class ____ { @Test public void testCorruptReplicaAfterFailover() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(DFS_NAMENODE_CORRUPT_BLOCK_DELETE_IMMEDIATELY_ENABLED, false); // Enable data to be written, to less replicas in case of pipeline failure. conf.setInt(HdfsClientConfigKeys.BlockWrite.ReplaceDatanodeOnFailure. MIN_REPLICATION, 2); try (MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf) .nnTopology(MiniDFSNNTopology.simpleHATopology()).numDataNodes(3) .build()) { cluster.transitionToActive(0); cluster.waitActive(); DistributedFileSystem dfs = cluster.getFileSystem(0); FSDataOutputStream out = dfs.create(new Path("/dir/file")); // Write some data and flush. for (int i = 0; i < 1024 * 1024; i++) { out.write(i); } out.hsync(); // Stop one datanode, so as to trigger update pipeline. MiniDFSCluster.DataNodeProperties dn = cluster.stopDataNode(0); // Write some more data and close the file. for (int i = 0; i < 1024 * 1024; i++) { out.write(i); } out.close(); BlockManager bm0 = cluster.getNamesystem(0).getBlockManager(); BlockManager bm1 = cluster.getNamesystem(1).getBlockManager(); // Mark datanodes as stale, as are marked if a namenode went through a // failover, to prevent replica deletion. bm0.getDatanodeManager().markAllDatanodesStaleAndSetKeyUpdateIfNeed(); bm1.getDatanodeManager().markAllDatanodesStaleAndSetKeyUpdateIfNeed(); // Restart the datanode cluster.restartDataNode(dn); // The replica from the datanode will be having lesser genstamp, so // would be marked as CORRUPT. GenericTestUtils.waitFor(() -> bm0.getCorruptBlocks() == 1, 100, 10000); // Perform failover to other namenode cluster.transitionToStandby(0); cluster.transitionToActive(1); cluster.waitActive(1); // The corrupt count should be same as first namenode. GenericTestUtils.waitFor(() -> bm1.getCorruptBlocks() == 1, 100, 10000); } } }
TestCorruptionWithFailover
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/temporal/TimestampPropertyTest.java
{ "start": 1798, "end": 4937 }
class ____ { private final DateFormat timestampFormat = new SimpleDateFormat( "HH:mm:ss.SSS" ); @Test public void testTime(SessionFactoryScope scope) { final Entity eOrig = new Entity(); eOrig.ts = new Date(); scope.inTransaction( session -> session.persist( eOrig ) ); scope.inTransaction( session -> { final Entity eGotten = session.get( Entity.class, eOrig.id ); final String tsOrigFormatted = timestampFormat.format( eOrig.ts ); final String tsGottenFormatted = timestampFormat.format( eGotten.ts ); assertEquals( tsOrigFormatted, tsGottenFormatted ); } ); scope.inTransaction( session -> { final Query<Entity> queryWithParameter = session.createQuery( "from TimestampPropertyTest$Entity where ts=?1" ) .setParameter( 1, eOrig.ts ); final Entity eQueriedWithParameter = queryWithParameter.uniqueResult(); assertNotNull( eQueriedWithParameter ); } ); final Entity eQueriedWithTimestamp = scope.fromTransaction( session -> { final Query<Entity> queryWithTimestamp = session.createQuery( "from TimestampPropertyTest$Entity where ts=?1" ) .setParameter( 1, eOrig.ts, StandardBasicTypes.TIMESTAMP ); final Entity queryResult = queryWithTimestamp.uniqueResult(); assertNotNull( queryResult ); return queryResult; } ); scope.inTransaction( session -> session.remove( eQueriedWithTimestamp ) ); } @Test public void testTimeGeneratedByColumnDefault(SessionFactoryScope scope) { final Entity eOrig = new Entity(); scope.inTransaction( session -> session.persist( eOrig ) ); assertNotNull( eOrig.tsColumnDefault ); scope.inTransaction( session -> { final Entity eGotten = session.get( Entity.class, eOrig.id ); final String tsColumnDefaultOrigFormatted = timestampFormat.format( eOrig.tsColumnDefault ); final String tsColumnDefaultGottenFormatted = timestampFormat.format( eGotten.tsColumnDefault ); assertEquals( tsColumnDefaultOrigFormatted, tsColumnDefaultGottenFormatted ); } ); scope.inTransaction( session -> { final Query<Entity> queryWithParameter = session.createQuery( "from TimestampPropertyTest$Entity where tsColumnDefault=?1" ) .setParameter( 1, eOrig.tsColumnDefault ); final Entity eQueriedWithParameter = queryWithParameter.uniqueResult(); assertNotNull( eQueriedWithParameter ); } ); final Entity eQueriedWithTimestamp = scope.fromTransaction( session -> { final Query<Entity> queryWithTimestamp = session.createQuery( "from TimestampPropertyTest$Entity where tsColumnDefault=?1" ) .setParameter( 1, eOrig.tsColumnDefault, StandardBasicTypes.TIMESTAMP ); final Entity queryResult = queryWithTimestamp.uniqueResult(); assertNotNull( queryResult ); return queryResult; } ); scope.inTransaction( session -> session.remove( eQueriedWithTimestamp ) ); } @jakarta.persistence.Entity @Table(name = "MyEntity") public static
TimestampPropertyTest
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/collection/Colour.java
{ "start": 198, "end": 236 }
enum ____ { RED, GREEN, BLUE; }
Colour
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/jdk/JDKValueInstantiators.java
{ "start": 6956, "end": 7303 }
class ____ extends JDKValueInstantiator { public TreeMapInstantiator() { super(TreeMap.class); } @Override public Object createUsingDefault(DeserializationContext ctxt) { return new TreeMap<>(); } } // @since 2.19: was missing private static
TreeMapInstantiator
java
apache__camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/model/complex/twoclassesandonelink/Security.java
{ "start": 1017, "end": 1718 }
class ____ { @DataField(pos = 6) private String instrumentNumber; @DataField(pos = 5) private String instrumentCode; public String getInstrumentNumber() { return instrumentNumber; } public void setInstrumentNumber(String instrumentNumber) { this.instrumentNumber = instrumentNumber; } public String getInstrumentCode() { return instrumentCode; } public void setInstrumentCode(String instrumentCode) { this.instrumentCode = instrumentCode; } @Override public String toString() { return "Model : " + Security.class.getName() + " : " + this.instrumentNumber + ", " + this.instrumentCode; } }
Security
java
elastic__elasticsearch
test/test-clusters/src/main/java/org/elasticsearch/test/cluster/LogType.java
{ "start": 517, "end": 1051 }
enum ____ { SERVER("%s.log"), SERVER_JSON("%s_server.json"), AUDIT("%s_audit.json"), SEARCH_SLOW("%s_index_search_slowlog.json"), INDEXING_SLOW("%s_index_indexing_slowlog.json"), ESQL_QUERY("%s_esql_querylog.json"), DEPRECATION("%s_deprecation.json"); private final String filenameFormat; LogType(String filenameFormat) { this.filenameFormat = filenameFormat; } public String resolveFilename(String clusterName) { return filenameFormat.formatted(clusterName); } }
LogType
java
spring-projects__spring-boot
module/spring-boot-http-codec/src/main/java/org/springframework/boot/http/codec/autoconfigure/HttpCodecsProperties.java
{ "start": 1056, "end": 1971 }
class ____ { /** * Whether to log form data at DEBUG level, and headers at TRACE level. */ private boolean logRequestDetails; /** * Limit on the number of bytes that can be buffered whenever the input stream needs * to be aggregated. This applies only to the auto-configured WebFlux server and * WebClient instances. By default this is not set, in which case individual codec * defaults apply. Most codecs are limited to 256K by default. */ private @Nullable DataSize maxInMemorySize; public boolean isLogRequestDetails() { return this.logRequestDetails; } public void setLogRequestDetails(boolean logRequestDetails) { this.logRequestDetails = logRequestDetails; } public @Nullable DataSize getMaxInMemorySize() { return this.maxInMemorySize; } public void setMaxInMemorySize(@Nullable DataSize maxInMemorySize) { this.maxInMemorySize = maxInMemorySize; } }
HttpCodecsProperties
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/InflightDataRescalingDescriptor.java
{ "start": 4683, "end": 6241 }
class ____ implements Serializable { public static final InflightDataGateOrPartitionRescalingDescriptor NO_STATE = new InflightDataGateOrPartitionRescalingDescriptor( EMPTY_INT_ARRAY, RescaleMappings.SYMMETRIC_IDENTITY, Collections.emptySet(), MappingType.IDENTITY) { private static final long serialVersionUID = 1L; @Override public int[] getOldSubtaskInstances() { return EMPTY_INT_ARRAY; } @Override public RescaleMappings getRescaleMappings() { return RescaleMappings.SYMMETRIC_IDENTITY; } }; private static final long serialVersionUID = 1L; /** Set when several operator instances are merged into one. */ private final int[] oldSubtaskIndexes; /** * Set when channels are merged because the connected operator has been rescaled for each * gate/partition. */ private final RescaleMappings rescaledChannelsMappings; /** All channels where upstream duplicates data (only valid for downstream mappings). */ private final Set<Integer> ambiguousSubtaskIndexes; private final MappingType mappingType; /** Type of mapping which should be used for this in-flight data. */ public
InflightDataGateOrPartitionRescalingDescriptor