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
alibaba__nacos
naming/src/test/java/com/alibaba/nacos/naming/pojo/instance/SnowFlakeInstanceIdGeneratorTest.java
{ "start": 1240, "end": 2188 }
class ____ { static { MockEnvironment environment = new MockEnvironment(); environment.setProperty("nacos.core.snowflake.worker-id", "-1"); EnvUtil.setEnvironment(environment); } @Test void testGenerateInstanceId() { final SnowFlakeInstanceIdGenerator instanceIdGenerator = new SnowFlakeInstanceIdGenerator(); Instance instance = new Instance(); Map<String, String> metaData = new HashMap<>(1); metaData.put(PreservedMetadataKeys.INSTANCE_ID_GENERATOR, SNOWFLAKE_INSTANCE_ID_GENERATOR); instance.setMetadata(metaData); instance.setServiceName("service"); instance.setClusterName("cluster"); instance.setIp("1.1.1.1"); instance.setPort(1000); String instanceId = instanceIdGenerator.generateInstanceId(instance); assertTrue(instanceId.endsWith("#cluster#service")); } }
SnowFlakeInstanceIdGeneratorTest
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4666CoreRealmImportTest.java
{ "start": 1242, "end": 4807 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Verify that API types from the Maven core realm are shared/imported into the plugin realm despite the plugin * declaring conflicting dependencies. For the core artifact filter, this boils down to the filter properly * recognizing such a conflicting dependency, i.e. knowing the relevant groupId:artifactId's. * * @throws Exception in case of failure */ @Test public void testit() throws Exception { File testDir = extractResources("/mng-4666"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteArtifacts("org.apache.maven", "maven-model", "0.1-stub"); verifier.deleteArtifacts("org.apache.maven", "maven-settings", "0.1-stub"); verifier.deleteArtifacts("org.apache.maven", "maven-project", "0.1-stub"); verifier.deleteArtifacts("org.apache.maven", "maven-artifact", "0.1-stub"); verifier.deleteArtifacts("org.apache.maven", "maven-core", "0.1-stub"); verifier.deleteArtifacts("org.apache.maven", "maven-plugin-api", "0.1-stub"); verifier.deleteArtifacts("org.apache.maven", "maven-plugin-descriptor", "0.1-stub"); verifier.deleteArtifacts("plexus", "plexus-container-default", "0.1-stub"); verifier.deleteArtifacts("org.codehaus.plexus", "plexus-container-default", "0.1-stub"); verifier.deleteArtifacts("org.codehaus.plexus", "plexus-component-api", "0.1-stub"); verifier.deleteArtifacts("org.codehaus.plexus", "plexus-utils", "0.1-stub"); verifier.deleteArtifacts("org.codehaus.plexus", "plexus-classworlds", "0.1-stub"); verifier.deleteArtifacts("org.sonatype.aether", "aether-api", "0.1-stub"); verifier.deleteArtifacts("org.sonatype.aether", "aether-spi", "0.1-stub"); verifier.deleteArtifacts("org.sonatype.aether", "aether-impl", "0.1-stub"); verifier.deleteArtifacts("org.sonatype.sisu", "sisu-inject-plexus", "0.1-stub"); verifier.deleteArtifacts("org.sonatype.spice", "spice-inject-plexus", "0.1-stub"); verifier.deleteArtifacts("classworlds", "classworlds", "0.1-stub"); verifier.filterFile("settings-template.xml", "settings.xml"); verifier.addCliArgument("-s"); verifier.addCliArgument("settings.xml"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); Properties props = verifier.loadProperties("target/type.properties"); List<String> types = getTypes(props); // MNG-4725, MNG-4807 types.remove("org.codehaus.plexus.configuration.PlexusConfiguration"); types.remove("org.codehaus.plexus.logging.Logger"); assertFalse(types.isEmpty()); for (String type : types) { assertEquals(props.get("plugin." + type), props.get("core." + type), type); } } private List<String> getTypes(Properties props) { List<String> types = new ArrayList<>(); for (Object o : props.keySet()) { String key = o.toString(); if (key.startsWith("core.")) { String type = key.substring(5); if (props.getProperty(key, "").length() > 0) { // types not in the core realm can't be exported/shared, so ignore those types.add(type); } } } return types; } }
MavenITmng4666CoreRealmImportTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DMSEndpointBuilderFactory.java
{ "start": 1640, "end": 18083 }
interface ____ extends EndpointProducerBuilder { default AdvancedDMSEndpointBuilder advanced() { return (AdvancedDMSEndpointBuilder) this; } /** * Access key for the cloud user. * * The option is a: <code>java.lang.String</code> type. * * Required: true * Group: producer * * @param accessKey the value to set * @return the dsl builder */ default DMSEndpointBuilder accessKey(String accessKey) { doSetProperty("accessKey", accessKey); return this; } /** * The username of a RabbitMQ instance. This option is mandatory when * creating a RabbitMQ instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param accessUser the value to set * @return the dsl builder */ default DMSEndpointBuilder accessUser(String accessUser) { doSetProperty("accessUser", accessUser); return this; } /** * A comma separated String of Availability Zones. This option is * mandatory when creating an instance and it cannot be an empty array. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param availableZones the value to set * @return the dsl builder */ default DMSEndpointBuilder availableZones(String availableZones) { doSetProperty("availableZones", availableZones); return this; } /** * DMS url. Carries higher precedence than region parameter based client * initialization. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param endpoint the value to set * @return the dsl builder */ default DMSEndpointBuilder endpoint(String endpoint) { doSetProperty("endpoint", endpoint); return this; } /** * The message engine. Either kafka or rabbitmq. If the parameter is not * specified, all instances will be queried. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param engine the value to set * @return the dsl builder */ default DMSEndpointBuilder engine(String engine) { doSetProperty("engine", engine); return this; } /** * The version of the message engine. This option is mandatory when * creating an instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param engineVersion the value to set * @return the dsl builder */ default DMSEndpointBuilder engineVersion(String engineVersion) { doSetProperty("engineVersion", engineVersion); return this; } /** * Ignore SSL verification. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer * * @param ignoreSslVerification the value to set * @return the dsl builder */ default DMSEndpointBuilder ignoreSslVerification(boolean ignoreSslVerification) { doSetProperty("ignoreSslVerification", ignoreSslVerification); return this; } /** * Ignore SSL verification. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer * * @param ignoreSslVerification the value to set * @return the dsl builder */ default DMSEndpointBuilder ignoreSslVerification(String ignoreSslVerification) { doSetProperty("ignoreSslVerification", ignoreSslVerification); return this; } /** * The id of the instance. This option is mandatory when deleting or * querying an instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param instanceId the value to set * @return the dsl builder */ default DMSEndpointBuilder instanceId(String instanceId) { doSetProperty("instanceId", instanceId); return this; } /** * The password for logging in to the Kafka Manager. This option is * mandatory when creating a Kafka instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param kafkaManagerPassword the value to set * @return the dsl builder */ default DMSEndpointBuilder kafkaManagerPassword(String kafkaManagerPassword) { doSetProperty("kafkaManagerPassword", kafkaManagerPassword); return this; } /** * The username for logging in to the Kafka Manager. This option is * mandatory when creating a Kafka instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param kafkaManagerUser the value to set * @return the dsl builder */ default DMSEndpointBuilder kafkaManagerUser(String kafkaManagerUser) { doSetProperty("kafkaManagerUser", kafkaManagerUser); return this; } /** * The name of the instance for creating and updating an instance. This * option is mandatory when creating an instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param name the value to set * @return the dsl builder */ default DMSEndpointBuilder name(String name) { doSetProperty("name", name); return this; } /** * The maximum number of partitions in a Kafka instance. This option is * mandatory when creating a Kafka instance. * * The option is a: <code>int</code> type. * * Group: producer * * @param partitionNum the value to set * @return the dsl builder */ default DMSEndpointBuilder partitionNum(int partitionNum) { doSetProperty("partitionNum", partitionNum); return this; } /** * The maximum number of partitions in a Kafka instance. This option is * mandatory when creating a Kafka instance. * * The option will be converted to a <code>int</code> type. * * Group: producer * * @param partitionNum the value to set * @return the dsl builder */ default DMSEndpointBuilder partitionNum(String partitionNum) { doSetProperty("partitionNum", partitionNum); return this; } /** * The password of a RabbitMQ instance. This option is mandatory when * creating a RabbitMQ instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param password the value to set * @return the dsl builder */ default DMSEndpointBuilder password(String password) { doSetProperty("password", password); return this; } /** * The product ID. This option is mandatory when creating an instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param productId the value to set * @return the dsl builder */ default DMSEndpointBuilder productId(String productId) { doSetProperty("productId", productId); return this; } /** * Cloud project ID. * * The option is a: <code>java.lang.String</code> type. * * Required: true * Group: producer * * @param projectId the value to set * @return the dsl builder */ default DMSEndpointBuilder projectId(String projectId) { doSetProperty("projectId", projectId); return this; } /** * Proxy server ip/hostname. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param proxyHost the value to set * @return the dsl builder */ default DMSEndpointBuilder proxyHost(String proxyHost) { doSetProperty("proxyHost", proxyHost); return this; } /** * Proxy authentication password. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param proxyPassword the value to set * @return the dsl builder */ default DMSEndpointBuilder proxyPassword(String proxyPassword) { doSetProperty("proxyPassword", proxyPassword); return this; } /** * Proxy server port. * * The option is a: <code>int</code> type. * * Group: producer * * @param proxyPort the value to set * @return the dsl builder */ default DMSEndpointBuilder proxyPort(int proxyPort) { doSetProperty("proxyPort", proxyPort); return this; } /** * Proxy server port. * * The option will be converted to a <code>int</code> type. * * Group: producer * * @param proxyPort the value to set * @return the dsl builder */ default DMSEndpointBuilder proxyPort(String proxyPort) { doSetProperty("proxyPort", proxyPort); return this; } /** * Proxy authentication user. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param proxyUser the value to set * @return the dsl builder */ default DMSEndpointBuilder proxyUser(String proxyUser) { doSetProperty("proxyUser", proxyUser); return this; } /** * DMS service region. * * The option is a: <code>java.lang.String</code> type. * * Required: true * Group: producer * * @param region the value to set * @return the dsl builder */ default DMSEndpointBuilder region(String region) { doSetProperty("region", region); return this; } /** * Secret key for the cloud user. * * The option is a: <code>java.lang.String</code> type. * * Required: true * Group: producer * * @param secretKey the value to set * @return the dsl builder */ default DMSEndpointBuilder secretKey(String secretKey) { doSetProperty("secretKey", secretKey); return this; } /** * The security group which the instance belongs to. This option is * mandatory when creating an instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param securityGroupId the value to set * @return the dsl builder */ default DMSEndpointBuilder securityGroupId(String securityGroupId) { doSetProperty("securityGroupId", securityGroupId); return this; } /** * Configuration object for cloud service authentication. * * The option is a: * <code>org.apache.camel.component.huaweicloud.common.models.ServiceKeys</code> type. * * Group: producer * * @param serviceKeys the value to set * @return the dsl builder */ default DMSEndpointBuilder serviceKeys(org.apache.camel.component.huaweicloud.common.models.ServiceKeys serviceKeys) { doSetProperty("serviceKeys", serviceKeys); return this; } /** * Configuration object for cloud service authentication. * * The option will be converted to a * <code>org.apache.camel.component.huaweicloud.common.models.ServiceKeys</code> type. * * Group: producer * * @param serviceKeys the value to set * @return the dsl builder */ default DMSEndpointBuilder serviceKeys(String serviceKeys) { doSetProperty("serviceKeys", serviceKeys); return this; } /** * The baseline bandwidth of a Kafka instance. This option is mandatory * when creating a Kafka instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param specification the value to set * @return the dsl builder */ default DMSEndpointBuilder specification(String specification) { doSetProperty("specification", specification); return this; } /** * The message storage space. This option is mandatory when creating an * instance. * * The option is a: <code>int</code> type. * * Group: producer * * @param storageSpace the value to set * @return the dsl builder */ default DMSEndpointBuilder storageSpace(int storageSpace) { doSetProperty("storageSpace", storageSpace); return this; } /** * The message storage space. This option is mandatory when creating an * instance. * * The option will be converted to a <code>int</code> type. * * Group: producer * * @param storageSpace the value to set * @return the dsl builder */ default DMSEndpointBuilder storageSpace(String storageSpace) { doSetProperty("storageSpace", storageSpace); return this; } /** * The storage I/O specification. This option is mandatory when creating * an instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param storageSpecCode the value to set * @return the dsl builder */ default DMSEndpointBuilder storageSpecCode(String storageSpecCode) { doSetProperty("storageSpecCode", storageSpecCode); return this; } /** * The subnet ID. This option is mandatory when creating an instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param subnetId the value to set * @return the dsl builder */ default DMSEndpointBuilder subnetId(String subnetId) { doSetProperty("subnetId", subnetId); return this; } /** * The VPC ID. This option is mandatory when creating an instance. * * The option is a: <code>java.lang.String</code> type. * * Group: producer * * @param vpcId the value to set * @return the dsl builder */ default DMSEndpointBuilder vpcId(String vpcId) { doSetProperty("vpcId", vpcId); return this; } } /** * Advanced builder for endpoint for the Huawei Distributed Message Service (DMS) component. */ public
DMSEndpointBuilder
java
google__auto
value/src/main/java/com/google/auto/value/processor/AutoValueBuilderProcessor.java
{ "start": 2968, "end": 3369 }
interface ____ an" + " @AutoValue class"); } } return false; } private void validate(Element annotatedType, String errorMessage) { Element container = annotatedType.getEnclosingElement(); if (!hasAnnotationMirror(container, AUTO_VALUE_NAME)) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, errorMessage, annotatedType); } } }
inside
java
jhy__jsoup
src/main/java/org/jsoup/safety/Safelist.java
{ "start": 24477, "end": 24717 }
class ____ extends TypedValue { TagName(String value) { super(value); } static TagName valueOf(String value) { return new TagName(Normalizer.lowerCase(value)); } } static
TagName
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2RelyingPartyInitiatedLogoutSuccessHandler.java
{ "start": 1772, "end": 6769 }
class ____ implements LogoutSuccessHandler { private final Log logger = LogFactory.getLog(getClass()); private final Saml2LogoutRequestResolver logoutRequestResolver; private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); private Saml2LogoutRequestRepository logoutRequestRepository = new HttpSessionLogoutRequestRepository(); /** * Constructs a {@link Saml2RelyingPartyInitiatedLogoutSuccessHandler} using the * provided parameters * @param logoutRequestResolver the {@link Saml2LogoutRequestResolver} to use */ public Saml2RelyingPartyInitiatedLogoutSuccessHandler(Saml2LogoutRequestResolver logoutRequestResolver) { this.logoutRequestResolver = logoutRequestResolver; } /** * Produce and send a SAML 2.0 Logout Response based on the SAML 2.0 Logout Request * received from the asserting party * @param request the HTTP request * @param response the HTTP response * @param authentication the current principal details * @throws IOException when failing to write to the response */ @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { Saml2LogoutRequest logoutRequest = this.logoutRequestResolver.resolve(request, authentication); if (logoutRequest == null) { this.logger.trace("Returning 401 since no logout request generated"); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } this.logoutRequestRepository.saveLogoutRequest(logoutRequest, request, response); if (logoutRequest.getBinding() == Saml2MessageBinding.REDIRECT) { doRedirect(request, response, logoutRequest); } else { doPost(response, logoutRequest); } } /** * Use this {@link Saml2LogoutRequestRepository} for saving the SAML 2.0 Logout * Request * @param logoutRequestRepository the {@link Saml2LogoutRequestRepository} to use */ public void setLogoutRequestRepository(Saml2LogoutRequestRepository logoutRequestRepository) { Assert.notNull(logoutRequestRepository, "logoutRequestRepository cannot be null"); this.logoutRequestRepository = logoutRequestRepository; } private void doRedirect(HttpServletRequest request, HttpServletResponse response, Saml2LogoutRequest logoutRequest) throws IOException { String location = logoutRequest.getLocation(); UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(location) .query(logoutRequest.getParametersQuery()); this.redirectStrategy.sendRedirect(request, response, uriBuilder.build(true).toUriString()); } private void doPost(HttpServletResponse response, Saml2LogoutRequest logoutRequest) throws IOException { String location = logoutRequest.getLocation(); String saml = logoutRequest.getSamlRequest(); String relayState = logoutRequest.getRelayState(); String html = createSamlPostRequestFormData(location, saml, relayState); response.setContentType(MediaType.TEXT_HTML_VALUE); response.getWriter().write(html); } private String createSamlPostRequestFormData(String location, String saml, String relayState) { StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html>\n"); html.append("<html>\n").append(" <head>\n"); html.append(" <meta http-equiv=\"Content-Security-Policy\" ") .append("content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">\n"); html.append(" <meta charset=\"utf-8\" />\n"); html.append(" </head>\n"); html.append(" <body>\n"); html.append(" <noscript>\n"); html.append(" <p>\n"); html.append(" <strong>Note:</strong> Since your browser does not support JavaScript,\n"); html.append(" you must press the Continue button once to proceed.\n"); html.append(" </p>\n"); html.append(" </noscript>\n"); html.append(" \n"); html.append(" <form action=\""); html.append(location); html.append("\" method=\"post\">\n"); html.append(" <div>\n"); html.append(" <input type=\"hidden\" name=\"SAMLRequest\" value=\""); html.append(HtmlUtils.htmlEscape(saml)); html.append("\"/>\n"); if (StringUtils.hasText(relayState)) { html.append(" <input type=\"hidden\" name=\"RelayState\" value=\""); html.append(HtmlUtils.htmlEscape(relayState)); html.append("\"/>\n"); } html.append(" </div>\n"); html.append(" <noscript>\n"); html.append(" <div>\n"); html.append(" <input type=\"submit\" value=\"Continue\"/>\n"); html.append(" </div>\n"); html.append(" </noscript>\n"); html.append(" </form>\n"); html.append(" \n"); html.append(" <script>window.onload = function() { document.forms[0].submit(); }</script>\n"); html.append(" </body>\n"); html.append("</html>"); return html.toString(); } }
Saml2RelyingPartyInitiatedLogoutSuccessHandler
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/SimpleUdfStreamOperatorFactory.java
{ "start": 1120, "end": 1703 }
class ____<OUT> extends SimpleOperatorFactory<OUT> implements UdfStreamOperatorFactory<OUT> { private final AbstractUdfStreamOperator<OUT, ?> operator; public SimpleUdfStreamOperatorFactory(AbstractUdfStreamOperator<OUT, ?> operator) { super(operator); this.operator = operator; } @Override public Function getUserFunction() { return operator.getUserFunction(); } @Override public String getUserFunctionClassName() { return operator.getUserFunction().getClass().getName(); } }
SimpleUdfStreamOperatorFactory
java
elastic__elasticsearch
modules/transport-netty4/src/main/java/org/elasticsearch/transport/netty4/Netty4Transport.java
{ "start": 15997, "end": 18610 }
class ____ extends ChannelInitializer<Channel> { protected final String name; private final boolean isRemoteClusterServerChannel; protected ServerChannelInitializer(String name) { this.name = name; this.isRemoteClusterServerChannel = remoteClusterPortEnabled && REMOTE_CLUSTER_PROFILE.equals(name); } @Override protected void initChannel(Channel ch) throws Exception { assert ch instanceof Netty4NioSocketChannel; NetUtils.tryEnsureReasonableKeepAliveConfig(((Netty4NioSocketChannel) ch).javaChannel()); Netty4TcpChannel nettyTcpChannel = new Netty4TcpChannel(ch, true, name, rstOnClose, ch.newSucceededFuture()); ch.attr(CHANNEL_KEY).set(nettyTcpChannel); setupPipeline(ch, isRemoteClusterServerChannel); serverAcceptedChannel(nettyTcpChannel); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Netty4TcpChannel channel = ctx.channel().attr(CHANNEL_KEY).get(); channel.setCloseException(exceptionFromThrowable(cause)); ExceptionsHelper.maybeDieOnAnotherThread(cause); super.exceptionCaught(ctx, cause); } } private void setupPipeline(Channel ch, boolean isRemoteClusterServerChannel) { final var pipeline = ch.pipeline(); pipeline.addLast("byte_buf_sizer", NettyByteBufSizer.INSTANCE); if (NetworkTraceFlag.TRACE_ENABLED) { pipeline.addLast("logging", ESLoggingHandler.INSTANCE); } pipeline.addLast( "chunked_writer", new Netty4WriteThrottlingHandler(getThreadPool().getThreadContext(), threadWatchdog.getActivityTrackerForCurrentThread()) ); pipeline.addLast( "dispatcher", new Netty4MessageInboundHandler( this, getInboundPipeline(ch, isRemoteClusterServerChannel), threadWatchdog.getActivityTrackerForCurrentThread() ) ); } protected InboundPipeline getInboundPipeline(Channel ch, boolean isRemoteClusterServerChannel) { return new InboundPipeline( getStatsTracker(), threadPool.relativeTimeInMillisSupplier(), new InboundDecoder(recycler), new InboundAggregator(getInflightBreaker(), getRequestHandlers()::getHandler, ignoreDeserializationErrors()), this::inboundMessage ); } @ChannelHandler.Sharable private static
ServerChannelInitializer
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/source/TestPropertyMapper.java
{ "start": 951, "end": 1868 }
class ____ implements PropertyMapper { private final MultiValueMap<ConfigurationPropertyName, String> fromConfig = new LinkedMultiValueMap<>(); private final Map<String, ConfigurationPropertyName> fromSource = new LinkedHashMap<>(); void addFromPropertySource(String from, String to) { this.fromSource.put(from, ConfigurationPropertyName.of(to)); } void addFromConfigurationProperty(ConfigurationPropertyName from, String... to) { for (String propertySourceName : to) { this.fromConfig.add(from, propertySourceName); } } @Override public List<String> map(ConfigurationPropertyName configurationPropertyName) { return this.fromConfig.getOrDefault(configurationPropertyName, Collections.emptyList()); } @Override public ConfigurationPropertyName map(String propertySourceName) { return this.fromSource.getOrDefault(propertySourceName, ConfigurationPropertyName.EMPTY); } }
TestPropertyMapper
java
quarkusio__quarkus
integration-tests/spring-boot-properties/src/main/java/io/quarkus/it/spring/boot/BeanProperties.java
{ "start": 49, "end": 685 }
class ____ { private final String finalValue; int packagePrivateValue; private int value; private InnerClass innerClass; public BeanProperties(String finalValue) { this.finalValue = finalValue; } public String getFinalValue() { return finalValue; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public InnerClass getInnerClass() { return innerClass; } public void setInnerClass(InnerClass innerClass) { this.innerClass = innerClass; } public static
BeanProperties
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateIndexTest9.java
{ "start": 967, "end": 2597 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "CREATE INDEX area_index ON xwarehouses e \n" + " (EXTRACTVALUE(VALUE(e),'/Warehouse/Area'));"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.ORACLE); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.ORACLE); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals("CREATE INDEX area_index ON xwarehouses e(EXTRACTVALUE(VALUE(e), '/Warehouse/Area'));", SQLUtils.toSQLString(stmt, JdbcConstants.ORACLE)); assertEquals(1, visitor.getTables().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("xwarehouses"))); assertEquals(0, visitor.getColumns().size()); // assertTrue(visitor.getColumns().contains(new TableStat.Column("xwarehouses", "sales_rep_id"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode"))); } }
OracleCreateIndexTest9
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/issues/AdviceWithCBRRouteIdTest.java
{ "start": 1070, "end": 3597 }
class ____ extends ContextTestSupport { @Test public void testAdviceCBR() throws Exception { AdviceWith.adviceWith("myRoute", context, new AdviceWithRouteBuilder() { @Override public void configure() { weaveById("foo").after().to("mock:foo2"); weaveById("bar").after().to("mock:bar2"); } }); getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:foo2").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:bar").expectedBodiesReceived("Bye World"); getMockEndpoint("mock:bar2").expectedBodiesReceived("Bye World"); getMockEndpoint("mock:baz").expectedBodiesReceived("Hi World"); template.sendBodyAndHeader("direct:start", "Hello World", "foo", "123"); template.sendBodyAndHeader("direct:start", "Bye World", "bar", "123"); template.sendBody("direct:start", "Hi World"); assertMockEndpointsSatisfied(); } @Test public void testAdviceToStringCBR() throws Exception { // pick first route from index 0 AdviceWith.adviceWith(0, context, new AdviceWithRouteBuilder() { @Override public void configure() { weaveByToString("To[mock:foo]").after().to("mock:foo2"); weaveByToString("To[mock:bar]").after().to("mock:bar2"); } }); getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:foo2").expectedBodiesReceived("Hello World"); getMockEndpoint("mock:bar").expectedBodiesReceived("Bye World"); getMockEndpoint("mock:bar2").expectedBodiesReceived("Bye World"); getMockEndpoint("mock:baz").expectedBodiesReceived("Hi World"); template.sendBodyAndHeader("direct:start", "Hello World", "foo", "123"); template.sendBodyAndHeader("direct:start", "Bye World", "bar", "123"); template.sendBody("direct:start", "Hi World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").routeId("myRoute") .choice().when(header("foo")).to("mock:foo").id("foo").when(header("bar")).to("mock:bar") .id("bar").otherwise().to("mock:baz").id("baz"); } }; } }
AdviceWithCBRRouteIdTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/TestJsonSerialize2.java
{ "start": 1780, "end": 1918 }
class ____ extends HashMap<SimpleKey, ActualValue> { } @JsonSerialize(contentUsing=SimpleValueSerializer.class) static
SimpleValueMap
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/create/MySqlCreateViewTest2.java
{ "start": 1126, "end": 3732 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "create view revenue0 as \n" + "select l_suppkey as supplier_no, sum(l_extendedprice * (1 - l_discount)) as total_revenue \n" + "from lineitem \n" + "where l_shipdate >= date '1993-01-01' and l_shipdate < date '1993-01-01' + interval '3' month \n" + "group by l_suppkey"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLCreateViewStatement stmt = (SQLCreateViewStatement) statementList.get(0); // print(statementList); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); assertEquals("CREATE VIEW revenue0\n" + "AS\n" + "SELECT l_suppkey AS supplier_no, sum(l_extendedprice * (1 - l_discount)) AS total_revenue\n" + "FROM lineitem\n" + "WHERE l_shipdate >= DATE '1993-01-01'\n" + "\tAND l_shipdate < DATE '1993-01-01' + INTERVAL '3' MONTH\n" + "GROUP BY l_suppkey", // SQLUtils.toMySqlString(stmt)); assertEquals("create view revenue0\n" + "as\n" + "select l_suppkey as supplier_no, sum(l_extendedprice * (1 - l_discount)) as total_revenue\n" + "from lineitem\n" + "where l_shipdate >= date '1993-01-01'\n" + "\tand l_shipdate < date '1993-01-01' + interval '3' month\n" + "group by l_suppkey", // SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION)); // 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(1, visitor.getTables().size()); assertEquals(4, visitor.getColumns().size()); assertEquals(2, visitor.getConditions().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("lineitem"))); assertTrue(visitor.getColumns().contains(new Column("lineitem", "l_shipdate"))); assertTrue(visitor.getColumns().contains(new Column("lineitem", "l_suppkey"))); } }
MySqlCreateViewTest2
java
apache__hadoop
hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/request/RequestWithHandle.java
{ "start": 990, "end": 1212 }
class ____ extends NFS3Request { protected final FileHandle handle; RequestWithHandle(FileHandle handle) { this.handle = handle; } public FileHandle getHandle() { return this.handle; } }
RequestWithHandle
java
mapstruct__mapstruct
core/src/test/java/org/mapstruct/test/model/SomeClass$NestedClass$FooImpl.java
{ "start": 433, "end": 511 }
class ____$NestedClass$FooImpl implements SomeClass.NestedClass.Foo { }
SomeClass
java
google__dagger
javatests/dagger/internal/codegen/LazyClassKeyMapBindingComponentProcessorTest.java
{ "start": 10539, "end": 11067 }
interface ____ {", " Provider<Map<Class<?>, Provider<Integer>>> classKey();", "}"); CompilerTests.daggerCompiler(fooBar, fooBar2, mapKeyBindingsModule, componentFile) .withProcessingOptions(compilerMode.processorOptions()) .compile(subject -> subject.hasErrorCount(0)); } @Test public void testProguardFile() throws Exception { Source fooKey = CompilerTests.javaSource( "test.FooKey", "package test;", "", "
TestComponent
java
google__guava
guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/ListenableFuture.java
{ "start": 3448, "end": 3906 }
interface ____ { void onInvoke(Object error); } void onInvoke(ResolveCallbackFn<T> resolve, RejectCallbackFn reject); } public Promise(PromiseExecutorCallbackFn<T> executor) {} @Override public native <V extends @Nullable Object> Promise<V> then( @JsOptional @Nullable IThenOnFulfilledCallbackFn<? super T, ? extends V> onFulfilled, @JsOptional @Nullable IThenOnRejectedCallbackFn<? extends V> onRejected); }
RejectCallbackFn
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/float_/FloatAssert_isLessThanOrEqualTo_float_Test.java
{ "start": 1371, "end": 2873 }
class ____ extends FloatAssertBaseTest { @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected FloatAssert invoke_api_method() { // trick to simulate a custom comparator given(floats.getComparator()).willReturn((Comparator) ALWAY_EQUAL_FLOAT); return assertions.isLessThanOrEqualTo(6.0f); } @Override protected void verify_internal_effects() { // verify we delegate to assertLessThanOrEqualTo when using a custom comparator verify(floats).getComparator(); verify(floats).assertLessThanOrEqualTo(getInfo(assertions), getActual(assertions), 6.0f); } @ParameterizedTest(name = "verify {0} <= {1} assertion succeeds") @CsvSource({ "1.0d, 1.0d", "0.0d, -0.0d", "-0.0d, 0.0d", "0.0d, 1.0d", "-1.0d, 0.0d" }) void should_pass_using_primitive_comparison(float actual, float expected) { assertThat(actual).isLessThanOrEqualTo(expected); } @Test void should_honor_user_specified_comparator() { // GIVEN final float one = 1.0f; // THEN assertThat(one).usingComparator(ALWAY_EQUAL_FLOAT) .isLessThanOrEqualTo(-one); } @Test void should_fail_if_actual_is_greater_than_expected() { // GIVEN float actual = 8.0f; float expected = 7.0f; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).isLessThanOrEqualTo(expected)); // THEN then(assertionError).hasMessage(shouldBeLessOrEqual(actual, expected).create()); } }
FloatAssert_isLessThanOrEqualTo_float_Test
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/batch/sql/CalcMergeTest.java
{ "start": 1072, "end": 1327 }
class ____ extends CalcMergeTestBase { @Override protected boolean isBatchMode() { return true; } @Override protected TableTestUtil getTableTestUtil() { return batchTestUtil(TableConfig.getDefault()); } }
CalcMergeTest
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateDataSourceUtil.java
{ "start": 202, "end": 1159 }
class ____ { public static <T> Optional<T> findDataSourceWithNameDefault(String persistenceUnitName, List<T> datasSources, Function<T, String> nameExtractor, Function<T, Boolean> defaultExtractor, Optional<String> datasource) { if (datasource.isPresent()) { String dataSourceName = datasource.get(); return datasSources.stream() .filter(i -> dataSourceName.equals(nameExtractor.apply(i))) .findFirst(); } else if (PersistenceUnitUtil.isDefaultPersistenceUnit(persistenceUnitName)) { return datasSources.stream() .filter(i -> defaultExtractor.apply(i)) .findFirst(); } else { // if it's not the default persistence unit, we mandate an explicit datasource to prevent common errors return Optional.empty(); } } }
HibernateDataSourceUtil
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/transport/SingleResultDeduplicatorTests.java
{ "start": 1764, "end": 7627 }
class ____ extends ESTestCase { public void testDeduplicatesWithoutShowingStaleData() { final SetOnce<ActionListener<Object>> firstListenerRef = new SetOnce<>(); final SetOnce<ActionListener<Object>> secondListenerRef = new SetOnce<>(); final var deduplicator = new SingleResultDeduplicator<>(new ThreadContext(Settings.EMPTY), l -> { if (firstListenerRef.trySet(l) == false) { secondListenerRef.set(l); } }); final Object result1 = new Object(); final Object result2 = new Object(); final int totalListeners = randomIntBetween(2, 10); final boolean[] called = new boolean[totalListeners]; deduplicator.execute(ActionTestUtils.assertNoFailureListener(response -> { assertFalse(called[0]); called[0] = true; assertEquals(result1, response); })); for (int i = 1; i < totalListeners; i++) { final int index = i; deduplicator.execute(ActionTestUtils.assertNoFailureListener(response -> { assertFalse(called[index]); called[index] = true; assertEquals(result2, response); })); } for (int i = 0; i < totalListeners; i++) { assertFalse(called[i]); } firstListenerRef.get().onResponse(result1); assertTrue(called[0]); for (int i = 1; i < totalListeners; i++) { assertFalse(called[i]); } secondListenerRef.get().onResponse(result2); for (int i = 0; i < totalListeners; i++) { assertTrue(called[i]); } } public void testThreadContextPreservation() { final var resources = new Releasable[1]; try { final var workerResponseHeaderValueCounter = new AtomicInteger(); final List<Integer> allSeenResponseHeaderValues = Collections.synchronizedList(new ArrayList<>()); final List<Integer> allSeenThreadHeaderValues = Collections.synchronizedList(new ArrayList<>()); final var threads = between(1, 5); final var future = new PlainActionFuture<Void>(); try (var listeners = new RefCountingListener(future)) { final var workerRequestHeaderName = "worker-request-header"; final var workerResponseHeaderName = "worker-response-header"; final var threadHeaderName = "test-header"; final var threadContext = new ThreadContext(Settings.EMPTY); final var deduplicator = new SingleResultDeduplicator<Void>(threadContext, l -> { threadContext.putHeader(workerRequestHeaderName, randomAlphaOfLength(5)); threadContext.addResponseHeader( workerResponseHeaderName, String.valueOf(workerResponseHeaderValueCounter.getAndIncrement()) ); allSeenThreadHeaderValues.add(Integer.valueOf(threadContext.getHeader(threadHeaderName))); l.onResponse(null); }); final var executor = EsExecutors.newFixed( "test", threads, 0, TestEsExecutors.testOnlyDaemonThreadFactory("test"), threadContext, EsExecutors.TaskTrackingConfig.DO_NOT_TRACK ); resources[0] = () -> ThreadPool.terminate(executor, 10, TimeUnit.SECONDS); final var barrier = new CyclicBarrier(threads); for (int i = 0; i < threads; i++) { try (var ignored = threadContext.stashContext()) { final var threadHeaderValue = String.valueOf(i); threadContext.putHeader(threadHeaderName, threadHeaderValue); executor.execute(ActionRunnable.wrap(listeners.<Void>acquire(v -> { // original request header before the work execution should be preserved assertEquals(threadHeaderValue, threadContext.getHeader(threadHeaderName)); // request header used by the work execution should *not* be preserved assertThat(threadContext.getHeaders(), not(hasKey(workerRequestHeaderName))); // response header should be preserved which is from a single execution of the work final List<String> responseHeader = threadContext.getResponseHeaders().get(workerResponseHeaderName); assertThat(responseHeader, hasSize(1)); allSeenResponseHeaderValues.add(Integer.valueOf(responseHeader.get(0))); }), listener -> { safeAwait(barrier); deduplicator.execute(listener); })); } } } future.actionGet(10, TimeUnit.SECONDS); assertThat(allSeenResponseHeaderValues, hasSize(threads)); // The total number of observed response header values consistent with how many times it is generated assertThat( Set.copyOf(allSeenResponseHeaderValues), equalTo(IntStream.range(0, workerResponseHeaderValueCounter.get()).boxed().collect(Collectors.toUnmodifiableSet())) ); // The following proves each work execution will see a different thread's context in that execution batch assertThat(Set.copyOf(allSeenThreadHeaderValues), hasSize(workerResponseHeaderValueCounter.get())); } finally { Releasables.closeExpectNoException(resources); } } }
SingleResultDeduplicatorTests
java
quarkusio__quarkus
extensions/oidc/runtime/src/main/java/io/quarkus/oidc/AuthorizationCodeTokens.java
{ "start": 82, "end": 3130 }
class ____ { private String idToken; private String accessToken; private String refreshToken; private Long accessTokenExpiresIn; private String accessTokenScope; public AuthorizationCodeTokens() { } public AuthorizationCodeTokens(String idToken, String accessToken, String refreshToken) { this(idToken, accessToken, refreshToken, null); } public AuthorizationCodeTokens(String idToken, String accessToken, String refreshToken, Long accessTokenExpiresIn) { this(idToken, accessToken, refreshToken, accessTokenExpiresIn, null); } public AuthorizationCodeTokens(String idToken, String accessToken, String refreshToken, Long accessTokenExpiresIn, String accessTokenScope) { this.idToken = idToken; this.accessToken = accessToken; this.refreshToken = refreshToken; this.accessTokenExpiresIn = accessTokenExpiresIn; this.accessTokenScope = accessTokenScope; } /** * Get the ID token * * @return ID token */ public String getIdToken() { return idToken; } /** * Set the ID token * * @param idToken ID token */ public void setIdToken(String idToken) { this.idToken = idToken; } /** * Get the access token * * @return the access token */ public String getAccessToken() { return accessToken; } /** * Set the access token * * @param accessToken the access token */ public void setAccessToken(String accessToken) { this.accessToken = accessToken; } /** * Get the refresh token * * @return refresh token */ public String getRefreshToken() { return refreshToken; } /** * Set the refresh token * * @param refreshToken refresh token */ public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } /** * Get the access token expires_in value in seconds. * It is relative to the time the access token is issued at. * * @return access token expires_in value in seconds. */ public Long getAccessTokenExpiresIn() { return accessTokenExpiresIn; } /** * Set the access token expires_in value in seconds. * It is relative to the time the access token is issued at. * * @param accessTokenExpiresIn access token expires_in value in seconds. */ public void setAccessTokenExpiresIn(Long accessTokenExpiresIn) { this.accessTokenExpiresIn = accessTokenExpiresIn; } /** * Get the access token scope. * * @return access token scope. */ public String getAccessTokenScope() { return accessTokenScope; } /** * Set the access token scope. * * @param accessTokenScope access token scope. */ public void setAccessTokenScope(String accessTokenScope) { this.accessTokenScope = accessTokenScope; } }
AuthorizationCodeTokens
java
apache__dubbo
dubbo-compatible/src/main/java/com/alibaba/dubbo/rpc/RpcException.java
{ "start": 853, "end": 1638 }
class ____ extends org.apache.dubbo.rpc.RpcException { public RpcException() { super(); } public RpcException(String message, Throwable cause) { super(message, cause); } public RpcException(String message) { super(message); } public RpcException(Throwable cause) { super(cause); } public RpcException(int code) { super(code); } public RpcException(int code, String message, Throwable cause) { super(code, message, cause); } public RpcException(int code, String message) { super(code, message); } public RpcException(int code, Throwable cause) { super(code, cause); } public boolean isForbidded() { return isForbidden(); } }
RpcException
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/ResourceAware.java
{ "start": 844, "end": 942 }
interface ____ represent an object which wishes to be injected with the {@link Resource} */ public
to
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/runtime/annotations/Usage.java
{ "start": 75, "end": 421 }
enum ____ { DEV_UI, DEV_MCP; public static EnumSet<Usage> onlyDevUI() { return EnumSet.of(Usage.DEV_UI); } public static EnumSet<Usage> onlyDevMCP() { return EnumSet.of(Usage.DEV_MCP); } public static EnumSet<Usage> devUIandDevMCP() { return EnumSet.of(Usage.DEV_UI, Usage.DEV_MCP); } }
Usage
java
apache__flink
flink-core/src/main/java/org/apache/flink/core/execution/RecoveryClaimMode.java
{ "start": 1270, "end": 2760 }
enum ____ implements DescribedEnum { CLAIM( "Flink will take ownership of the given snapshot. It will clean the" + " snapshot once it is subsumed by newer ones."), NO_CLAIM( "Flink will not claim ownership of the snapshot files. However it will make sure it" + " does not depend on any artefacts from the restored snapshot. In order to do that," + " Flink will take the first checkpoint as a full one, which means it might" + " reupload/duplicate files that are part of the restored checkpoint."), @Deprecated LEGACY( "This is the mode in which Flink worked until 1.15. It will not claim ownership of the" + " snapshot and will not delete the files. However, it can directly depend on" + " the existence of the files of the restored checkpoint. It might not be safe" + " to delete checkpoints that were restored in legacy mode. This mode is" + " deprecated, please use CLAIM or NO_CLAIM mode to get a clear state file" + " ownership."); private final String description; RecoveryClaimMode(String description) { this.description = description; } @Override @Internal public InlineElement getDescription() { return text(description); } public static final RecoveryClaimMode DEFAULT = NO_CLAIM; }
RecoveryClaimMode
java
bumptech__glide
integration/cronet/src/main/java/com/bumptech/glide/integration/cronet/ChromiumRequestSerializer.java
{ "start": 6297, "end": 13444 }
class ____ extends Callback { private final List<Listener> listeners = new ArrayList<>(2); private GlideUrl glideUrl; private Priority priority; private long startTime; private UrlRequest request; private long endTimeMs; private long responseStartTimeMs; private volatile boolean isCancelled; private BufferQueue.Builder builder; private final Supplier<Executor> executorSupplier; Job(Supplier<Executor> executorSupplier) { this.executorSupplier = executorSupplier; } void init(GlideUrl glideUrl) { startTime = System.currentTimeMillis(); this.glideUrl = glideUrl; } void addListener(Listener listener) { synchronized (ChromiumRequestSerializer.this) { listeners.add(listener); } } void removeListener(Listener listener) { synchronized (ChromiumRequestSerializer.this) { // Note: multiple cancellation calls + a subsequent request for a url may mean we fail to // remove the listener here because that listener is actually for a previous request. Since // that race is harmless, we simply ignore it. listeners.remove(listener); if (listeners.isEmpty()) { isCancelled = true; jobs.remove(glideUrl); } } // The request may not have started yet, so request may be null. if (isCancelled) { UrlRequest localRequest = request; if (localRequest != null) { localRequest.cancel(); } } } @Override public void onRedirectReceived(UrlRequest urlRequest, UrlResponseInfo urlResponseInfo, String s) throws Exception { urlRequest.followRedirect(); } @Override public void onResponseStarted(UrlRequest request, UrlResponseInfo info) { responseStartTimeMs = System.currentTimeMillis(); builder = BufferQueue.builder(); request.read(builder.getFirstBuffer(info)); } @Override public void onReadCompleted( UrlRequest urlRequest, UrlResponseInfo urlResponseInfo, ByteBuffer byteBuffer) throws Exception { request.read(builder.getNextBuffer(byteBuffer)); } @Override public void onSucceeded(UrlRequest request, final UrlResponseInfo info) { executorSupplier .get() .execute( new PriorityRunnable(priority) { @Override public void run() { onRequestFinished( info, null /*exception*/, false /*wasCancelled*/, builder.build().coalesceToBuffer()); } }); } @Override public void onFailed( UrlRequest urlRequest, final UrlResponseInfo urlResponseInfo, final CronetException e) { executorSupplier .get() .execute( new PriorityRunnable(priority) { @Override public void run() { onRequestFinished(urlResponseInfo, e, false /*wasCancelled*/, null /*buffer*/); } }); } @Override public void onCanceled(UrlRequest urlRequest, @Nullable final UrlResponseInfo urlResponseInfo) { executorSupplier .get() .execute( new PriorityRunnable(priority) { @Override public void run() { onRequestFinished( urlResponseInfo, null /*exception*/, true /*wasCancelled*/, null /*buffer*/); } }); } private void onRequestFinished( UrlResponseInfo info, @Nullable CronetException e, boolean wasCancelled, ByteBuffer buffer) { synchronized (ChromiumRequestSerializer.this) { jobs.remove(glideUrl); } Exception exception = getExceptionIfFailed(info, e, wasCancelled); boolean isSuccess = exception == null && !wasCancelled; endTimeMs = System.currentTimeMillis(); maybeLogResult(isSuccess, exception, wasCancelled, buffer); if (isSuccess) { notifySuccess(buffer); } else { notifyFailure(exception); } if (dataLogger != null) { dataLogger.logNetworkData(info, startTime, responseStartTimeMs, endTimeMs); } builder = null; jobPool.put(this); } private void notifySuccess(ByteBuffer buffer) { ByteBuffer toNotify = buffer; /* Locking here isn't necessary and is potentially dangerous. There's an optimization in * Glide that avoids re-posting results if the callback onRequestComplete triggers is called * on the calling thread. If that were ever to happen here (the request is cached in memory?), * this might block all requests for a while. Locking isn't necessary because the Job is * removed from the serializer's job set at the beginning of onRequestFinished. After that * point, whatever thread we're on is the only one that has access to the Job. Subsequent * requests for the same image would trigger an additional RPC/Job. */ for (int i = 0, size = listeners.size(); i < size; i++) { Listener listener = listeners.get(i); listener.onRequestComplete(toNotify); toNotify = (ByteBuffer) toNotify.asReadOnlyBuffer().position(0); } } private void notifyFailure(Exception exception) { /* Locking here isn't necessary and is potentially dangerous. There's an optimization in * Glide that avoids re-posting results if the callback onRequestComplete triggers is called * on the calling thread. If that were ever to happen here (the request is cached in memory?), * this might block all requests for a while. Locking isn't necessary because the Job is * removed from the serializer's job set at the beginning of onRequestFinished. After that * point, whatever thread we're on is the only one that has access to the Job. Subsequent * requests for the same image would trigger an additional RPC/Job. */ for (int i = 0, size = listeners.size(); i < size; i++) { Listener listener = listeners.get(i); listener.onRequestFailed(exception); } } private void maybeLogResult( boolean isSuccess, Exception exception, boolean wasCancelled, ByteBuffer buffer) { if (isSuccess && Log.isLoggable(TAG, Log.VERBOSE)) { Log.v( TAG, "Successfully completed request" + ", url: " + glideUrl + ", duration: " + (System.currentTimeMillis() - startTime) + ", file size: " + (buffer.limit() / 1024) + "kb"); } else if (!isSuccess && Log.isLoggable(TAG, Log.ERROR) && !wasCancelled) { Log.e(TAG, "Request failed, url: " + glideUrl, exception); } } private void clearListeners() { synchronized (ChromiumRequestSerializer.this) { listeners.clear(); request = null; isCancelled = false; } } } private
Job
java
google__dagger
javatests/dagger/functional/producers/ProvidesInProducerTest.java
{ "start": 1207, "end": 1291 }
class ____ { @ProductionComponent(modules = TestModule.class)
ProvidesInProducerTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/Canceling.java
{ "start": 2788, "end": 4441 }
class ____ implements StateFactory<Canceling> { private final Context context; private final Logger log; private final ExecutionGraph executionGraph; private final ExecutionGraphHandler executionGraphHandler; private final OperatorCoordinatorHandler operatorCoordinatorHandler; private final ClassLoader userCodeClassLoader; private final List<ExceptionHistoryEntry> failureCollection; public Factory( Context context, ExecutionGraph executionGraph, ExecutionGraphHandler executionGraphHandler, OperatorCoordinatorHandler operatorCoordinatorHandler, Logger log, ClassLoader userCodeClassLoader, List<ExceptionHistoryEntry> failureCollection) { this.context = context; this.log = log; this.executionGraph = executionGraph; this.executionGraphHandler = executionGraphHandler; this.operatorCoordinatorHandler = operatorCoordinatorHandler; this.userCodeClassLoader = userCodeClassLoader; this.failureCollection = failureCollection; } public Class<Canceling> getStateClass() { return Canceling.class; } public Canceling getState() { return new Canceling( context, executionGraph, executionGraphHandler, operatorCoordinatorHandler, log, userCodeClassLoader, failureCollection); } } }
Factory
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/RecursiveComparisonAssert.java
{ "start": 42388, "end": 44471 }
class ____ { * int number; * String street; * * // only compares number, ouch! * {@literal @}Override * public boolean equals(final Object other) { * if (!(other instanceof Address)) return false; * Address castOther = (Address) other; * return Objects.equals(number, castOther.number); * } * } * * Person sherlock = new Person("Sherlock", 1.80); * sherlock.home.address.street = "Baker Street"; * sherlock.home.address.number = 221; * * Person sherlock2 = new Person("Sherlock", 1.80); * sherlock2.home.address.street = "Butcher Street"; * sherlock2.home.address.number = 221; * * // Assertion succeeds because: * // - overridden equals are used * // - Address has overridden equals and does not compare street fields. * assertThat(sherlock).usingRecursiveComparison() * .usingOverriddenEquals() * .isEqualTo(sherlock2); * * // To avoid using Address overridden equals, don't call usingOverriddenEquals() or call ignoringAllOverriddenEquals() * // (calling ignoringAllOverriddenEquals() is actually not required as this is the default behavior). * // This assertion fails as it will compare home.address.street fields which differ * assertThat(sherlock).usingRecursiveComparison() * //.ignoringAllOverriddenEquals() // not needed as this is the default * .isEqualTo(sherlock2);</code></pre> * * @return this {@link RecursiveComparisonAssert} to chain other methods. */ public SELF ignoringAllOverriddenEquals() { recursiveComparisonConfiguration.ignoreAllOverriddenEquals(); return myself; } /** * By default, the recursive comparison compare recursively all fields including the ones whose type have overridden equals * <b>except fields with java types</b> (at some point we need to compare something!). * <p> * This method instructs the recursive comparison to use overridden equals. * <p> * Example: * <pre><code class='java'>
Address
java
dropwizard__dropwizard
dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/UnitOfWorkApplicationListenerTest.java
{ "start": 11102, "end": 12637 }
class ____ implements MockResourceInterface { @UnitOfWork(readOnly = false, cacheMode = CacheMode.NORMAL, transactional = true, flushMode = FlushMode.AUTO) public void methodWithDefaultAnnotation() { } @UnitOfWork(readOnly = true, cacheMode = CacheMode.NORMAL, transactional = true, flushMode = FlushMode.AUTO) public void methodWithReadOnlyAnnotation() { } @UnitOfWork(readOnly = false, cacheMode = CacheMode.IGNORE, transactional = true, flushMode = FlushMode.AUTO) public void methodWithCacheModeIgnoreAnnotation() { } @UnitOfWork(readOnly = false, cacheMode = CacheMode.NORMAL, transactional = true, flushMode = FlushMode.ALWAYS) public void methodWithFlushModeAlwaysAnnotation() { } @UnitOfWork(readOnly = false, cacheMode = CacheMode.NORMAL, transactional = false, flushMode = FlushMode.AUTO) public void methodWithTransactionalFalseAnnotation() { } @UnitOfWork(readOnly = true) @Override public void handlingMethodAnnotated() { } @Override public void definitionMethodAnnotated() { } @UnitOfWork(readOnly = false) @Override public void bothMethodsAnnotated() { } @UnitOfWork("analytics") public void methodWithUnitOfWorkOnAnalyticsDatabase() { } @UnitOfWork("warehouse") public void methodWithUnitOfWorkOnNotRegisteredDatabase() { } } public
MockResource
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBooleanPropertyTests.java
{ "start": 7112, "end": 7279 }
class ____ { @Bean String foo() { return "foo"; } } @Configuration(proxyBeanMethods = false) @ConditionalOnBooleanProperty("test") static
BeanConfiguration
java
spring-projects__spring-boot
build-plugin/spring-boot-gradle-plugin/src/dockerTest/java/org/springframework/boot/gradle/tasks/bundling/BootBuildImageRegistryIntegrationTests.java
{ "start": 3818, "end": 4071 }
class ____ {"); writer.println(); writer.println(" public static void main(String[] args) {"); writer.println(" }"); writer.println(); writer.println("}"); } catch (IOException ex) { throw new RuntimeException(ex); } } }
Main
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/suggest/completion/RegexOptions.java
{ "start": 1239, "end": 4687 }
class ____ implements ToXContentFragment, Writeable { static final ParseField REGEX_OPTIONS = new ParseField("regex"); private static final ParseField FLAGS_VALUE = new ParseField("flags", "flags_value"); private static final ParseField MAX_DETERMINIZED_STATES = new ParseField("max_determinized_states"); /** * regex: { * "flags" : STRING | INT * "max_determinized_states" : INT * } */ private static final ObjectParser<Builder, Void> PARSER = new ObjectParser<>(REGEX_OPTIONS.getPreferredName(), Builder::new); static { PARSER.declareInt(Builder::setMaxDeterminizedStates, MAX_DETERMINIZED_STATES); PARSER.declareField((parser, builder, aVoid) -> { if (parser.currentToken() == XContentParser.Token.VALUE_STRING) { builder.setFlags(parser.text()); } else if (parser.currentToken() == XContentParser.Token.VALUE_NUMBER) { builder.setFlagsValue(parser.intValue()); } else { throw new ElasticsearchParseException( REGEX_OPTIONS.getPreferredName() + " " + FLAGS_VALUE.getPreferredName() + " supports string or number" ); } }, FLAGS_VALUE, ObjectParser.ValueType.VALUE); } public static Builder builder() { return new Builder(); } static RegexOptions parse(XContentParser parser) throws IOException { return PARSER.parse(parser, null).build(); } private final int flagsValue; private final int maxDeterminizedStates; private RegexOptions(int flagsValue, int maxDeterminizedStates) { this.flagsValue = flagsValue; this.maxDeterminizedStates = maxDeterminizedStates; } /** * Read from a stream. */ RegexOptions(StreamInput in) throws IOException { this.flagsValue = in.readVInt(); this.maxDeterminizedStates = in.readVInt(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVInt(flagsValue); out.writeVInt(maxDeterminizedStates); } /** * Returns internal regular expression syntax flag value * see {@link RegexpFlag#value()} */ public int getFlagsValue() { return flagsValue; } /** * Returns the maximum automaton states allowed for fuzzy expansion */ public int getMaxDeterminizedStates() { return maxDeterminizedStates; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RegexOptions that = (RegexOptions) o; if (flagsValue != that.flagsValue) return false; return maxDeterminizedStates == that.maxDeterminizedStates; } @Override public int hashCode() { int result = flagsValue; result = 31 * result + maxDeterminizedStates; return result; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(REGEX_OPTIONS.getPreferredName()); builder.field(FLAGS_VALUE.getPreferredName(), flagsValue); builder.field(MAX_DETERMINIZED_STATES.getPreferredName(), maxDeterminizedStates); builder.endObject(); return builder; } /** * Options for regular expression queries */ public static
RegexOptions
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/assertj/MockMvcTesterIntegrationTests.java
{ "start": 24166, "end": 24387 }
class ____ { @ModelAttribute void populate(Model model) { model.addAttribute("locale", Locale.UK); } @RequestMapping("/locale") String handle() { return "view"; } } @Controller static
SessionController
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/RedeclaringRepositoryMethodsTests.java
{ "start": 1649, "end": 2564 }
class ____ { @Autowired RedeclaringRepositoryMethodsRepository repository; private User ollie; private User tom; @BeforeEach void setup() { ollie = new User("Oliver", "Gierke", "ogierke@gopivotal.com"); tom = new User("Thomas", "Darimont", "tdarimont@gopivotal.com"); } @Test // DATAJPA-398 void adjustedWellKnownPagedFindAllMethodShouldReturnOnlyTheUserWithFirstnameOliver() { ollie = repository.save(ollie); tom = repository.save(tom); Page<User> page = repository.findAll(PageRequest.of(0, 2)); assertThat(page.getNumberOfElements()).isOne(); assertThat(page.getContent().get(0).getFirstname()).isEqualTo("Oliver"); } @Test // DATAJPA-398 void adjustedWllKnownFindAllMethodShouldReturnAnEmptyList() { ollie = repository.save(ollie); tom = repository.save(tom); List<User> result = repository.findAll(); assertThat(result).isEmpty(); } }
RedeclaringRepositoryMethodsTests
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/ScoreOperator.java
{ "start": 750, "end": 3304 }
class ____ extends AbstractPageMappingOperator { public record ScoreOperatorFactory(ExpressionScorer.Factory scorerFactory, int scoreBlockPosition) implements OperatorFactory { @Override public Operator get(DriverContext driverContext) { return new ScoreOperator(driverContext.blockFactory(), scorerFactory.get(driverContext), scoreBlockPosition); } @Override public String describe() { return "ScoreOperator[scorer=" + scorerFactory + "]"; } } private final BlockFactory blockFactory; private final ExpressionScorer scorer; private final int scoreBlockPosition; public ScoreOperator(BlockFactory blockFactory, ExpressionScorer scorer, int scoreBlockPosition) { this.blockFactory = blockFactory; this.scorer = scorer; this.scoreBlockPosition = scoreBlockPosition; } @Override protected Page process(Page page) { assert page.getBlockCount() > scoreBlockPosition : "Expected to get a score block in position " + scoreBlockPosition; assert page.getBlock(scoreBlockPosition).asVector() instanceof DoubleVector : "Expected a DoubleVector as a score block, got " + page.getBlock(scoreBlockPosition).asVector(); Block[] blocks = new Block[page.getBlockCount()]; for (int i = 0; i < page.getBlockCount(); i++) { if (i == scoreBlockPosition) { blocks[i] = calculateScoresBlock(page); } else { blocks[i] = page.getBlock(i); } } return new Page(blocks); } private Block calculateScoresBlock(Page page) { try (DoubleBlock evalScores = scorer.score(page); DoubleBlock existingScores = page.getBlock(scoreBlockPosition)) { // TODO Optimize for constant scores? int rowCount = page.getPositionCount(); DoubleVector.Builder builder = blockFactory.newDoubleVectorFixedBuilder(rowCount); for (int i = 0; i < rowCount; i++) { builder.appendDouble(existingScores.getDouble(i) + evalScores.getDouble(i)); } return builder.build().asBlock(); } } @Override public String toString() { return getClass().getSimpleName() + "[scorer=" + scorer + "]"; } @Override public void close() { Releasables.closeExpectNoException(scorer, super::close); } /** * Evaluates the score of an expression one {@link Page} at a time. */ public
ScoreOperator
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/associations/ManyToOneTest.java
{ "start": 1413, "end": 2147 }
class ____ { @Id @GeneratedValue private Long id; @Column(name = "`number`") private String number; @ManyToOne @JoinColumn(name = "person_id", foreignKey = @ForeignKey(name = "PERSON_ID_FK") ) private Person person; //Getters and setters are omitted for brevity //end::associations-many-to-one-example[] public Phone() { } public Phone(String number) { this.number = number; } public Long getId() { return id; } public String getNumber() { return number; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } //tag::associations-many-to-one-example[] } //end::associations-many-to-one-example[] }
Phone
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryDefaultInEnumSwitchTest.java
{ "start": 17203, "end": 17809 }
enum ____ { ONE, TWO, THREE } boolean m(boolean f, Case c) { if (f) { switch (c) { case ONE: case TWO: case THREE: return true; default: return false; } } else { return false; } } } """) .addOutputLines( "Test.java", """
Case
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractTemporalAssert.java
{ "start": 1197, "end": 1300 }
class ____ all implementations of assertions for {@link Temporal}s. * @since 3.7.0 */ public abstract
for
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/AbstractPatternConverter.java
{ "start": 992, "end": 1286 }
class ____ provides the formatting functionality that derived classes need. * <p> * Conversion specifiers in a conversion patterns are parsed to individual PatternConverters. Each of which is * responsible for converting an object in a converter specific manner. * </p> */ public abstract
that
java
google__dagger
javatests/dagger/internal/codegen/ScopingValidationTest.java
{ "start": 20565, "end": 21199 }
interface ____ {", " SimpleType type();", "}"); CompilerTests.daggerCompiler( type, simpleScope, scopeA, scopeB, componentA, componentB1, componentB2, componentC) .compile( subject -> { subject.hasErrorCount(0); subject.hasWarningCount(0); }); } @Test public void componentWithoutScopeCannotDependOnScopedComponent() { Source type = CompilerTests.javaSource( "test.SimpleType", "package test;", "", "import javax.inject.Inject;", "", "
ComponentC
java
apache__kafka
server/src/main/java/org/apache/kafka/server/purgatory/DelayedDeleteRecords.java
{ "start": 1513, "end": 5258 }
class ____ extends DelayedOperation { private static final Logger LOG = LoggerFactory.getLogger(DelayedDeleteRecords.class); // migration from kafka.server.DelayedDeleteRecordsMetrics private static final KafkaMetricsGroup METRICS_GROUP = new KafkaMetricsGroup("kafka.server", "DelayedDeleteRecordsMetrics"); private static final Meter AGGREGATE_EXPIRATION_METER = METRICS_GROUP.newMeter("ExpiresPerSec", "requests", TimeUnit.SECONDS); private final Map<TopicPartition, DeleteRecordsPartitionStatus> deleteRecordsStatus; private final BiConsumer<TopicPartition, DeleteRecordsPartitionStatus> onAcksPending; private final Consumer<Map<TopicPartition, DeleteRecordsPartitionResult>> responseCallback; public DelayedDeleteRecords(long delayMs, Map<TopicPartition, DeleteRecordsPartitionStatus> deleteRecordsStatus, // To maintain compatibility with dependency packages, the logic has been moved to the caller. BiConsumer<TopicPartition, DeleteRecordsPartitionStatus> onAcksPending, Consumer<Map<TopicPartition, DeleteRecordsPartitionResult>> responseCallback) { super(delayMs); this.onAcksPending = onAcksPending; this.deleteRecordsStatus = Map.copyOf(deleteRecordsStatus); this.responseCallback = responseCallback; // first update the acks pending variable according to the error code deleteRecordsStatus.forEach((topicPartition, status) -> { if (status.responseStatus().errorCode() == Errors.NONE.code()) { // Timeout error state will be cleared when required acks are received status.setAcksPending(true); status.responseStatus().setErrorCode(Errors.REQUEST_TIMED_OUT.code()); } else { status.setAcksPending(false); } LOG.trace("Initial partition status for {} is {}", topicPartition, status); }); } /** * The delayed delete records operation can be completed if every partition specified in the request satisfied one of the following: * * 1) There was an error while checking if all replicas have caught up to the deleteRecordsOffset: set an error in response * 2) The low watermark of the partition has caught up to the deleteRecordsOffset. set the low watermark in response * */ @Override public boolean tryComplete() { // check for each partition if it still has pending acks deleteRecordsStatus.forEach((topicPartition, status) -> { LOG.trace("Checking delete records satisfaction for {}, current status {}", topicPartition, status); // skip those partitions that have already been satisfied if (status.acksPending()) { onAcksPending.accept(topicPartition, status); } }); // check if every partition has satisfied at least one of case A or B return deleteRecordsStatus.values().stream().noneMatch(DeleteRecordsPartitionStatus::acksPending) && forceComplete(); } @Override public void onExpiration() { AGGREGATE_EXPIRATION_METER.mark(deleteRecordsStatus.values().stream().filter(DeleteRecordsPartitionStatus::acksPending).count()); } /** * Upon completion, return the current response status along with the error code per partition */ @Override public void onComplete() { responseCallback.accept(deleteRecordsStatus.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().responseStatus()))); } }
DelayedDeleteRecords
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/TestSequenceFileAppend.java
{ "start": 1748, "end": 13739 }
class ____ { private static Configuration conf; private static FileSystem fs; private static Path ROOT_PATH = new Path(GenericTestUtils.getTestDir().getAbsolutePath()); @BeforeAll public static void setUp() throws Exception { conf = new Configuration(); conf.set("io.serializations", "org.apache.hadoop.io.serializer.JavaSerialization"); conf.set("fs.file.impl", "org.apache.hadoop.fs.RawLocalFileSystem"); fs = FileSystem.get(conf); } @AfterAll public static void tearDown() throws Exception { fs.close(); } @Test @Timeout(value = 30) public void testAppend() throws Exception { Path file = new Path(ROOT_PATH, "testseqappend.seq"); fs.delete(file, true); Text key1 = new Text("Key1"); Text value1 = new Text("Value1"); Text value2 = new Text("Updated"); SequenceFile.Metadata metadata = new SequenceFile.Metadata(); metadata.set(key1, value1); Writer.Option metadataOption = Writer.metadata(metadata); Writer writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), metadataOption); writer.append(1L, "one"); writer.append(2L, "two"); writer.close(); verify2Values(file); metadata.set(key1, value2); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), metadataOption); // Verify the Meta data is not changed assertEquals(value1, writer.metadata.get(key1)); writer.append(3L, "three"); writer.append(4L, "four"); writer.close(); verifyAll4Values(file); // Verify the Meta data readable after append Reader reader = new Reader(conf, Reader.file(file)); assertEquals(value1, reader.getMetadata().get(key1)); reader.close(); // Verify failure if the compression details are different try { Option wrongCompressOption = Writer.compression(CompressionType.RECORD, new GzipCodec()); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), wrongCompressOption); writer.close(); fail("Expected IllegalArgumentException for compression options"); } catch (IllegalArgumentException IAE) { // Expected exception. Ignore it } try { Option wrongCompressOption = Writer.compression(CompressionType.BLOCK, new DefaultCodec()); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), wrongCompressOption); writer.close(); fail("Expected IllegalArgumentException for compression options"); } catch (IllegalArgumentException IAE) { // Expected exception. Ignore it } fs.deleteOnExit(file); } @Test @Timeout(value = 30) public void testAppendRecordCompression() throws Exception { GenericTestUtils.assumeInNativeProfile(); Path file = new Path(ROOT_PATH, "testseqappendblockcompr.seq"); fs.delete(file, true); Option compressOption = Writer.compression(CompressionType.RECORD, new GzipCodec()); Writer writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), compressOption); writer.append(1L, "one"); writer.append(2L, "two"); writer.close(); verify2Values(file); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), compressOption); writer.append(3L, "three"); writer.append(4L, "four"); writer.close(); verifyAll4Values(file); fs.deleteOnExit(file); } @Test @Timeout(value = 30) public void testAppendBlockCompression() throws Exception { GenericTestUtils.assumeInNativeProfile(); Path file = new Path(ROOT_PATH, "testseqappendblockcompr.seq"); fs.delete(file, true); Option compressOption = Writer.compression(CompressionType.BLOCK, new GzipCodec()); Writer writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), compressOption); writer.append(1L, "one"); writer.append(2L, "two"); writer.close(); verify2Values(file); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), compressOption); writer.append(3L, "three"); writer.append(4L, "four"); writer.close(); verifyAll4Values(file); // Verify failure if the compression details are different or not Provided try { writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true)); writer.close(); fail("Expected IllegalArgumentException for compression options"); } catch (IllegalArgumentException IAE) { // Expected exception. Ignore it } // Verify failure if the compression details are different try { Option wrongCompressOption = Writer.compression(CompressionType.RECORD, new GzipCodec()); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), wrongCompressOption); writer.close(); fail("Expected IllegalArgumentException for compression options"); } catch (IllegalArgumentException IAE) { // Expected exception. Ignore it } try { Option wrongCompressOption = Writer.compression(CompressionType.BLOCK, new DefaultCodec()); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), wrongCompressOption); writer.close(); fail("Expected IllegalArgumentException for compression options"); } catch (IllegalArgumentException IAE) { // Expected exception. Ignore it } fs.deleteOnExit(file); } @Test @Timeout(value = 30) public void testAppendNoneCompression() throws Exception { Path file = new Path(ROOT_PATH, "testseqappendnonecompr.seq"); fs.delete(file, true); Option compressOption = Writer.compression(CompressionType.NONE); Writer writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), compressOption); writer.append(1L, "one"); writer.append(2L, "two"); writer.close(); verify2Values(file); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), compressOption); writer.append(3L, "three"); writer.append(4L, "four"); writer.close(); verifyAll4Values(file); // Verify failure if the compression details are different or not Provided try { writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true)); writer.close(); fail("Expected IllegalArgumentException for compression options"); } catch (IllegalArgumentException iae) { // Expected exception. Ignore it } // Verify failure if the compression details are different try { Option wrongCompressOption = Writer.compression(CompressionType.RECORD, new GzipCodec()); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), wrongCompressOption); writer.close(); fail("Expected IllegalArgumentException for compression options"); } catch (IllegalArgumentException iae) { // Expected exception. Ignore it } // Codec should be ignored Option noneWithCodec = Writer.compression(CompressionType.NONE, new DefaultCodec()); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), noneWithCodec); writer.close(); fs.deleteOnExit(file); } @Test @Timeout(value = 30) public void testAppendSort() throws Exception { GenericTestUtils.assumeInNativeProfile(); Path file = new Path(ROOT_PATH, "testseqappendSort.seq"); fs.delete(file, true); Path sortedFile = new Path(ROOT_PATH, "testseqappendSort.seq.sort"); fs.delete(sortedFile, true); SequenceFile.Sorter sorter = new SequenceFile.Sorter(fs, new JavaSerializationComparator<Long>(), Long.class, String.class, conf); Option compressOption = Writer.compression(CompressionType.BLOCK, new GzipCodec()); Writer writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), compressOption); writer.append(2L, "two"); writer.append(1L, "one"); writer.close(); writer = SequenceFile.createWriter(conf, SequenceFile.Writer.file(file), SequenceFile.Writer.keyClass(Long.class), SequenceFile.Writer.valueClass(String.class), SequenceFile.Writer.appendIfExists(true), compressOption); writer.append(4L, "four"); writer.append(3L, "three"); writer.close(); // Sort file after append sorter.sort(file, sortedFile); verifyAll4Values(sortedFile); fs.deleteOnExit(file); fs.deleteOnExit(sortedFile); } private void verify2Values(Path file) throws IOException { Reader reader = new Reader(conf, Reader.file(file)); assertEquals(1L, reader.next((Object) null)); assertEquals("one", reader.getCurrentValue((Object) null)); assertEquals(2L, reader.next((Object) null)); assertEquals("two", reader.getCurrentValue((Object) null)); assertNull(reader.next((Object) null)); reader.close(); } private void verifyAll4Values(Path file) throws IOException { Reader reader = new Reader(conf, Reader.file(file)); assertEquals(1L, reader.next((Object) null)); assertEquals("one", reader.getCurrentValue((Object) null)); assertEquals(2L, reader.next((Object) null)); assertEquals("two", reader.getCurrentValue((Object) null)); assertEquals(3L, reader.next((Object) null)); assertEquals("three", reader.getCurrentValue((Object) null)); assertEquals(4L, reader.next((Object) null)); assertEquals("four", reader.getCurrentValue((Object) null)); assertNull(reader.next((Object) null)); reader.close(); } }
TestSequenceFileAppend
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/SampleBooleanAggregator.java
{ "start": 6984, "end": 7862 }
class ____ implements AggregatorState { private final GroupingState internalState; private SingleState(BigArrays bigArrays, int limit) { this.internalState = new GroupingState(bigArrays, limit); } public void add(boolean value) { internalState.add(0, value); } @Override public void toIntermediate(Block[] blocks, int offset, DriverContext driverContext) { blocks[offset] = toBlock(driverContext.blockFactory()); } Block toBlock(BlockFactory blockFactory) { try (var intValues = blockFactory.newConstantIntVector(0, 1)) { return internalState.toBlock(blockFactory, intValues); } } @Override public void close() { Releasables.closeExpectNoException(internalState); } } }
SingleState
java
spring-projects__spring-boot
module/spring-boot-webflux-test/src/test/java/org/springframework/boot/webflux/test/autoconfigure/JsonController.java
{ "start": 1096, "end": 1283 }
class ____ { @GetMapping(value = "/json", produces = MediaType.APPLICATION_JSON_VALUE) public Mono<ExamplePojo> json() { return Mono.just(new ExamplePojo("a", "b")); } }
JsonController
java
alibaba__nacos
common/src/main/java/com/alibaba/nacos/common/packagescan/resource/ResourcePatternResolver.java
{ "start": 1116, "end": 1454 }
interface ____. * * <p>{@link PathMatchingResourcePatternResolver} is a standalone implementation * that is usable outside an {@code ApplicationContext}, also used by * properties. * * <p>Can be used with any sort of location pattern (e.g. "/WEB-INF/*-context.xml"): * Input patterns have to match the strategy implementation. This
too
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/persistence/TestingLongStateHandleHelper.java
{ "start": 1266, "end": 2689 }
class ____ implements RetrievableStateStorageHelper<TestingLongStateHandleHelper.LongStateHandle> { private static final List<LongStateHandle> STATE_STORAGE = new ArrayList<>(); @Override public RetrievableStateHandle<LongStateHandle> store(LongStateHandle state) { final int pos = STATE_STORAGE.size(); STATE_STORAGE.add(state); return new LongRetrievableStateHandle(pos); } public static LongStateHandle createState(long value) { return new LongStateHandle(value); } public static long getStateHandleValueByIndex(int index) { return STATE_STORAGE.get(index).getValue(); } public static int getDiscardCallCountForStateHandleByIndex(int index) { return STATE_STORAGE.get(index).getNumberOfSuccessfulDiscardCalls(); } public static int getGlobalStorageSize() { return STATE_STORAGE.size(); } public static void clearGlobalState() { STATE_STORAGE.clear(); } public static int getGlobalDiscardCount() { return STATE_STORAGE.stream() .mapToInt(LongStateHandle::getNumberOfSuccessfulDiscardCalls) .sum(); } /** * Serialized callback that can be used in {@code LongStateHandle} to trigger functionality * within the {@link LongStateHandle#discardState()} call. */ @FunctionalInterface public
TestingLongStateHandleHelper
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/OneInputStreamOperatorOutput.java
{ "start": 1620, "end": 3980 }
class ____ extends OutputBase { private final OneInputStreamOperator<RowData, RowData> operator; public OneInputStreamOperatorOutput(OneInputStreamOperator<RowData, RowData> operator) { super(operator); this.operator = operator; } @Override public void emitWatermark(Watermark mark) { try { operator.processWatermark(mark); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } @Override public void emitWatermarkStatus(WatermarkStatus watermarkStatus) { try { operator.processWatermarkStatus(watermarkStatus); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } @Override public void emitLatencyMarker(LatencyMarker latencyMarker) { try { operator.processLatencyMarker(latencyMarker); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } @Override public void emitRecordAttributes(RecordAttributes recordAttributes) { try { operator.processRecordAttributes(recordAttributes); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } @Override public void emitWatermark(WatermarkEvent watermark) { try { operator.processWatermark(watermark); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } @Override public void collect(StreamRecord<RowData> record) { pushToOperator(record); } @Override public <X> void collect(OutputTag<X> outputTag, StreamRecord<X> record) { pushToOperator(record); } protected <X> void pushToOperator(StreamRecord<X> record) { try { // we know that the given outputTag matches our OutputTag so the record // must be of the type that our operator expects. @SuppressWarnings("unchecked") StreamRecord<RowData> castRecord = (StreamRecord<RowData>) record; operator.processElement(castRecord); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } }
OneInputStreamOperatorOutput
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/InvalidZoneIdTest.java
{ "start": 881, "end": 1241 }
class ____ { private final CompilationTestHelper compilationHelper = CompilationTestHelper.newInstance(InvalidZoneId.class, getClass()); @Test public void positiveCase() { compilationHelper .addSourceLines( "a/A.java", """ package a; import java.time.ZoneId;
InvalidZoneIdTest
java
google__guava
guava/src/com/google/common/collect/RegularImmutableBiMap.java
{ "start": 10736, "end": 11308 }
class ____<K, V> implements Serializable { private final ImmutableBiMap<K, V> forward; InverseSerializedForm(ImmutableBiMap<K, V> forward) { this.forward = forward; } Object readResolve() { return forward.inverse(); } @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 1; } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible @GwtIncompatible Object writeReplace() { return super.writeReplace(); } }
InverseSerializedForm
java
redisson__redisson
redisson/src/main/java/org/redisson/api/options/CommonParams.java
{ "start": 740, "end": 985 }
class ____ extends BaseOptions<CommonOptions, Codec> implements CommonOptions { private final String name; CommonParams(String name) { this.name = name; } public String getName() { return name; } }
CommonParams
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ExplicitArgumentTypeStrategy.java
{ "start": 1715, "end": 2445 }
class ____ implements ArgumentTypeStrategy { private final DataType expectedDataType; public ExplicitArgumentTypeStrategy(DataType expectedDataType) { this.expectedDataType = Preconditions.checkNotNull(expectedDataType); } @Override public Optional<DataType> inferArgumentType( CallContext callContext, int argumentPos, boolean throwOnFailure) { final LogicalType expectedType = expectedDataType.getLogicalType(); final LogicalType actualType = callContext.getArgumentDataTypes().get(argumentPos).getLogicalType(); // if logical types match, we return the expected data type // for ensuring the expected conversion
ExplicitArgumentTypeStrategy
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/accept/HeaderContentNegotiationStrategy.java
{ "start": 1320, "end": 2278 }
class ____ implements ContentNegotiationStrategy { /** * {@inheritDoc} * @throws HttpMediaTypeNotAcceptableException if the 'Accept' header cannot be parsed */ @Override public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException { String[] headerValueArray = request.getHeaderValues(HttpHeaders.ACCEPT); if (headerValueArray == null) { return MEDIA_TYPE_ALL_LIST; } List<String> headerValues = Arrays.asList(headerValueArray); try { List<MediaType> mediaTypes = MediaType.parseMediaTypes(headerValues); MimeTypeUtils.sortBySpecificity(mediaTypes); return !CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST; } catch (InvalidMediaTypeException | InvalidMimeTypeException ex) { throw new HttpMediaTypeNotAcceptableException( "Could not parse 'Accept' header " + headerValues + ": " + ex.getMessage()); } } }
HeaderContentNegotiationStrategy
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/TestSchemaValidation.java
{ "start": 11417, "end": 11480 }
class ____ { double x; double y; } public static
Point
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/admin/TerminateTransactionOptions.java
{ "start": 949, "end": 1204 }
class ____ extends AbstractOptions<TerminateTransactionOptions> { @Override public String toString() { return "TerminateTransactionOptions{" + "timeoutMs=" + timeoutMs + '}'; } }
TerminateTransactionOptions
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-client/runtime/src/main/java/io/quarkus/restclient/runtime/PathTemplateInjectionFilter.java
{ "start": 212, "end": 555 }
class ____ implements ClientRequestFilter { @Override public void filter(ClientRequestContext requestContext) { Object prop = requestContext.getConfiguration().getProperty("UrlPathTemplate"); if (prop != null) { requestContext.setProperty("UrlPathTemplate", prop); } } }
PathTemplateInjectionFilter
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Issue215_float_array.java
{ "start": 280, "end": 997 }
class ____ extends TestCase { public void test_for_issue() throws Exception { float[] values = new float[128]; Random random = new Random(); for (int i = 0; i < values.length; ++i) { values[i] = random.nextFloat(); } Map<String, float[]> map = new HashMap<String, float[]>(); map.put("val", values); String text = JSON.toJSONString(map); System.out.println(text); Map<String, float[]> map2 = JSON.parseObject(text, new TypeReference<HashMap<String, float[]>>() {}); float[] values2 = (float[]) map2.get("val"); Assert.assertTrue(Arrays.equals(values2, values)); } }
Issue215_float_array
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/multipart/MultipartProgrammaticTest.java
{ "start": 851, "end": 2020 }
class ____ { private static final Logger log = Logger.getLogger(MultipartProgrammaticTest.class); private static final int BYTES_SENT = 5_000_000; // 5 megs @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(Resource.class, FormData.class, Client.class)); @TestHTTPResource URI baseUri; @Test void shouldUploadBiggishFile() { Client client = RestClientBuilder.newBuilder().baseUri(baseUri).build(Client.class); AtomicLong i = new AtomicLong(); Multi<Byte> content = Multi.createBy().repeating().supplier( () -> (byte) ((i.getAndIncrement() + 1) % 123)).atMost(BYTES_SENT); String result = client.postMultipart(ClientMultipartForm.create() .multiAsBinaryFileUpload("fileFormName", "fileName", content, MediaType.APPLICATION_OCTET_STREAM) .stringFileUpload("otherFormName", "whatever", "test", MediaType.TEXT_PLAIN)); assertThat(result).isEqualTo("fileFormName/fileName-test"); } @Path("/multipart") public
MultipartProgrammaticTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/bean/BeanWithInputStreamBodyTest.java
{ "start": 1110, "end": 4438 }
class ____ extends ContextTestSupport { @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("myBean", new MyCoolBean()); return jndi; } @Override public boolean isUseRouteBuilder() { return false; } @Test public void testBeanWithInputStreamBody() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start").bean(MyCoolBean.class).to("mock:result"); } }); context.start(); getMockEndpoint("mock:result").expectedBodiesReceived("There is 11 bytes"); InputStream bais = new ByteArrayInputStream("Hello World".getBytes()); template.sendBody("direct:start", bais); assertMockEndpointsSatisfied(); } @Test public void testBeanWithInputStreamBodyMethod() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start").bean(MyCoolBean.class, "doSomething").to("mock:result"); } }); context.start(); getMockEndpoint("mock:result").expectedBodiesReceived("There is 11 bytes"); InputStream bais = new ByteArrayInputStream("Hello World".getBytes()); template.sendBody("direct:start", bais); assertMockEndpointsSatisfied(); } @Test public void testToBeanWithInputStreamBody() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start").to("bean:myBean").to("mock:result"); } }); context.start(); getMockEndpoint("mock:result").expectedBodiesReceived("There is 11 bytes"); InputStream bais = new ByteArrayInputStream("Hello World".getBytes()); template.sendBody("direct:start", bais); assertMockEndpointsSatisfied(); } @Test public void testToBeanWithInputStreamBodyMethod() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start").to("bean:myBean?method=doSomething").to("mock:result"); } }); context.start(); getMockEndpoint("mock:result").expectedBodiesReceived("There is 11 bytes"); InputStream bais = new ByteArrayInputStream("Hello World".getBytes()); template.sendBody("direct:start", bais); assertMockEndpointsSatisfied(); } @Test public void testToBeanWithInputStreamBodyMethodOGNL() throws Exception { context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start").to("bean:myBean?method=doSomething(${body})").to("mock:result"); } }); context.start(); getMockEndpoint("mock:result").expectedBodiesReceived("There is 11 bytes"); InputStream bais = new ByteArrayInputStream("Hello World".getBytes()); template.sendBody("direct:start", bais); assertMockEndpointsSatisfied(); } public static final
BeanWithInputStreamBodyTest
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/weaving/AspectJWeavingEnabler.java
{ "start": 3543, "end": 4237 }
class ____ implements ClassFileTransformer { private final ClassFileTransformer delegate; public AspectJClassBypassingClassFileTransformer(ClassFileTransformer delegate) { this.delegate = delegate; } @Override public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { if (className.startsWith("org.aspectj") || className.startsWith("org/aspectj")) { return classfileBuffer; } return this.delegate.transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer); } } }
AspectJClassBypassingClassFileTransformer
java
FasterXML__jackson-core
src/test/java/tools/jackson/core/unittest/write/BoundsChecksWithGeneratorTest.java
{ "start": 1313, "end": 1443 }
interface ____ { void call(JsonGenerator g, char[] data, int offset, int len) throws Exception; }
CharBackedOperation
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/jdk8/FlowableCollectWithCollectorSingle.java
{ "start": 1464, "end": 2594 }
class ____<T, A, R> extends Single<R> implements FuseToFlowable<R> { final Flowable<T> source; final Collector<? super T, A, R> collector; public FlowableCollectWithCollectorSingle(Flowable<T> source, Collector<? super T, A, R> collector) { this.source = source; this.collector = collector; } @Override public Flowable<R> fuseToFlowable() { return new FlowableCollectWithCollector<>(source, collector); } @Override protected void subscribeActual(@NonNull SingleObserver<? super R> observer) { A container; BiConsumer<A, ? super T> accumulator; Function<A, R> finisher; try { container = collector.supplier().get(); accumulator = collector.accumulator(); finisher = collector.finisher(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); EmptyDisposable.error(ex, observer); return; } source.subscribe(new CollectorSingleObserver<>(observer, container, accumulator, finisher)); } static final
FlowableCollectWithCollectorSingle
java
quarkusio__quarkus
independent-projects/tools/devtools-common/src/test/java/io/quarkus/platform/catalog/predicate/ExtensionPredicateTest.java
{ "start": 267, "end": 1357 }
class ____ { @Test void rejectUnlisted() { ExtensionPredicate predicate = new ExtensionPredicate("foo"); Extension extension = Extension.builder() .setArtifact(ArtifactCoords.jar("g", "a", "v")) .setMetadata(Extension.MD_UNLISTED, true); assertThat(predicate).rejects(extension); } @Test void acceptKeywordInArtifactId() { ExtensionPredicate predicate = new ExtensionPredicate("foo"); Extension extension = Extension.builder() .setArtifact(ArtifactCoords.jar("g", "foo-bar", "1.0")) .build(); assertThat(predicate).accepts(extension); } @Test void acceptKeywordInLabel() { ExtensionPredicate predicate = new ExtensionPredicate("foo"); Extension extension = Extension.builder() .setArtifact(ArtifactCoords.jar("g", "a", "1.0")) .setMetadata(Extension.MD_KEYWORDS, Arrays.asList("foo", "bar")) .build(); assertThat(predicate).accepts(extension); } }
ExtensionPredicateTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/blocklist/BlocklistOperations.java
{ "start": 935, "end": 1260 }
interface ____ { /** * Add new blocked node records. If a node (identified by node id) already exists, the newly * added one will be merged with the existing one. * * @param newNodes the new blocked node records */ void addNewBlockedNodes(Collection<BlockedNode> newNodes); }
BlocklistOperations
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/select/OracleSelectTest19.java
{ "start": 978, "end": 3185 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "SELECT ddf.file_name file_name, vdf.status status, ddf.tablespace_name tablespace_name" + ", '', ddf.autoextensible autoextensible" + " , ddf.increment_by increment_by, ddf.maxbytes max_file_size, vdf.create_bytes " + "FROM sys.dba_data_files ddf, v$datafile vdf /*+ all_rows use_concat */ " + "WHERE (ddf.file_name = vdf.name) " + "UNION ALL " + "SELECT dtf.file_name file_name, vtf.status status, dtf.tablespace_name tablespace_name" + " , '', dtf.autoextensible autoextensible, dtf.increment_by increment_by" + " , dtf.maxbytes max_file_size, vtf.create_bytes " + "FROM sys.dba_temp_files dtf, v$tempfile vtf " + "WHERE (dtf.file_id = vtf.file#) "; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(4, visitor.getTables().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("sys.dba_data_files"))); assertEquals(17, visitor.getColumns().size()); assertTrue(visitor.containsColumn("sys.dba_data_files", "file_name")); assertTrue(visitor.containsColumn("v$datafile", "status")); assertTrue(visitor.containsColumn("sys.dba_data_files", "tablespace_name")); } }
OracleSelectTest19
java
google__auto
value/src/test/java/com/google/auto/value/extension/toprettystring/ToPrettyStringValidatorTest.java
{ "start": 4512, "end": 4858 }
class ____"); } @Test public void onlyOneToPrettyStringMethod_superclass() { JavaFileObject superclass = JavaFileObjects.forSourceLines( "test.Superclass", "package test;", "", "import com.google.auto.value.extension.toprettystring.ToPrettyString;", "", "
Test
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/retry/MaxRetriesRetryPolicyTests.java
{ "start": 1209, "end": 4968 }
class ____ { @Test void maxRetries() { var retryPolicy = RetryPolicy.builder().maxRetries(2).delay(Duration.ZERO).build(); var backOffExecution = retryPolicy.getBackOff().start(); var throwable = mock(Throwable.class); assertThat(retryPolicy.shouldRetry(throwable)).isTrue(); assertThat(backOffExecution.nextBackOff()).isZero(); assertThat(retryPolicy.shouldRetry(throwable)).isTrue(); assertThat(backOffExecution.nextBackOff()).isZero(); assertThat(retryPolicy.shouldRetry(throwable)).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(STOP); assertThat(retryPolicy.shouldRetry(throwable)).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(STOP); } @Test void maxRetriesZero() { var retryPolicy = RetryPolicy.builder().maxRetries(0).delay(Duration.ZERO).build(); var backOffExecution = retryPolicy.getBackOff().start(); var throwable = mock(Throwable.class); assertThat(retryPolicy.shouldRetry(throwable)).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(STOP); assertThat(retryPolicy.shouldRetry(throwable)).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(STOP); } @Test void maxRetriesAndPredicate() { var retryPolicy = RetryPolicy.builder() .maxRetries(4) .delay(Duration.ofMillis(1)) .predicate(NumberFormatException.class::isInstance) .build(); var backOffExecution = retryPolicy.getBackOff().start(); // 4 retries assertThat(retryPolicy.shouldRetry(new NumberFormatException())).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(1); assertThat(retryPolicy.shouldRetry(new IllegalStateException())).isFalse(); assertThat(backOffExecution.nextBackOff()).isEqualTo(1); assertThat(retryPolicy.shouldRetry(new IllegalStateException())).isFalse(); assertThat(backOffExecution.nextBackOff()).isEqualTo(1); assertThat(retryPolicy.shouldRetry(new CustomNumberFormatException())).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(1); // After policy exhaustion assertThat(retryPolicy.shouldRetry(new NumberFormatException())).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(STOP); assertThat(retryPolicy.shouldRetry(new IllegalStateException())).isFalse(); assertThat(backOffExecution.nextBackOff()).isEqualTo(STOP); } @Test void maxRetriesWithIncludesAndExcludes() { var retryPolicy = RetryPolicy.builder() .maxRetries(6) .includes(RuntimeException.class, IOException.class) .excludes(FileNotFoundException.class, CustomFileSystemException.class) .build(); var backOffExecution = retryPolicy.getBackOff().start(); // 6 retries assertThat(retryPolicy.shouldRetry(new IOException())).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(DEFAULT_DELAY); assertThat(retryPolicy.shouldRetry(new RuntimeException())).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(DEFAULT_DELAY); assertThat(retryPolicy.shouldRetry(new FileNotFoundException())).isFalse(); assertThat(backOffExecution.nextBackOff()).isEqualTo(DEFAULT_DELAY); assertThat(retryPolicy.shouldRetry(new FileSystemException("file"))).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(DEFAULT_DELAY); assertThat(retryPolicy.shouldRetry(new CustomFileSystemException("file"))).isFalse(); assertThat(backOffExecution.nextBackOff()).isEqualTo(DEFAULT_DELAY); assertThat(retryPolicy.shouldRetry(new IOException())).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(DEFAULT_DELAY); // After policy exhaustion assertThat(retryPolicy.shouldRetry(new IOException())).isTrue(); assertThat(backOffExecution.nextBackOff()).isEqualTo(STOP); } @SuppressWarnings("serial") private static
MaxRetriesRetryPolicyTests
java
apache__spark
common/network-shuffle/src/test/java/org/apache/spark/network/shuffle/RemoteBlockPushResolverSuite.java
{ "start": 85107, "end": 85593 }
class ____ { private final int shuffleId; private final int shuffleMergeId; private final int mapIndex; private final int reduceId; private final ByteBuffer buffer; PushBlock(int shuffleId, int shuffleMergeId, int mapIndex, int reduceId, ByteBuffer buffer) { this.shuffleId = shuffleId; this.shuffleMergeId = shuffleMergeId; this.mapIndex = mapIndex; this.reduceId = reduceId; this.buffer = buffer; } } private static
PushBlock
java
apache__camel
components/camel-kamelet/src/test/java/org/apache/camel/component/kamelet/KameletLocalBeanJoorExternalTest.java
{ "start": 1225, "end": 2886 }
class ____ extends CamelTestSupport { @Test public void testOne() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Hi John we are going to Moes"); template.sendBody("direct:moe", "John"); MockEndpoint.assertIsSatisfied(context); } @Test public void testTwo() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Hi Jack we are going to Shamrock", "Hi Mary we are going to Moes"); template.sendBody("direct:shamrock", "Jack"); template.sendBody("direct:moe", "Mary"); MockEndpoint.assertIsSatisfied(context); } // ********************************************** // // test set-up // // ********************************************** @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { routeTemplate("whereTo") .templateParameter("bar") // name of bar .templateBean("myBar", "joor", "resource:classpath:mybar.joor") .from("kamelet:source") // must use {{myBar}} to refer to the local bean .to("bean:{{myBar}}"); from("direct:shamrock") .kamelet("whereTo?bar=Shamrock") .to("mock:result"); from("direct:moe") .kamelet("whereTo?bar=Moes") .to("mock:result"); } }; } }
KameletLocalBeanJoorExternalTest
java
apache__camel
core/camel-core-languages/src/main/java/org/apache/camel/language/header/HeaderLanguage.java
{ "start": 1194, "end": 1794 }
class ____ extends LanguageSupport { public static Expression header(String headerName) { return ExpressionBuilder.headerExpression(headerName); } @Override public Predicate createPredicate(String expression) { return ExpressionToPredicateAdapter.toPredicate(createExpression(expression)); } @Override public Expression createExpression(String expression) { if (expression != null && isStaticResource(expression)) { expression = loadResource(expression); } return HeaderLanguage.header(expression); } }
HeaderLanguage
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/util/StreamUtils.java
{ "start": 943, "end": 1995 }
class ____ { /** * A collector that returns all results that are the maximum based on the provided comparator. * * @param comparator The comparator to order the items in the stream * @param downstream Which collector to use to combine the results * @param <T> The type of objects being streamed * @param <A> The mutable accumulation type of the reduction operation * @param <D> The result type of the reduction operation * @return A new collector to provide the desired result */ public static <T, A, D> Collector<T, ?, D> maxAll(Comparator<? super T> comparator, Collector<? super T, A, D> downstream) { Supplier<A> downstreamSupplier = downstream.supplier(); BiConsumer<A, ? super T> downstreamAccumulator = downstream.accumulator(); BinaryOperator<A> downstreamCombiner = downstream.combiner(); /** * Container used to hold the accumulator and object */
StreamUtils
java
google__truth
core/src/test/java/com/google/common/truth/PrimitiveBooleanArraySubjectTest.java
{ "start": 1080, "end": 3110 }
class ____ { @Test public void isEqualTo() { assertThat(array(true, false, true)).isEqualTo(array(true, false, true)); } @SuppressWarnings("TruthSelfEquals") @Test public void isEqualTo_same() { boolean[] same = array(true, false, true); assertThat(same).isEqualTo(same); } @Test public void asList() { assertThat(array(true, true, false)).asList().containsAtLeast(true, false); } @Test public void isEqualTo_fail_unequalOrdering() { AssertionError e = expectFailure( whenTesting -> whenTesting.that(array(true, false, true)).isEqualTo(array(false, true, true))); assertFailureValue(e, "differs at index", "[0]"); } @Test public void isEqualTo_fail_notAnArray() { expectFailure( whenTesting -> whenTesting.that(array(true, false, true)).isEqualTo(new Object())); } @Test public void isNotEqualTo_sameLengths() { assertThat(array(true, false)).isNotEqualTo(array(true, true)); } @Test public void isNotEqualTo_differentLengths() { assertThat(array(true, false)).isNotEqualTo(array(true, false, true)); } @Test public void isNotEqualTo_differentTypes() { assertThat(array(true, false)).isNotEqualTo(new Object()); } @Test public void isNotEqualTo_failEquals() { expectFailure( whenTesting -> whenTesting.that(array(true, false)).isNotEqualTo(array(true, false))); } @SuppressWarnings("TruthSelfEquals") @Test public void isNotEqualTo_failSame() { boolean[] same = array(true, false); expectFailure(whenTesting -> whenTesting.that(same).isNotEqualTo(same)); } @Test public void hasLengthNullArray() { AssertionError e = expectFailure(whenTesting -> whenTesting.that((boolean[]) null).hasLength(1)); assertFailureKeys(e, "expected an array with length", "but was"); assertFailureValue(e, "expected an array with length", "1"); } private static boolean[] array(boolean... ts) { return ts; } }
PrimitiveBooleanArraySubjectTest
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/compression/AirCompressorFactory.java
{ "start": 1051, "end": 1697 }
class ____ implements BlockCompressionFactory { private final Compressor internalCompressor; private final Decompressor internalDecompressor; public AirCompressorFactory(Compressor internalCompressor, Decompressor internalDecompressor) { this.internalCompressor = internalCompressor; this.internalDecompressor = internalDecompressor; } @Override public BlockCompressor getCompressor() { return new AirBlockCompressor(internalCompressor); } @Override public BlockDecompressor getDecompressor() { return new AirBlockDecompressor(internalDecompressor); } }
AirCompressorFactory
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest140.java
{ "start": 804, "end": 1362 }
class ____ extends TestCase { public void test_false() throws Exception { WallProvider provider = new MySqlWallProvider(); String sql = "SELECT name, '******' password, createTime from user " + "where name like 'admin%' "// + " AND 8600=CONVERT(INT,(SELECT CHAR(113)+CHAR(118)+CHAR(100)+CHAR(114)+CHAR(113)+(SELECT (CASE WHEN (8600=8600) THEN CHAR(49) ELSE CHAR(48) END))+CHAR(113)+CHAR(118)+CHAR(98)+CHAR(97)+CHAR(113))) AND '%'=''"; assertFalse(provider.checkValid(sql)); } }
MySqlWallTest140
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1707/Issue1707Test.java
{ "start": 507, "end": 757 }
class ____ { @RegisterExtension final GeneratedSource generatedSource = new GeneratedSource().addComparisonToFixtureFor( Converter.class ); @ProcessorTest public void codeShouldBeGeneratedCorrectly() { } }
Issue1707Test
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/api/ApplicationClientProtocol.java
{ "start": 15008, "end": 15831 }
interface ____ by clients to obtain a new {@link ReservationId} for * submitting new reservations.</p> * * <p>The <code>ResourceManager</code> responds with a new, unique, * {@link ReservationId} which is used by the client to submit * a new reservation.</p> * * @param request to get a new <code>ReservationId</code> * @return response containing the new <code>ReservationId</code> to be used * to submit a new reservation * @throws YarnException if the reservation system is not enabled. * @throws IOException on IO failures. * @see #submitReservation(ReservationSubmissionRequest) */ @Public @Unstable @Idempotent GetNewReservationResponse getNewReservation( GetNewReservationRequest request) throws YarnException, IOException; /** * <p> * The
used
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBeanTests.java
{ "start": 13465, "end": 13669 }
class ____ extends NestedCheckedException { public CustomServiceLocatorException2(Throwable cause) { super("", cause); } } @SuppressWarnings("serial") public static
CustomServiceLocatorException2
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/common/settings/MockSecureSettings.java
{ "start": 982, "end": 3950 }
class ____ implements SecureSettings { private Map<String, String> secureStrings = new HashMap<>(); private Map<String, byte[]> files = new HashMap<>(); private Map<String, byte[]> sha256Digests = new HashMap<>(); private Set<String> settingNames = new HashSet<>(); private final AtomicBoolean closed = new AtomicBoolean(false); public MockSecureSettings() {} private MockSecureSettings(MockSecureSettings source) { secureStrings.putAll(source.secureStrings); files.putAll(source.files); sha256Digests.putAll(source.sha256Digests); settingNames.addAll(source.settingNames); } @Override public boolean isLoaded() { return true; } @Override public Set<String> getSettingNames() { return settingNames; } @Override public SecureString getString(String setting) { ensureOpen(); final String s = secureStrings.get(setting); if (s == null) { return null; } return new SecureString(s.toCharArray()); } @Override public InputStream getFile(String setting) { ensureOpen(); return new ByteArrayInputStream(files.get(setting)); } @Override public byte[] getSHA256Digest(String setting) { return sha256Digests.get(setting); } public void setString(String setting, String value) { ensureOpen(); secureStrings.put(setting, value); sha256Digests.put(setting, MessageDigests.sha256().digest(value.getBytes(StandardCharsets.UTF_8))); settingNames.add(setting); } public void setFile(String setting, byte[] value) { ensureOpen(); files.put(setting, value); sha256Digests.put(setting, MessageDigests.sha256().digest(value)); settingNames.add(setting); } /** Merge the given secure settings into this one. */ public void merge(MockSecureSettings secureSettings) { for (String setting : secureSettings.getSettingNames()) { if (settingNames.contains(setting)) { throw new IllegalArgumentException("Cannot overwrite existing secure setting " + setting); } } settingNames.addAll(secureSettings.settingNames); secureStrings.putAll(secureSettings.secureStrings); sha256Digests.putAll(secureSettings.sha256Digests); files.putAll(secureSettings.files); } @Override public void close() throws IOException { closed.set(true); } private void ensureOpen() { if (closed.get()) { throw new IllegalStateException("secure settings are already closed"); } } public SecureSettings clone() { ensureOpen(); return new MockSecureSettings(this); } @Override public void writeTo(StreamOutput out) throws IOException { throw new IllegalStateException("Not supported, implement me!"); } }
MockSecureSettings
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/spi/RuntimeConfigurableServerRestHandler.java
{ "start": 68, "end": 388 }
interface ____ extends GenericRuntimeConfigurableServerRestHandler<RuntimeConfiguration> { @Override default Class<RuntimeConfiguration> getConfigurationClass() { return RuntimeConfiguration.class; } void configure(RuntimeConfiguration configuration); }
RuntimeConfigurableServerRestHandler
java
micronaut-projects__micronaut-core
http-netty/src/main/java/io/micronaut/http/netty/channel/converters/EpollChannelOptionFactory.java
{ "start": 1232, "end": 1341 }
class ____ implements ChannelOptionFactory { static { // force loading the
EpollChannelOptionFactory
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/expr/OracleIsOfTypeExpr.java
{ "start": 1035, "end": 3343 }
class ____ extends SQLExprImpl implements OracleExpr, SQLReplaceable { private SQLExpr expr; private List<SQLExpr> types = new ArrayList<SQLExpr>(); @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OracleIsOfTypeExpr that = (OracleIsOfTypeExpr) o; if (expr != null ? !expr.equals(that.expr) : that.expr != null) { return false; } return types != null ? types.equals(that.types) : that.types == null; } @Override public int hashCode() { int result = expr != null ? expr.hashCode() : 0; result = 31 * result + (types != null ? types.hashCode() : 0); return result; } @Override protected void accept0(SQLASTVisitor visitor) { accept0((OracleASTVisitor) visitor); } @Override public void accept0(OracleASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, expr); acceptChild(visitor, types); } visitor.endVisit(this); } @Override public boolean replace(SQLExpr expr, SQLExpr target) { if (this.expr == expr) { setExpr(target); return true; } for (int i = 0; i < types.size(); i++) { if (types.get(i) == expr) { target.setParent(this); types.set(i, target); return true; } } return false; } @Override public SQLExpr clone() { OracleIsOfTypeExpr x = new OracleIsOfTypeExpr(); if (expr != null) { x.setExpr(expr); } return null; } @Override public List<SQLObject> getChildren() { List children = new ArrayList<SQLExpr>(); if (expr != null) { children.add(expr); } children.addAll(types); return children; } public SQLExpr getExpr() { return expr; } public void setExpr(SQLExpr expr) { if (expr != null) { expr.setParent(this); } this.expr = expr; } public List<SQLExpr> getTypes() { return types; } }
OracleIsOfTypeExpr
java
apache__camel
components/camel-milo/src/main/java/org/apache/camel/component/milo/browse/MiloBrowseEndpoint.java
{ "start": 7526, "end": 8444 }
class ____ conversion {} -> {}", nodeClasses, mask); nodeClassMask = mask; } public int getNodeClassMask() { return nodeClassMask; } public void setDirection(BrowseDirection direction) { this.direction = direction; } public boolean isRecursive() { return recursive; } public void setRecursive(boolean recursive) { this.recursive = recursive; } public int getDepth() { return depth; } public void setDepth(int depth) { this.depth = depth; } public String getFilter() { return filter; } public void setFilter(String filter) { this.filter = filter; } public int getMaxNodeIdsPerRequest() { return maxNodeIdsPerRequest; } public void setMaxNodeIdsPerRequest(int maxNodeIdsPerRequest) { this.maxNodeIdsPerRequest = maxNodeIdsPerRequest; } }
list
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/runtime/metrics/MetricsFactory.java
{ "start": 1653, "end": 4738 }
interface ____ { /** * @param description Description text of the eventual metric (optional). * @return The builder with added description. */ MetricBuilder description(String description); /** * @param key The tag key. * @param value The tag value. * @return The builder with added tag. */ MetricBuilder tag(String key, String value); /** * Specify the metric unit (optional) * * @param unit Base unit of the eventual metric * @return The builder with added base unit. */ MetricBuilder unit(String unit); /** * Register a counter that retrieves its value from a supplier function * * @param countFunction Function supplying a monotonically increasing number value */ void buildCounter(Supplier<Number> countFunction); /** * Register a counter that retrieves its value by the applying a function * to an object * * @param obj Object instance to observe * @param countFunction Function returning a monotonically increasing value */ <T, R extends Number> void buildCounter(T obj, Function<T, R> countFunction); /** * Register a gauge that retrieves its value from a supplier function * * @param gaugeFunction Function supplying number value */ void buildGauge(Supplier<Number> gaugeFunction); /** * Register a gauge that retrieves its value by applying a function * to an object * * @param obj Object instance to observe * @param gaugeFunction Function returning a number value */ <T, R extends Number> void buildGauge(T obj, Function<T, R> gaugeFunction); /** * @return TimeRecorder to measure passage of time using * incremental updates. */ TimeRecorder buildTimer(); /** * Wrap a {@link Runnable} so that it is timed when invoked. * * @param f The Runnable to time when it is invoked. * @return The wrapped Runnable. */ Runnable buildTimer(Runnable f); /** * Wrap a {@link Callable} so that it is timed when invoked. * * @param f The Callable to time when it is invoked. * @param <T> The return type of the callable. * @return The wrapped callable. */ <T> Callable<T> buildTimer(Callable<T> f); /** * Wrap a {@link Supplier} so that it is timed when invoked. * * @param f The {@code Supplier} to time when it is invoked. * @param <T> The return type of the {@code Supplier} result. * @return The wrapped supplier. */ <T> Supplier<T> buildTimer(Supplier<T> f); } /** * A time recorder that tracks elapsed time using incremental updates * using a duration with a specified time unit. */
MetricBuilder
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-test/src/test/java/smoketest/test/web/UserVehicleControllerTests.java
{ "start": 1731, "end": 3899 }
class ____ { private static final VehicleIdentificationNumber VIN = new VehicleIdentificationNumber("00000000000000000"); @Autowired private MockMvcTester mvc; @Autowired private ApplicationContext applicationContext; @MockitoBean private UserVehicleService userVehicleService; @Test void getVehicleWhenRequestingTextShouldReturnMakeAndModel() { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); assertThat(this.mvc.get().uri("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)).hasStatusOk() .hasBodyTextEqualTo("Honda Civic"); } @Test void getVehicleWhenRequestingJsonShouldReturnMakeAndModel() { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); assertThat(this.mvc.get().uri("/sboot/vehicle").accept(MediaType.APPLICATION_JSON)).hasStatusOk() .bodyJson() .isLenientlyEqualTo("{'make':'Honda','model':'Civic'}"); } @Test void getVehicleWhenRequestingHtmlShouldReturnMakeAndModel() { given(this.userVehicleService.getVehicleDetails("sboot")).willReturn(new VehicleDetails("Honda", "Civic")); assertThat(this.mvc.get().uri("/sboot/vehicle.html").accept(MediaType.TEXT_HTML)).hasStatusOk() .bodyText() .contains("<h1>Honda Civic</h1>"); } @Test void getVehicleWhenUserNotFoundShouldReturnNotFound() { given(this.userVehicleService.getVehicleDetails("sboot")).willThrow(new UserNameNotFoundException("sboot")); assertThat(this.mvc.get().uri("/sboot/vehicle")).hasStatus(HttpStatus.NOT_FOUND); } @Test void getVehicleWhenVinNotFoundShouldReturnNotFound() { given(this.userVehicleService.getVehicleDetails("sboot")) .willThrow(new VehicleIdentificationNumberNotFoundException(VIN)); assertThat(this.mvc.get().uri("/sboot/vehicle")).hasStatus(HttpStatus.NOT_FOUND); } @Test void welcomeCommandLineRunnerShouldNotBeAvailable() { // Since we're a @WebMvcTest WelcomeCommandLineRunner should not be available. assertThatExceptionOfType(NoSuchBeanDefinitionException.class) .isThrownBy(() -> this.applicationContext.getBean(WelcomeCommandLineRunner.class)); } }
UserVehicleControllerTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java
{ "start": 6313, "end": 36108 }
class ____ found: " + proxyInterfaceName, e ); } } public boolean useDynamicInsert() { return dynamicInsert; } abstract int nextSubclassId(); public abstract int getSubclassId(); public boolean useDynamicUpdate() { return dynamicUpdate; } public void setDynamicInsert(boolean dynamicInsert) { this.dynamicInsert = dynamicInsert; } public void setDynamicUpdate(boolean dynamicUpdate) { this.dynamicUpdate = dynamicUpdate; } public String getDiscriminatorValue() { return discriminatorValue; } public void addSubclass(Subclass subclass) throws MappingException { // inheritance cycle detection (paranoid check) PersistentClass superclass = getSuperclass(); while ( superclass != null ) { if ( subclass.getEntityName().equals( superclass.getEntityName() ) ) { throw new MappingException( "Circular inheritance mapping: '" + subclass.getEntityName() + "' will have itself as superclass when extending '" + getEntityName() + "'" ); } superclass = superclass.getSuperclass(); } subclasses.add( subclass ); } public boolean hasSubclasses() { return !subclasses.isEmpty(); } public int getSubclassSpan() { int span = subclasses.size(); for ( var subclass : subclasses ) { span += subclass.getSubclassSpan(); } return span; } /** * Get the subclasses in a special 'order', most derived subclasses first. */ public List<Subclass> getSubclasses() { @SuppressWarnings("unchecked") final List<Subclass>[] subclassLists = new List[subclasses.size() + 1]; int j; for (j = 0; j < subclasses.size(); j++) { subclassLists[j] = subclasses.get(j).getSubclasses(); } subclassLists[j] = subclasses; return new JoinedList<>( subclassLists ); } public List<PersistentClass> getSubclassClosure() { final ArrayList<List<PersistentClass>> lists = new ArrayList<>(); lists.add( List.of( this ) ); for ( var subclass : getSubclasses() ) { lists.add( subclass.getSubclassClosure() ); } return new JoinedList<>( lists ); } public Table getIdentityTable() { return getRootTable(); } public List<Subclass> getDirectSubclasses() { return subclasses; } @Override public void addProperty(Property property) { properties.add( property ); declaredProperties.add( property ); property.setPersistentClass( this ); } @Internal public void movePropertyToJoin(Property property, Join join) { assert joins.contains( join ); assert property.getPersistentClass() == this; properties.remove( property ); declaredProperties.remove( property ); join.addProperty( property ); } @Internal protected void moveSubclassPropertyToJoin(Property property) { subclassProperties.remove( property ); } @Override public boolean contains(Property property) { return properties.contains( property ); } public abstract Table getTable(); public String getEntityName() { return entityName; } public abstract boolean isMutable(); public abstract boolean hasIdentifierProperty(); public abstract Property getIdentifierProperty(); public abstract Property getDeclaredIdentifierProperty(); public abstract KeyValue getIdentifier(); public abstract Property getVersion(); public abstract Property getDeclaredVersion(); public abstract Value getDiscriminator(); public abstract boolean isInherited(); public abstract boolean isPolymorphic(); public abstract boolean isVersioned(); public boolean isCached() { return isCached; } public void setCached(boolean cached) { isCached = cached; } public CacheLayout getQueryCacheLayout() { return queryCacheLayout; } public void setQueryCacheLayout(CacheLayout queryCacheLayout) { this.queryCacheLayout = queryCacheLayout; } public abstract String getCacheConcurrencyStrategy(); public abstract String getNaturalIdCacheRegionName(); public abstract PersistentClass getSuperclass(); /** * @deprecated No longer supported */ @Deprecated public boolean isExplicitPolymorphism() { return false; } public abstract boolean isDiscriminatorInsertable(); public abstract List<Property> getPropertyClosure(); public abstract List<Table> getTableClosure(); public abstract List<KeyValue> getKeyClosure(); protected void addSubclassProperty(Property prop) { subclassProperties.add( prop ); } protected void addSubclassJoin(Join join) { subclassJoins.add( join ); } protected void addSubclassTable(Table subclassTable) { subclassTables.add( subclassTable ); } public List<Property> getSubclassPropertyClosure() { final ArrayList<List<Property>> lists = new ArrayList<>(); lists.add( getPropertyClosure() ); lists.add( subclassProperties ); for ( var join : subclassJoins ) { lists.add( join.getProperties() ); } return new JoinedList<>( lists ); } public List<Join> getSubclassJoinClosure() { return new JoinedList<>( getJoinClosure(), subclassJoins ); } public List<Table> getSubclassTableClosure() { return new JoinedList<>( getTableClosure(), subclassTables ); } public boolean isClassOrSuperclassJoin(Join join) { return joins.contains( join ); } public boolean isClassOrSuperclassTable(Table closureTable) { return getTable() == closureTable; } public boolean isLazy() { return lazy; } public void setLazy(boolean lazy) { this.lazy = lazy; } public abstract boolean isConcreteProxy(); public abstract boolean hasEmbeddedIdentifier(); public abstract Table getRootTable(); public abstract RootClass getRootClass(); public abstract KeyValue getKey(); public void setDiscriminatorValue(String discriminatorValue) { this.discriminatorValue = discriminatorValue; } public void setEntityName(String entityName) { this.entityName = entityName == null ? null : entityName.intern(); } public void createPrimaryKey() { //Primary key constraint final var table = getTable(); final var primaryKey = new PrimaryKey( table ); primaryKey.setName( PK_ALIAS.toAliasString( table.getName() ) ); primaryKey.addColumns( getKey() ); if ( addPartitionKeyToPrimaryKey() ) { for ( var property : getProperties() ) { if ( property.getValue().isPartitionKey() ) { primaryKey.addColumns( property.getValue() ); } } } table.setPrimaryKey( primaryKey ); } private boolean addPartitionKeyToPrimaryKey() { return metadataBuildingContext.getMetadataCollector() .getDatabase().getDialect() .addPartitionKeyToPrimaryKey(); } public abstract String getWhere(); public int getBatchSize() { return batchSize; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } public boolean hasSelectBeforeUpdate() { return selectBeforeUpdate; } public void setSelectBeforeUpdate(boolean selectBeforeUpdate) { this.selectBeforeUpdate = selectBeforeUpdate; } /** * Build a list of properties which may be referenced in association mappings. * <p> * Includes properties defined in superclasses of the mapping inheritance. * Includes all properties defined as part of a join. * * @see #getReferencedProperty * @return The referenceable property iterator. */ public List<Property> getReferenceableProperties() { return getPropertyClosure(); } /** * Given a property path, locate the appropriate referenceable property reference. * <p> * A referenceable property is a property which can be a target of a foreign-key * mapping (e.g. {@code @ManyToOne}, {@code @OneToOne}). * * @param propertyPath The property path to resolve into a property reference. * * @return The property reference (never null). * * @throws MappingException If the property could not be found. */ public Property getReferencedProperty(String propertyPath) throws MappingException { try { return getRecursiveProperty( propertyPath, getReferenceableProperties() ); } catch ( MappingException e ) { throw new MappingException( "property-ref [" + propertyPath + "] not found on entity [" + getEntityName() + "]", e ); } } public Property getRecursiveProperty(String propertyPath) throws MappingException { try { return getRecursiveProperty( propertyPath, getPropertyClosure() ); } catch ( MappingException e ) { throw new MappingException( "property [" + propertyPath + "] not found on entity [" + getEntityName() + "]", e ); } } private Property getRecursiveProperty(String propertyPath, List<Property> properties) throws MappingException { Property property = null; var tokens = new StringTokenizer( propertyPath, ".", false ); try { while ( tokens.hasMoreElements() ) { final String element = (String) tokens.nextElement(); if ( property == null ) { Property identifierProperty = getIdentifierProperty(); if ( identifierProperty != null && identifierProperty.getName().equals( element ) ) { // we have a mapped identifier property and the root of // the incoming property path matched that identifier // property property = identifierProperty; } else if ( identifierProperty == null && getIdentifierMapper() != null ) { // we have an embedded composite identifier try { identifierProperty = getProperty( element, getIdentifierMapper().getProperties() ); // the root of the incoming property path matched one // of the embedded composite identifier properties property = identifierProperty; } catch ( MappingException ignore ) { // ignore it... } } if ( property == null ) { property = getProperty( element, properties ); } } else { //flat recursive algorithm final var value = (Component) property.getValue(); property = value.getProperty( element ); } } } catch ( MappingException e ) { throw new MappingException( "property [" + propertyPath + "] not found on entity [" + getEntityName() + "]" ); } return property; } private Property getProperty(String propertyName, List<Property> properties) throws MappingException { final String root = root( propertyName ); for ( var property : properties ) { if ( property.getName().equals( root ) || ( property instanceof Backref || property instanceof IndexBackref ) && property.getName().equals( propertyName ) ) { return property; } } throw new MappingException( "property [" + propertyName + "] not found on entity [" + getEntityName() + "]" ); } @Override public Property getProperty(String propertyName) throws MappingException { final var identifierProperty = getIdentifierProperty(); if ( identifierProperty != null && identifierProperty.getName().equals( root( propertyName ) ) ) { return identifierProperty; } else { List<Property> closure = getPropertyClosure(); final var identifierMapper = getIdentifierMapper(); if ( identifierMapper != null ) { closure = new JoinedList<>( identifierMapper.getProperties(), closure ); } return getProperty( propertyName, closure ); } } /** * Check to see if this PersistentClass defines a property with the given name. * * @param name The property name to check * * @return {@code true} if a property with that name exists; {@code false} if not */ public boolean hasProperty(String name) { final var identifierProperty = getIdentifierProperty(); if ( identifierProperty != null && identifierProperty.getName().equals( name ) ) { return true; } else { for ( var property : getPropertyClosure() ) { if ( property.getName().equals( name ) ) { return true; } } return false; } } /** * Check to see if a property with the given name exists in the super hierarchy * of this PersistentClass. Does not check this PersistentClass, just up the * hierarchy * * @param name The property name to check * * @return {@code true} if a property with that name exists; {@code false} if not */ public boolean isPropertyDefinedInSuperHierarchy(String name) { return getSuperclass() != null && getSuperclass().isPropertyDefinedInHierarchy( name ); } /** * Check to see if a property with the given name exists in this PersistentClass * or in any of its super hierarchy. Unlike {@link #isPropertyDefinedInSuperHierarchy}, * this method does check this PersistentClass * * @param name The property name to check * * @return {@code true} if a property with that name exists; {@code false} if not */ public boolean isPropertyDefinedInHierarchy(String name) { return hasProperty( name ) || getSuperMappedSuperclass() != null && getSuperMappedSuperclass().isPropertyDefinedInHierarchy( name ) || getSuperclass() != null && getSuperclass().isPropertyDefinedInHierarchy( name ); } public OptimisticLockStyle getOptimisticLockStyle() { return optimisticLockStyle; } public void setOptimisticLockStyle(OptimisticLockStyle optimisticLockStyle) { this.optimisticLockStyle = optimisticLockStyle; } public void validate(Metadata mapping) throws MappingException { for ( var prop : getProperties() ) { if ( !prop.isValid( mapping ) ) { final var type = prop.getType(); final int actualColumns = prop.getColumnSpan(); final int requiredColumns = type.getColumnSpan( mapping ); throw new MappingException( "Property '" + qualify( getEntityName(), prop.getName() ) + "' maps to " + actualColumns + " columns but " + requiredColumns + " columns are required (type '" + type.getName() + "' spans " + requiredColumns + " columns)" ); } } checkPropertyDuplication(); checkColumnDuplication(); } private void checkPropertyDuplication() throws MappingException { final HashSet<String> names = new HashSet<>(); for ( var property : getProperties() ) { if ( !names.add( property.getName() ) ) { throw new MappingException( "Duplicate property mapping of " + property.getName() + " found in " + getEntityName() ); } } } public boolean isDiscriminatorValueNotNull() { return NOT_NULL_DISCRIMINATOR_MAPPING.equals( getDiscriminatorValue() ); } public boolean isDiscriminatorValueNull() { return NULL_DISCRIMINATOR_MAPPING.equals( getDiscriminatorValue() ); } public Map<String, MetaAttribute> getMetaAttributes() { return metaAttributes; } public void setMetaAttributes(java.util.Map<String,MetaAttribute> metas) { this.metaAttributes = metas; } public MetaAttribute getMetaAttribute(String name) { return metaAttributes == null ? null : metaAttributes.get( name ); } @Override public String toString() { return getClass().getSimpleName() + '(' + getEntityName() + ')'; } public List<Join> getJoins() { return joins; } public List<Join> getJoinClosure() { return joins; } public void addJoin(Join join) { if ( !joins.contains( join ) ) { joins.add( join ); } join.setPersistentClass( this ); } public int getJoinClosureSpan() { return joins.size(); } public int getPropertyClosureSpan() { int span = properties.size(); for ( var join : joins ) { span += join.getPropertySpan(); } return span; } public int getJoinNumber(Property prop) { int result = 1; for ( var join : getSubclassJoinClosure() ) { if ( join.containsProperty( prop ) ) { return result; } result++; } return 0; } /** * Build a list of the properties defined on this class. The returned * iterator only accounts for "normal" properties (i.e. non-identifier * properties). * <p> * Differs from {@link #getUnjoinedProperties} in that the returned list * will include properties defined as part of a join. * <p> * Differs from {@link #getReferenceableProperties} in that the properties * defined in superclasses of the mapping inheritance are not included. * * @return A list over the "normal" properties. */ public List<Property> getProperties() { final ArrayList<List<Property>> list = new ArrayList<>(); list.add( properties ); for ( var join : joins ) { list.add( join.getProperties() ); } return new JoinedList<>( list ); } /** * Get a list of the properties defined on this class <b>which * are not defined as part of a join</b>. As with {@link #getProperties}, * the returned iterator only accounts for non-identifier properties. * * @return An iterator over the non-joined "normal" properties. */ public List<Property> getUnjoinedProperties() { return properties; } public void setCustomSQLInsert(String customSQLInsert, boolean callable, ExecuteUpdateResultCheckStyle checkStyle) { this.customSQLInsert = customSQLInsert; this.customInsertCallable = callable; this.insertExpectation = expectationConstructor( checkStyle ); } public String getCustomSQLInsert() { return customSQLInsert; } public boolean isCustomInsertCallable() { return customInsertCallable; } public void setCustomSQLUpdate(String customSQLUpdate, boolean callable, ExecuteUpdateResultCheckStyle checkStyle) { this.customSQLUpdate = customSQLUpdate; this.customUpdateCallable = callable; this.updateExpectation = expectationConstructor( checkStyle ); } public String getCustomSQLUpdate() { return customSQLUpdate; } public boolean isCustomUpdateCallable() { return customUpdateCallable; } public void setCustomSQLDelete(String customSQLDelete, boolean callable, ExecuteUpdateResultCheckStyle checkStyle) { this.customSQLDelete = customSQLDelete; this.customDeleteCallable = callable; this.deleteExpectation = expectationConstructor( checkStyle ); } public String getCustomSQLDelete() { return customSQLDelete; } public boolean isCustomDeleteCallable() { return customDeleteCallable; } public void addFilter( String name, String condition, boolean autoAliasInjection, java.util.Map<String, String> aliasTableMap, java.util.Map<String, String> aliasEntityMap) { filters.add( new FilterConfiguration( name, condition, autoAliasInjection, aliasTableMap, aliasEntityMap, this ) ); } public java.util.List<FilterConfiguration> getFilters() { return filters; } public boolean isForceDiscriminator() { return false; } public abstract boolean isJoinedSubclass(); public String getLoaderName() { return loaderName; } public void setLoaderName(String loaderName) { this.loaderName = loaderName == null ? null : loaderName.intern(); } public abstract Set<String> getSynchronizedTables(); public void addSynchronizedTable(String table) { synchronizedTables.add( table ); } public Boolean isAbstract() { return isAbstract; } public void setAbstract(Boolean isAbstract) { this.isAbstract = isAbstract; } protected List<Property> getNonDuplicatedProperties() { return getUnjoinedProperties(); } protected void checkColumnDuplication() { final String owner = "entity '" + getEntityName() + "'"; final HashSet<String> cols = new HashSet<>(); if ( getIdentifierMapper() == null ) { //an identifier mapper => getKey will be included in the getNonDuplicatedPropertyIterator() //and checked later, so it needs to be excluded getKey().checkColumnDuplication( cols, owner ); } if ( isDiscriminatorInsertable() && getDiscriminator() != null ) { getDiscriminator().checkColumnDuplication( cols, owner ); } final var softDeleteColumn = getRootClass().getSoftDeleteColumn(); if ( softDeleteColumn != null ) { softDeleteColumn.getValue().checkColumnDuplication( cols, owner ); } checkPropertyColumnDuplication( cols, getNonDuplicatedProperties(), owner ); for ( var join : getJoins() ) { cols.clear(); join.getKey().checkColumnDuplication( cols, owner ); checkPropertyColumnDuplication( cols, join.getProperties(), owner ); } } public abstract Object accept(PersistentClassVisitor mv); public String getJpaEntityName() { return jpaEntityName; } public void setJpaEntityName(String jpaEntityName) { this.jpaEntityName = jpaEntityName; } public boolean hasPojoRepresentation() { return getClassName() != null; } public boolean hasSubselectLoadableCollections() { return hasSubselectLoadableCollections; } public void setSubselectLoadableCollections(boolean hasSubselectCollections) { this.hasSubselectLoadableCollections = hasSubselectCollections; } public boolean hasCollectionNotReferencingPK() { return hasCollectionNotReferencingPK( properties ); } private boolean hasCollectionNotReferencingPK(Collection<Property> properties) { for ( var property : properties ) { final var value = property.getValue(); if ( value instanceof Component component ) { if ( hasCollectionNotReferencingPK( component.getProperties() ) ) { return true; } } else if ( value instanceof org.hibernate.mapping.Collection collection ) { if ( !( (CollectionType) collection.getType() ).useLHSPrimaryKey() ) { return true; } } } return false; } public boolean hasPartitionedSelectionMapping() { final var superclass = getSuperclass(); if ( superclass != null && superclass.hasPartitionedSelectionMapping() ) { return true; } for ( var property : getProperties() ) { if ( property.getValue() instanceof BasicValue basicValue && basicValue.isPartitionKey() ) { return true; } } return false; } public Component getIdentifierMapper() { return identifierMapper; } public Component getDeclaredIdentifierMapper() { return declaredIdentifierMapper; } public void setDeclaredIdentifierMapper(Component declaredIdentifierMapper) { this.declaredIdentifierMapper = declaredIdentifierMapper; } public boolean hasIdentifierMapper() { return identifierMapper != null; } public void addCallbackDefinitions(java.util.List<CallbackDefinition> callbackDefinitions) { if ( callbackDefinitions != null && !callbackDefinitions.isEmpty() ) { if ( this.callbackDefinitions == null ) { this.callbackDefinitions = new ArrayList<>(); } this.callbackDefinitions.addAll( callbackDefinitions ); } } public java.util.List<CallbackDefinition> getCallbackDefinitions() { return callbackDefinitions == null ? emptyList() : unmodifiableList( callbackDefinitions ); } public void setIdentifierMapper(Component handle) { this.identifierMapper = handle; } private Boolean hasNaturalId; public boolean hasNaturalId() { if ( hasNaturalId == null ) { hasNaturalId = determineIfNaturalIdDefined(); } return hasNaturalId; } private boolean determineIfNaturalIdDefined() { final List<Property> properties = getRootClass().getProperties(); for ( var property : properties ) { if ( property.isNaturalIdentifier() ) { return true; } } return false; } // The following methods are added to support @MappedSuperclass in the metamodel public List<Property> getDeclaredProperties() { final ArrayList<List<Property>> lists = new ArrayList<>(); lists.add( declaredProperties ); for ( var join : joins ) { lists.add( join.getDeclaredProperties() ); } return new JoinedList<>( lists ); } public void addMappedSuperclassProperty(Property property) { properties.add( property ); property.setPersistentClass( this ); } public MappedSuperclass getSuperMappedSuperclass() { return superMappedSuperclass; } public void setSuperMappedSuperclass(MappedSuperclass superMappedSuperclass) { this.superMappedSuperclass = superMappedSuperclass; } public void assignCheckConstraintsToTable(Dialect dialect, TypeConfiguration types) { for ( var checkConstraint : checkConstraints ) { container( collectColumnNames( checkConstraint.getConstraint(), dialect, types ) ) .getTable().addCheck( checkConstraint ); } } // End of @MappedSuperclass support public void prepareForMappingModel(RuntimeModelCreationContext context) { if ( !joins.isEmpty() ) { // we need to deal with references to secondary tables // in SQL formulas final var dialect = context.getDialect(); final var types = context.getTypeConfiguration(); // now, move @Formulas to the correct AttributeContainers //TODO: skip this step for hbm.xml for ( var property : new ArrayList<>( properties ) ) { for ( var selectable : property.getSelectables() ) { if ( selectable.isFormula() && properties.contains( property ) ) { final var formula = (Formula) selectable; final var container = container( collectColumnNames( formula.getTemplate( dialect, types ) ) ); if ( !container.contains( property ) ) { properties.remove( property ); container.addProperty( property ); break; //TODO: embeddables } } } } } properties.sort( comparing( Property::getName ) ); } private AttributeContainer container(List<String> constrainedColumnNames) { final long matches = matchesInTable( constrainedColumnNames, getTable() ); if ( matches == constrainedColumnNames.size() ) { // perfect, all columns matched in the primary table return this; } else { // go searching for a secondary table which better matches AttributeContainer result = this; long max = matches; for ( var join : getJoins() ) { long secondaryMatches = matchesInTable( constrainedColumnNames, join.getTable() ); if ( secondaryMatches > max ) { result = join; max = secondaryMatches; } } return result; } } private static long matchesInTable(List<String> names, Table table) { return table.getColumns().stream() .filter( col -> col.isQuoted() ? names.contains( col.getName() ) : names.stream().anyMatch( name -> name.equalsIgnoreCase( col.getName() ) ) ) .count(); } public void addCheckConstraint(CheckConstraint checkConstraint) { checkConstraints.add( checkConstraint ); } public List<CheckConstraint> getCheckConstraints() { return checkConstraints; } public Table getImplicitTable() { return getTable(); } @Override public Table findTable(String name) { if ( getTable().getName().equals( name ) ) { return getTable(); } final var secondaryTable = findSecondaryTable( name ); if ( secondaryTable != null ) { return secondaryTable.getTable(); } return null; } @Override public Table getTable(String name) { final var table = findTable( name ); if ( table == null ) { throw new MappingException( "Could not locate Table : " + name ); } return table; } @Override public Join findSecondaryTable(String name) { for ( int i = 0; i < joins.size(); i++ ) { final var join = joins.get( i ); if ( join.getTable().getNameIdentifier().matches( name ) ) { return join; } } return null; } @Override public Join getSecondaryTable(String name) { final var secondaryTable = findSecondaryTable( name ); if ( secondaryTable == null ) { throw new MappingException( "Could not locate secondary Table : " + name ); } return secondaryTable; } @Override public IdentifiableTypeClass getSuperType() { final var superPersistentClass = getSuperclass(); if ( superPersistentClass != null ) { return superPersistentClass; } return superMappedSuperclass; } @Override public List<IdentifiableTypeClass> getSubTypes() { throw new UnsupportedOperationException( "Not implemented yet" ); } @Override @Deprecated(forRemoval = true) public void applyProperty(Property property) { final var table = property.getValue().getTable(); if ( table.equals( getImplicitTable() ) ) { addProperty( property ); } else { final var secondaryTable = getSecondaryTable( table.getName() ); secondaryTable.addProperty( property ); } } private boolean containsColumn(Column column) { for ( var declaredProperty : declaredProperties ) { if ( declaredProperty.getSelectables().contains( column ) ) { return true; } } return false; } @Internal public boolean isDefinedOnMultipleSubclasses(Column column) { PersistentClass declaringType = null; for ( var persistentClass : getSubclassClosure() ) { if ( persistentClass.containsColumn( column ) ) { if ( declaringType != null && declaringType != persistentClass ) { return true; } else { declaringType = persistentClass; } } } return false; } @Internal public PersistentClass getSuperPersistentClass() { final var superclass = getSuperclass(); return superclass == null ? getSuperPersistentClass( getSuperMappedSuperclass() ) : superclass; } private static PersistentClass getSuperPersistentClass(MappedSuperclass mappedSuperclass) { if ( mappedSuperclass != null ) { final var superclass = mappedSuperclass.getSuperPersistentClass(); return superclass == null ? getSuperPersistentClass( mappedSuperclass.getSuperMappedSuperclass() ) : superclass; } return null; } public Supplier<? extends Expectation> getInsertExpectation() { return insertExpectation; } public void setInsertExpectation(Supplier<? extends Expectation> insertExpectation) { this.insertExpectation = insertExpectation; } public Supplier<? extends Expectation> getUpdateExpectation() { return updateExpectation; } public void setUpdateExpectation(Supplier<? extends Expectation> updateExpectation) { this.updateExpectation = updateExpectation; } public Supplier<? extends Expectation> getDeleteExpectation() { return deleteExpectation; } public void setDeleteExpectation(Supplier<? extends Expectation> deleteExpectation) { this.deleteExpectation = deleteExpectation; } public void removeProperty(Property property) { if ( !declaredProperties.remove( property ) ) { throw new IllegalArgumentException( "Property not among declared properties: " + property.getName() ); } properties.remove( property ); } public void createConstraints(MetadataBuildingContext context) { } }
not
java
apache__hadoop
hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-workload/src/main/java/org/apache/hadoop/tools/dynamometer/workloadgenerator/audit/AuditReplayMapper.java
{ "start": 7107, "end": 12932 }
enum ____ { READ, WRITE } private long startTimestampMs; private int numThreads; private double rateFactor; private long highestTimestamp; private Long highestSequence; private List<AuditReplayThread> threads; private DelayQueue<AuditReplayCommand> commandQueue; private Function<Long, Long> relativeToAbsoluteTimestamp; private AuditCommandParser commandParser; private ScheduledThreadPoolExecutor progressExecutor; @Override public String getDescription() { return "This mapper replays audit log files."; } @Override public List<String> getConfigDescriptions() { return Lists.newArrayList( INPUT_PATH_KEY + " (required): Path to directory containing input files.", OUTPUT_PATH_KEY + " (required): Path to destination for output files.", NUM_THREADS_KEY + " (default " + NUM_THREADS_DEFAULT + "): Number of threads to use per mapper for replay.", CREATE_BLOCKS_KEY + " (default " + CREATE_BLOCKS_DEFAULT + "): Whether or not to create 1-byte blocks when " + "performing `create` commands.", RATE_FACTOR_KEY + " (default " + RATE_FACTOR_DEFAULT + "): Multiplicative speed at which to replay the audit " + "log; e.g. a value of 2.0 would make the replay occur at " + "twice the original speed. This can be useful " + "to induce heavier loads."); } @Override public boolean verifyConfigurations(Configuration conf) { return conf.get(INPUT_PATH_KEY) != null && conf.get(OUTPUT_PATH_KEY) != null; } @Override public void setup(final Mapper.Context context) throws IOException { Configuration conf = context.getConfiguration(); // WorkloadDriver ensures that the starttimestamp is set startTimestampMs = conf.getLong(WorkloadDriver.START_TIMESTAMP_MS, -1); numThreads = conf.getInt(NUM_THREADS_KEY, NUM_THREADS_DEFAULT); rateFactor = conf.getDouble(RATE_FACTOR_KEY, RATE_FACTOR_DEFAULT); try { commandParser = conf.getClass(COMMAND_PARSER_KEY, COMMAND_PARSER_DEFAULT, AuditCommandParser.class).getConstructor().newInstance(); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new IOException( "Exception encountered while instantiating the command parser", e); } commandParser.initialize(conf); relativeToAbsoluteTimestamp = (input) -> startTimestampMs + Math.round(input / rateFactor); LOG.info("Starting " + numThreads + " threads"); progressExecutor = new ScheduledThreadPoolExecutor(1); // half of the timeout or once per minute if none specified long progressFrequencyMs = conf.getLong(MRJobConfig.TASK_TIMEOUT, 2 * 60 * 1000) / 2; progressExecutor.scheduleAtFixedRate(context::progress, progressFrequencyMs, progressFrequencyMs, TimeUnit.MILLISECONDS); threads = new ArrayList<>(); ConcurrentMap<String, FileSystem> fsCache = new ConcurrentHashMap<>(); commandQueue = new DelayQueue<>(); for (int i = 0; i < numThreads; i++) { AuditReplayThread thread = new AuditReplayThread(context, commandQueue, fsCache); threads.add(thread); thread.start(); } } @Override public void map(LongWritable lineNum, Text inputLine, Mapper.Context context) throws IOException, InterruptedException { AuditReplayCommand cmd = commandParser.parse(lineNum.get(), inputLine, relativeToAbsoluteTimestamp); long delay = cmd.getDelay(TimeUnit.MILLISECONDS); // Prevent from loading too many elements into memory all at once if (delay > MAX_READAHEAD_MS) { Thread.sleep(delay - (MAX_READAHEAD_MS / 2)); } commandQueue.put(cmd); highestTimestamp = cmd.getAbsoluteTimestamp(); highestSequence = cmd.getSequence(); } @Override public void cleanup(Mapper.Context context) throws InterruptedException, IOException { for (AuditReplayThread t : threads) { // Add in an indicator for each thread to shut down after the last real // command t.addToQueue(AuditReplayCommand.getPoisonPill(highestTimestamp + 1)); } Optional<Exception> threadException = Optional.empty(); for (AuditReplayThread t : threads) { t.join(); t.drainCounters(context); t.drainCommandLatencies(context); if (t.getException() != null) { threadException = Optional.of(t.getException()); } } progressExecutor.shutdown(); if (threadException.isPresent()) { throw new RuntimeException("Exception in AuditReplayThread", threadException.get()); } LOG.info("Time taken to replay the logs in ms: " + (System.currentTimeMillis() - startTimestampMs)); long totalCommands = context.getCounter(REPLAYCOUNTERS.TOTALCOMMANDS) .getValue(); if (totalCommands != 0) { double percentageOfInvalidOps = context.getCounter(REPLAYCOUNTERS.TOTALINVALIDCOMMANDS).getValue() * 100.0 / totalCommands; LOG.info("Percentage of invalid ops: " + percentageOfInvalidOps); } } @Override public void configureJob(Job job) { job.setMapOutputKeyClass(UserCommandKey.class); job.setMapOutputValueClass(CountTimeWritable.class); job.setInputFormatClass(NoSplitTextInputFormat.class); job.setNumReduceTasks(1); job.setReducerClass(AuditReplayReducer.class); job.setOutputKeyClass(UserCommandKey.class); job.setOutputValueClass(CountTimeWritable.class); job.setOutputFormatClass(TextOutputFormat.class); TextOutputFormat.setOutputPath(job, new Path( job.getConfiguration().get(OUTPUT_PATH_KEY))); job.getConfiguration().set(TextOutputFormat.SEPARATOR, ","); } }
CommandType
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/metrics/StateStoreMBean.java
{ "start": 1103, "end": 1329 }
interface ____ { long getReadOps(); double getReadAvg(); long getWriteOps(); double getWriteAvg(); long getFailureOps(); double getFailureAvg(); long getRemoveOps(); double getRemoveAvg(); }
StateStoreMBean
java
apache__flink
flink-table/flink-table-api-java/src/test/java/org/apache/flink/table/utils/CatalogManagerMocks.java
{ "start": 1477, "end": 4180 }
class ____ { public static final String DEFAULT_CATALOG = TableConfigOptions.TABLE_CATALOG_NAME.defaultValue(); public static final String DEFAULT_DATABASE = TableConfigOptions.TABLE_DATABASE_NAME.defaultValue(); public static CatalogManager createEmptyCatalogManager() { return createCatalogManager(null, null); } public static CatalogManager createCatalogManager(CatalogStore catalogStore) { return createCatalogManager( CatalogStoreHolder.newBuilder() .catalogStore(catalogStore) .classloader(CatalogManagerMocks.class.getClassLoader()) .config(new Configuration()) .build()); } public static CatalogManager createCatalogManager( @Nullable CatalogStoreHolder catalogStoreHolder) { return createCatalogManager(null, catalogStoreHolder); } public static CatalogManager createCatalogManager(@Nullable Catalog catalog) { return createCatalogManager(catalog, null); } public static CatalogManager createCatalogManager( @Nullable Catalog catalog, @Nullable CatalogStoreHolder catalogStoreHolder) { final CatalogManager.Builder builder = preparedCatalogManager(); if (catalog != null) { builder.defaultCatalog(DEFAULT_CATALOG, catalog); } if (catalogStoreHolder != null) { builder.catalogStoreHolder(catalogStoreHolder); } final CatalogManager catalogManager = builder.build(); catalogManager.initSchemaResolver( true, ExpressionResolverMocks.dummyResolver(), new ParserMock()); return catalogManager; } public static CatalogManager.Builder preparedCatalogManager() { return CatalogManager.newBuilder() .classLoader(CatalogManagerMocks.class.getClassLoader()) .config(new Configuration()) .defaultCatalog(DEFAULT_CATALOG, createEmptyCatalog()) .catalogStoreHolder( CatalogStoreHolder.newBuilder() .classloader(CatalogManagerMocks.class.getClassLoader()) .config(new Configuration()) .catalogStore(new GenericInMemoryCatalogStore()) .build()) .executionConfig(new ExecutionConfig()); } public static Catalog createEmptyCatalog() { return new GenericInMemoryCatalog(DEFAULT_CATALOG, DEFAULT_DATABASE); } private CatalogManagerMocks() { // no instantiation } }
CatalogManagerMocks
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/jackson/SimpleGrantedAuthorityMixin.java
{ "start": 912, "end": 1399 }
class ____ in serialize/deserialize * {@link org.springframework.security.core.authority.SimpleGrantedAuthority}. * * @author Sebastien Deleuze * @author Jitendra Singh * @since 7.0 * @see CoreJacksonModule * @see SecurityJacksonModules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY, isGetterVisibility = JsonAutoDetect.Visibility.NONE) public abstract
helps
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/ArrayAppendPrependTypeStrategy.java
{ "start": 1649, "end": 2449 }
class ____ implements TypeStrategy { @Override public Optional<DataType> inferType(CallContext callContext) { final List<DataType> argumentDataTypes = callContext.getArgumentDataTypes(); final DataType arrayDataType = argumentDataTypes.get(0); final DataType elementToAddDataType = argumentDataTypes.get(1); final LogicalType arrayElementLogicalType = arrayDataType.getLogicalType().getChildren().get(0); if (elementToAddDataType.getLogicalType().isNullable() && !arrayElementLogicalType.isNullable()) { return Optional.of( DataTypes.ARRAY(fromLogicalToDataType(arrayElementLogicalType).nullable())); } return Optional.of(arrayDataType); } }
ArrayAppendPrependTypeStrategy
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/service/SwitchService.java
{ "start": 1108, "end": 3570 }
class ____ { public static final String SWITCH_META_DATA_ID = "com.alibaba.nacos.meta.switch"; public static final String FIXED_DELAY_TIME = "fixedDelayTime"; private static volatile Map<String, String> switches = new HashMap<>(); public static int getSwitchInteger(String key, int defaultValue) { int rtn; try { String status = switches.get(key); rtn = status != null ? Integer.parseInt(status) : defaultValue; } catch (Exception e) { rtn = defaultValue; LogUtil.FATAL_LOG.error("corrupt switch value {}={}", key, switches.get(key)); } return rtn; } /** * Load config. * * @param config config content string value. */ public static void load(String config) { if (StringUtils.isBlank(config)) { FATAL_LOG.warn("switch config is blank."); return; } FATAL_LOG.warn("[switch-config] {}", config); Map<String, String> map = new HashMap<>(30); try (StringReader reader = new StringReader(config)) { for (String line : IoUtils.readLines(reader)) { if (!StringUtils.isBlank(line) && !line.startsWith("#")) { String[] array = line.split("="); if (array.length != 2) { LogUtil.FATAL_LOG.error("corrupt switch record {}", line); continue; } String key = array[0].trim(); String value = array[1].trim(); map.put(key, value); } switches = map; FATAL_LOG.warn("[reload-switches] {}", getSwitches()); } } catch (IOException e) { LogUtil.FATAL_LOG.warn("[reload-switches] error! {}", config); } } public static String getSwitches() { StringBuilder sb = new StringBuilder(); String split = ""; for (Map.Entry<String, String> entry : switches.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); sb.append(split); sb.append(key); sb.append('='); sb.append(value); split = "; "; } return sb.toString(); } }
SwitchService
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSEditLog.java
{ "start": 28107, "end": 62717 }
interface ____ not added to * other types of {@link JournalManager}. */ if (jm instanceof FileJournalManager) { ((FileJournalManager)jm).setLastReadableTxId(synctxid); } } isSyncRunning = false; } this.notifyAll(); } } } // // print statistics every 1 minute. // private void printStatistics(boolean force) { long now = monotonicNow(); if (lastPrintTime + 60000 > now && !force) { return; } lastPrintTime = now; StringBuilder buf = new StringBuilder(); buf.append("Number of transactions: ") .append(numTransactions) .append(" Total time for transactions(ms): ") .append(totalTimeTransactions) .append(" Number of transactions batched in Syncs: ") .append(numTransactionsBatchedInSync.longValue()) .append(" Number of syncs: ") .append(editLogStream.getNumSync()) .append(" SyncTimes(ms): ") .append(journalSet.getSyncTimes()); LOG.info(buf.toString()); } /** Record the RPC IDs if necessary */ private void logRpcIds(FSEditLogOp op, boolean toLogRpcIds) { if (toLogRpcIds) { Pair<byte[], Integer> clientIdAndCallId = NameNode.getClientIdAndCallId(this.ipProxyUsers); op.setRpcClientId(clientIdAndCallId.getLeft()); op.setRpcCallId(clientIdAndCallId.getRight()); } } public void logAppendFile(String path, INodeFile file, boolean newBlock, boolean toLogRpcIds) { FileUnderConstructionFeature uc = file.getFileUnderConstructionFeature(); assert uc != null; AppendOp op = AppendOp.getInstance(cache.get()).setPath(path) .setClientName(uc.getClientName()) .setClientMachine(uc.getClientMachine()) .setNewBlock(newBlock); logRpcIds(op, toLogRpcIds); logEdit(op); } /** * Add open lease record to edit log. * Records the block locations of the last block. */ public void logOpenFile(String path, INodeFile newNode, boolean overwrite, boolean toLogRpcIds) { Preconditions.checkArgument(newNode.isUnderConstruction()); PermissionStatus permissions = newNode.getPermissionStatus(); AddOp op = AddOp.getInstance(cache.get()) .setInodeId(newNode.getId()) .setPath(path) .setReplication(newNode.getFileReplication()) .setModificationTime(newNode.getModificationTime()) .setAccessTime(newNode.getAccessTime()) .setBlockSize(newNode.getPreferredBlockSize()) .setBlocks(newNode.getBlocks()) .setPermissionStatus(permissions) .setClientName(newNode.getFileUnderConstructionFeature().getClientName()) .setClientMachine( newNode.getFileUnderConstructionFeature().getClientMachine()) .setOverwrite(overwrite) .setStoragePolicyId(newNode.getLocalStoragePolicyID()) .setErasureCodingPolicyId(newNode.getErasureCodingPolicyID()); AclFeature f = newNode.getAclFeature(); if (f != null) { op.setAclEntries(AclStorage.readINodeLogicalAcl(newNode)); } XAttrFeature x = newNode.getXAttrFeature(); if (x != null) { op.setXAttrs(x.getXAttrs()); } logRpcIds(op, toLogRpcIds); logEdit(op); } /** * Add close lease record to edit log. */ public void logCloseFile(String path, INodeFile newNode) { CloseOp op = CloseOp.getInstance(cache.get()) .setPath(path) .setReplication(newNode.getFileReplication()) .setModificationTime(newNode.getModificationTime()) .setAccessTime(newNode.getAccessTime()) .setBlockSize(newNode.getPreferredBlockSize()) .setBlocks(newNode.getBlocks()) .setPermissionStatus(newNode.getPermissionStatus()); logEdit(op); } public void logAddBlock(String path, INodeFile file) { Preconditions.checkArgument(file.isUnderConstruction()); BlockInfo[] blocks = file.getBlocks(); Preconditions.checkState(blocks != null && blocks.length > 0); BlockInfo pBlock = blocks.length > 1 ? blocks[blocks.length - 2] : null; BlockInfo lastBlock = blocks[blocks.length - 1]; AddBlockOp op = AddBlockOp.getInstance(cache.get()).setPath(path) .setPenultimateBlock(pBlock).setLastBlock(lastBlock); logEdit(op); } public void logUpdateBlocks(String path, INodeFile file, boolean toLogRpcIds) { Preconditions.checkArgument(file.isUnderConstruction()); UpdateBlocksOp op = UpdateBlocksOp.getInstance(cache.get()) .setPath(path) .setBlocks(file.getBlocks()); logRpcIds(op, toLogRpcIds); logEdit(op); } /** * Add create directory record to edit log */ public void logMkDir(String path, INode newNode) { PermissionStatus permissions = newNode.getPermissionStatus(); MkdirOp op = MkdirOp.getInstance(cache.get()) .setInodeId(newNode.getId()) .setPath(path) .setTimestamp(newNode.getModificationTime()) .setPermissionStatus(permissions); AclFeature f = newNode.getAclFeature(); if (f != null) { op.setAclEntries(AclStorage.readINodeLogicalAcl(newNode)); } XAttrFeature x = newNode.getXAttrFeature(); if (x != null) { op.setXAttrs(x.getXAttrs()); } logEdit(op); } /** * Add rename record to edit log. * * The destination should be the file name, not the destination directory. * TODO: use String parameters until just before writing to disk */ void logRename(String src, String dst, long timestamp, boolean toLogRpcIds) { RenameOldOp op = RenameOldOp.getInstance(cache.get()) .setSource(src) .setDestination(dst) .setTimestamp(timestamp); logRpcIds(op, toLogRpcIds); logEdit(op); } /** * Add rename record to edit log. * * The destination should be the file name, not the destination directory. */ void logRename(String src, String dst, long timestamp, boolean toLogRpcIds, Options.Rename... options) { RenameOp op = RenameOp.getInstance(cache.get()) .setSource(src) .setDestination(dst) .setTimestamp(timestamp) .setOptions(options); logRpcIds(op, toLogRpcIds); logEdit(op); } /** * Add set replication record to edit log */ void logSetReplication(String src, short replication) { SetReplicationOp op = SetReplicationOp.getInstance(cache.get()) .setPath(src) .setReplication(replication); logEdit(op); } /** * Add set storage policy id record to edit log */ void logSetStoragePolicy(String src, byte policyId) { SetStoragePolicyOp op = SetStoragePolicyOp.getInstance(cache.get()) .setPath(src).setPolicyId(policyId); logEdit(op); } /** Add set namespace quota record to edit log * * @param src the string representation of the path to a directory * @param nsQuota namespace quota * @param dsQuota diskspace quota */ void logSetQuota(String src, long nsQuota, long dsQuota) { SetQuotaOp op = SetQuotaOp.getInstance(cache.get()) .setSource(src) .setNSQuota(nsQuota) .setDSQuota(dsQuota); logEdit(op); } /** Add set quota by storage type record to edit log */ void logSetQuotaByStorageType(String src, long dsQuota, StorageType type) { SetQuotaByStorageTypeOp op = SetQuotaByStorageTypeOp.getInstance(cache.get()) .setSource(src) .setQuotaByStorageType(dsQuota, type); logEdit(op); } /** Add set permissions record to edit log */ void logSetPermissions(String src, FsPermission permissions) { SetPermissionsOp op = SetPermissionsOp.getInstance(cache.get()) .setSource(src) .setPermissions(permissions); logEdit(op); } /** Add set owner record to edit log */ void logSetOwner(String src, String username, String groupname) { SetOwnerOp op = SetOwnerOp.getInstance(cache.get()) .setSource(src) .setUser(username) .setGroup(groupname); logEdit(op); } /** * concat(trg,src..) log */ void logConcat(String trg, String[] srcs, long timestamp, boolean toLogRpcIds) { ConcatDeleteOp op = ConcatDeleteOp.getInstance(cache.get()) .setTarget(trg) .setSources(srcs) .setTimestamp(timestamp); logRpcIds(op, toLogRpcIds); logEdit(op); } /** * Add delete file record to edit log */ void logDelete(String src, long timestamp, boolean toLogRpcIds) { DeleteOp op = DeleteOp.getInstance(cache.get()) .setPath(src) .setTimestamp(timestamp); logRpcIds(op, toLogRpcIds); logEdit(op); } /** * Add truncate file record to edit log */ void logTruncate(String src, String clientName, String clientMachine, long size, long timestamp, Block truncateBlock) { TruncateOp op = TruncateOp.getInstance(cache.get()) .setPath(src) .setClientName(clientName) .setClientMachine(clientMachine) .setNewLength(size) .setTimestamp(timestamp) .setTruncateBlock(truncateBlock); logEdit(op); } /** * Add legacy block generation stamp record to edit log */ void logLegacyGenerationStamp(long genstamp) { SetGenstampV1Op op = SetGenstampV1Op.getInstance(cache.get()) .setGenerationStamp(genstamp); logEdit(op); } /** * Add generation stamp record to edit log */ void logGenerationStamp(long genstamp) { SetGenstampV2Op op = SetGenstampV2Op.getInstance(cache.get()) .setGenerationStamp(genstamp); logEdit(op); } /** * Record a newly allocated block ID in the edit log */ void logAllocateBlockId(long blockId) { AllocateBlockIdOp op = AllocateBlockIdOp.getInstance(cache.get()) .setBlockId(blockId); logEdit(op); } /** * Add access time record to edit log */ void logTimes(String src, long mtime, long atime) { TimesOp op = TimesOp.getInstance(cache.get()) .setPath(src) .setModificationTime(mtime) .setAccessTime(atime); logEdit(op); } /** * Add a create symlink record. */ void logSymlink(String path, String value, long mtime, long atime, INodeSymlink node, boolean toLogRpcIds) { SymlinkOp op = SymlinkOp.getInstance(cache.get()) .setId(node.getId()) .setPath(path) .setValue(value) .setModificationTime(mtime) .setAccessTime(atime) .setPermissionStatus(node.getPermissionStatus()); logRpcIds(op, toLogRpcIds); logEdit(op); } /** * log delegation token to edit log * @param id DelegationTokenIdentifier * @param expiryTime of the token */ void logGetDelegationToken(DelegationTokenIdentifier id, long expiryTime) { GetDelegationTokenOp op = GetDelegationTokenOp.getInstance(cache.get()) .setDelegationTokenIdentifier(id) .setExpiryTime(expiryTime); logEdit(op); } void logRenewDelegationToken(DelegationTokenIdentifier id, long expiryTime) { RenewDelegationTokenOp op = RenewDelegationTokenOp.getInstance(cache.get()) .setDelegationTokenIdentifier(id) .setExpiryTime(expiryTime); logEdit(op); } void logCancelDelegationToken(DelegationTokenIdentifier id) { CancelDelegationTokenOp op = CancelDelegationTokenOp.getInstance(cache.get()) .setDelegationTokenIdentifier(id); logEdit(op); } void logUpdateMasterKey(DelegationKey key) { UpdateMasterKeyOp op = UpdateMasterKeyOp.getInstance(cache.get()) .setDelegationKey(key); logEdit(op); } void logReassignLease(String leaseHolder, String src, String newHolder) { ReassignLeaseOp op = ReassignLeaseOp.getInstance(cache.get()) .setLeaseHolder(leaseHolder) .setPath(src) .setNewHolder(newHolder); logEdit(op); } /** * Log that a snapshot is created. * @param snapRoot Root of the snapshot. * @param snapName Name of the snapshot. * @param toLogRpcIds If it is logging RPC ids. * @param mtime The snapshot creation time set by Time.now(). */ void logCreateSnapshot(String snapRoot, String snapName, boolean toLogRpcIds, long mtime) { CreateSnapshotOp op = CreateSnapshotOp.getInstance(cache.get()) .setSnapshotRoot(snapRoot).setSnapshotName(snapName) .setSnapshotMTime(mtime); logRpcIds(op, toLogRpcIds); logEdit(op); } /** * Log that a snapshot is deleted. * @param snapRoot Root of the snapshot. * @param snapName Name of the snapshot. * @param toLogRpcIds If it is logging RPC ids. * @param mtime The snapshot deletion time set by Time.now(). */ void logDeleteSnapshot(String snapRoot, String snapName, boolean toLogRpcIds, long mtime) { DeleteSnapshotOp op = DeleteSnapshotOp.getInstance(cache.get()) .setSnapshotRoot(snapRoot).setSnapshotName(snapName) .setSnapshotMTime(mtime); logRpcIds(op, toLogRpcIds); logEdit(op); } /** * Log that a snapshot is renamed. * @param path Root of the snapshot. * @param snapOldName Old name of the snapshot. * @param snapNewName New name the snapshot will be renamed to. * @param toLogRpcIds If it is logging RPC ids. * @param mtime The snapshot modification time set by Time.now(). */ void logRenameSnapshot(String path, String snapOldName, String snapNewName, boolean toLogRpcIds, long mtime) { RenameSnapshotOp op = RenameSnapshotOp.getInstance(cache.get()) .setSnapshotRoot(path).setSnapshotOldName(snapOldName) .setSnapshotNewName(snapNewName).setSnapshotMTime(mtime); logRpcIds(op, toLogRpcIds); logEdit(op); } void logAllowSnapshot(String path) { AllowSnapshotOp op = AllowSnapshotOp.getInstance(cache.get()) .setSnapshotRoot(path); logEdit(op); } void logDisallowSnapshot(String path) { DisallowSnapshotOp op = DisallowSnapshotOp.getInstance(cache.get()) .setSnapshotRoot(path); logEdit(op); } /** * Log a CacheDirectiveInfo returned from * {@link CacheManager#addDirective(CacheDirectiveInfo, FSPermissionChecker, * EnumSet)} */ void logAddCacheDirectiveInfo(CacheDirectiveInfo directive, boolean toLogRpcIds) { AddCacheDirectiveInfoOp op = AddCacheDirectiveInfoOp.getInstance(cache.get()) .setDirective(directive); logRpcIds(op, toLogRpcIds); logEdit(op); } void logModifyCacheDirectiveInfo( CacheDirectiveInfo directive, boolean toLogRpcIds) { ModifyCacheDirectiveInfoOp op = ModifyCacheDirectiveInfoOp.getInstance( cache.get()).setDirective(directive); logRpcIds(op, toLogRpcIds); logEdit(op); } void logRemoveCacheDirectiveInfo(Long id, boolean toLogRpcIds) { RemoveCacheDirectiveInfoOp op = RemoveCacheDirectiveInfoOp.getInstance(cache.get()).setId(id); logRpcIds(op, toLogRpcIds); logEdit(op); } void logAddCachePool(CachePoolInfo pool, boolean toLogRpcIds) { AddCachePoolOp op = AddCachePoolOp.getInstance(cache.get()).setPool(pool); logRpcIds(op, toLogRpcIds); logEdit(op); } void logModifyCachePool(CachePoolInfo info, boolean toLogRpcIds) { ModifyCachePoolOp op = ModifyCachePoolOp.getInstance(cache.get()).setInfo(info); logRpcIds(op, toLogRpcIds); logEdit(op); } void logRemoveCachePool(String poolName, boolean toLogRpcIds) { RemoveCachePoolOp op = RemoveCachePoolOp.getInstance(cache.get()).setPoolName(poolName); logRpcIds(op, toLogRpcIds); logEdit(op); } void logStartRollingUpgrade(long startTime) { RollingUpgradeStartOp op = RollingUpgradeStartOp.getInstance(cache.get()); op.setTime(startTime); logEdit(op); } void logFinalizeRollingUpgrade(long finalizeTime) { RollingUpgradeOp op = RollingUpgradeFinalizeOp.getInstance(cache.get()); op.setTime(finalizeTime); logEdit(op); } void logSetAcl(String src, List<AclEntry> entries) { final SetAclOp op = SetAclOp.getInstance(cache.get()); op.src = src; op.aclEntries = entries; logEdit(op); } void logSetXAttrs(String src, List<XAttr> xAttrs, boolean toLogRpcIds) { final SetXAttrOp op = SetXAttrOp.getInstance(cache.get()); op.src = src; op.xAttrs = xAttrs; logRpcIds(op, toLogRpcIds); logEdit(op); } void logRemoveXAttrs(String src, List<XAttr> xAttrs, boolean toLogRpcIds) { final RemoveXAttrOp op = RemoveXAttrOp.getInstance(cache.get()); op.src = src; op.xAttrs = xAttrs; logRpcIds(op, toLogRpcIds); logEdit(op); } void logAddErasureCodingPolicy(ErasureCodingPolicy ecPolicy, boolean toLogRpcIds) { AddErasureCodingPolicyOp op = AddErasureCodingPolicyOp.getInstance(cache.get()); op.setErasureCodingPolicy(ecPolicy); logRpcIds(op, toLogRpcIds); logEdit(op); } void logEnableErasureCodingPolicy(String ecPolicyName, boolean toLogRpcIds) { EnableErasureCodingPolicyOp op = EnableErasureCodingPolicyOp.getInstance(cache.get()); op.setErasureCodingPolicy(ecPolicyName); logRpcIds(op, toLogRpcIds); logEdit(op); } void logDisableErasureCodingPolicy(String ecPolicyName, boolean toLogRpcIds) { DisableErasureCodingPolicyOp op = DisableErasureCodingPolicyOp.getInstance(cache.get()); op.setErasureCodingPolicy(ecPolicyName); logRpcIds(op, toLogRpcIds); logEdit(op); } void logRemoveErasureCodingPolicy(String ecPolicyName, boolean toLogRpcIds) { RemoveErasureCodingPolicyOp op = RemoveErasureCodingPolicyOp.getInstance(cache.get()); op.setErasureCodingPolicy(ecPolicyName); logRpcIds(op, toLogRpcIds); logEdit(op); } /** * Get all the journals this edit log is currently operating on. */ List<JournalAndStream> getJournals() { // The list implementation is CopyOnWriteArrayList, // so we don't need to synchronize this method. return journalSet.getAllJournalStreams(); } /** * Used only by tests. */ @VisibleForTesting public JournalSet getJournalSet() { return journalSet; } @VisibleForTesting synchronized void setJournalSetForTesting(JournalSet js) { this.journalSet = js; } /** * Used only by tests. */ @VisibleForTesting void setMetricsForTests(NameNodeMetrics metrics) { this.metrics = metrics; } /** * Return a manifest of what finalized edit logs are available */ public synchronized RemoteEditLogManifest getEditLogManifest(long fromTxId) throws IOException { return journalSet.getEditLogManifest(fromTxId); } /** * Finalizes the current edit log and opens a new log segment. * * @param layoutVersion The layout version of the new edit log segment. * @return the transaction id of the BEGIN_LOG_SEGMENT transaction in the new * log. */ synchronized long rollEditLog(int layoutVersion) throws IOException { LOG.info("Rolling edit logs"); endCurrentLogSegment(true); long nextTxId = getLastWrittenTxId() + 1; startLogSegmentAndWriteHeaderTxn(nextTxId, layoutVersion); assert curSegmentTxId == nextTxId; return nextTxId; } /** * Remote namenode just has started a log segment, start log segment locally. */ public synchronized void startLogSegment(long txid, boolean abortCurrentLogSegment, int layoutVersion) throws IOException { LOG.info("Started a new log segment at txid " + txid); if (isSegmentOpen()) { if (getLastWrittenTxId() == txid - 1) { //In sync with the NN, so end and finalize the current segment` endCurrentLogSegment(false); } else { //Missed some transactions: probably lost contact with NN temporarily. final String mess = "Cannot start a new log segment at txid " + txid + " since only up to txid " + getLastWrittenTxId() + " have been written in the log segment starting at " + getCurSegmentTxId() + "."; if (abortCurrentLogSegment) { //Mark the current segment as aborted. LOG.warn(mess); abortCurrentLogSegment(); } else { throw new IOException(mess); } } } setNextTxId(txid); startLogSegment(txid, layoutVersion); } /** * Start writing to the log segment with the given txid. * Transitions from BETWEEN_LOG_SEGMENTS state to IN_LOG_SEGMENT state. */ private void startLogSegment(final long segmentTxId, int layoutVersion) throws IOException { assert Thread.holdsLock(this); LOG.info("Starting log segment at " + segmentTxId); Preconditions.checkArgument(segmentTxId > 0, "Bad txid: %s", segmentTxId); Preconditions.checkState(state == State.BETWEEN_LOG_SEGMENTS, "Bad state: %s", state); Preconditions.checkState(segmentTxId > curSegmentTxId, "Cannot start writing to log segment " + segmentTxId + " when previous log segment started at " + curSegmentTxId); Preconditions.checkArgument(segmentTxId == txid + 1, "Cannot start log segment at txid %s when next expected " + "txid is %s", segmentTxId, txid + 1); numTransactions = 0; totalTimeTransactions = 0; numTransactionsBatchedInSync.reset(); // TODO no need to link this back to storage anymore! // See HDFS-2174. storage.attemptRestoreRemovedStorage(); try { editLogStream = journalSet.startLogSegment(segmentTxId, layoutVersion); } catch (IOException ex) { final String msg = "Unable to start log segment " + segmentTxId + ": too few journals successfully started."; LOG.error(msg, ex); synchronized (journalSetLock) { IOUtils.cleanupWithLogger(LOG, journalSet); } terminate(1, msg); } curSegmentTxId = segmentTxId; state = State.IN_SEGMENT; } synchronized void startLogSegmentAndWriteHeaderTxn(final long segmentTxId, int layoutVersion) throws IOException { startLogSegment(segmentTxId, layoutVersion); logEdit(LogSegmentOp.getInstance(cache.get(), FSEditLogOpCodes.OP_START_LOG_SEGMENT)); logSync(); } /** * Finalize the current log segment. * Transitions from IN_SEGMENT state to BETWEEN_LOG_SEGMENTS state. */ public synchronized void endCurrentLogSegment(boolean writeEndTxn) { LOG.info("Ending log segment " + curSegmentTxId + ", " + getLastWrittenTxId()); Preconditions.checkState(isSegmentOpen(), "Bad state: %s", state); if (writeEndTxn) { logEdit(LogSegmentOp.getInstance(cache.get(), FSEditLogOpCodes.OP_END_LOG_SEGMENT)); } // always sync to ensure all edits are flushed. logSyncAll(); printStatistics(true); final long lastTxId = getLastWrittenTxId(); final long lastSyncedTxId = getSyncTxId(); Preconditions.checkArgument(lastTxId == lastSyncedTxId, "LastWrittenTxId %s is expected to be the same as lastSyncedTxId %s", lastTxId, lastSyncedTxId); try { journalSet.finalizeLogSegment(curSegmentTxId, lastTxId); editLogStream = null; } catch (IOException e) { //All journals have failed, it will be handled in logSync. } state = State.BETWEEN_LOG_SEGMENTS; } /** * Abort all current logs. Called from the backup node. */ synchronized void abortCurrentLogSegment() { try { //Check for null, as abort can be called any time. if (editLogStream != null) { editLogStream.abort(); editLogStream = null; state = State.BETWEEN_LOG_SEGMENTS; } } catch (IOException e) { LOG.warn("All journals failed to abort", e); } } /** * Archive any log files that are older than the given txid. * * If the edit log is not open for write, then this call returns with no * effect. */ @Override public synchronized void purgeLogsOlderThan(final long minTxIdToKeep) { // Should not purge logs unless they are open for write. // This prevents the SBN from purging logs on shared storage, for example. if (!isOpenForWrite()) { return; } Preconditions.checkArgument( curSegmentTxId == HdfsServerConstants.INVALID_TXID || // on format this is no-op minTxIdToKeep <= curSegmentTxId, "cannot purge logs older than txid " + minTxIdToKeep + " when current segment starts at " + curSegmentTxId); if (minTxIdToKeep == 0) { return; } // This could be improved to not need synchronization. But currently, // journalSet is not threadsafe, so we need to synchronize this method. try { journalSet.purgeLogsOlderThan(minTxIdToKeep); } catch (IOException ex) { //All journals have failed, it will be handled in logSync. } } /** * The actual sync activity happens while not synchronized on this object. * Thus, synchronized activities that require that they are not concurrent * with file operations should wait for any running sync to finish. */ synchronized void waitForSyncToFinish() { while (isSyncRunning) { try { wait(1000); } catch (InterruptedException ie) {} } } /** * Return the txid of the last synced transaction. */ public synchronized long getSyncTxId() { return synctxid; } // sets the initial capacity of the flush buffer. synchronized void setOutputBufferCapacity(int size) { journalSet.setOutputBufferCapacity(size); } /** * Create (or find if already exists) an edit output stream, which * streams journal records (edits) to the specified backup node.<br> * * The new BackupNode will start receiving edits the next time this * NameNode's logs roll. * * @param bnReg the backup node registration information. * @param nnReg this (active) name-node registration. * @throws IOException */ synchronized void registerBackupNode( NamenodeRegistration bnReg, // backup node NamenodeRegistration nnReg) // active name-node throws IOException { if(bnReg.isRole(NamenodeRole.CHECKPOINT)) return; // checkpoint node does not stream edits JournalManager jas = findBackupJournal(bnReg); if (jas != null) { // already registered LOG.info("Backup node " + bnReg + " re-registers"); return; } LOG.info("Registering new backup node: " + bnReg); BackupJournalManager bjm = new BackupJournalManager(bnReg, nnReg); synchronized(journalSetLock) { journalSet.add(bjm, false); } } synchronized void releaseBackupStream(NamenodeRegistration registration) throws IOException { BackupJournalManager bjm = this.findBackupJournal(registration); if (bjm != null) { LOG.info("Removing backup journal " + bjm); synchronized(journalSetLock) { journalSet.remove(bjm); } } } /** * Find the JournalAndStream associated with this BackupNode. * * @return null if it cannot be found */ private synchronized BackupJournalManager findBackupJournal( NamenodeRegistration bnReg) { for (JournalManager bjm : journalSet.getJournalManagers()) { if ((bjm instanceof BackupJournalManager) && ((BackupJournalManager) bjm).matchesRegistration(bnReg)) { return (BackupJournalManager) bjm; } } return null; } /** Write the batch of edits to edit log. */ public synchronized void journal(long firstTxId, int numTxns, byte[] data) { final long expectedTxId = getLastWrittenTxId() + 1; Preconditions.checkState(firstTxId == expectedTxId, "received txid batch starting at %s but expected txid %s", firstTxId, expectedTxId); setNextTxId(firstTxId + numTxns - 1); logEdit(data.length, data); logSync(); } /** * Write an operation to the edit log. Do not sync to persistent * store yet. */ synchronized void logEdit(final int length, final byte[] data) { beginTransaction(null); long start = monotonicNow(); try { editLogStream.writeRaw(data, 0, length); } catch (IOException ex) { // All journals have failed, it will be handled in logSync. } endTransaction(start); } void recoverUnclosedStreams() throws IOException { recoverUnclosedStreams(false); } /** * Run recovery on all journals to recover any unclosed segments */ synchronized void recoverUnclosedStreams(boolean terminateOnFailure) throws IOException { Preconditions.checkState( state == State.BETWEEN_LOG_SEGMENTS, "May not recover segments - wrong state: %s", state); try { journalSet.recoverUnfinalizedSegments(); } catch (IOException ex) { if (terminateOnFailure) { final String msg = "Unable to recover log segments: " + "too few journals successfully recovered."; LOG.error(msg, ex); synchronized (journalSetLock) { IOUtils.cleanupWithLogger(LOG, journalSet); } terminate(1, msg); } else { throw ex; } } } public long getSharedLogCTime() throws IOException { for (JournalAndStream jas : journalSet.getAllJournalStreams()) { if (jas.isShared()) { return jas.getManager().getJournalCTime(); } } throw new IOException("No shared log found."); } public synchronized void doPreUpgradeOfSharedLog() throws IOException { for (JournalAndStream jas : journalSet.getAllJournalStreams()) { if (jas.isShared()) { jas.getManager().doPreUpgrade(); } } } public synchronized void doUpgradeOfSharedLog() throws IOException { for (JournalAndStream jas : journalSet.getAllJournalStreams()) { if (jas.isShared()) { jas.getManager().doUpgrade(storage); } } } public synchronized void doFinalizeOfSharedLog() throws IOException { for (JournalAndStream jas : journalSet.getAllJournalStreams()) { if (jas.isShared()) { jas.getManager().doFinalize(); } } } public synchronized boolean canRollBackSharedLog(StorageInfo prevStorage, int targetLayoutVersion) throws IOException { for (JournalAndStream jas : journalSet.getAllJournalStreams()) { if (jas.isShared()) { return jas.getManager().canRollBack(storage, prevStorage, targetLayoutVersion); } } throw new IOException("No shared log found."); } public synchronized void doRollback() throws IOException { for (JournalAndStream jas : journalSet.getAllJournalStreams()) { if (jas.isShared()) { jas.getManager().doRollback(); } } } public synchronized void discardSegments(long markerTxid) throws IOException { for (JournalAndStream jas : journalSet.getAllJournalStreams()) { jas.getManager().discardSegments(markerTxid); } } @Override public void selectInputStreams(Collection<EditLogInputStream> streams, long fromTxId, boolean inProgressOk, boolean onlyDurableTxns) throws IOException { journalSet.selectInputStreams(streams, fromTxId, inProgressOk, onlyDurableTxns); } public Collection<EditLogInputStream> selectInputStreams( long fromTxId, long toAtLeastTxId) throws IOException { return selectInputStreams(fromTxId, toAtLeastTxId, null, true, false); } public Collection<EditLogInputStream> selectInputStreams( long fromTxId, long toAtLeastTxId, MetaRecoveryContext recovery, boolean inProgressOK) throws IOException { return selectInputStreams(fromTxId, toAtLeastTxId, recovery, inProgressOK, false); } /** * Select a list of input streams. * * @param fromTxId first transaction in the selected streams * @param toAtLeastTxId the selected streams must contain this transaction * @param recovery recovery context * @param inProgressOk set to true if in-progress streams are OK * @param onlyDurableTxns set to true if streams are bounded * by the durable TxId */ public Collection<EditLogInputStream> selectInputStreams(long fromTxId, long toAtLeastTxId, MetaRecoveryContext recovery, boolean inProgressOk, boolean onlyDurableTxns) throws IOException { List<EditLogInputStream> streams = new ArrayList<EditLogInputStream>(); synchronized(journalSetLock) { Preconditions.checkState(journalSet.isOpen(), "Cannot call " + "selectInputStreams() on closed FSEditLog"); selectInputStreams(streams, fromTxId, inProgressOk, onlyDurableTxns); } try { checkForGaps(streams, fromTxId, toAtLeastTxId, inProgressOk); } catch (IOException e) { if (recovery != null) { // If recovery mode is enabled, continue loading even if we know we // can't load up to toAtLeastTxId. LOG.error("Exception while selecting input streams", e); } else { closeAllStreams(streams); throw e; } } return streams; } /** * Check for gaps in the edit log input stream list. * Note: we're assuming that the list is sorted and that txid ranges don't * overlap. This could be done better and with more generality with an * interval tree. */ private void checkForGaps(List<EditLogInputStream> streams, long fromTxId, long toAtLeastTxId, boolean inProgressOk) throws IOException { Iterator<EditLogInputStream> iter = streams.iterator(); long txId = fromTxId; while (true) { if (txId > toAtLeastTxId) return; if (!iter.hasNext()) break; EditLogInputStream elis = iter.next(); if (elis.getFirstTxId() > txId) break; long next = elis.getLastTxId(); if (next == HdfsServerConstants.INVALID_TXID) { if (!inProgressOk) { throw new RuntimeException("inProgressOk = false, but " + "selectInputStreams returned an in-progress edit " + "log input stream (" + elis + ")"); } // We don't know where the in-progress stream ends. // It could certainly go all the way up to toAtLeastTxId. return; } txId = next + 1; } throw new IOException(String.format("Gap in transactions. Expected to " + "be able to read up until at least txid %d but unable to find any " + "edit logs containing txid %d", toAtLeastTxId, txId)); } /** * Close all the streams in a collection * @param streams The list of streams to close */ static void closeAllStreams(Iterable<EditLogInputStream> streams) { for (EditLogInputStream s : streams) { IOUtils.closeStream(s); } } /** * Retrieve the implementation
is
java
apache__flink
flink-core/src/main/java/org/apache/flink/util/ProcessorArchitecture.java
{ "start": 1170, "end": 4605 }
enum ____ { /** The Intel x86 processor architecture. */ X86(MemoryAddressSize._32_BIT, "x86", "i386", "i486", "i586", "i686"), /** The AMD 64 bit processor architecture. */ AMD64(MemoryAddressSize._64_BIT, "amd64", "x86_64"), /** The ARM 32 bit processor architecture. */ ARMv7(MemoryAddressSize._32_BIT, "armv7", "arm"), /** The 64 bit ARM processor architecture. */ AARCH64(MemoryAddressSize._64_BIT, "aarch64"), /** The little-endian mode of the 64 bit Power-PC architecture. */ PPC64_LE(MemoryAddressSize._64_BIT, "ppc64le"), /** * Unknown architecture, could not be determined. This one conservatively assumes 32 bit, * because 64 bit platforms typically support 32 bit memory spaces. */ UNKNOWN(MemoryAddressSize._32_BIT, "unknown"); // ------------------------------------------------------------------------ private static final ProcessorArchitecture CURRENT = readArchFromSystemProperties(); private final MemoryAddressSize addressSize; private final String name; private final List<String> alternativeNames; ProcessorArchitecture(MemoryAddressSize addressSize, String name, String... alternativeNames) { this.addressSize = addressSize; this.name = name; this.alternativeNames = Collections.unmodifiableList(Arrays.asList(alternativeNames)); } /** Gets the address size of the memory (32 bit, 64 bit). */ public MemoryAddressSize getAddressSize() { return addressSize; } /** * Gets the primary name of the processor architecture. The primary name would for example be * "x86" or "amd64". */ public String getArchitectureName() { return name; } /** * Gets the alternative names for the processor architecture. Alternative names are for example * "i586" for "x86", or "x86_64" for "amd64". */ public List<String> getAlternativeNames() { return alternativeNames; } // ------------------------------------------------------------------------ /** Gets the ProcessorArchitecture of the system running this process. */ public static ProcessorArchitecture getProcessorArchitecture() { return CURRENT; } /** * Gets the MemorySize of the ProcessorArchitecture of this process. * * <p>Note that the memory address size might be different than the actual hardware * architecture, due to the installed OS (32bit OS) or when installing a 32 bit JRE in a 64 bit * OS. */ public static MemoryAddressSize getMemoryAddressSize() { return getProcessorArchitecture().getAddressSize(); } private static ProcessorArchitecture readArchFromSystemProperties() { final String sysArchName = System.getProperty("os.arch"); if (sysArchName == null) { return UNKNOWN; } for (ProcessorArchitecture arch : values()) { if (sysArchName.equalsIgnoreCase(arch.name)) { return arch; } for (String altName : arch.alternativeNames) { if (sysArchName.equalsIgnoreCase(altName)) { return arch; } } } return UNKNOWN; } // ------------------------------------------------------------------------ /** The memory address size of the processor. */ public
ProcessorArchitecture
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/KubernetesCronjobComponentBuilderFactory.java
{ "start": 4644, "end": 5660 }
class ____ extends AbstractComponentBuilder<KubernetesCronJobComponent> implements KubernetesCronjobComponentBuilder { @Override protected KubernetesCronJobComponent buildConcreteComponent() { return new KubernetesCronJobComponent(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "kubernetesClient": ((KubernetesCronJobComponent) component).setKubernetesClient((io.fabric8.kubernetes.client.KubernetesClient) value); return true; case "lazyStartProducer": ((KubernetesCronJobComponent) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((KubernetesCronJobComponent) component).setAutowiredEnabled((boolean) value); return true; default: return false; } } } }
KubernetesCronjobComponentBuilderImpl
java
apache__rocketmq
test/src/test/java/org/apache/rocketmq/test/client/producer/querymsg/QueryMsgByKeyIT.java
{ "start": 1499, "end": 5889 }
class ____ extends BaseConf { private static Logger logger = LoggerFactory.getLogger(QueryMsgByKeyIT.class); private RMQNormalProducer producer = null; private String topic = null; @Before public void setUp() { topic = initTopic(); logger.info(String.format("use topic: %s;", topic)); producer = getProducer(NAMESRV_ADDR, topic); } @After public void tearDown() { shutdown(); } @Test public void testQueryMsg() { int msgSize = 20; String key = "jueyin"; long begin = System.currentTimeMillis(); List<Object> msgs = MQMessageFactory.getKeyMsg(topic, key, msgSize); producer.send(msgs); Assert.assertEquals("Not all are sent", msgSize, producer.getAllUndupMsgBody().size()); List<MessageExt> queryMsgs = null; try { TestUtils.waitForMoment(500 * 3); queryMsgs = producer.getProducer().queryMessage(topic, key, msgSize, begin - 5000, System.currentTimeMillis() + 5000).getMessageList(); } catch (Exception e) { } assertThat(queryMsgs).isNotNull(); assertThat(queryMsgs.size()).isEqualTo(msgSize); } @Test public void testQueryMax() { int msgSize = 500; int max = 64 * BROKER_NUM; String key = "jueyin"; long begin = System.currentTimeMillis(); List<Object> msgs = MQMessageFactory.getKeyMsg(topic, key, msgSize); producer.send(msgs); Assert.assertEquals("Not all are sent", msgSize, producer.getAllUndupMsgBody().size()); List<MessageExt> queryMsgs = null; try { queryMsgs = producer.getProducer().queryMessage(topic, key, msgSize, begin - 15000, System.currentTimeMillis() + 15000).getMessageList(); int i = 3; while (queryMsgs == null || queryMsgs.size() != BROKER_NUM) { i--; queryMsgs = producer.getProducer().queryMessage(topic, key, msgSize, begin - 15000, System.currentTimeMillis() + 15000).getMessageList(); TestUtils.waitForMoment(1000); if (i == 0 || queryMsgs != null && queryMsgs.size() == max) { break; } } } catch (Exception e) { } assertThat(queryMsgs).isNotNull(); assertThat(queryMsgs.size()).isEqualTo(max); } @Test(expected = MQClientException.class) public void testQueryMsgWithSameHash1() throws Exception { int msgSize = 1; String topicA = "AaTopic"; String keyA = "Aa"; String topicB = "BBTopic"; String keyB = "BB"; initTopicWithName(topicA); initTopicWithName(topicB); RMQNormalProducer producerA = getProducer(NAMESRV_ADDR, topicA); RMQNormalProducer producerB = getProducer(NAMESRV_ADDR, topicB); List<Object> msgA = MQMessageFactory.getKeyMsg(topicA, keyA, msgSize); List<Object> msgB = MQMessageFactory.getKeyMsg(topicB, keyB, msgSize); producerA.send(msgA); producerB.send(msgB); long begin = System.currentTimeMillis() - 500000; long end = System.currentTimeMillis() + 500000; producerA.getProducer().queryMessage(topicA, keyB, msgSize * 10, begin, end).getMessageList(); } @Test public void testQueryMsgWithSameHash2() throws Exception { int msgSize = 1; String topicA = "AaAaTopic"; String keyA = "Aa"; String topicB = "BBBBTopic"; String keyB = "Aa"; initTopicWithName(topicA); initTopicWithName(topicB); RMQNormalProducer producerA = getProducer(NAMESRV_ADDR, topicA); RMQNormalProducer producerB = getProducer(NAMESRV_ADDR, topicB); List<Object> msgA = MQMessageFactory.getKeyMsg(topicA, keyA, msgSize); List<Object> msgB = MQMessageFactory.getKeyMsg(topicB, keyB, msgSize); producerA.send(msgA); producerB.send(msgB); long begin = System.currentTimeMillis() - 500000; long end = System.currentTimeMillis() + 500000; List<MessageExt> list = producerA.getProducer().queryMessage(topicA, keyA, msgSize * 10, begin, end).getMessageList(); assertThat(list).isNotNull(); assertThat(list.size()).isEqualTo(1); } }
QueryMsgByKeyIT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/identifier/composite/Event.java
{ "start": 356, "end": 1032 }
class ____ { @Id private EventId id; @Column(name = "event_key") private String key; @Column(name = "event_value") private String value; //Getters and setters are omitted for brevity //end::identifiers-composite-generated-mapping-example[] public EventId getId() { return id; } public void setId(EventId id) { this.id = id; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } //tag::identifiers-composite-generated-mapping-example[] } //end::identifiers-composite-generated-mapping-example[]
Event
java
elastic__elasticsearch
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/toolchain/OracleOpenJdkToolchainResolver.java
{ "start": 1202, "end": 5523 }
interface ____ { JavaLanguageVersion languageVersion(); String url(String os, String arch, String extension); } record ReleaseJdkBuild(JavaLanguageVersion languageVersion, String host, String version, String buildNumber, String hash) implements JdkBuild { @Override public String url(String os, String arch, String extension) { return "https://" + host + "/java/GA/jdk" + version + "/" + hash + "/" + buildNumber + "/GPL/openjdk-" + version + "_" + os + "-" + arch + "_bin." + extension; } } private static final Pattern VERSION_PATTERN = Pattern.compile( "(\\d+)(\\.\\d+\\.\\d+(?:\\.\\d+)?)?\\+(\\d+(?:\\.\\d+)?)(@([a-f0-9]{32}))?" ); private static final List<OperatingSystem> supportedOperatingSystems = List.of( OperatingSystem.MAC_OS, OperatingSystem.LINUX, OperatingSystem.WINDOWS ); // package private so it can be replaced by tests List<JdkBuild> builds = List.of( getBundledJdkBuild(VersionProperties.getBundledJdkVersion(), VersionProperties.getBundledJdkMajorVersion()) ); static JdkBuild getBundledJdkBuild(String bundledJdkVersion, String bundledJkdMajorVersionString) { JavaLanguageVersion bundledJdkMajorVersion = JavaLanguageVersion.of(bundledJkdMajorVersionString); Matcher jdkVersionMatcher = VERSION_PATTERN.matcher(bundledJdkVersion); if (jdkVersionMatcher.matches() == false) { throw new IllegalStateException("Unable to parse bundled JDK version " + bundledJdkVersion); } String baseVersion = jdkVersionMatcher.group(1) + (jdkVersionMatcher.group(2) != null ? (jdkVersionMatcher.group(2)) : ""); String build = jdkVersionMatcher.group(3); String hash = jdkVersionMatcher.group(5); return new ReleaseJdkBuild(bundledJdkMajorVersion, "download.oracle.com", baseVersion, build, hash); } /** * We need some place to map JavaLanguageVersion to buildNumber, minor version etc. * */ @Override public Optional<JavaToolchainDownload> resolve(JavaToolchainRequest request) { JdkBuild build = findSupportedBuild(request); if (build == null) { return Optional.empty(); } OperatingSystem operatingSystem = request.getBuildPlatform().getOperatingSystem(); String extension = operatingSystem.equals(OperatingSystem.WINDOWS) ? "zip" : "tar.gz"; String arch = toArchString(request.getBuildPlatform().getArchitecture()); String os = toOsString(operatingSystem); return Optional.of(() -> URI.create(build.url(os, arch, extension))); } /** * Check if request can be full-filled by this resolver: * 1. BundledJdkVendor should match openjdk * 2. language version should match bundled jdk version * 3. vendor must be any or oracle * 4. Aarch64 windows images are not supported */ private JdkBuild findSupportedBuild(JavaToolchainRequest request) { if (VersionProperties.getBundledJdkVendor().toLowerCase().equals("openjdk") == false) { return null; } JavaToolchainSpec javaToolchainSpec = request.getJavaToolchainSpec(); if (anyVendorOr(javaToolchainSpec.getVendor().get(), JvmVendorSpec.ORACLE) == false) { return null; } BuildPlatform buildPlatform = request.getBuildPlatform(); Architecture architecture = buildPlatform.getArchitecture(); OperatingSystem operatingSystem = buildPlatform.getOperatingSystem(); if (supportedOperatingSystems.contains(operatingSystem) == false || Architecture.AARCH64 == architecture && OperatingSystem.WINDOWS == operatingSystem) { return null; } JavaLanguageVersion languageVersion = javaToolchainSpec.getLanguageVersion().get(); for (JdkBuild build : builds) { if (build.languageVersion().equals(languageVersion)) { return build; } } return null; } }
JdkBuild
java
apache__hadoop
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/ZombieJobProducer.java
{ "start": 1046, "end": 4309 }
class ____ implements JobStoryProducer { private final JobTraceReader reader; private final ZombieCluster cluster; private boolean hasRandomSeed = false; private long randomSeed = 0; private ZombieJobProducer(JobTraceReader reader, ZombieCluster cluster, boolean hasRandomSeed, long randomSeed) { this.reader = reader; this.cluster = cluster; this.hasRandomSeed = hasRandomSeed; this.randomSeed = (hasRandomSeed) ? randomSeed : System.nanoTime(); } /** * Constructor * * @param path * Path to the JSON trace file, possibly compressed. * @param cluster * The topology of the cluster that corresponds to the jobs in the * trace. The argument can be null if we do not have knowledge of the * cluster topology. * @param conf * @throws IOException */ public ZombieJobProducer(Path path, ZombieCluster cluster, Configuration conf) throws IOException { this(new JobTraceReader(path, conf), cluster, false, -1); } /** * Constructor * * @param path * Path to the JSON trace file, possibly compressed. * @param cluster * The topology of the cluster that corresponds to the jobs in the * trace. The argument can be null if we do not have knowledge of the * cluster topology. * @param conf * @param randomSeed * use a deterministic seed. * @throws IOException */ public ZombieJobProducer(Path path, ZombieCluster cluster, Configuration conf, long randomSeed) throws IOException { this(new JobTraceReader(path, conf), cluster, true, randomSeed); } /** * Constructor * * @param input * The input stream for the JSON trace. * @param cluster * The topology of the cluster that corresponds to the jobs in the * trace. The argument can be null if we do not have knowledge of the * cluster topology. * @throws IOException */ public ZombieJobProducer(InputStream input, ZombieCluster cluster) throws IOException { this(new JobTraceReader(input), cluster, false, -1); } /** * Constructor * * @param input * The input stream for the JSON trace. * @param cluster * The topology of the cluster that corresponds to the jobs in the * trace. The argument can be null if we do not have knowledge of the * cluster topology. * @param randomSeed * use a deterministic seed. * @throws IOException */ public ZombieJobProducer(InputStream input, ZombieCluster cluster, long randomSeed) throws IOException { this(new JobTraceReader(input), cluster, true, randomSeed); } @Override public ZombieJob getNextJob() throws IOException { LoggedJob job = reader.getNext(); if (job == null) { return null; } else if (hasRandomSeed) { long subRandomSeed = RandomSeedGenerator.getSeed( "forZombieJob" + job.getJobID(), randomSeed); return new ZombieJob(job, cluster, subRandomSeed); } else { return new ZombieJob(job, cluster); } } @Override public void close() throws IOException { reader.close(); } }
ZombieJobProducer