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
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/OrderByColumnNameTest.java
{ "start": 2764, "end": 3152 }
class ____ { private String name; private int id; public Widgets() { } @Column(name = "name_1") public String getName() { return name; } public void setName(String name) { this.name = name; } @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } } @Entity(name = "Widget1") public static
Widgets
java
apache__camel
components/camel-jacksonxml/src/main/java/org/apache/camel/component/jacksonxml/JacksonXMLDataFormat.java
{ "start": 22840, "end": 24534 }
enum ____ types [SerializationFeature,DeserializationFeature,MapperFeature,FromXmlParser.Feature]"); } } if (modules != null) { for (Module module : modules) { LOG.info("Registering module: {}", module); xmlMapper.registerModules(module); } } if (moduleClassNames != null) { Iterable<?> it = ObjectHelper.createIterable(moduleClassNames); for (Object o : it) { String name = o.toString(); Class<Module> clazz = camelContext.getClassResolver().resolveMandatoryClass(name, Module.class); Module module = camelContext.getInjector().newInstance(clazz); LOG.info("Registering module: {} -> {}", name, module); xmlMapper.registerModule(module); } } if (moduleRefs != null) { Iterable<?> it = ObjectHelper.createIterable(moduleRefs); for (Object o : it) { String name = o.toString(); if (name.startsWith("#")) { name = name.substring(1); } Module module = CamelContextHelper.mandatoryLookup(camelContext, name, Module.class); LOG.info("Registering module: {} -> {}", name, module); xmlMapper.registerModule(module); } } if (org.apache.camel.util.ObjectHelper.isNotEmpty(timezone)) { LOG.debug("Setting timezone to XML Mapper: {}", timezone); xmlMapper.setTimeZone(timezone); } } @Override protected void doStop() throws Exception { // noop } }
of
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/Client.java
{ "start": 14333, "end": 19622 }
class ____ extends SubjectInheritingThread { private InetSocketAddress server; // server ip:port private final ConnectionId remoteId; // connection id private AuthMethod authMethod; // authentication method private AuthProtocol authProtocol; private int serviceClass; private SaslRpcClient saslRpcClient; private Socket socket = null; // connected socket private IpcStreams ipcStreams; private final int maxResponseLength; private final int rpcTimeout; private int maxIdleTime; //connections will be culled if it was idle for //maxIdleTime msecs private final RetryPolicy connectionRetryPolicy; private final int maxRetriesOnSasl; private int maxRetriesOnSocketTimeouts; private final boolean tcpNoDelay; // if T then disable Nagle's Algorithm private final boolean tcpLowLatency; // if T then use low-delay QoS private final boolean doPing; //do we need to send ping message private final int pingInterval; // how often sends ping to the server private final int soTimeout; // used by ipc ping and rpc timeout private byte[] pingRequest; // ping message // currently active calls private Hashtable<Integer, Call> calls = new Hashtable<Integer, Call>(); private AtomicLong lastActivity = new AtomicLong();// last I/O activity time private AtomicBoolean shouldCloseConnection = new AtomicBoolean(); // indicate if the connection is closed private IOException closeException; // close reason private final Thread rpcRequestThread; private final SynchronousQueue<Pair<Call, ResponseBuffer>> rpcRequestQueue = new SynchronousQueue<>(true); private AtomicReference<Thread> connectingThread = new AtomicReference<>(); private final Consumer<Connection> removeMethod; Connection(ConnectionId remoteId, int serviceClass, Consumer<Connection> removeMethod) { this.remoteId = remoteId; this.server = remoteId.getAddress(); this.rpcRequestThread = new SubjectInheritingThread(new RpcRequestSender(), "IPC Parameter Sending Thread for " + remoteId); this.rpcRequestThread.setDaemon(true); this.maxResponseLength = remoteId.conf.getInt( CommonConfigurationKeys.IPC_MAXIMUM_RESPONSE_LENGTH, CommonConfigurationKeys.IPC_MAXIMUM_RESPONSE_LENGTH_DEFAULT); this.rpcTimeout = remoteId.getRpcTimeout(); this.maxIdleTime = remoteId.getMaxIdleTime(); this.connectionRetryPolicy = remoteId.connectionRetryPolicy; this.maxRetriesOnSasl = remoteId.getMaxRetriesOnSasl(); this.maxRetriesOnSocketTimeouts = remoteId.getMaxRetriesOnSocketTimeouts(); this.tcpNoDelay = remoteId.getTcpNoDelay(); this.tcpLowLatency = remoteId.getTcpLowLatency(); this.doPing = remoteId.getDoPing(); if (doPing) { // construct a RPC header with the callId as the ping callId ResponseBuffer buf = new ResponseBuffer(); RpcRequestHeaderProto pingHeader = ProtoUtil .makeRpcRequestHeader(RpcKind.RPC_PROTOCOL_BUFFER, OperationProto.RPC_FINAL_PACKET, PING_CALL_ID, RpcConstants.INVALID_RETRY_COUNT, clientId); try { pingHeader.writeDelimitedTo(buf); } catch (IOException e) { throw new IllegalStateException("Failed to write to buf for " + remoteId + " in " + Client.this + " due to " + e, e); } pingRequest = buf.toByteArray(); } this.pingInterval = remoteId.getPingInterval(); if (rpcTimeout > 0) { // effective rpc timeout is rounded up to multiple of pingInterval // if pingInterval < rpcTimeout. this.soTimeout = (doPing && pingInterval < rpcTimeout) ? pingInterval : rpcTimeout; } else { this.soTimeout = pingInterval; } this.serviceClass = serviceClass; this.removeMethod = removeMethod; if (LOG.isDebugEnabled()) { LOG.debug("The ping interval is " + this.pingInterval + " ms."); } UserGroupInformation ticket = remoteId.getTicket(); // try SASL if security is enabled or if the ugi contains tokens. // this causes a SIMPLE client with tokens to attempt SASL boolean trySasl = UserGroupInformation.isSecurityEnabled() || (ticket != null && !ticket.getTokens().isEmpty()); this.authProtocol = trySasl ? AuthProtocol.SASL : AuthProtocol.NONE; this.setName("IPC Client (" + socketFactory.hashCode() +") connection to " + server.toString() + " from " + ((ticket==null)?"an unknown user":ticket.getUserName())); this.setDaemon(true); } /** Update lastActivity with the current time. */ private void touch() { lastActivity.set(Time.now()); } /** * Add a call to this connection's call queue and notify * a listener; synchronized. * Returns false if called during shutdown. * @param call to add * @return true if the call was added. */ private synchronized boolean addCall(Call call) { if (shouldCloseConnection.get()) return false; calls.put(call.id, call); notify(); return true; } /** This
Connection
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/strictness/StrictnessWithSettingsTest.java
{ "start": 530, "end": 1803 }
class ____ { public @Rule MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); IMethods lenientMock; IMethods regularMock; IMethods strictMock; @Before public void before() { lenientMock = mock(IMethods.class, withSettings().strictness(Strictness.LENIENT)); regularMock = mock(IMethods.class); strictMock = mock(IMethods.class, withSettings().strictness(Strictness.STRICT_STUBS)); } @Test public void mock_is_lenient() { when(lenientMock.simpleMethod("1")).thenReturn("1"); // lenient mock does not throw ProductionCode.simpleMethod(lenientMock, "3"); } @Test public void mock_is_strict_with_default_settings() { when(regularMock.simpleMethod("3")).thenReturn("3"); Assertions.assertThatThrownBy(() -> ProductionCode.simpleMethod(regularMock, "4")) .isInstanceOf(PotentialStubbingProblem.class); } @Test public void mock_is_strict_with_explicit_settings() { when(strictMock.simpleMethod("2")).thenReturn("2"); Assertions.assertThatThrownBy(() -> ProductionCode.simpleMethod(strictMock, "5")) .isInstanceOf(PotentialStubbingProblem.class); } }
StrictnessWithSettingsTest
java
greenrobot__greendao
tests/DaoTest/src/androidTest/java/org/greenrobot/greendao/daotest/entity/IndexedStringEntityTest.java
{ "start": 1039, "end": 1434 }
class ____ extends AbstractDaoTestLongPk<IndexedStringEntityDao, IndexedStringEntity> { public IndexedStringEntityTest() { super(IndexedStringEntityDao.class); } @Override protected IndexedStringEntity createEntity(Long key) { IndexedStringEntity entity = new IndexedStringEntity(); entity.setId(key); return entity; } }
IndexedStringEntityTest
java
apache__hadoop
hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/NfsExports.java
{ "start": 1651, "end": 3670 }
class ____ { private static NfsExports exports = null; public static synchronized NfsExports getInstance(Configuration conf) { if (exports == null) { String matchHosts = conf.get( CommonConfigurationKeys.NFS_EXPORTS_ALLOWED_HOSTS_KEY, CommonConfigurationKeys.NFS_EXPORTS_ALLOWED_HOSTS_KEY_DEFAULT); int cacheSize = conf.getInt(Nfs3Constant.NFS_EXPORTS_CACHE_SIZE_KEY, Nfs3Constant.NFS_EXPORTS_CACHE_SIZE_DEFAULT); long expirationPeriodNano = conf.getLong( Nfs3Constant.NFS_EXPORTS_CACHE_EXPIRYTIME_MILLIS_KEY, Nfs3Constant.NFS_EXPORTS_CACHE_EXPIRYTIME_MILLIS_DEFAULT) * 1000 * 1000; try { exports = new NfsExports(cacheSize, expirationPeriodNano, matchHosts); } catch (IllegalArgumentException e) { LOG.error("Invalid NFS Exports provided: ", e); return exports; } } return exports; } public static final Logger LOG = LoggerFactory.getLogger(NfsExports.class); // only support IPv4 now private static final String IP_ADDRESS = "(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})"; private static final String SLASH_FORMAT_SHORT = IP_ADDRESS + "/(\\d{1,3})"; private static final String SLASH_FORMAT_LONG = IP_ADDRESS + "/" + IP_ADDRESS; private static final Pattern CIDR_FORMAT_SHORT = Pattern.compile(SLASH_FORMAT_SHORT); private static final Pattern CIDR_FORMAT_LONG = Pattern.compile(SLASH_FORMAT_LONG); // Hostnames are composed of series of 'labels' concatenated with dots. // Labels can be between 1-63 characters long, and can only take // letters, digits & hyphens. They cannot start and end with hyphens. For // more details, refer RFC-1123 & http://en.wikipedia.org/wiki/Hostname private static final String LABEL_FORMAT = "[a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?"; private static final Pattern HOSTNAME_FORMAT = Pattern.compile("^(" + LABEL_FORMAT + "\\.)*" + LABEL_FORMAT + "$"); static
NfsExports
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/ability/register/impl/SdkClientAbilities.java
{ "start": 934, "end": 2283 }
class ____ extends AbstractAbilityRegistry { private static final SdkClientAbilities INSTANCE = new SdkClientAbilities(); { /* * example: * There is a function named "compression". * The key is from <p>AbilityKey</p>, the value is whether turn on. * * You can add a new public field in <p>AbilityKey</p> like: * <code>DATA_COMPRESSION("compression", "description about this ability")</code> * * And then you need to declare whether turn on in the ability table, you can: * <code>supportedAbilities.put(AbilityKey.DATA_COMPRESSION, true);</code> means that current client support compression. * */ // put ability here, which you want current client supports supportedAbilities.put(AbilityKey.SDK_CLIENT_FUZZY_WATCH, true); supportedAbilities.put(AbilityKey.SDK_CLIENT_DISTRIBUTED_LOCK, true); supportedAbilities.put(AbilityKey.SDK_MCP_REGISTRY, true); supportedAbilities.put(AbilityKey.SDK_AGENT_REGISTRY, true); } /**. * get static ability current server supports * * @return static ability */ public static Map<AbilityKey, Boolean> getStaticAbilities() { return INSTANCE.getSupportedAbilities(); } }
SdkClientAbilities
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/saml/UnresolvedEntity.java
{ "start": 1631, "end": 11357 }
class ____ implements EntityDescriptor { private String entityId; private String sourceLocation; UnresolvedEntity(String entityId, String sourceLocation) { this.entityId = entityId; this.sourceLocation = sourceLocation; } @Override public String getEntityID() { return entityId; } @Override public String toString() { return getID(); } @Override public void setEntityID(String id) { throw new UnsupportedOperationException("Cannot set Entity Id of " + this); } @Override public String getID() { return "Unresolved-SAML-Entity{" + entityId + '}'; } @Override public void setID(String newID) { throw new UnsupportedOperationException("Cannot set Element ID of " + this); } @Override public Extensions getExtensions() { return null; } @Override public void setExtensions(Extensions extensions) { throw new UnsupportedOperationException("Cannot set extensions on " + this); } @Override public List<RoleDescriptor> getRoleDescriptors() { throw SamlUtils.samlException( "Cannot get role descriptors" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", sourceLocation, entityId ); } @Override public List<RoleDescriptor> getRoleDescriptors(QName typeOrName) { throw SamlUtils.samlException( "Cannot get role descriptors [type/name={}]" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", typeOrName, sourceLocation, entityId ); } @Override public List<RoleDescriptor> getRoleDescriptors(QName typeOrName, String supportedProtocol) { throw SamlUtils.samlException( "Cannot get role descriptors [type/name={}][protocol={}]" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", typeOrName, supportedProtocol, sourceLocation, entityId ); } @Override public IDPSSODescriptor getIDPSSODescriptor(String supportedProtocol) { throw SamlUtils.samlException( "Cannot get IdP SSO descriptor [protocol={}]" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", supportedProtocol, sourceLocation, entityId ); } @Override public SPSSODescriptor getSPSSODescriptor(String supportedProtocol) { throw SamlUtils.samlException( "Cannot get SP SSO descriptor [protocol={}]" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", supportedProtocol, sourceLocation, entityId ); } @Override public AuthnAuthorityDescriptor getAuthnAuthorityDescriptor(String supportedProtocol) { throw SamlUtils.samlException( "Cannot get authn authority descriptor [protocol={}]" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", supportedProtocol, sourceLocation, entityId ); } @Override public AttributeAuthorityDescriptor getAttributeAuthorityDescriptor(String supportedProtocol) { throw SamlUtils.samlException( "Cannot get attribute authority descriptor [protocol={}]" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", supportedProtocol, sourceLocation, entityId ); } @Override public PDPDescriptor getPDPDescriptor(String supportedProtocol) { throw SamlUtils.samlException( "Cannot get PDP descriptor [protocol={}]" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", supportedProtocol, sourceLocation, entityId ); } @Override public AffiliationDescriptor getAffiliationDescriptor() { throw SamlUtils.samlException( "Cannot get affiliation descriptor" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", sourceLocation, entityId ); } @Override public void setAffiliationDescriptor(AffiliationDescriptor descriptor) { throw new UnsupportedOperationException("Cannot set affiliation descriptor of " + this); } @Override public Organization getOrganization() { throw SamlUtils.samlException( "Cannot get organization" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", sourceLocation, entityId ); } @Override public void setOrganization(Organization organization) { throw new UnsupportedOperationException("Cannot set organization of " + this); } @Override public List<ContactPerson> getContactPersons() { return List.of(); } @Override public List<AdditionalMetadataLocation> getAdditionalMetadataLocations() { return List.of(); } @Override public AttributeMap getUnknownAttributes() { return null; } @Override public String getSignatureReferenceID() { throw SamlUtils.samlException( "Cannot get signature reference id" + " because the metadata [location={}] for SAML entity [id={}] could not be resolved", sourceLocation, entityId ); } @Nullable @Override public Duration getCacheDuration() { return null; } @Override public void setCacheDuration(Duration duration) { throw new UnsupportedOperationException("Cannot set cache duration of " + this); } @Override public boolean isValid() { return false; } @Nullable @Override public Instant getValidUntil() { return null; } @Override public void setValidUntil(Instant validUntil) { throw new UnsupportedOperationException("Cannot set valid-until of " + this); } @Override public boolean isSigned() { return false; } @Nullable @Override public Signature getSignature() { return null; } @Override public void setSignature(Signature newSignature) { throw new UnsupportedOperationException("Cannot set signature of " + this); } @Override public void detach() {} @Nullable @Override public Element getDOM() { return null; } @Override public QName getElementQName() { return EntityDescriptor.ELEMENT_QNAME; } @Override public IDIndex getIDIndex() { throw new UnsupportedOperationException("Cannot get ID Index of " + this); } @Override public NamespaceManager getNamespaceManager() { throw new UnsupportedOperationException("Cannot get namespace manager of " + this); } @Override public Set<Namespace> getNamespaces() { throw new UnsupportedOperationException("Cannot get namespaces of " + this); } @Nullable @Override public String getNoNamespaceSchemaLocation() { return null; } @Nullable @Override public List<XMLObject> getOrderedChildren() { return List.of(); } @Nullable @Override public XMLObject getParent() { return null; } @Nullable @Override public String getSchemaLocation() { return null; } @Nullable @Override public QName getSchemaType() { return null; } @Override public boolean hasChildren() { return false; } @Override public boolean hasParent() { return false; } @Override public void releaseChildrenDOM(boolean propagateRelease) { } @Override public void releaseDOM() { } @Override public void releaseParentDOM(boolean propagateRelease) { } @Nullable @Override public XMLObject resolveID(String id) { return null; } @Nullable @Override public XMLObject resolveIDFromRoot(String id) { return null; } @Override public void setDOM(Element dom) { throw new UnsupportedOperationException("Cannot set DOM of " + this); } @Override public void setNoNamespaceSchemaLocation(String location) { throw new UnsupportedOperationException("Cannot set no-namespace-schema-location of " + this); } @Override public void setParent(XMLObject parent) { throw new UnsupportedOperationException("Cannot set parent of " + this); } @Override public void setSchemaLocation(String location) { throw new UnsupportedOperationException("Cannot set schema location of " + this); } @Nullable @Override public Boolean isNil() { return null; } @Nullable @Override public XSBooleanValue isNilXSBoolean() { return null; } @Override public void setNil(Boolean newNil) { throw new UnsupportedOperationException("Cannot set NIL of " + this); } @Override public void setNil(XSBooleanValue newNil) { throw new UnsupportedOperationException("Cannot set NIL of " + this); } @Override public LockableClassToInstanceMultiMap<Object> getObjectMetadata() { throw new UnsupportedOperationException("Cannot get object-metadata of " + this); } }
UnresolvedEntity
java
quarkusio__quarkus
integration-tests/maven/src/test/resources-filtered/projects/codegen-config-factory/constants/src/main/java/org/acme/AcmeConstants.java
{ "start": 26, "end": 193 }
interface ____ { String ACME_CONFIG_FACTORY_PROP = "acme-config-factory"; String ACME_CONFIG_PROVIDER_PROP = "acme-config-provider"; String NA = "n/a"; }
AcmeConstants
java
spring-projects__spring-framework
spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DefaultDatabaseClient.java
{ "start": 20639, "end": 21246 }
class ____ implements BindTarget { final Statement statement; StatementWrapper(Statement statement) { this.statement = statement; } @Override public void bind(String identifier, Object value) { this.statement.bind(identifier, value); } @Override public void bind(int index, Object value) { this.statement.bind(index, value); } @Override public void bindNull(String identifier, Class<?> type) { this.statement.bindNull(identifier, type); } @Override public void bindNull(int index, Class<?> type) { this.statement.bindNull(index, type); } } }
StatementWrapper
java
netty__netty
transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketTcpMd5Test.java
{ "start": 1542, "end": 6188 }
class ____ { private static final byte[] SERVER_KEY = "abc".getBytes(CharsetUtil.US_ASCII); private static final byte[] BAD_KEY = "def".getBytes(CharsetUtil.US_ASCII); private static EventLoopGroup GROUP; private EpollServerSocketChannel server; @BeforeAll public static void beforeClass() { GROUP = new MultiThreadIoEventLoopGroup(1, EpollIoHandler.newFactory()); } @AfterAll public static void afterClass() { GROUP.shutdownGracefully(); } @BeforeEach public void setup() { ServerBootstrap bootstrap = new ServerBootstrap(); server = (EpollServerSocketChannel) bootstrap.group(GROUP) .channel(EpollServerSocketChannel.class) .childHandler(new ChannelInboundHandlerAdapter()) .bind(new InetSocketAddress(NetUtil.LOCALHOST4, 0)).syncUninterruptibly().channel(); } @AfterEach public void teardown() { server.close().syncUninterruptibly(); } @Test public void testServerSocketChannelOption() throws Exception { try { server.config().setOption(EpollChannelOption.TCP_MD5SIG, Collections.<InetAddress, byte[]>singletonMap(NetUtil.LOCALHOST4, SERVER_KEY)); server.config().setOption(EpollChannelOption.TCP_MD5SIG, Collections.<InetAddress, byte[]>emptyMap()); } catch (ChannelException ce) { handleException(ce); } } private static void handleException(ChannelException ce) { if (ce.getMessage().contains("Protocol not available")) { // Some operating systems don't allow or support the TCP_MD5SIG option. // Abort the test (instead of failing) if that's the case. Assumptions.abort(ce.getMessage()); } throw ce; } @Test public void testServerOption() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); EpollServerSocketChannel ch = (EpollServerSocketChannel) bootstrap.group(GROUP) .channel(EpollServerSocketChannel.class) .childHandler(new ChannelInboundHandlerAdapter()) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); try { ch.config().setOption(EpollChannelOption.TCP_MD5SIG, Collections.<InetAddress, byte[]>singletonMap(NetUtil.LOCALHOST4, SERVER_KEY)); ch.config().setOption(EpollChannelOption.TCP_MD5SIG, Collections.<InetAddress, byte[]>emptyMap()); } catch (ChannelException ce) { handleException(ce); } finally { ch.close().syncUninterruptibly(); } } @Test public void testKeyMismatch() throws Exception { try { server.config().setOption(EpollChannelOption.TCP_MD5SIG, Collections.<InetAddress, byte[]>singletonMap(NetUtil.LOCALHOST4, SERVER_KEY)); } catch (ChannelException ce) { handleException(ce); } assertThrows(ConnectTimeoutException.class, new Executable() { @Override public void execute() throws Throwable { EpollSocketChannel client = (EpollSocketChannel) new Bootstrap().group(GROUP) .channel(EpollSocketChannel.class) .handler(new ChannelInboundHandlerAdapter()) .option(EpollChannelOption.TCP_MD5SIG, Collections.<InetAddress, byte[]>singletonMap(NetUtil.LOCALHOST4, BAD_KEY)) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) .connect(server.localAddress()).syncUninterruptibly().channel(); client.close().syncUninterruptibly(); } }); } @Test public void testKeyMatch() throws Exception { try { server.config().setOption(EpollChannelOption.TCP_MD5SIG, Collections.<InetAddress, byte[]>singletonMap(NetUtil.LOCALHOST4, SERVER_KEY)); } catch (ChannelException ce) { handleException(ce); } EpollSocketChannel client = (EpollSocketChannel) new Bootstrap().group(GROUP) .channel(EpollSocketChannel.class) .handler(new ChannelInboundHandlerAdapter()) .option(EpollChannelOption.TCP_MD5SIG, Collections.<InetAddress, byte[]>singletonMap(NetUtil.LOCALHOST4, SERVER_KEY)) .connect(server.localAddress()).syncUninterruptibly().channel(); client.close().syncUninterruptibly(); } }
EpollSocketTcpMd5Test
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/properties/PropertyFunctionOptionalPropertyPlaceholderTest.java
{ "start": 9266, "end": 10005 }
class ____ implements PropertiesFunction, CamelContextAware { private CamelContext camelContext; @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public String getName() { return "magic"; } @Override public String apply(String remainder) { return "myMagic".equals(remainder) ? "magic" : null; } @Override public boolean optional(String remainder) { return "myOptional".equals(remainder); } } }
MagicFunction
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/postgresql/PGResourceTest.java
{ "start": 161, "end": 409 }
class ____ extends SQLResourceTest { public PGResourceTest() { super(DbType.postgresql); } @Test public void test() throws Exception { fileTest(0, 999, i -> "bvt/parser/postgresql/" + i + ".txt"); } }
PGResourceTest
java
spring-projects__spring-framework
framework-docs/src/main/java/org/springframework/docs/web/webmvc/mvcconfig/mvcconfigapiversion/WebConfiguration.java
{ "start": 958, "end": 1163 }
class ____ implements WebMvcConfigurer { @Override public void configureApiVersioning(ApiVersionConfigurer configurer) { configurer.useRequestHeader("API-Version"); } } // end::snippet[]
WebConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/array/HANAUnnestFunction.java
{ "start": 11478, "end": 15265 }
class ____ implements SelfRenderingExpression { private final Expression argument; private final String tableName; private final List<ColumnInfo> idColumns; public TableColumnReferenceExpression(Expression argument, String tableName, List<ColumnInfo> idColumns) { this.argument = argument; this.tableName = tableName; this.idColumns = idColumns; } @Override public void renderToSql( SqlAppender sqlAppender, SqlAstTranslator<?> walker, SessionFactoryImplementor sessionFactory) { sqlAppender.appendSql( tableName ); sqlAppender.appendSql( ".v" ); } @Override public JdbcMappingContainer getExpressionType() { return argument.getExpressionType(); } public List<ColumnInfo> getIdColumns() { return idColumns; } } @Override protected void renderXmlTable( SqlAppender sqlAppender, Expression array, BasicPluralType<?, ?> pluralType, @Nullable SqlTypedMapping sqlTypedMapping, AnonymousTupleTableGroupProducer tupleType, String tableIdentifierVariable, SqlAstTranslator<?> walker) { final XmlHelper.CollectionTags collectionTags = XmlHelper.determineCollectionTags( (BasicPluralJavaType<?>) pluralType.getJavaTypeDescriptor(), walker.getSessionFactory() ); sqlAppender.appendSql( "xmltable('/" ); sqlAppender.appendSql( collectionTags.rootName() ); sqlAppender.appendSql( '/' ); sqlAppender.appendSql( collectionTags.elementName() ); sqlAppender.appendSql( "' passing " ); array.accept( walker ); sqlAppender.appendSql( " columns" ); char separator = ' '; final int offset; if ( array instanceof TableColumnReferenceExpression expression ) { offset = expression.getIdColumns().size(); for ( ColumnInfo columnInfo : expression.getIdColumns() ) { sqlAppender.appendSql( separator ); sqlAppender.appendSql( columnInfo.name() ); sqlAppender.appendSql( ' ' ); sqlAppender.appendSql( columnInfo.ddlType() ); sqlAppender.appendSql( " path 'ancestor::" ); sqlAppender.appendSql( collectionTags.rootName() ); sqlAppender.appendSql( "/@" ); sqlAppender.appendSql( columnInfo.name() ); sqlAppender.appendSql( '\'' ); separator = ','; } } else { offset = 0; } if ( tupleType.findSubPart( CollectionPart.Nature.ELEMENT.getName(), null ) == null ) { tupleType.forEachSelectable( offset, (selectionIndex, selectableMapping) -> { if ( selectionIndex == 0 ) { sqlAppender.append( ' ' ); } else { sqlAppender.append( ',' ); } sqlAppender.append( selectableMapping.getSelectionExpression() ); if ( CollectionPart.Nature.INDEX.getName().equals( selectableMapping.getSelectableName() ) ) { sqlAppender.append( " for ordinality" ); } else { sqlAppender.append( ' ' ); sqlAppender.append( getDdlType( selectableMapping, SqlTypes.XML_ARRAY, walker ) ); sqlAppender.appendSql( " path '" ); sqlAppender.appendSql( selectableMapping.getSelectableName() ); sqlAppender.appendSql( "'" ); } } ); } else { tupleType.forEachSelectable( offset, (selectionIndex, selectableMapping) -> { if ( selectionIndex == 0 ) { sqlAppender.append( ' ' ); } else { sqlAppender.append( ',' ); } sqlAppender.append( selectableMapping.getSelectionExpression() ); if ( CollectionPart.Nature.INDEX.getName().equals( selectableMapping.getSelectableName() ) ) { sqlAppender.append( " for ordinality" ); } else { sqlAppender.append( ' ' ); sqlAppender.append( getDdlType( selectableMapping, SqlTypes.XML_ARRAY, walker ) ); sqlAppender.appendSql( " path '" ); sqlAppender.appendSql( "." ); sqlAppender.appendSql( "'" ); } } ); } sqlAppender.appendSql( ')' ); } static
TableColumnReferenceExpression
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/bind/annotation/CookieValue.java
{ "start": 1439, "end": 2291 }
interface ____ { /** * Alias for {@link #name}. */ @AliasFor("name") String value() default ""; /** * The name of the cookie to bind to. * @since 4.2 */ @AliasFor("value") String name() default ""; /** * Whether the cookie is required. * <p>Defaults to {@code true}, leading to an exception being thrown * if the cookie is missing in the request. Switch this to * {@code false} if you prefer a {@code null} value if the cookie is * not present in the request. * <p>Alternatively, provide a {@link #defaultValue}, which implicitly * sets this flag to {@code false}. */ boolean required() default true; /** * The default value to use as a fallback. * <p>Supplying a default value implicitly sets {@link #required} to * {@code false}. */ String defaultValue() default ValueConstants.DEFAULT_NONE; }
CookieValue
java
apache__camel
core/camel-base/src/main/java/org/apache/camel/impl/converter/AnnotationTypeConverterLoader.java
{ "start": 13579, "end": 14068 }
class ____ to ignore the type converter when having load errors if (AnnotationHelper.hasAnnotation(type, Converter.class, true)) { if (type.getAnnotation(Converter.class) != null) { ignore = type.getAnnotation(Converter.class).ignoreOnLoadError(); } } // if we should ignore then only log at debug level if (ignore) { LOG.debug("Ignoring converter type: {} as a dependent
allow
java
playframework__playframework
web/play-java-forms/src/main/java/play/data/validation/Constraints.java
{ "start": 15981, "end": 16094 }
interface ____ { Email[] value(); } } /** Validator for {@code @Email} fields. */ public static
List
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/RequestToViewNameTranslator.java
{ "start": 1011, "end": 1452 }
interface ____ { /** * Translate the given {@link HttpServletRequest} into a view name. * @param request the incoming {@link HttpServletRequest} providing * the context from which a view name is to be resolved * @return the view name, or {@code null} if no default found * @throws Exception if view name translation fails */ @Nullable String getViewName(HttpServletRequest request) throws Exception; }
RequestToViewNameTranslator
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java
{ "start": 55211, "end": 55391 }
class ____ implements DynamicIntroductionAdvice { @Override public boolean implementsInterface(Class<?> intf) { return true; } } public static
DummyIntroductionAdviceImpl
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/RequestPartMethodArgumentResolver.java
{ "start": 5994, "end": 6381 }
class ____ extends ServerHttpRequestDecorator { private final Part part; public PartServerHttpRequest(ServerHttpRequest delegate, Part part) { super(delegate); this.part = part; } @Override public HttpHeaders getHeaders() { return this.part.headers(); } @Override public Flux<DataBuffer> getBody() { return this.part.content(); } } }
PartServerHttpRequest
java
spring-projects__spring-security
cas/src/test/java/org/springframework/security/cas/web/CasGatewayResolverRequestMatcherTests.java
{ "start": 1061, "end": 2499 }
class ____ { CasGatewayResolverRequestMatcher matcher = new CasGatewayResolverRequestMatcher(new ServiceProperties()); @Test void constructorWhenServicePropertiesNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> new CasGatewayResolverRequestMatcher(null)) .withMessage("serviceProperties cannot be null"); } @Test void matchesWhenAlreadyGatewayedThenReturnsFalse() { MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession().setAttribute("_const_cas_gateway_", "yes"); boolean matches = this.matcher.matches(request); assertThat(matches).isFalse(); } @Test void matchesWhenNotGatewayedThenReturnsTrue() { MockHttpServletRequest request = new MockHttpServletRequest(); boolean matches = this.matcher.matches(request); assertThat(matches).isTrue(); } @Test void matchesWhenNoSessionThenReturnsTrue() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(null); boolean matches = this.matcher.matches(request); assertThat(matches).isTrue(); } @Test void matchesWhenNotGatewayedAndCheckedAgainThenSavesAsGatewayedAndReturnsFalse() { MockHttpServletRequest request = new MockHttpServletRequest(); boolean matches = this.matcher.matches(request); boolean secondMatch = this.matcher.matches(request); assertThat(matches).isTrue(); assertThat(secondMatch).isFalse(); } }
CasGatewayResolverRequestMatcherTests
java
google__error-prone
core/src/test/java/com/google/errorprone/fixes/SuggestedFixesTest.java
{ "start": 32995, "end": 33326 }
class ____ { public static void verifyNotNull(int a) {} } """) .expectUnchanged() .addInputLines( "Test.java", """ import static com.google.common.base.Preconditions.checkNotNull; import static pkg.Lib.verifyNotNull;
Lib
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/signatures/IncomingsTest.java
{ "start": 654, "end": 1267 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(ProducerOnA.class, ProducerOnB.class, MyBeanUsingMultipleIncomings.class)); @Inject MyBeanUsingMultipleIncomings bean; @Test public void testIncomingsWithTwoSources() { await().until(() -> bean.list().size() == 6); assertThat(bean.list()).containsSubsequence("a", "b", "c"); assertThat(bean.list()).containsSubsequence("d", "e", "f"); } @ApplicationScoped public static
IncomingsTest
java
google__dagger
javatests/dagger/hilt/android/OptionalInjectTestClasses.java
{ "start": 4443, "end": 4885 }
class ____ { @Provides static String provideAppString() { return APP_BINDING; } @Provides @ActivityLevel static String provideActivityString() { return ACTIVITY_BINDING; } @Provides @FragmentLevel static String provideFragmentString() { return FRAGMENT_BINDING; } @Provides @ViewLevel static String provideViewString() { return VIEW_BINDING; } } }
AppModule
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/support/ExecutorSubscribableChannel.java
{ "start": 3524, "end": 6063 }
class ____ implements MessageHandlingRunnable { private final Message<?> inputMessage; private final MessageHandler messageHandler; private int interceptorIndex = -1; public SendTask(Message<?> message, MessageHandler messageHandler) { this.inputMessage = message; this.messageHandler = messageHandler; } @Override public Message<?> getMessage() { return this.inputMessage; } @Override public MessageHandler getMessageHandler() { return this.messageHandler; } @Override public void run() { Message<?> message = this.inputMessage; try { message = applyBeforeHandle(message); if (message == null) { return; } this.messageHandler.handleMessage(message); triggerAfterMessageHandled(message, null); } catch (Exception ex) { triggerAfterMessageHandled(message, ex); if (ex instanceof MessagingException messagingException) { throw messagingException; } String description = "Failed to handle " + message + " to " + this + " in " + this.messageHandler; throw new MessageDeliveryException(message, description, ex); } catch (Throwable err) { String description = "Failed to handle " + message + " to " + this + " in " + this.messageHandler; MessageDeliveryException ex2 = new MessageDeliveryException(message, description, err); triggerAfterMessageHandled(message, ex2); throw ex2; } } private @Nullable Message<?> applyBeforeHandle(Message<?> message) { Message<?> messageToUse = message; for (ExecutorChannelInterceptor interceptor : executorInterceptors) { messageToUse = interceptor.beforeHandle(messageToUse, ExecutorSubscribableChannel.this, this.messageHandler); if (messageToUse == null) { String name = interceptor.getClass().getSimpleName(); if (logger.isDebugEnabled()) { logger.debug(name + " returned null from beforeHandle, i.e. precluding the send."); } triggerAfterMessageHandled(message, null); return null; } this.interceptorIndex++; } return messageToUse; } private void triggerAfterMessageHandled(Message<?> message, @Nullable Exception ex) { for (int i = this.interceptorIndex; i >= 0; i--) { ExecutorChannelInterceptor interceptor = executorInterceptors.get(i); try { interceptor.afterMessageHandled(message, ExecutorSubscribableChannel.this, this.messageHandler, ex); } catch (Throwable ex2) { logger.error("Exception from afterMessageHandled in " + interceptor, ex2); } } } } }
SendTask
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/lib/MutableInverseQuantiles.java
{ "start": 1740, "end": 3887 }
class ____ extends Quantile { InversePercentile(double inversePercentile) { super(inversePercentile/100, inversePercentile/1000); } } @VisibleForTesting public static final Quantile[] INVERSE_QUANTILES = {new InversePercentile(50), new InversePercentile(25), new InversePercentile(10), new InversePercentile(5), new InversePercentile(1)}; /** * Instantiates a new {@link MutableInverseQuantiles} for a metric that rolls itself * over on the specified time interval. * * @param name of the metric * @param description long-form textual description of the metric * @param sampleName type of items in the stream (e.g., "Ops") * @param valueName type of the values * @param intervalSecs rollover interval (in seconds) of the estimator */ public MutableInverseQuantiles(String name, String description, String sampleName, String valueName, int intervalSecs) { super(name, description, sampleName, valueName, intervalSecs); } /** * Sets quantileInfo. * * @param ucName capitalized name of the metric * @param uvName capitalized type of the values * @param desc uncapitalized long-form textual description of the metric * @param lvName uncapitalized type of the values * @param df Number formatter for inverse percentile value */ void setQuantiles(String ucName, String uvName, String desc, String lvName, DecimalFormat df) { for (int i = 0; i < INVERSE_QUANTILES.length; i++) { double inversePercentile = 100 * (1 - INVERSE_QUANTILES[i].quantile); String nameTemplate = ucName + df.format(inversePercentile) + "thInversePercentile" + uvName; String descTemplate = df.format(inversePercentile) + " inverse percentile " + lvName + " with " + getInterval() + " second interval for " + desc; addQuantileInfo(i, info(nameTemplate, descTemplate)); } } /** * Returns the array of Inverse Quantiles declared in MutableInverseQuantiles. * * @return array of Inverse Quantiles */ public synchronized Quantile[] getQuantiles() { return INVERSE_QUANTILES; } }
InversePercentile
java
quarkusio__quarkus
integration-tests/kafka-devservices/src/test/java/io/quarkus/it/kafka/continuoustesting/BaseDevServiceTest.java
{ "start": 361, "end": 4053 }
class ____ { static List<Container> getAllContainers() { return DockerClientFactory.lazyClient().listContainersCmd().exec().stream() .toList(); } static List<Container> getAllContainers(LaunchMode launchMode) { return DockerClientFactory.lazyClient().listContainersCmd().exec().stream() .filter(container -> getLaunchMode(container) == launchMode) .toList(); } static List<Container> getKafkaContainers() { return DockerClientFactory.lazyClient().listContainersCmd().exec().stream() .filter(BaseDevServiceTest::isKafkaContainer) .toList(); } static List<Container> getKafkaContainers(LaunchMode launchMode) { return DockerClientFactory.lazyClient().listContainersCmd().exec().stream() .filter(BaseDevServiceTest::isKafkaContainer) .filter(container -> getLaunchMode(container) == launchMode) .toList(); } static void stopAllContainers() { DockerClientFactory.lazyClient().listContainersCmd().exec().stream() .filter(BaseDevServiceTest::isKafkaContainer) .forEach(c -> DockerClientFactory.lazyClient().stopContainerCmd(c.getId()).exec()); } static List<Container> getKafkaContainersExcludingExisting(Collection<Container> existingContainers) { return getKafkaContainers().stream() .filter(container -> existingContainers.stream().noneMatch( existing -> existing.getId().equals(container.getId()))) .toList(); } static List<Container> getKafkaContainersExcludingExisting(LaunchMode launchMode, Collection<Container> existingContainers) { return getKafkaContainers(launchMode).stream() .filter(container -> existingContainers.stream().noneMatch( existing -> existing.getId().equals(container.getId()))) .toList(); } static List<Container> getAllContainersExcludingExisting(Collection<Container> existingContainers) { return getAllContainers().stream().filter( container -> existingContainers.stream().noneMatch( existing -> existing.getId().equals(container.getId()))) .toList(); } static List<Container> getAllContainersExcludingExisting(LaunchMode launchMode, Collection<Container> existingContainers) { return getAllContainers(launchMode).stream().filter( container -> existingContainers.stream().noneMatch( existing -> existing.getId().equals(container.getId()))) .toList(); } static LaunchMode getLaunchMode(Container container) { String launchMode = container.getLabels().get(Labels.QUARKUS_LAUNCH_MODE); return launchMode == null ? null : LaunchMode.valueOf(launchMode.toUpperCase()); } static boolean isKafkaContainer(Container container) { // This could be redpanda or kafka-native or other variants return container.getImage().contains("kafka") || container.getImage().contains("redpanda"); } static String prettyPrintContainerList(List<Container> newContainers) { return newContainers.stream() .map(c -> Arrays.toString(c.getPorts()) + " -- " + Arrays.toString(c.getNames()) + " -- " + c.getLabels()) .collect(Collectors.joining(", \n")); } static boolean hasPublicPort(Container newContainer, int newPort) { return Arrays.stream(newContainer.getPorts()).anyMatch(p -> p.getPublicPort() == newPort); } }
BaseDevServiceTest
java
resilience4j__resilience4j
resilience4j-rxjava2/src/main/java/io/github/resilience4j/micrometer/transformer/FlowableTimer.java
{ "start": 920, "end": 1328 }
class ____<T> extends Flowable<T> { private final Timer timer; private final Publisher<T> upstream; FlowableTimer(Publisher<T> upstream, Timer timer) { this.timer = timer; this.upstream = upstream; } @Override protected void subscribeActual(Subscriber<? super T> downstream) { upstream.subscribe(new TimerSubscriber(downstream, timer)); }
FlowableTimer
java
spring-projects__spring-framework
spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/AbstractStompBrokerRelayIntegrationTests.java
{ "start": 17633, "end": 18190 }
class ____ extends StompFrameMessageMatcher { private final String receiptId; public StompReceiptFrameMessageMatcher(String sessionId, String receipt) { super(StompCommand.RECEIPT, sessionId); this.receiptId = receipt; } @Override protected boolean matchInternal(StompHeaderAccessor headers, Object payload) { return (this.receiptId.equals(headers.getReceiptId())); } @Override public String toString() { return super.toString() + ", receiptId=\"" + this.receiptId + "\""; } } private static
StompReceiptFrameMessageMatcher
java
google__truth
extensions/proto/src/main/java/com/google/common/truth/extensions/proto/IterableOfProtosSubject.java
{ "start": 2756, "end": 30781 }
class ____<M extends Message> extends IterableSubject { /* * Storing a FailureMetadata instance in a Subject subclass is generally a bad practice. For an * explanation of why it works out OK here, see LiteProtoSubject. */ private final FailureMetadata metadata; private final @Nullable Iterable<M> actual; private final FluentEqualityConfig config; private final TextFormat.Printer protoPrinter; protected IterableOfProtosSubject( FailureMetadata failureMetadata, @Nullable Iterable<M> messages) { this(failureMetadata, FluentEqualityConfig.defaultInstance(), messages); } IterableOfProtosSubject( FailureMetadata failureMetadata, FluentEqualityConfig config, @Nullable Iterable<M> messages) { super(failureMetadata, messages); this.metadata = failureMetadata; this.actual = messages; this.config = config; this.protoPrinter = TextFormat.printer().usingTypeRegistry(config.useTypeRegistry()); } @Override protected String actualCustomStringRepresentation() { if (actual == null) { return "null"; } StringBuilder sb = new StringBuilder().append('['); boolean first = true; for (M element : actual) { if (!first) { sb.append(", "); } first = false; try { protoPrinter.print(element, sb); } catch (IOException impossible) { throw new AssertionError(impossible); } } return sb.append(']').toString(); } /** * Specifies a way to pair up unexpected and missing elements in the message when an assertion * fails. For example: * * <pre>{@code * assertThat(actualFoos) * .ignoringRepeatedFieldOrder() * .ignoringFields(Foo.BAR_FIELD_NUMBER) * .displayingDiffsPairedBy(Foo::getId) * .containsExactlyElementsIn(expectedFoos); * }</pre> * * <p>On assertions where it makes sense to do so, the elements are paired as follows: they are * keyed by {@code keyFunction}, and if an unexpected element and a missing element have the same * non-null key then the they are paired up. (Elements with null keys are not paired.) The failure * message will show paired elements together, and a diff will be shown. * * <p>The expected elements given in the assertion should be uniquely keyed by {@code * keyFunction}. If multiple missing elements have the same key then the pairing will be skipped. * * <p>Useful key functions will have the property that key equality is less strict than the * already specified equality rules; i.e. given {@code actual} and {@code expected} values with * keys {@code actualKey} and {@code expectedKey}, if {@code actual} and {@code expected} compare * equal given the rest of the directives such as {@code ignoringRepeatedFieldOrder} and {@code * ignoringFields}, then it is guaranteed that {@code actualKey} is equal to {@code expectedKey}, * but there are cases where {@code actualKey} is equal to {@code expectedKey} but the direct * comparison fails. * * <p>Note that calling this method makes no difference to whether a test passes or fails, it just * improves the message if it fails. */ public IterableOfProtosUsingCorrespondence<M> displayingDiffsPairedBy( Function<? super M, ?> keyFunction) { return usingCorrespondence().displayingDiffsPairedBy(keyFunction); } ////////////////////////////////////////////////////////////////////////////////////////////////// // ProtoFluentAssertion Configuration ////////////////////////////////////////////////////////////////////////////////////////////////// IterableOfProtosFluentAssertion<M> usingConfig(FluentEqualityConfig newConfig) { return new IterableOfProtosFluentAssertionImpl<>( new IterableOfProtosSubject<>(metadata, newConfig, actual)); } /** * Specifies that the 'has' bit of individual fields should be ignored when comparing for * equality. * * <p>For version 2 Protocol Buffers, this setting determines whether two protos with the same * value for a field compare equal if one explicitly sets the value, and the other merely * implicitly uses the schema-defined default. This setting also determines whether unknown fields * should be considered in the comparison. By {@code ignoringFieldAbsence()}, unknown fields are * ignored, and value-equal fields as specified above are considered equal. * * <p>For version 3 Protocol Buffers, this setting does not affect primitive fields, because their * default value is indistinguishable from unset. */ public IterableOfProtosFluentAssertion<M> ignoringFieldAbsence() { return usingConfig(config.ignoringFieldAbsence()); } /** * Specifies that the 'has' bit of these explicitly specified top-level field numbers should be * ignored when comparing for equality. Sub-fields must be specified explicitly (via {@link * FieldDescriptor}) if they are to be ignored as well. * * <p>Use {@link #ignoringFieldAbsence()} instead to ignore the 'has' bit for all fields. * * @see #ignoringFieldAbsence() for details */ public IterableOfProtosFluentAssertion<M> ignoringFieldAbsenceOfFields( int firstFieldNumber, int... rest) { return usingConfig(config.ignoringFieldAbsenceOfFields(asList(firstFieldNumber, rest))); } /** * Specifies that the 'has' bit of these explicitly specified top-level field numbers should be * ignored when comparing for equality. Sub-fields must be specified explicitly (via {@link * FieldDescriptor}) if they are to be ignored as well. * * <p>Use {@link #ignoringFieldAbsence()} instead to ignore the 'has' bit for all fields. * * @see #ignoringFieldAbsence() for details */ public IterableOfProtosFluentAssertion<M> ignoringFieldAbsenceOfFields( Iterable<Integer> fieldNumbers) { return usingConfig(config.ignoringFieldAbsenceOfFields(fieldNumbers)); } /** * Specifies that the 'has' bit of these explicitly specified field descriptors should be ignored * when comparing for equality. Sub-fields must be specified explicitly if they are to be ignored * as well. * * <p>Use {@link #ignoringFieldAbsence()} instead to ignore the 'has' bit for all fields. * * @see #ignoringFieldAbsence() for details */ public IterableOfProtosFluentAssertion<M> ignoringFieldAbsenceOfFieldDescriptors( FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return usingConfig( config.ignoringFieldAbsenceOfFieldDescriptors(asList(firstFieldDescriptor, rest))); } /** * Specifies that the 'has' bit of these explicitly specified field descriptors should be ignored * when comparing for equality. Sub-fields must be specified explicitly if they are to be ignored * as well. * * <p>Use {@link #ignoringFieldAbsence()} instead to ignore the 'has' bit for all fields. * * @see #ignoringFieldAbsence() for details */ public IterableOfProtosFluentAssertion<M> ignoringFieldAbsenceOfFieldDescriptors( Iterable<FieldDescriptor> fieldDescriptors) { return usingConfig(config.ignoringFieldAbsenceOfFieldDescriptors(fieldDescriptors)); } /** * Specifies that the ordering of repeated fields, at all levels, should be ignored when comparing * for equality. * * <p>This setting applies to all repeated fields recursively, but it does not ignore structure. * For example, with {@link #ignoringRepeatedFieldOrder()}, a repeated {@code int32} field {@code * bar}, set inside a repeated message field {@code foo}, the following protos will all compare * equal: * * <pre>{@code * message1: { * foo: { * bar: 1 * bar: 2 * } * foo: { * bar: 3 * bar: 4 * } * } * * message2: { * foo: { * bar: 2 * bar: 1 * } * foo: { * bar: 4 * bar: 3 * } * } * * message3: { * foo: { * bar: 4 * bar: 3 * } * foo: { * bar: 2 * bar: 1 * } * } * }</pre> * * <p>However, the following message will compare equal to none of these: * * <pre>{@code * message4: { * foo: { * bar: 1 * bar: 3 * } * foo: { * bar: 2 * bar: 4 * } * } * }</pre> * * <p>This setting does not apply to map fields, for which field order is always ignored. The * serialization order of map fields is undefined, and it may change from runtime to runtime. */ public IterableOfProtosFluentAssertion<M> ignoringRepeatedFieldOrder() { return usingConfig(config.ignoringRepeatedFieldOrder()); } /** * Specifies that the ordering of repeated fields for these explicitly specified top-level field * numbers should be ignored when comparing for equality. Sub-fields must be specified explicitly * (via {@link FieldDescriptor}) if their orders are to be ignored as well. * * <p>Use {@link #ignoringRepeatedFieldOrder()} instead to ignore order for all fields. * * @see #ignoringRepeatedFieldOrder() for details. */ public IterableOfProtosFluentAssertion<M> ignoringRepeatedFieldOrderOfFields( int firstFieldNumber, int... rest) { return usingConfig(config.ignoringRepeatedFieldOrderOfFields(asList(firstFieldNumber, rest))); } /** * Specifies that the ordering of repeated fields for these explicitly specified top-level field * numbers should be ignored when comparing for equality. Sub-fields must be specified explicitly * (via {@link FieldDescriptor}) if their orders are to be ignored as well. * * <p>Use {@link #ignoringRepeatedFieldOrder()} instead to ignore order for all fields. * * @see #ignoringRepeatedFieldOrder() for details. */ public IterableOfProtosFluentAssertion<M> ignoringRepeatedFieldOrderOfFields( Iterable<Integer> fieldNumbers) { return usingConfig(config.ignoringRepeatedFieldOrderOfFields(fieldNumbers)); } /** * Specifies that the ordering of repeated fields for these explicitly specified field descriptors * should be ignored when comparing for equality. Sub-fields must be specified explicitly if their * orders are to be ignored as well. * * <p>Use {@link #ignoringRepeatedFieldOrder()} instead to ignore order for all fields. * * @see #ignoringRepeatedFieldOrder() for details. */ public IterableOfProtosFluentAssertion<M> ignoringRepeatedFieldOrderOfFieldDescriptors( FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return usingConfig( config.ignoringRepeatedFieldOrderOfFieldDescriptors(asList(firstFieldDescriptor, rest))); } /** * Specifies that the ordering of repeated fields for these explicitly specified field descriptors * should be ignored when comparing for equality. Sub-fields must be specified explicitly if their * orders are to be ignored as well. * * <p>Use {@link #ignoringRepeatedFieldOrder()} instead to ignore order for all fields. * * @see #ignoringRepeatedFieldOrder() for details. */ public IterableOfProtosFluentAssertion<M> ignoringRepeatedFieldOrderOfFieldDescriptors( Iterable<FieldDescriptor> fieldDescriptors) { return usingConfig(config.ignoringRepeatedFieldOrderOfFieldDescriptors(fieldDescriptors)); } /** * Specifies that, for all repeated and map fields, any elements in the 'actual' proto which are * not found in the 'expected' proto are ignored, with the exception of fields in the expected * proto which are empty. To ignore empty repeated fields as well, use {@link * #comparingExpectedFieldsOnly}. * * <p>This rule is applied independently from {@link #ignoringRepeatedFieldOrder}. If ignoring * repeated field order AND extra repeated field elements, all that is tested is that the expected * elements comprise a subset of the actual elements. If not ignoring repeated field order, but * still ignoring extra repeated field elements, the actual elements must contain a subsequence * that matches the expected elements for the test to pass. (The subsequence rule does not apply * to Map fields, which are always compared by key.) */ public IterableOfProtosFluentAssertion<M> ignoringExtraRepeatedFieldElements() { return usingConfig(config.ignoringExtraRepeatedFieldElements()); } /** * Specifies that extra repeated field elements for these explicitly specified top-level field * numbers should be ignored. Sub-fields must be specified explicitly (via {@link * FieldDescriptor}) if their extra elements are to be ignored as well. * * <p>Use {@link #ignoringExtraRepeatedFieldElements()} instead to ignore these for all fields. * * @see #ignoringExtraRepeatedFieldElements() for details. */ public IterableOfProtosFluentAssertion<M> ignoringExtraRepeatedFieldElementsOfFields( int firstFieldNumber, int... rest) { return usingConfig( config.ignoringExtraRepeatedFieldElementsOfFields(asList(firstFieldNumber, rest))); } /** * Specifies that extra repeated field elements for these explicitly specified top-level field * numbers should be ignored. Sub-fields must be specified explicitly (via {@link * FieldDescriptor}) if their extra elements are to be ignored as well. * * <p>Use {@link #ignoringExtraRepeatedFieldElements()} instead to ignore these for all fields. * * @see #ignoringExtraRepeatedFieldElements() for details. */ public IterableOfProtosFluentAssertion<M> ignoringExtraRepeatedFieldElementsOfFields( Iterable<Integer> fieldNumbers) { return usingConfig(config.ignoringExtraRepeatedFieldElementsOfFields(fieldNumbers)); } /** * Specifies that extra repeated field elements for these explicitly specified field descriptors * should be ignored. Sub-fields must be specified explicitly if their extra elements are to be * ignored as well. * * <p>Use {@link #ignoringExtraRepeatedFieldElements()} instead to ignore these for all fields. * * @see #ignoringExtraRepeatedFieldElements() for details. */ public IterableOfProtosFluentAssertion<M> ignoringExtraRepeatedFieldElementsOfFieldDescriptors( FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return usingConfig( config.ignoringExtraRepeatedFieldElementsOfFieldDescriptors( asList(firstFieldDescriptor, rest))); } /** * Specifies that extra repeated field elements for these explicitly specified field descriptors * should be ignored. Sub-fields must be specified explicitly if their extra elements are to be * ignored as well. * * <p>Use {@link #ignoringExtraRepeatedFieldElements()} instead to ignore these for all fields. * * @see #ignoringExtraRepeatedFieldElements() for details. */ public IterableOfProtosFluentAssertion<M> ignoringExtraRepeatedFieldElementsOfFieldDescriptors( Iterable<FieldDescriptor> fieldDescriptors) { return usingConfig( config.ignoringExtraRepeatedFieldElementsOfFieldDescriptors(fieldDescriptors)); } /** * Compares double fields as equal if they are both finite and their absolute difference is less * than or equal to {@code tolerance}. * * @param tolerance A finite, non-negative tolerance. */ public IterableOfProtosFluentAssertion<M> usingDoubleTolerance(double tolerance) { return usingConfig(config.usingDoubleTolerance(tolerance)); } /** * Compares double fields with these explicitly specified top-level field numbers using the * provided absolute tolerance. * * @param tolerance A finite, non-negative tolerance. */ public IterableOfProtosFluentAssertion<M> usingDoubleToleranceForFields( double tolerance, int firstFieldNumber, int... rest) { return usingConfig( config.usingDoubleToleranceForFields(tolerance, asList(firstFieldNumber, rest))); } /** * Compares double fields with these explicitly specified top-level field numbers using the * provided absolute tolerance. * * @param tolerance A finite, non-negative tolerance. */ public IterableOfProtosFluentAssertion<M> usingDoubleToleranceForFields( double tolerance, Iterable<Integer> fieldNumbers) { return usingConfig(config.usingDoubleToleranceForFields(tolerance, fieldNumbers)); } /** * Compares double fields with these explicitly specified fields using the provided absolute * tolerance. * * @param tolerance A finite, non-negative tolerance. */ public IterableOfProtosFluentAssertion<M> usingDoubleToleranceForFieldDescriptors( double tolerance, FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return usingConfig( config.usingDoubleToleranceForFieldDescriptors( tolerance, asList(firstFieldDescriptor, rest))); } /** * Compares double fields with these explicitly specified fields using the provided absolute * tolerance. * * @param tolerance A finite, non-negative tolerance. */ public IterableOfProtosFluentAssertion<M> usingDoubleToleranceForFieldDescriptors( double tolerance, Iterable<FieldDescriptor> fieldDescriptors) { return usingConfig(config.usingDoubleToleranceForFieldDescriptors(tolerance, fieldDescriptors)); } /** * Compares float fields as equal if they are both finite and their absolute difference is less * than or equal to {@code tolerance}. * * @param tolerance A finite, non-negative tolerance. */ public IterableOfProtosFluentAssertion<M> usingFloatTolerance(float tolerance) { return usingConfig(config.usingFloatTolerance(tolerance)); } /** * Compares float fields with these explicitly specified top-level field numbers using the * provided absolute tolerance. * * @param tolerance A finite, non-negative tolerance. */ public IterableOfProtosFluentAssertion<M> usingFloatToleranceForFields( float tolerance, int firstFieldNumber, int... rest) { return usingConfig( config.usingFloatToleranceForFields(tolerance, asList(firstFieldNumber, rest))); } /** * Compares float fields with these explicitly specified top-level field numbers using the * provided absolute tolerance. * * @param tolerance A finite, non-negative tolerance. */ public IterableOfProtosFluentAssertion<M> usingFloatToleranceForFields( float tolerance, Iterable<Integer> fieldNumbers) { return usingConfig(config.usingFloatToleranceForFields(tolerance, fieldNumbers)); } /** * Compares float fields with these explicitly specified fields using the provided absolute * tolerance. * * @param tolerance A finite, non-negative tolerance. */ public IterableOfProtosFluentAssertion<M> usingFloatToleranceForFieldDescriptors( float tolerance, FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return usingConfig( config.usingFloatToleranceForFieldDescriptors( tolerance, asList(firstFieldDescriptor, rest))); } /** * Compares float fields with these explicitly specified top-level field numbers using the * provided absolute tolerance. * * @param tolerance A finite, non-negative tolerance. */ public IterableOfProtosFluentAssertion<M> usingFloatToleranceForFieldDescriptors( float tolerance, Iterable<FieldDescriptor> fieldDescriptors) { return usingConfig(config.usingFloatToleranceForFieldDescriptors(tolerance, fieldDescriptors)); } /** * Limits the comparison of Protocol buffers to the fields set in the expected proto(s). When * multiple protos are specified, the comparison is limited to the union of set fields in all the * expected protos. * * <p>The "expected proto(s)" are those passed to the method in {@link * IterableOfProtosUsingCorrespondence} at the end of the call-chain. * * <p>Fields not set in the expected proto(s) are ignored. In particular, proto3 fields which have * their default values are ignored, as these are indistinguishable from unset fields. If you want * to assert that a proto3 message has certain fields with default values, you cannot use this * method. */ public IterableOfProtosFluentAssertion<M> comparingExpectedFieldsOnly() { return usingConfig(config.comparingExpectedFieldsOnly()); } /** * Limits the comparison of Protocol buffers to the defined {@link FieldScope}. * * <p>This method is additive and has well-defined ordering semantics. If the invoking {@link * ProtoFluentAssertion} is already scoped to a {@link FieldScope} {@code X}, and this method is * invoked with {@link FieldScope} {@code Y}, the resultant {@link ProtoFluentAssertion} is * constrained to the intersection of {@link FieldScope}s {@code X} and {@code Y}. * * <p>By default, {@link ProtoFluentAssertion} is constrained to {@link FieldScopes#all()}, that * is, no fields are excluded from comparison. */ public IterableOfProtosFluentAssertion<M> withPartialScope(FieldScope fieldScope) { return usingConfig(config.withPartialScope(checkNotNull(fieldScope, "fieldScope"))); } /** * Excludes the top-level message fields with the given tag numbers from the comparison. * * <p>This method adds on any previous {@link FieldScope} related settings, overriding previous * changes to ensure the specified fields are ignored recursively. All sub-fields of these field * numbers are ignored, and all sub-messages of type {@code M} will also have these field numbers * ignored. * * <p>If an invalid field number is supplied, the terminal comparison operation will throw a * runtime exception. */ public IterableOfProtosFluentAssertion<M> ignoringFields(int firstFieldNumber, int... rest) { return ignoringFields(asList(firstFieldNumber, rest)); } /** * Excludes the top-level message fields with the given tag numbers from the comparison. * * <p>This method adds on any previous {@link FieldScope} related settings, overriding previous * changes to ensure the specified fields are ignored recursively. All sub-fields of these field * numbers are ignored, and all sub-messages of type {@code M} will also have these field numbers * ignored. * * <p>If an invalid field number is supplied, the terminal comparison operation will throw a * runtime exception. */ public IterableOfProtosFluentAssertion<M> ignoringFields(Iterable<Integer> fieldNumbers) { return usingConfig(config.ignoringFields(fieldNumbers)); } /** * Excludes all message fields matching the given {@link FieldDescriptor}s from the comparison. * * <p>This method adds on any previous {@link FieldScope} related settings, overriding previous * changes to ensure the specified fields are ignored recursively. All sub-fields of these field * descriptors are ignored, no matter where they occur in the tree. * * <p>If a field descriptor which does not, or cannot occur in the proto structure is supplied, it * is silently ignored. */ public IterableOfProtosFluentAssertion<M> ignoringFieldDescriptors( FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) { return ignoringFieldDescriptors(asList(firstFieldDescriptor, rest)); } /** * Excludes all message fields matching the given {@link FieldDescriptor}s from the comparison. * * <p>This method adds on any previous {@link FieldScope} related settings, overriding previous * changes to ensure the specified fields are ignored recursively. All sub-fields of these field * descriptors are ignored, no matter where they occur in the tree. * * <p>If a field descriptor which does not, or cannot occur in the proto structure is supplied, it * is silently ignored. */ public IterableOfProtosFluentAssertion<M> ignoringFieldDescriptors( Iterable<FieldDescriptor> fieldDescriptors) { return usingConfig(config.ignoringFieldDescriptors(fieldDescriptors)); } /** * Excludes all specific field paths under the argument {@link FieldScope} from the comparison. * * <p>This method is additive and has well-defined ordering semantics. If the invoking {@link * ProtoFluentAssertion} is already scoped to a {@link FieldScope} {@code X}, and this method is * invoked with {@link FieldScope} {@code Y}, the resultant {@link ProtoFluentAssertion} is * constrained to the subtraction of {@code X - Y}. * * <p>By default, {@link ProtoFluentAssertion} is constrained to {@link FieldScopes#all()}, that * is, no fields are excluded from comparison. */ public IterableOfProtosFluentAssertion<M> ignoringFieldScope(FieldScope fieldScope) { return usingConfig(config.ignoringFieldScope(checkNotNull(fieldScope, "fieldScope"))); } /** * If set, in the event of a comparison failure, the error message printed will list only those * specific fields that did not match between the actual and expected values. Useful for very * large protocol buffers. * * <p>This a purely cosmetic setting, and it has no effect on the behavior of the test. */ public IterableOfProtosFluentAssertion<M> reportingMismatchesOnly() { return usingConfig(config.reportingMismatchesOnly()); } /** * Specifies the {@link TypeRegistry} and {@link ExtensionRegistry} to use for {@link * com.google.protobuf.Any Any} messages. * * <p>To compare the value of an {@code Any} message, ProtoTruth looks in the given type registry * for a descriptor for the message's type URL: * * <ul> * <li>If ProtoTruth finds a descriptor, it unpacks the value and compares it against the * expected value, respecting any configuration methods used for the assertion. * <li>If ProtoTruth does not find a descriptor (or if the value can't be deserialized with the * descriptor), it compares the raw, serialized bytes of the expected and actual values. * </ul> * * <p>When ProtoTruth unpacks a value, it is parsing a serialized proto. That proto may contain * extensions. To look up those extensions, ProtoTruth uses the provided {@link * ExtensionRegistry}. * * @since 1.1 */ public IterableOfProtosFluentAssertion<M> unpackingAnyUsing( TypeRegistry typeRegistry, ExtensionRegistry extensionRegistry) { return usingConfig(config.unpackingAnyUsing(typeRegistry, extensionRegistry)); } ////////////////////////////////////////////////////////////////////////////////////////////////// // Overrides for IterableSubject Methods ////////////////////////////////////////////////////////////////////////////////////////////////// /** * @deprecated Protos do not implement {@link Comparable}, so you must {@linkplain * #isInStrictOrder(Comparator) supply a comparator}. * @throws ClassCastException always */ @Override @Deprecated public final void isInStrictOrder() { throw new ClassCastException( "Protos do not implement Comparable, so you must supply a Comparator."); } /** * @deprecated Protos do not implement {@link Comparable}, so you must {@linkplain * #isInOrder(Comparator) supply a comparator}. * @throws ClassCastException always */ @Override @Deprecated public final void isInOrder() { throw new ClassCastException( "Protos do not implement Comparable, so you must supply a Comparator."); } ////////////////////////////////////////////////////////////////////////////////////////////////// // UsingCorrespondence Methods ////////////////////////////////////////////////////////////////////////////////////////////////// // A forwarding implementation of IterableSubject.UsingCorrespondence which passes the expected // protos to FluentEqualityConfig before comparing. This is required to support // displayingDiffsPairedBy(), since we can't pass the user to a vanilla // IterableSubject.UsingCorrespondence until we know what the expected messages are. private static
IterableOfProtosSubject
java
apache__camel
components/camel-xslt-saxon/src/test/java/org/apache/camel/component/xslt/SaxonUriResolverTest.java
{ "start": 1402, "end": 2706 }
class ____ extends CamelTestSupport { private static final String XSL_PATH = "org/apache/camel/component/xslt/transform_includes_data.xsl"; private static final String XML_DATA = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><root>1</root>"; private static final String XML_RESP = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><MyDate>February</MyDate>"; @Test public void test() throws Exception { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); Source xsl = fromClasspath(XSL_PATH); xsl.setSystemId("classpath:/" + XSL_PATH); Source xml = fromString(XML_DATA); TransformerFactory factory = new TransformerFactoryImpl(); Transformer transformer = factory.newTransformer(xsl); transformer.setURIResolver(new XsltUriResolver(context(), XSL_PATH)); transformer.transform(xml, result); assertEquals(XML_RESP, writer.toString()); } protected Source fromString(String data) { return new StreamSource(new StringReader(data)); } protected Source fromClasspath(String path) throws IOException { return new StreamSource( ResourceHelper.resolveMandatoryResourceAsInputStream(context(), path)); } }
SaxonUriResolverTest
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/utils/ChecksumsTest.java
{ "start": 1034, "end": 3380 }
class ____ { @Test public void testUpdateByteBuffer() { byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5}; doTestUpdateByteBuffer(bytes, ByteBuffer.allocate(bytes.length)); doTestUpdateByteBuffer(bytes, ByteBuffer.allocateDirect(bytes.length)); } private void doTestUpdateByteBuffer(byte[] bytes, ByteBuffer buffer) { buffer.put(bytes); buffer.flip(); Checksum bufferCrc = new CRC32C(); Checksums.update(bufferCrc, buffer, buffer.remaining()); assertEquals(Crc32C.compute(bytes, 0, bytes.length), bufferCrc.getValue()); assertEquals(0, buffer.position()); } @Test public void testUpdateByteBufferWithOffsetPosition() { byte[] bytes = new byte[]{-2, -1, 0, 1, 2, 3, 4, 5}; doTestUpdateByteBufferWithOffsetPosition(bytes, ByteBuffer.allocate(bytes.length), 2); doTestUpdateByteBufferWithOffsetPosition(bytes, ByteBuffer.allocateDirect(bytes.length), 2); } @Test public void testUpdateInt() { final int value = 1000; final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.putInt(value); Checksum crc1 = new CRC32C(); Checksum crc2 = new CRC32C(); Checksums.updateInt(crc1, value); crc2.update(buffer.array(), buffer.arrayOffset(), 4); assertEquals(crc1.getValue(), crc2.getValue(), "Crc values should be the same"); } @Test public void testUpdateLong() { final long value = Integer.MAX_VALUE + 1; final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(value); Checksum crc1 = new CRC32C(); Checksum crc2 = new CRC32C(); Checksums.updateLong(crc1, value); crc2.update(buffer.array(), buffer.arrayOffset(), 8); assertEquals(crc1.getValue(), crc2.getValue(), "Crc values should be the same"); } private void doTestUpdateByteBufferWithOffsetPosition(byte[] bytes, ByteBuffer buffer, int offset) { buffer.put(bytes); buffer.flip(); buffer.position(offset); Checksum bufferCrc = new CRC32C(); Checksums.update(bufferCrc, buffer, buffer.remaining()); assertEquals(Crc32C.compute(bytes, offset, buffer.remaining()), bufferCrc.getValue()); assertEquals(offset, buffer.position()); } }
ChecksumsTest
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3925MergedPluginExecutionOrderTest.java
{ "start": 1153, "end": 2732 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Test that multiple plugin executions bound to the same phase by child and parent are executed in the proper * order when no {@code <pluginManagement>} is involved. * * @throws Exception in case of failure */ @Test public void testitWithoutPluginMngt() throws Exception { testitMNG3925("test-1"); } /** * Test that multiple plugin executions bound to the same phase by child and parent are executed in the proper * order when {@code <pluginManagement>} is involved. * * @throws Exception in case of failure */ @Test public void testitWithPluginMngt() throws Exception { testitMNG3925("test-2"); } private void testitMNG3925(String project) throws Exception { File testDir = extractResources("/mng-3925"); Verifier verifier = newVerifier(new File(new File(testDir, project), "sub").getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); List<String> lines = verifier.loadLines("target/exec.log"); // Order is parent first and child appended, unless child overrides parent execution via equal id List<String> expected = Arrays.asList(new String[] {"parent-1", "parent-2", "child-default", "child-1", "child-2"}); assertEquals(expected, lines); } }
MavenITmng3925MergedPluginExecutionOrderTest
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/concurrent/DiscardPolicy.java
{ "start": 966, "end": 1090 }
class ____<E> implements Rejector<E> { @Override public void reject(final E e, final Queue<E> queue) {} }
DiscardPolicy
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/YarnClient.java
{ "start": 27358, "end": 29467 }
interface ____ by clients to get the list of reservations in a plan. * The reservationId will be used to search for reservations to list if it is * provided. Otherwise, it will select active reservations within the * startTime and endTime (inclusive). * </p> * * @param request to list reservations in a plan. Contains fields to select * String queue, ReservationId reservationId, long startTime, * long endTime, and a bool includeReservationAllocations. * * queue: Required. Cannot be null or empty. Refers to the * reservable queue in the scheduler that was selected when * creating a reservation submission * {@link ReservationSubmissionRequest}. * * reservationId: Optional. If provided, other fields will * be ignored. * * startTime: Optional. If provided, only reservations that * end after the startTime will be selected. This defaults * to 0 if an invalid number is used. * * endTime: Optional. If provided, only reservations that * start on or before endTime will be selected. This defaults * to Long.MAX_VALUE if an invalid number is used. * * includeReservationAllocations: Optional. Flag that * determines whether the entire reservation allocations are * to be returned. Reservation allocations are subject to * change in the event of re-planning as described by * {@link ReservationDefinition}. * * @return response that contains information about reservations that are * being searched for. * @throws YarnException if the request is invalid * @throws IOException if the request failed otherwise * */ @Public @Unstable public abstract ReservationListResponse listReservations( ReservationListRequest request) throws YarnException, IOException; /** * <p> * The
used
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase/hadoop-yarn-server-timelineservice-hbase-common/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/entity/EntityTable.java
{ "start": 3336, "end": 3389 }
class ____ extends BaseTable<EntityTable> { }
EntityTable
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/common/util/BigArraysTests.java
{ "start": 1928, "end": 27589 }
class ____ extends ESTestCase { private final BigArrays bigArrays = new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), new NoneCircuitBreakerService()); public void testByteArrayGrowth() { final int totalLen = randomIntBetween(1, 4000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); ByteArray array = bigArrays.newByteArray(startLen, randomBoolean()); byte[] ref = new byte[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomByte(); array = bigArrays.grow(array, i + 1); array.set(i, ref[i]); } for (int i = 0; i < totalLen; ++i) { assertEquals(ref[i], array.get(i)); } array.close(); } public void testIntArrayGrowth() { final int totalLen = randomIntBetween(1, 1000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); IntArray array = bigArrays.newIntArray(startLen, randomBoolean()); int[] ref = new int[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomInt(); array = bigArrays.grow(array, i + 1); array.set(i, ref[i]); } for (int i = 0; i < totalLen; ++i) { assertEquals(ref[i], array.get(i)); } array.close(); } public void testLongArrayGrowth() { final int totalLen = randomIntBetween(1, 1000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); LongArray array = bigArrays.newLongArray(startLen, randomBoolean()); long[] ref = new long[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomLong(); array = bigArrays.grow(array, i + 1); array.set(i, ref[i]); } for (int i = 0; i < totalLen; ++i) { assertEquals(ref[i], array.get(i)); } array.close(); } public void testFloatArrayGrowth() { final int totalLen = randomIntBetween(1, 1000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); FloatArray array = bigArrays.newFloatArray(startLen, randomBoolean()); float[] ref = new float[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomFloat(); array = bigArrays.grow(array, i + 1); array.set(i, ref[i]); } for (int i = 0; i < totalLen; ++i) { assertEquals(ref[i], array.get(i), 0.001d); } array.close(); } public void testDoubleArrayGrowth() { final int totalLen = randomIntBetween(1, 1000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); DoubleArray array = bigArrays.newDoubleArray(startLen, randomBoolean()); double[] ref = new double[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomDouble(); array = bigArrays.grow(array, i + 1); array.set(i, ref[i]); } for (int i = 0; i < totalLen; ++i) { assertEquals(ref[i], array.get(i), 0.001d); } array.close(); } public void testObjectArrayGrowth() { final int totalLen = randomIntBetween(1, 1000000); final int startLen = randomIntBetween(1, randomBoolean() ? 1000 : totalLen); ObjectArray<Object> array = bigArrays.newObjectArray(startLen); final Object[] pool = new Object[100]; for (int i = 0; i < pool.length; ++i) { pool[i] = new Object(); } Object[] ref = new Object[totalLen]; for (int i = 0; i < totalLen; ++i) { ref[i] = randomFrom(pool); array = bigArrays.grow(array, i + 1); array.set(i, ref[i]); assertEquals(ref[i], array.getAndSet(i, ref[i])); } for (int i = 0; i < totalLen; ++i) { assertSame(ref[i], array.get(i)); } array.close(); } public void testByteArrayFill() { final int len = randomIntBetween(1, 100000); final int fromIndex = randomIntBetween(0, len - 1); final int toIndex = randomBoolean() ? Math.min(fromIndex + randomInt(100), len) // single page : randomIntBetween(fromIndex, len); // likely multiple pages final ByteArray array2 = bigArrays.newByteArray(len, randomBoolean()); final byte[] array1 = new byte[len]; for (int i = 0; i < len; ++i) { array1[i] = randomByte(); array2.set(i, array1[i]); } final byte rand = randomByte(); Arrays.fill(array1, fromIndex, toIndex, rand); array2.fill(fromIndex, toIndex, rand); for (int i = 0; i < len; ++i) { assertEquals(array1[i], array2.get(i), 0.001d); } array2.close(); } public void testFloatArrayFill() { final int len = randomIntBetween(1, 100000); final int fromIndex = randomIntBetween(0, len - 1); final int toIndex = randomBoolean() ? Math.min(fromIndex + randomInt(100), len) // single page : randomIntBetween(fromIndex, len); // likely multiple pages final FloatArray array2 = bigArrays.newFloatArray(len, randomBoolean()); final float[] array1 = new float[len]; for (int i = 0; i < len; ++i) { array1[i] = randomFloat(); array2.set(i, array1[i]); } final float rand = randomFloat(); Arrays.fill(array1, fromIndex, toIndex, rand); array2.fill(fromIndex, toIndex, rand); for (int i = 0; i < len; ++i) { assertEquals(array1[i], array2.get(i), 0.001d); } array2.close(); } public void testDoubleArrayFill() { final int len = randomIntBetween(1, 100000); final int fromIndex = randomIntBetween(0, len - 1); final int toIndex = randomBoolean() ? Math.min(fromIndex + randomInt(100), len) // single page : randomIntBetween(fromIndex, len); // likely multiple pages final DoubleArray array2 = bigArrays.newDoubleArray(len, randomBoolean()); final double[] array1 = new double[len]; for (int i = 0; i < len; ++i) { array1[i] = randomDouble(); array2.set(i, array1[i]); } final double rand = randomDouble(); Arrays.fill(array1, fromIndex, toIndex, rand); array2.fill(fromIndex, toIndex, rand); for (int i = 0; i < len; ++i) { assertEquals(array1[i], array2.get(i), 0.001d); } array2.close(); } public void testIntArrayFill() { final int len = randomIntBetween(1, 100000); final int fromIndex = randomIntBetween(0, len - 1); final int toIndex = randomBoolean() ? Math.min(fromIndex + randomInt(100), len) // single page : randomIntBetween(fromIndex, len); // likely multiple pages final IntArray array2 = bigArrays.newIntArray(len, randomBoolean()); final int[] array1 = new int[len]; for (int i = 0; i < len; ++i) { array1[i] = randomInt(); array2.set(i, array1[i]); } final int rand = randomInt(); Arrays.fill(array1, fromIndex, toIndex, rand); array2.fill(fromIndex, toIndex, rand); for (int i = 0; i < len; ++i) { assertEquals(array1[i], array2.get(i)); } array2.close(); } public void testLongArrayFill() { final int len = randomIntBetween(1, 100000); final int fromIndex = randomIntBetween(0, len - 1); final int toIndex = randomBoolean() ? Math.min(fromIndex + randomInt(100), len) // single page : randomIntBetween(fromIndex, len); // likely multiple pages final LongArray array2 = bigArrays.newLongArray(len, randomBoolean()); final long[] array1 = new long[len]; for (int i = 0; i < len; ++i) { array1[i] = randomLong(); array2.set(i, array1[i]); } final long rand = randomLong(); Arrays.fill(array1, fromIndex, toIndex, rand); array2.fill(fromIndex, toIndex, rand); for (int i = 0; i < len; ++i) { assertEquals(array1[i], array2.get(i)); } array2.close(); } public void testSerializeDoubleArray() throws Exception { int len = randomIntBetween(1, 100_000); DoubleArray array1 = bigArrays.newDoubleArray(len, randomBoolean()); for (int i = 0; i < len; ++i) { array1.set(i, randomDouble()); } if (randomBoolean()) { len = randomIntBetween(len, len * 3 / 2); array1 = bigArrays.resize(array1, len); } BytesStreamOutput out = new BytesStreamOutput(); array1.writeTo(out); final DoubleArray array2 = bigArrays.newDoubleArray(len, randomBoolean()); array2.fillWith(out.bytes().streamInput()); for (int i = 0; i < len; i++) { assertThat(array2.get(i), equalTo(array1.get(i))); } final DoubleArray array3 = DoubleArray.readFrom(out.bytes().streamInput()); assertThat(array3.size(), equalTo((long) len)); for (int i = 0; i < len; i++) { assertThat(array3.get(i), equalTo(array1.get(i))); } Releasables.close(array1, array2, array3); } public void testSerializeLongArray() throws Exception { int len = randomIntBetween(1, 100_000); LongArray array1 = bigArrays.newLongArray(len, randomBoolean()); for (int i = 0; i < len; ++i) { array1.set(i, randomLong()); } if (randomBoolean()) { len = randomIntBetween(len, len * 3 / 2); array1 = bigArrays.resize(array1, len); } BytesStreamOutput out = new BytesStreamOutput(); array1.writeTo(out); final LongArray array2 = bigArrays.newLongArray(len, randomBoolean()); array2.fillWith(out.bytes().streamInput()); for (int i = 0; i < len; i++) { assertThat(array2.get(i), equalTo(array1.get(i))); } final LongArray array3 = LongArray.readFrom(out.bytes().streamInput()); assertThat(array3.size(), equalTo((long) len)); for (int i = 0; i < len; i++) { assertThat(array3.get(i), equalTo(array1.get(i))); } Releasables.close(array1, array2, array3); } public void testSerializeIntArray() throws Exception { int len = randomIntBetween(1, 100_000); IntArray array1 = bigArrays.newIntArray(len, randomBoolean()); for (int i = 0; i < len; ++i) { array1.set(i, randomInt()); } if (randomBoolean()) { len = randomIntBetween(len, len * 3 / 2); array1 = bigArrays.resize(array1, len); } BytesStreamOutput out = new BytesStreamOutput(); array1.writeTo(out); final IntArray array2 = bigArrays.newIntArray(len, randomBoolean()); array2.fillWith(out.bytes().streamInput()); for (int i = 0; i < len; i++) { assertThat(array2.get(i), equalTo(array1.get(i))); } final IntArray array3 = IntArray.readFrom(out.bytes().streamInput()); assertThat(array3.size(), equalTo((long) len)); for (int i = 0; i < len; i++) { assertThat(array3.get(i), equalTo(array1.get(i))); } Releasables.close(array1, array2, array3); } public void testByteArrayBulkGet() { final byte[] array1 = new byte[randomIntBetween(1, 4000000)]; random().nextBytes(array1); final ByteArray array2 = bigArrays.newByteArray(array1.length, randomBoolean()); for (int i = 0; i < array1.length; ++i) { array2.set(i, array1[i]); } final BytesRef ref = new BytesRef(); for (int i = 0; i < 1000; ++i) { final int offset = randomInt(array1.length - 1); final int len = randomInt(Math.min(randomBoolean() ? 10 : Integer.MAX_VALUE, array1.length - offset)); array2.get(offset, len, ref); assertEquals(new BytesRef(array1, offset, len), ref); } array2.close(); } public void testByteArrayBulkSet() { final byte[] array1 = new byte[randomIntBetween(1, 4000000)]; random().nextBytes(array1); final ByteArray array2 = bigArrays.newByteArray(array1.length, randomBoolean()); for (int i = 0; i < array1.length;) { final int len = Math.min(array1.length - i, randomBoolean() ? randomInt(10) : randomInt(3 * PageCacheRecycler.BYTE_PAGE_SIZE)); array2.set(i, array1, i, len); i += len; } for (int i = 0; i < array1.length; ++i) { assertEquals(array1[i], array2.get(i)); } array2.close(); } public void testByteIterator() throws Exception { final byte[] bytes = new byte[randomIntBetween(1, 4000000)]; random().nextBytes(bytes); ByteArray array = bigArrays.newByteArray(bytes.length, randomBoolean()); array.fillWith(new ByteArrayStreamInput(bytes)); for (int i = 0; i < bytes.length; i++) { assertEquals(bytes[i], array.get(i)); } BytesRefIterator it = array.iterator(); BytesRef ref; int offset = 0; while ((ref = it.next()) != null) { for (int i = 0; i < ref.length; i++) { assertEquals(bytes[offset], ref.bytes[ref.offset + i]); offset++; } } assertThat(offset, equalTo(bytes.length)); int newLen = randomIntBetween(bytes.length, bytes.length + 100_000); array = bigArrays.resize(array, newLen); it = array.iterator(); offset = 0; while ((ref = it.next()) != null) { for (int i = 0; i < ref.length; i++) { if (offset < bytes.length) { assertEquals(bytes[offset], ref.bytes[ref.offset + i]); } offset++; } } assertThat(offset, equalTo(newLen)); array.close(); } public void testByteArrayEquals() { final ByteArray empty1 = byteArrayWithBytes(BytesRef.EMPTY_BYTES); final ByteArray empty2 = byteArrayWithBytes(BytesRef.EMPTY_BYTES); // identity = equality assertTrue(BigArrays.equals(empty1, empty1)); // equality: both empty assertTrue(BigArrays.equals(empty1, empty2)); empty1.close(); empty2.close(); // not equal: contents differ final ByteArray a1 = byteArrayWithBytes(new byte[] { 0 }); final ByteArray a2 = byteArrayWithBytes(new byte[] { 1 }); assertFalse(BigArrays.equals(a1, a2)); a1.close(); a2.close(); // not equal: contents differ final ByteArray a3 = byteArrayWithBytes(new byte[] { 1, 2, 3 }); final ByteArray a4 = byteArrayWithBytes(new byte[] { 1, 1, 3 }); assertFalse(BigArrays.equals(a3, a4)); a3.close(); a4.close(); // not equal: contents differ final ByteArray a5 = byteArrayWithBytes(new byte[] { 1, 2, 3 }); final ByteArray a6 = byteArrayWithBytes(new byte[] { 1, 2, 4 }); assertFalse(BigArrays.equals(a5, a6)); a5.close(); a6.close(); } public void testByteArrayHashCode() { // null arg has hashCode 0 assertEquals(0, BigArrays.hashCode(null)); // empty array should have equal hash final int emptyHash = Arrays.hashCode(BytesRef.EMPTY_BYTES); final ByteArray emptyByteArray = byteArrayWithBytes(BytesRef.EMPTY_BYTES); final int emptyByteArrayHash = BigArrays.hashCode(emptyByteArray); assertEquals(emptyHash, emptyByteArrayHash); emptyByteArray.close(); // FUN FACT: Arrays.hashCode() and BytesReference.bytesHashCode() are inconsistent for empty byte[] // final int emptyHash3 = new BytesArray(BytesRef.EMPTY_BYTES).hashCode(); // assertEquals(emptyHash1, emptyHash3); -> fail (1 vs. 0) // large arrays should be different final byte[] array1 = new byte[randomIntBetween(1, 4000000)]; random().nextBytes(array1); final int array1Hash = Arrays.hashCode(array1); final ByteArray array2 = byteArrayWithBytes(array1); final int array2Hash = BigArrays.hashCode(array2); assertEquals(array1Hash, array2Hash); array2.close(); } private ByteArray byteArrayWithBytes(byte[] bytes) { ByteArray bytearray = bigArrays.newByteArray(bytes.length); for (int i = 0; i < bytes.length; ++i) { bytearray.set(i, bytes[i]); } return bytearray; } public void testMaxSizeExceededOnNew() throws Exception { final long size = scaledRandomIntBetween(5, 1 << 22); final long maxSize = size - 1; for (BigArraysHelper bigArraysHelper : bigArrayCreators(maxSize, true)) { try { bigArraysHelper.arrayAllocator.apply(size); fail("circuit breaker should trip"); } catch (CircuitBreakingException e) { assertEquals(maxSize, e.getByteLimit()); assertThat(e.getBytesWanted(), greaterThanOrEqualTo(size)); } assertEquals(0, bigArraysHelper.bigArrays.breakerService().getBreaker(CircuitBreaker.REQUEST).getUsed()); } } public void testMaxSizeExceededOnResize() throws Exception { for (String type : Arrays.asList("Byte", "Int", "Long", "Float", "Double", "Object")) { final int maxSize = randomIntBetween(1 << 8, 1 << 14); HierarchyCircuitBreakerService hcbs = new HierarchyCircuitBreakerService( CircuitBreakerMetrics.NOOP, Settings.builder() .put(REQUEST_CIRCUIT_BREAKER_LIMIT_SETTING.getKey(), maxSize, ByteSizeUnit.BYTES) .put(HierarchyCircuitBreakerService.USE_REAL_MEMORY_USAGE_SETTING.getKey(), false) .build(), Collections.emptyList(), new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS) ); BigArrays bigArrays = new BigArrays(null, hcbs, CircuitBreaker.REQUEST).withCircuitBreaking(); Method create = BigArrays.class.getMethod("new" + type + "Array", long.class); final int size = scaledRandomIntBetween(10, maxSize / 16); BigArray array = (BigArray) create.invoke(bigArrays, size); Method resize = BigArrays.class.getMethod("resize", array.getClass().getInterfaces()[0], long.class); while (true) { long newSize = array.size() * 2; try { array = (BigArray) resize.invoke(bigArrays, array, newSize); } catch (InvocationTargetException e) { assertTrue(e.getCause() instanceof CircuitBreakingException); break; } } assertEquals(array.ramBytesUsed(), hcbs.getBreaker(CircuitBreaker.REQUEST).getUsed()); array.close(); assertEquals(0, hcbs.getBreaker(CircuitBreaker.REQUEST).getUsed()); } } public void testEstimatedBytesSameAsActualBytes() throws Exception { final int maxSize = 1 << scaledRandomIntBetween(15, 22); final long size = randomIntBetween((1 << 14) + 1, maxSize); for (final BigArraysHelper bigArraysHelper : bigArrayCreators(maxSize, false)) { final BigArray bigArray = bigArraysHelper.arrayAllocator.apply(size); assertEquals(bigArraysHelper.ramEstimator.apply(size).longValue(), bigArray.ramBytesUsed()); } } public void testOverSizeUsesMinPageCount() { final int pageSize = 1 << (randomIntBetween(2, 16)); final int minSize = randomIntBetween(1, pageSize) * randomIntBetween(1, 100); final long size = BigArrays.overSize(minSize, pageSize, 1); assertThat(size, greaterThanOrEqualTo((long) minSize)); if (size >= pageSize) { assertThat(size + " is a multiple of " + pageSize, size % pageSize, equalTo(0L)); } assertThat(size - minSize, lessThan((long) pageSize)); } /** * Test the pattern we use to pre-allocate space for many {@link BigArray}s. */ public void testPreallocate() { ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); HierarchyCircuitBreakerService realBreakers = new HierarchyCircuitBreakerService( CircuitBreakerMetrics.NOOP, Settings.EMPTY, List.of(), clusterSettings ); BigArrays unPreAllocated = new MockBigArrays(new MockPageCacheRecycler(Settings.EMPTY), realBreakers); long toPreallocate = randomLongBetween(4000, 10000); CircuitBreaker realBreaker = realBreakers.getBreaker(CircuitBreaker.REQUEST); assertThat(realBreaker.getUsed(), equalTo(0L)); try ( PreallocatedCircuitBreakerService prealloctedBreakerService = new PreallocatedCircuitBreakerService( realBreakers, CircuitBreaker.REQUEST, toPreallocate, "test" ) ) { assertThat(realBreaker.getUsed(), equalTo(toPreallocate)); BigArrays preallocated = unPreAllocated.withBreakerService(prealloctedBreakerService); // We don't grab any bytes just making a new BigArrays assertThat(realBreaker.getUsed(), equalTo(toPreallocate)); List<BigArray> arrays = new ArrayList<>(); for (int i = 0; i < 30; i++) { // We're well under the preallocation so grabbing a little array doesn't allocate anything arrays.add(preallocated.newLongArray(1)); assertThat(realBreaker.getUsed(), equalTo(toPreallocate)); } // Allocating a large array *does* allocate some bytes arrays.add(preallocated.newLongArray(1024)); long expectedMin = (PageCacheRecycler.LONG_PAGE_SIZE + arrays.size()) * Long.BYTES; assertThat(realBreaker.getUsed(), greaterThanOrEqualTo(expectedMin)); // 64 should be enough room for each BigArray object assertThat(realBreaker.getUsed(), lessThanOrEqualTo(expectedMin + 64 * arrays.size())); Releasables.close(arrays); } assertThat(realBreaker.getUsed(), equalTo(0L)); } private List<BigArraysHelper> bigArrayCreators(final long maxSize, final boolean withBreaking) { final BigArrays byteBigArrays = newBigArraysInstance(maxSize, withBreaking); BigArraysHelper byteHelper = new BigArraysHelper( byteBigArrays, (Long size) -> byteBigArrays.newByteArray(size), (Long size) -> BigByteArray.estimateRamBytes(size) ); final BigArrays intBigArrays = newBigArraysInstance(maxSize, withBreaking); BigArraysHelper intHelper = new BigArraysHelper( intBigArrays, (Long size) -> intBigArrays.newIntArray(size), (Long size) -> BigIntArray.estimateRamBytes(size) ); final BigArrays longBigArrays = newBigArraysInstance(maxSize, withBreaking); BigArraysHelper longHelper = new BigArraysHelper( longBigArrays, (Long size) -> longBigArrays.newLongArray(size), (Long size) -> BigLongArray.estimateRamBytes(size) ); final BigArrays floatBigArrays = newBigArraysInstance(maxSize, withBreaking); BigArraysHelper floatHelper = new BigArraysHelper( floatBigArrays, (Long size) -> floatBigArrays.newFloatArray(size), (Long size) -> BigFloatArray.estimateRamBytes(size) ); final BigArrays doubleBigArrays = newBigArraysInstance(maxSize, withBreaking); BigArraysHelper doubleHelper = new BigArraysHelper( doubleBigArrays, (Long size) -> doubleBigArrays.newDoubleArray(size), (Long size) -> BigDoubleArray.estimateRamBytes(size) ); final BigArrays objectBigArrays = newBigArraysInstance(maxSize, withBreaking); BigArraysHelper objectHelper = new BigArraysHelper( objectBigArrays, (Long size) -> objectBigArrays.newObjectArray(size), (Long size) -> BigObjectArray.estimateRamBytes(size) ); return Arrays.asList(byteHelper, intHelper, longHelper, floatHelper, doubleHelper, objectHelper); } private BigArrays newBigArraysInstance(final long maxSize, final boolean withBreaking) { HierarchyCircuitBreakerService hcbs = new HierarchyCircuitBreakerService( CircuitBreakerMetrics.NOOP, Settings.builder() .put(REQUEST_CIRCUIT_BREAKER_LIMIT_SETTING.getKey(), maxSize, ByteSizeUnit.BYTES) .put(HierarchyCircuitBreakerService.USE_REAL_MEMORY_USAGE_SETTING.getKey(), false) .build(), Collections.emptyList(), new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS) ); BigArrays bigArrays = new BigArrays(null, hcbs, CircuitBreaker.REQUEST); return (withBreaking ? bigArrays.withCircuitBreaking() : bigArrays); } private static
BigArraysTests
java
apache__flink
flink-streaming-java/src/test/java/org/apache/flink/streaming/runtime/operators/windowing/AllWindowTranslationTest.java
{ "start": 72699, "end": 73259 }
class ____ extends ProcessAllWindowFunction< Tuple2<String, Integer>, Tuple3<String, String, Integer>, TimeWindow> { @Override public void process( Context ctx, Iterable<Tuple2<String, Integer>> values, Collector<Tuple3<String, String, Integer>> out) throws Exception { for (Tuple2<String, Integer> in : values) { out.collect(new Tuple3<>(in.f0, in.f0, in.f1)); } } } }
TestProcessAllWindowFunction
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/SampleBytesRefAggregatorFunctionSupplier.java
{ "start": 653, "end": 1716 }
class ____ implements AggregatorFunctionSupplier { private final int limit; public SampleBytesRefAggregatorFunctionSupplier(int limit) { this.limit = limit; } @Override public List<IntermediateStateDesc> nonGroupingIntermediateStateDesc() { return SampleBytesRefAggregatorFunction.intermediateStateDesc(); } @Override public List<IntermediateStateDesc> groupingIntermediateStateDesc() { return SampleBytesRefGroupingAggregatorFunction.intermediateStateDesc(); } @Override public SampleBytesRefAggregatorFunction aggregator(DriverContext driverContext, List<Integer> channels) { return SampleBytesRefAggregatorFunction.create(driverContext, channels, limit); } @Override public SampleBytesRefGroupingAggregatorFunction groupingAggregator(DriverContext driverContext, List<Integer> channels) { return SampleBytesRefGroupingAggregatorFunction.create(channels, driverContext, limit); } @Override public String describe() { return "sample of bytes"; } }
SampleBytesRefAggregatorFunctionSupplier
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/google/SetGenerators.java
{ "start": 8025, "end": 8573 }
class ____ extends TestStringSetGenerator { @Override protected SortedSet<String> create(String[] elements) { return ImmutableSortedSet.<String>reverseOrder().addAll(asList(elements).iterator()).build(); } @SuppressWarnings("CanIgnoreReturnValueSuggester") // see ImmutableSortedSetExplicitComparator @Override public List<String> order(List<String> insertionOrder) { sort(insertionOrder, Collections.reverseOrder()); return insertionOrder; } } public static
ImmutableSortedSetReversedOrderGenerator
java
quarkusio__quarkus
extensions/reactive-pg-client/deployment/src/test/java/io/quarkus/reactive/pg/client/ConfigActiveFalseNamedDatasourceStaticInjectionTest.java
{ "start": 500, "end": 2032 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .overrideConfigKey("quarkus.datasource.ds-1.active", "false") // We need at least one build-time property for the datasource, // otherwise it's considered unconfigured at build time... .overrideConfigKey("quarkus.datasource.ds-1.db-kind", "postgresql") .assertException(e -> assertThat(e) // Can't use isInstanceOf due to weird classloading in tests .satisfies(t -> assertThat(t.getClass().getName()).isEqualTo(InactiveBeanException.class.getName())) .hasMessageContainingAll("Datasource 'ds-1' was deactivated through configuration properties.", "To avoid this exception while keeping the bean inactive", // Message from Arc with generic hints "To activate the datasource, set configuration property 'quarkus.datasource.\"ds-1\".active'" + " to 'true' and configure datasource 'ds-1'", "Refer to https://quarkus.io/guides/datasource for guidance.", "This bean is injected into", MyBean.class.getName() + "#pool"));; @Inject MyBean myBean; @Test public void test() { Assertions.fail("Startup should have failed"); } @ApplicationScoped public static
ConfigActiveFalseNamedDatasourceStaticInjectionTest
java
elastic__elasticsearch
x-pack/qa/repository-old-versions-compatibility/src/javaRestTest/java/org/elasticsearch/oldrepos/OldRepositoriesIT.java
{ "start": 911, "end": 6876 }
class ____ extends AbstractUpgradeCompatibilityTestCase { static { clusterConfig = config -> config.setting("xpack.license.self_generated.type", "trial"); } public OldRepositoriesIT(Version version) { super(version); } /** * Test case restoring a snapshot created in ES_v5 - Basic mapping * 1. Index Created in ES_v5 * 2. Added 1 documents to index and created a snapshot (Steps 1-2 into resources/snapshot_v5.zip) * 3. Index Restored to version: Current-1: 8.x * 4. Cluster upgraded to version Current: 9.x */ public void testRestoreMountIndexVersion5() throws Exception { verifyCompatibility(TestSnapshotCases.ES_VERSION_5); } /** * Test case mounting a snapshot created in ES_v6 - Basic mapping * 1. Index Created in ES_v6 * 2. Added 1 documents to index and created a snapshot (Steps 1-2 into resources/snapshot_v6.zip) * 3. Index Restored to version: Current-1: 8.x * 4. Cluster upgraded to version Current: 9.x */ public void testRestoreMountIndexVersion6() throws Exception { verifyCompatibility(TestSnapshotCases.ES_VERSION_6); } /** * Test case restoring snapshot created in ES_v5 - Custom-analyzer including a standard-token-filter { * "settings": { * "analysis": { * "analyzer": { * "custom_analyzer": { * "type": "custom", * "tokenizer": "standard", * "filter": [ * "standard", * "lowercase" * ] * } * } * } * }, * "mappings": { * "my_type": { * "properties": { * "content": { * "type": "text", * "analyzer": "custom_analyzer" * } * } * } * } * } * 1. Index Created in ES_v5 * 2. Added 1 documents to index and created a snapshot (Steps 1-2 into resources/snapshot_v5_standard_token_filter.zip) * 3. Index Restored to version: Current: 9.x */ public void testRestoreMountVersion5StandardTokenFilter() throws Exception { verifyCompatibilityNoUpgrade(TestSnapshotCases.ES_VERSION_5_STANDARD_TOKEN_FILTER, warnings -> { assertEquals(1, warnings.size()); assertEquals("The [standard] token filter is " + "deprecated and will be removed in a future version.", warnings.getFirst()); }); } /** * Test case restoring snapshot created in ES_v6 - Custom-analyzer including a standard-token-filter { * "settings": { * "analysis": { * "analyzer": { * "custom_analyzer": { * "type": "custom", * "tokenizer": "standard", * "filter": [ * "standard", * "lowercase" * ] * } * } * } * }, * "mappings": { * "my_type": { * "properties": { * "content": { * "type": "text", * "analyzer": "custom_analyzer" * } * } * } * } * } * 1. Index Created in ES_v6 * 2. Added 1 documents to index and created a snapshot (Steps 1-2 into resources/snapshot_v6_standard_token_filter.zip) * 3. Index Restored to version: Current: 9.x */ public void testRestoreMountVersion6StandardTokenFilter() throws Exception { verifyCompatibilityNoUpgrade(TestSnapshotCases.ES_VERSION_6_STANDARD_TOKEN_FILTER, warnings -> { assertEquals(1, warnings.size()); assertEquals("The [standard] token filter is " + "deprecated and will be removed in a future version.", warnings.getFirst()); }); } /** * Test case restoring snapshot created with luceneCoded8.0 * 1. Index Created in ES_v6 * 2. Cluster upgraded to ES_v7.0.0 -> LuceneVersion 8.0.0 -> LuceneCodec lucene80 * 3. Added 1 documents to index and created a snapshot (Steps 1-3 into resources/snapshot_vlucene_80.zip) * 4. Index Restored to version: Current : 9.x */ public void testRestoreMountVersion6LuceneCodec80() throws Exception { verifyCompatibilityNoUpgrade(TestSnapshotCases.ES_VERSION_6_LUCENE_CODEC_80); } /** * Test case restoring snapshot created with luceneCoded8.4 * 1. Index Created in ES_v6 * 2. Cluster upgraded to ES_v7.6.0 -> LuceneVersion 8.4.0 -> LuceneCodec lucene84 * 3. Added 1 documents to index and created a snapshot (Steps 1-3 into resources/snapshot_vlucene_84.zip) * 4. Index Restored to version: Current: 9.x */ public void testRestoreMountVersion6LuceneCodec84() throws Exception { verifyCompatibilityNoUpgrade(TestSnapshotCases.ES_VERSION_6_LUCENE_CODEC_84); } /** * Test case restoring snapshot created with luceneCoded8.4 * 1. Index Created in ES_v6 * 2. Cluster upgraded to ES_v7.9.0 -> LuceneVersion 8.6.0 -> LuceneCodec lucene86 * 3. Added 1 documents to index and created a snapshot (Steps 1-3 into resources/snapshot_vlucene_86.zip) * 4. Index Restored to version: Current: 9.x */ public void testRestoreMountVersion6LuceneCodec86() throws Exception { verifyCompatibilityNoUpgrade(TestSnapshotCases.ES_VERSION_6_LUCENE_CODEC_86); } /** * Test case restoring snapshot created with luceneCoded8.4 * 1. Index Created in ES_v6 * 2. Cluster upgraded to ES_v7.10.0 -> LuceneVersion 8.7.0 -> LuceneCodec lucene87 * 3. Added 1 documents to index and created a snapshot (Steps 1-3 into resources/snapshot_vlucene_87.zip) * 4. Index Restored to version: Current: 9.x */ public void testRestoreMountVersion6LuceneCodec87() throws Exception { verifyCompatibilityNoUpgrade(TestSnapshotCases.ES_VERSION_6_LUCENE_CODEC_87); } }
OldRepositoriesIT
java
google__dagger
javatests/dagger/functional/assisted/subpackage/InaccessibleFooFactory.java
{ "start": 781, "end": 869 }
interface ____ { InaccessibleFoo create(AssistedDep assistedDep); }
InaccessibleFooFactory
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-common/deployment/src/main/java/io/quarkus/resteasy/reactive/common/deployment/QuarkusResteasyReactiveDotNames.java
{ "start": 420, "end": 1931 }
class ____ { public static final DotName HTTP_SERVER_REQUEST = DotName.createSimple(HttpServerRequest.class.getName()); public static final DotName HTTP_SERVER_RESPONSE = DotName.createSimple(HttpServerResponse.class.getName()); public static final DotName ROUTING_CONTEXT = DotName.createSimple(RoutingContext.class.getName()); public static final DotName JSON_IGNORE = DotName.createSimple("com.fasterxml.jackson.annotation.JsonIgnore"); public static final DotName JSONB_TRANSIENT = DotName.createSimple("jakarta.json.bind.annotation.JsonbTransient"); public static final IgnoreTypeForReflectionPredicate IGNORE_TYPE_FOR_REFLECTION_PREDICATE = new IgnoreTypeForReflectionPredicate(); public static final IgnoreFieldForReflectionPredicate IGNORE_FIELD_FOR_REFLECTION_PREDICATE = new IgnoreFieldForReflectionPredicate(); public static final IgnoreMethodForReflectionPredicate IGNORE_METHOD_FOR_REFLECTION_PREDICATE = new IgnoreMethodForReflectionPredicate(); private static final String[] PACKAGES_IGNORED_FOR_REFLECTION = { // JSON-P "jakarta.json.", "jakarta.json.", // Jackson "com.fasterxml.jackson.databind.", // JAX-RS "jakarta.ws.rs.", // RESTEasy "org.jboss.resteasy.reactive", // Vert.x JSON layer "io.vertx.core.json.", // Mutiny "io.smallrye.mutiny." }; private static
QuarkusResteasyReactiveDotNames
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/cookie/CookieFactory.java
{ "start": 905, "end": 1435 }
interface ____ { /** * The default {@link CookieFactory} instance. */ CookieFactory INSTANCE = SoftServiceLoader .load(CookieFactory.class) .firstOr("io.micronaut.http.cookie.HttpCookieFactory", CookieFactory.class.getClassLoader()) .map(ServiceDefinition::load) .orElse(null); /** * Create a new cookie. * * @param name The name * @param value The value * @return A Cookie instance */ Cookie create(String name, String value); }
CookieFactory
java
apache__kafka
server/src/main/java/org/apache/kafka/server/Assignment.java
{ "start": 1125, "end": 2494 }
class ____ not converted to a Java record since record classes are meant for pure data, but this one contains a Runnable * * @param topicIdPartition The topic ID and partition index of the replica. * @param directoryId The ID of the directory we are placing the replica into. * @param submissionTimeNs The time in monotonic nanosecond when this assignment was created. * @param successCallback The callback to invoke on success. */ record Assignment(TopicIdPartition topicIdPartition, Uuid directoryId, long submissionTimeNs, Runnable successCallback) { /** * Check if this Assignment is still valid to be sent. * * @param nodeId The broker ID. * @param image The metadata image. * @return True only if the Assignment is still valid. */ boolean valid(int nodeId, MetadataImage image) { TopicImage topicImage = image.topics().getTopic(topicIdPartition.topicId()); if (topicImage == null) { return false; // The topic has been deleted. } PartitionRegistration partition = topicImage.partitions().get(topicIdPartition.partitionId()); if (partition == null) { return false; // The partition no longer exists. } // Check if this broker is still a replica. return Replicas.contains(partition.replicas, nodeId); } }
is
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TestInstancePostProcessorTests.java
{ "start": 6050, "end": 6330 }
class ____ extends AbstractInstancePostProcessor { BarInstancePostProcessor() { super("bar"); } @Override public ExtensionContextScope getTestInstantiationExtensionContextScope(ExtensionContext rootContext) { return TEST_METHOD; } } static
BarInstancePostProcessor
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/inject/qualifiers/NoneQualifier.java
{ "start": 996, "end": 1770 }
class ____<T> extends FilteringQualifier<T> { @SuppressWarnings("rawtypes") public static final NoneQualifier INSTANCE = new NoneQualifier(); private NoneQualifier() { } @Override public boolean doesQualify(Class<T> beanType, BeanType<T> candidate) { if (candidate instanceof BeanDefinition<T> beanDefinition) { return beanDefinition.getDeclaredQualifier() == null; } return !AnnotationUtil.hasDeclaredQualifierAnnotation(candidate.getAnnotationMetadata()); } @Override public boolean doesQualify(Class<T> beanType, QualifiedBeanType<T> candidate) { return candidate.getDeclaredQualifier() == null; } @Override public String toString() { return "None"; } }
NoneQualifier
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java
{ "start": 122895, "end": 123209 }
class ____ extends AbstractPluralAttributeSecondPass { public PluralAttributeBagSecondPass( MappingDocument sourceDocument, PluralAttributeSource attributeSource, Collection collectionBinding) { super( sourceDocument, attributeSource, collectionBinding ); } } private
PluralAttributeBagSecondPass
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeTimeIntervalTest.java
{ "start": 1023, "end": 2862 }
class ____ { @Test public void just() { Maybe.just(1) .timeInterval() .test() .assertValueCount(1) .assertNoErrors() .assertComplete(); } @Test public void empty() { Maybe.empty() .timeInterval() .test() .assertResult(); } @Test public void error() { Maybe.error(new TestException()) .timeInterval() .test() .assertFailure(TestException.class); } @Test public void justSeconds() { Maybe.just(1) .timeInterval(TimeUnit.SECONDS) .test() .assertValueCount(1) .assertNoErrors() .assertComplete(); } @Test public void justScheduler() { Maybe.just(1) .timeInterval(Schedulers.single()) .test() .assertValueCount(1) .assertNoErrors() .assertComplete(); } @Test public void justSecondsScheduler() { Maybe.just(1) .timeInterval(TimeUnit.SECONDS, Schedulers.single()) .test() .assertValueCount(1) .assertNoErrors() .assertComplete(); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeMaybe(m -> m.timeInterval()); } @Test public void dispose() { TestHelper.checkDisposed(MaybeSubject.create().timeInterval()); } @Test public void timeInfo() { TestScheduler scheduler = new TestScheduler(); MaybeSubject<Integer> ms = MaybeSubject.create(); TestObserver<Timed<Integer>> to = ms .timeInterval(scheduler) .test(); scheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS); ms.onSuccess(1); to.assertResult(new Timed<>(1, 1000L, TimeUnit.MILLISECONDS)); } }
MaybeTimeIntervalTest
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/integration/AbstractMockitoBeanAndGenericsIntegrationTests.java
{ "start": 1739, "end": 1808 }
class ____ { String speak() { return "Hi"; } } static
Something
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AzureBlockManager.java
{ "start": 1012, "end": 1090 }
class ____ managing Azure Data Lake Storage (ADLS) blocks. */ public abstract
for
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/async/AsyncEndpointPolicyTest.java
{ "start": 4127, "end": 5969 }
class ____ implements Policy { private final String name; private int invoked; public MyPolicy(String name) { this.name = name; } @Override public void beforeWrap(Route route, NamedNode definition) { // no need to modify the route } @Override public Processor wrap(Route route, final Processor processor) { return new AsyncProcessor() { public boolean process(final Exchange exchange, final AsyncCallback callback) { invoked++; // let the original processor continue routing exchange.getIn().setHeader(name, "was wrapped"); AsyncProcessor ap = AsyncProcessorConverterHelper.convert(processor); ap.process(exchange, doneSync -> { exchange.getIn().setHeader(name, "policy finished execution"); callback.done(false); }); return false; } public void process(Exchange exchange) { final AsyncProcessorAwaitManager awaitManager = PluginHelper.getAsyncProcessorAwaitManager(exchange.getContext()); awaitManager.process(this, exchange); } public CompletableFuture<Exchange> processAsync(Exchange exchange) { AsyncCallbackToCompletableFutureAdapter<Exchange> callback = new AsyncCallbackToCompletableFutureAdapter<>(exchange); process(exchange, callback); return callback.getFuture(); } }; } public int getInvoked() { return invoked; } } }
MyPolicy
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/UnitTestcaseTimeLimit.java
{ "start": 1162, "end": 1231 }
class ____ { public final int timeOutSecs = 10; }
UnitTestcaseTimeLimit
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/ClassUtils.java
{ "start": 20204, "end": 20470 }
class ____ a primitive wrapper array class */ public static boolean isPrimitiveWrapperArray(Class<?> clazz) { Assert.notNull(clazz, "Class must not be null"); return (clazz.isArray() && isPrimitiveWrapper(clazz.componentType())); } /** * Resolve the given
is
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/scheduler/ExecutorScheduler.java
{ "start": 4131, "end": 4353 }
interface ____ { void delete(ExecutorTrackedRunnable r); } /** * A Runnable that wraps a task and has reference back to its parent worker to * remove itself once completed or cancelled */ static final
WorkerDelete
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/typeutils/TypeInformationTestBase.java
{ "start": 4770, "end": 5896 }
class ____ extends TypeInformation<Object> { @Override public boolean isBasicType() { return false; } @Override public boolean isTupleType() { return false; } @Override public int getArity() { return 0; } @Override public int getTotalFields() { return 0; } @Override public Class<Object> getTypeClass() { return null; } @Override public boolean isKeyType() { return false; } @Override public TypeSerializer<Object> createSerializer(SerializerConfig config) { return null; } @Override public String toString() { return null; } @Override public boolean equals(Object obj) { return false; } @Override public int hashCode() { return 0; } @Override public boolean canEqual(Object obj) { return false; } } }
UnrelatedTypeInfo
java
apache__flink
flink-yarn-tests/src/test/java/org/apache/flink/yarn/testjob/YarnTestArchiveJob.java
{ "start": 5046, "end": 6511 }
class ____<T> extends RichSourceFunction<T> implements ResultTypeQueryable<T> { private final List<T> inputDataset; private final String resourcePath; private final TypeInformation<T> returnType; SourceFunctionWithArchive( List<T> inputDataset, String resourcePath, TypeInformation<T> returnType) { this.inputDataset = inputDataset; this.resourcePath = resourcePath; this.returnType = returnType; } public void open(OpenContext openContext) throws Exception { for (Map.Entry<String, String> entry : srcFiles.entrySet()) { Path path = Paths.get(resourcePath + File.separator + entry.getKey()); String content = new String(Files.readAllBytes(path)); checkArgument( entry.getValue().equals(content), "The content of the unpacked file should be identical to the original file's."); } } @Override public void run(SourceContext<T> ctx) { for (T t : inputDataset) { synchronized (ctx.getCheckpointLock()) { ctx.collect(t); } } } @Override public void cancel() {} @Override public TypeInformation<T> getProducedType() { return this.returnType; } } }
SourceFunctionWithArchive
java
apache__dubbo
dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetConfig.java
{ "start": 2361, "end": 9483 }
class ____ implements BaseCommand { private final FrameworkModel frameworkModel; public GetConfig(FrameworkModel frameworkModel) { this.frameworkModel = frameworkModel; } @Override public String execute(CommandContext commandContext, String[] args) { boolean http = commandContext.isHttp(); StringBuilder plainOutput = new StringBuilder(); Map<String, Object> frameworkMap = new HashMap<>(); appendFrameworkConfig(args, plainOutput, frameworkMap); if (http) { return JsonUtils.toJson(frameworkMap); } else { return plainOutput.toString(); } } private void appendFrameworkConfig(String[] args, StringBuilder plainOutput, Map<String, Object> frameworkMap) { for (ApplicationModel applicationModel : frameworkModel.getApplicationModels()) { Map<String, Object> applicationMap = new HashMap<>(); frameworkMap.put(applicationModel.getDesc(), applicationMap); plainOutput .append("ApplicationModel: ") .append(applicationModel.getDesc()) .append("\n"); ConfigManager configManager = applicationModel.getApplicationConfigManager(); appendApplicationConfigs(args, plainOutput, applicationModel, applicationMap, configManager); } } private static void appendApplicationConfigs( String[] args, StringBuilder plainOutput, ApplicationModel applicationModel, Map<String, Object> applicationMap, ConfigManager configManager) { Optional<ApplicationConfig> applicationConfig = configManager.getApplication(); applicationConfig.ifPresent(config -> appendConfig("ApplicationConfig", config.getName(), config, plainOutput, applicationMap, args)); for (ProtocolConfig protocol : configManager.getProtocols()) { appendConfigs("ProtocolConfig", protocol.getName(), protocol, plainOutput, applicationMap, args); } for (RegistryConfig registry : configManager.getRegistries()) { appendConfigs("RegistryConfig", registry.getId(), registry, plainOutput, applicationMap, args); } for (MetadataReportConfig metadataConfig : configManager.getMetadataConfigs()) { appendConfigs( "MetadataReportConfig", metadataConfig.getId(), metadataConfig, plainOutput, applicationMap, args); } for (ConfigCenterConfig configCenter : configManager.getConfigCenters()) { appendConfigs("ConfigCenterConfig", configCenter.getId(), configCenter, plainOutput, applicationMap, args); } Optional<MetricsConfig> metricsConfig = configManager.getMetrics(); metricsConfig.ifPresent( config -> appendConfig("MetricsConfig", config.getId(), config, plainOutput, applicationMap, args)); Optional<TracingConfig> tracingConfig = configManager.getTracing(); tracingConfig.ifPresent( config -> appendConfig("TracingConfig", config.getId(), config, plainOutput, applicationMap, args)); Optional<MonitorConfig> monitorConfig = configManager.getMonitor(); monitorConfig.ifPresent( config -> appendConfig("MonitorConfig", config.getId(), config, plainOutput, applicationMap, args)); Optional<SslConfig> sslConfig = configManager.getSsl(); sslConfig.ifPresent( config -> appendConfig("SslConfig", config.getId(), config, plainOutput, applicationMap, args)); for (ModuleModel moduleModel : applicationModel.getModuleModels()) { Map<String, Object> moduleMap = new HashMap<>(); applicationMap.put(moduleModel.getDesc(), moduleMap); plainOutput.append("ModuleModel: ").append(moduleModel.getDesc()).append("\n"); ModuleConfigManager moduleConfigManager = moduleModel.getConfigManager(); appendModuleConfigs(args, plainOutput, moduleMap, moduleConfigManager); } } private static void appendModuleConfigs( String[] args, StringBuilder plainOutput, Map<String, Object> moduleMap, ModuleConfigManager moduleConfigManager) { for (ProviderConfig provider : moduleConfigManager.getProviders()) { appendConfigs("ProviderConfig", provider.getId(), provider, plainOutput, moduleMap, args); } for (ConsumerConfig consumer : moduleConfigManager.getConsumers()) { appendConfigs("ConsumerConfig", consumer.getId(), consumer, plainOutput, moduleMap, args); } Optional<ModuleConfig> moduleConfig = moduleConfigManager.getModule(); moduleConfig.ifPresent( config -> appendConfig("ModuleConfig", config.getId(), config, plainOutput, moduleMap, args)); for (ServiceConfigBase<?> service : moduleConfigManager.getServices()) { appendConfigs("ServiceConfig", service.getUniqueServiceName(), service, plainOutput, moduleMap, args); } for (ReferenceConfigBase<?> reference : moduleConfigManager.getReferences()) { appendConfigs("ReferenceConfig", reference.getUniqueServiceName(), reference, plainOutput, moduleMap, args); } } @SuppressWarnings("unchecked") private static void appendConfigs( String type, String id, Object config, StringBuilder plainOutput, Map<String, Object> map, String[] args) { if (!isMatch(type, id, args)) { return; } id = id == null ? "(empty)" : id; plainOutput .append(type) .append(": ") .append(id) .append("\n") .append(config) .append("\n\n"); Map<String, Object> typeMap = (Map<String, Object>) map.computeIfAbsent(type, k -> new HashMap<String, Object>()); typeMap.put(id, config); } private static void appendConfig( String type, String id, Object config, StringBuilder plainOutput, Map<String, Object> map, String[] args) { if (!isMatch(type, id, args)) { return; } id = id == null ? "(empty)" : id; plainOutput .append(type) .append(": ") .append(id) .append("\n") .append(config) .append("\n\n"); map.put(type, config); } private static boolean isMatch(String type, String id, String[] args) { if (args == null) { return true; } switch (args.length) { case 1: if (!Objects.equals(args[0], type)) { return false; } break; case 2: if (!Objects.equals(args[0], type) || !Objects.equals(args[1], id)) { return false; } break; default: } return true; } }
GetConfig
java
google__auto
value/src/main/java/com/google/auto/value/processor/KotlinMetadata.java
{ "start": 7667, "end": 8089 }
class ____ { final Object /* KotlinClassHeader */ wrapped; KotlinClassHeader( Integer k, int[] mv, String[] d1, String[] d2, String xs, String pn, Integer xi) throws ReflectiveOperationException { this.wrapped = NEW_KOTLIN_CLASS_HEADER.newInstance(k, mv, d1, d2, xs, pn, xi); } } @SuppressWarnings({"JavaLangClash", "SameNameButDifferent"}) // "Class" private static
KotlinClassHeader
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/ui/ExtendedModelMap.java
{ "start": 870, "end": 1288 }
class ____ to handler methods by Spring MVC, typically via * a declaration of the {@link org.springframework.ui.Model} interface. There is no need to * build it within user code; a plain {@link org.springframework.ui.ModelMap} or even a just * a regular {@link Map} with String keys will be good enough to return a user model. * * @author Juergen Hoeller * @since 2.5.1 */ @SuppressWarnings("serial") public
exposed
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/indices/flush/ShardFlushRequest.java
{ "start": 913, "end": 2034 }
class ____ extends ReplicationRequest<ShardFlushRequest> { private final FlushRequest request; /** * Creates a request for a resolved shard id and SplitShardCountSummary (used * to determine if the request needs to be executed on a split shard not yet seen by the * coordinator that sent the request) */ public ShardFlushRequest(FlushRequest request, ShardId shardId, SplitShardCountSummary reshardSplitShardCountSummary) { super(shardId, reshardSplitShardCountSummary); this.request = request; this.waitForActiveShards = ActiveShardCount.NONE; // don't wait for any active shards before proceeding, by default } public ShardFlushRequest(StreamInput in) throws IOException { super(in); request = new FlushRequest(in); } FlushRequest getRequest() { return request; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); request.writeTo(out); } @Override public String toString() { return "flush {" + shardId + "}"; } }
ShardFlushRequest
java
apache__camel
components/camel-azure/camel-azure-storage-queue/src/main/java/org/apache/camel/component/azure/storage/queue/QueueEndpoint.java
{ "start": 1771, "end": 3967 }
class ____ extends ScheduledPollEndpoint implements EndpointServiceLocation { private QueueServiceClient queueServiceClient; @UriParam private QueueConfiguration configuration; public QueueEndpoint(final String uri, final Component component, final QueueConfiguration configuration) { super(uri, component); this.configuration = configuration; } @Override public Producer createProducer() throws Exception { return new QueueProducer(this); } @Override public Consumer createConsumer(Processor processor) throws Exception { if (ObjectHelper.isEmpty(configuration.getQueueName())) { throw new IllegalArgumentException("QueueName must be set."); } QueueConsumer consumer = new QueueConsumer(this, processor); configureConsumer(consumer); return consumer; } @Override public void doStart() throws Exception { super.doStart(); queueServiceClient = configuration.getServiceClient() != null ? configuration.getServiceClient() : QueueClientFactory.createQueueServiceClient(configuration); } /** * The component configurations */ public QueueConfiguration getConfiguration() { return configuration; } public void setConfiguration(QueueConfiguration configuration) { this.configuration = configuration; } public QueueServiceClient getQueueServiceClient() { return queueServiceClient; } @Override public String getServiceUrl() { if (ObjectHelper.isNotEmpty(configuration.getAccountName()) && ObjectHelper.isNotEmpty(configuration.getQueueName())) { return "azure-storage-queue:" + configuration.getAccountName() + "/" + configuration.getQueueName(); } return null; } @Override public String getServiceProtocol() { return "storage-queue"; } @Override public Map<String, String> getServiceMetadata() { if (configuration.getCredentialType() != null) { return Map.of("credentialType", configuration.getCredentialType().name()); } return null; } }
QueueEndpoint
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/parser/EqlBaseBaseListener.java
{ "start": 453, "end": 18227 }
class ____ implements EqlBaseListener { /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterSingleStatement(EqlBaseParser.SingleStatementContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitSingleStatement(EqlBaseParser.SingleStatementContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterSingleExpression(EqlBaseParser.SingleExpressionContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitSingleExpression(EqlBaseParser.SingleExpressionContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterStatement(EqlBaseParser.StatementContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitStatement(EqlBaseParser.StatementContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterQuery(EqlBaseParser.QueryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitQuery(EqlBaseParser.QueryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterSequenceParams(EqlBaseParser.SequenceParamsContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitSequenceParams(EqlBaseParser.SequenceParamsContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterSequence(EqlBaseParser.SequenceContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitSequence(EqlBaseParser.SequenceContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterSample(EqlBaseParser.SampleContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitSample(EqlBaseParser.SampleContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterJoin(EqlBaseParser.JoinContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitJoin(EqlBaseParser.JoinContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterPipe(EqlBaseParser.PipeContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitPipe(EqlBaseParser.PipeContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterJoinKeys(EqlBaseParser.JoinKeysContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitJoinKeys(EqlBaseParser.JoinKeysContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterJoinTerm(EqlBaseParser.JoinTermContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitJoinTerm(EqlBaseParser.JoinTermContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterSequenceTerm(EqlBaseParser.SequenceTermContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitSequenceTerm(EqlBaseParser.SequenceTermContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterSubquery(EqlBaseParser.SubqueryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitSubquery(EqlBaseParser.SubqueryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEventQuery(EqlBaseParser.EventQueryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEventQuery(EqlBaseParser.EventQueryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEventFilter(EqlBaseParser.EventFilterContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEventFilter(EqlBaseParser.EventFilterContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterExpression(EqlBaseParser.ExpressionContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitExpression(EqlBaseParser.ExpressionContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterLogicalNot(EqlBaseParser.LogicalNotContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitLogicalNot(EqlBaseParser.LogicalNotContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterBooleanDefault(EqlBaseParser.BooleanDefaultContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitBooleanDefault(EqlBaseParser.BooleanDefaultContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterProcessCheck(EqlBaseParser.ProcessCheckContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitProcessCheck(EqlBaseParser.ProcessCheckContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterLogicalBinary(EqlBaseParser.LogicalBinaryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitLogicalBinary(EqlBaseParser.LogicalBinaryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterValueExpressionDefault(EqlBaseParser.ValueExpressionDefaultContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitValueExpressionDefault(EqlBaseParser.ValueExpressionDefaultContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterComparison(EqlBaseParser.ComparisonContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitComparison(EqlBaseParser.ComparisonContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterOperatorExpressionDefault(EqlBaseParser.OperatorExpressionDefaultContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitOperatorExpressionDefault(EqlBaseParser.OperatorExpressionDefaultContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterArithmeticBinary(EqlBaseParser.ArithmeticBinaryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitArithmeticBinary(EqlBaseParser.ArithmeticBinaryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterArithmeticUnary(EqlBaseParser.ArithmeticUnaryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitArithmeticUnary(EqlBaseParser.ArithmeticUnaryContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterPredicate(EqlBaseParser.PredicateContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitPredicate(EqlBaseParser.PredicateContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterConstantDefault(EqlBaseParser.ConstantDefaultContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitConstantDefault(EqlBaseParser.ConstantDefaultContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterFunction(EqlBaseParser.FunctionContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitFunction(EqlBaseParser.FunctionContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterDereference(EqlBaseParser.DereferenceContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitDereference(EqlBaseParser.DereferenceContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterParenthesizedExpression(EqlBaseParser.ParenthesizedExpressionContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitParenthesizedExpression(EqlBaseParser.ParenthesizedExpressionContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterFunctionExpression(EqlBaseParser.FunctionExpressionContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitFunctionExpression(EqlBaseParser.FunctionExpressionContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterFunctionName(EqlBaseParser.FunctionNameContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitFunctionName(EqlBaseParser.FunctionNameContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterNullLiteral(EqlBaseParser.NullLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitNullLiteral(EqlBaseParser.NullLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterNumericLiteral(EqlBaseParser.NumericLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitNumericLiteral(EqlBaseParser.NumericLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterBooleanLiteral(EqlBaseParser.BooleanLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitBooleanLiteral(EqlBaseParser.BooleanLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterStringLiteral(EqlBaseParser.StringLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitStringLiteral(EqlBaseParser.StringLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterComparisonOperator(EqlBaseParser.ComparisonOperatorContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitComparisonOperator(EqlBaseParser.ComparisonOperatorContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterBooleanValue(EqlBaseParser.BooleanValueContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitBooleanValue(EqlBaseParser.BooleanValueContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterQualifiedName(EqlBaseParser.QualifiedNameContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitQualifiedName(EqlBaseParser.QualifiedNameContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterIdentifier(EqlBaseParser.IdentifierContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitIdentifier(EqlBaseParser.IdentifierContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterTimeUnit(EqlBaseParser.TimeUnitContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitTimeUnit(EqlBaseParser.TimeUnitContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterDecimalLiteral(EqlBaseParser.DecimalLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitDecimalLiteral(EqlBaseParser.DecimalLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterIntegerLiteral(EqlBaseParser.IntegerLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitIntegerLiteral(EqlBaseParser.IntegerLiteralContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterString(EqlBaseParser.StringContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitString(EqlBaseParser.StringContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEventValue(EqlBaseParser.EventValueContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEventValue(EqlBaseParser.EventValueContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) {} /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) {} }
EqlBaseBaseListener
java
elastic__elasticsearch
x-pack/plugin/sql/qa/server/src/main/java/org/elasticsearch/xpack/sql/qa/geo/GeoDataLoader.java
{ "start": 1296, "end": 7030 }
class ____ { public static void main(String[] args) throws Exception { try (RestClient client = RestClient.builder(new HttpHost("localhost", 9200)).build()) { loadOGCDatasetIntoEs(client, "ogc"); loadGeoDatasetIntoEs(client, "geo"); Loggers.getLogger(GeoDataLoader.class).info("Geo data loaded"); } } protected static void loadOGCDatasetIntoEs(RestClient client, String index) throws Exception { createIndex(client, index, createOGCIndexRequest()); loadData(client, index, readResource("/ogc/ogc.json")); List<String> aliases = """ lakes road_segments divided_routes forests bridges streams buildings ponds named_places map_neatlines """.lines().toList(); for (String alias : aliases) { makeFilteredAlias(client, alias, index, String.format(java.util.Locale.ROOT, "\"term\" : { \"ogc_type\" : \"%s\" }", alias)); } } private static String createOGCIndexRequest() throws Exception { XContentBuilder createIndex = JsonXContent.contentBuilder().startObject(); createIndex.startObject("settings"); { createIndex.field("number_of_shards", 1); } createIndex.endObject(); createIndex.startObject("mappings"); { createIndex.startObject("properties"); { // Common createIndex.startObject("ogc_type").field("type", "keyword").endObject(); createIndex.startObject("fid").field("type", "integer").endObject(); createString("name", createIndex); // Type specific createIndex.startObject("shore").field("type", "shape").endObject(); // lakes createString("aliases", createIndex); // road_segments createIndex.startObject("num_lanes").field("type", "integer").endObject(); // road_segments, divided_routes createIndex.startObject("centerline").field("type", "shape").endObject(); // road_segments, streams createIndex.startObject("centerlines").field("type", "shape").endObject(); // divided_routes createIndex.startObject("boundary").field("type", "shape").endObject(); // forests, named_places createIndex.startObject("position").field("type", "shape").endObject(); // bridges, buildings createString("address", createIndex); // buildings createIndex.startObject("footprint").field("type", "shape").endObject(); // buildings createIndex.startObject("type").field("type", "keyword").endObject(); // ponds createIndex.startObject("shores").field("type", "shape").endObject(); // ponds createIndex.startObject("neatline").field("type", "shape").endObject(); // map_neatlines } createIndex.endObject(); } createIndex.endObject().endObject(); return Strings.toString(createIndex); } private static void createIndex(RestClient client, String index, String settingsMappings) throws IOException { Request createIndexRequest = new Request("PUT", "/" + index); createIndexRequest.setEntity(new StringEntity(settingsMappings, ContentType.APPLICATION_JSON)); client.performRequest(createIndexRequest); } static void loadGeoDatasetIntoEs(RestClient client, String index) throws Exception { createIndex(client, index, readResource("/geo/geosql.json")); loadData(client, index, readResource("/geo/geosql-bulk.json")); } private static void loadData(RestClient client, String index, String bulk) throws IOException { Request request = new Request("POST", "/" + index + "/_bulk"); request.addParameter("refresh", "true"); request.setJsonEntity(bulk); Response response = client.performRequest(request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("Cannot load data " + response.getStatusLine()); } String bulkResponseStr = EntityUtils.toString(response.getEntity()); Map<String, Object> bulkResponseMap = XContentHelper.convertToMap(JsonXContent.jsonXContent, bulkResponseStr, false); if ((boolean) bulkResponseMap.get("errors")) { throw new RuntimeException("Failed to load bulk data " + bulkResponseStr); } } public static void makeFilteredAlias(RestClient client, String aliasName, String index, String filter) throws Exception { Request request = new Request("POST", "/" + index + "/_alias/" + aliasName); request.setJsonEntity("{\"filter\" : { " + filter + " } }"); client.performRequest(request); } private static String readResource(String location) throws IOException { URL dataSet = SqlSpecTestCase.class.getResource(location); if (dataSet == null) { throw new IllegalArgumentException("Can't find [" + location + "]"); } StringBuilder builder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(readFromJarUrl(dataSet), StandardCharsets.UTF_8))) { String line = reader.readLine(); while (line != null) { if (line.trim().startsWith("//") == false) { builder.append(line); builder.append('\n'); } line = reader.readLine(); } return builder.toString(); } } }
GeoDataLoader
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 20693, "end": 20896 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return dialect.supportsStandardCurrentTimestampFunction(); } } public static
UsesStandardCurrentTimestampFunction
java
apache__camel
components/camel-metrics/src/test/java/org/apache/camel/component/metrics/HistogramRouteTest.java
{ "start": 2005, "end": 4267 }
class ____ extends CamelSpringTestSupport { @EndpointInject("mock:out") private MockEndpoint endpoint; @Produce("direct:in") private ProducerTemplate producer; private MetricRegistry mockRegistry; private Histogram mockHistogram; private InOrder inOrder; @Override protected AbstractApplicationContext createApplicationContext() { return new AnnotationConfigApplicationContext(); } @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); mockRegistry = Mockito.mock(MetricRegistry.class); context.getRegistry().bind(METRIC_REGISTRY_NAME, mockRegistry); mockHistogram = Mockito.mock(Histogram.class); inOrder = Mockito.inOrder(mockRegistry, mockHistogram); return context; } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:in") .to("metrics:histogram:A?value=332491") .to("mock:out"); } }; } @Override public void doPostTearDown() { endpoint.reset(); reset(mockRegistry); } @Test public void testOverrideMetricsName() throws Exception { when(mockRegistry.histogram("B")).thenReturn(mockHistogram); endpoint.expectedMessageCount(1); producer.sendBodyAndHeader(new Object(), HEADER_METRIC_NAME, "B"); endpoint.assertIsSatisfied(); inOrder.verify(mockRegistry, times(1)).histogram("B"); inOrder.verify(mockHistogram, times(1)).update(332491L); inOrder.verifyNoMoreInteractions(); } @Test public void testOverrideValue() throws Exception { when(mockRegistry.histogram("A")).thenReturn(mockHistogram); endpoint.expectedMessageCount(1); producer.sendBodyAndHeader(new Object(), HEADER_HISTOGRAM_VALUE, 181L); endpoint.assertIsSatisfied(); inOrder.verify(mockRegistry, times(1)).histogram("A"); inOrder.verify(mockHistogram, times(1)).update(181L); inOrder.verifyNoMoreInteractions(); } }
HistogramRouteTest
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-jersey/src/main/java/smoketest/jersey/ReverseEndpoint.java
{ "start": 873, "end": 1035 }
class ____ { @GET public String reverse(@QueryParam("input") @NotNull String input) { return new StringBuilder(input).reverse().toString(); } }
ReverseEndpoint
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/MonoReduceTest.java
{ "start": 1327, "end": 9825 }
class ____ extends ReduceOperatorTest<String, String>{ @Override protected Scenario<String, String> defaultScenarioOptions(Scenario<String, String> defaultOptions) { return defaultOptions.receive(1, i -> item(0)); } @Override protected List<Scenario<String, String>> scenarios_operatorSuccess() { return Arrays.asList( scenario(f -> f.reduce((a, b) -> a)) ); } @Override protected List<Scenario<String, String>> scenarios_operatorError() { return Arrays.asList( scenario(f -> f.reduce((a, b) -> null)) ); } private static final Logger LOG = LoggerFactory.getLogger(MonoReduceTest.class); /*@Test public void constructors() { ConstructorTestBuilder ctb = new ConstructorTestBuilder(MonoReduce.class); ctb.addRef("source", Mono.never()); ctb.addRef("aggregator", (BiFunction<Object, Object, Object>) (a, b) -> b); ctb.test(); } */ @Test public void normal() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 10) .reduce((a, b) -> a + b) .subscribe(ts); ts.assertValues(55) .assertNoError() .assertComplete(); } @Test public void normalBackpressured() { AssertSubscriber<Integer> ts = AssertSubscriber.create(0L); Flux.range(1, 10) .reduce((a, b) -> a + b) .subscribe(ts); ts.assertNoValues() .assertNoError() .assertNotComplete(); ts.request(1); ts.assertValues(55) .assertNoError() .assertComplete(); } @Test public void single() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.just(1) .reduce((a, b) -> a + b) .subscribe(ts); ts.assertValues(1) .assertNoError() .assertComplete(); } @Test public void empty() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.<Integer>empty().reduce((a, b) -> a + b) .subscribe(ts); ts.assertNoValues() .assertNoError() .assertComplete(); } @Test public void error() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.<Integer>error(new RuntimeException("forced failure")).reduce((a, b) -> a + b) .subscribe(ts); ts.assertNoValues() .assertError(RuntimeException.class) .assertErrorWith(e -> assertThat(e).hasMessageContaining("forced failure")) .assertNotComplete(); } @Test public void aggregatorThrows() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 10) .reduce((a, b) -> { throw new RuntimeException("forced failure"); }) .subscribe(ts); ts.assertNoValues() .assertError(RuntimeException.class) .assertErrorWith(e -> assertThat(e).hasMessageContaining("forced failure")) .assertNotComplete(); } @Test public void aggregatorReturnsNull() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Flux.range(1, 10) .reduce((a, b) -> null) .subscribe(ts); ts.assertNoValues() .assertError(NullPointerException.class) .assertNotComplete(); } /* see issue #230 */ @Test public void should_reduce_to_10_events() { AtomicInteger count = new AtomicInteger(); AtomicInteger countNulls = new AtomicInteger(); Flux.range(0, 10).flatMap(x -> Flux.range(0, 2) .map(y -> blockingOp(x, y)) .subscribeOn(Schedulers.boundedElastic()) .reduce((l, r) -> l + "_" + r) // .log("reduced."+x) .doOnSuccess(s -> { if (s == null) countNulls.incrementAndGet(); else count.incrementAndGet(); LOG.info("Completed with {}", s); }) ).blockLast(); assertThat(count).hasValue(10); assertThat(countNulls).hasValue(0); } private static String blockingOp(Integer x, Integer y) { try { sleep(1000 - x * 100); } catch (InterruptedException e) { e.printStackTrace(); } return "x" + x + "y" + y; } @Test public void onNextAndCancelRace() { final AssertSubscriber<Integer> testSubscriber = AssertSubscriber.create(); MonoReduce.ReduceSubscriber<Integer> sub = new MonoReduce.ReduceSubscriber<>(testSubscriber, (current, next) -> current + next); sub.onSubscribe(Operators.emptySubscription()); //the race alone _could_ previously produce a NPE RaceTestUtils.race(() -> sub.onNext(1), sub::cancel); testSubscriber.assertNoError(); //to be even more sure, we try an onNext AFTER the cancel sub.onNext(2); testSubscriber.assertNoError(); } @Test public void discardAccumulatedOnCancel() { final List<Object> discarded = new ArrayList<>(); final AssertSubscriber<Object> testSubscriber = new AssertSubscriber<>( Operators.enableOnDiscard(Context.empty(), discarded::add)); MonoReduce.ReduceSubscriber<Integer> sub = new MonoReduce.ReduceSubscriber<>(testSubscriber, (current, next) -> current + next); sub.onSubscribe(Operators. emptySubscription()); sub.onNext(1); assertThat(sub.aggregate).isEqualTo(1); sub.cancel(); testSubscriber.assertNoError(); assertThat(discarded).containsExactly(1); } @Test public void discardOnError() { final List<Object> discarded = new ArrayList<>(); final AssertSubscriber<Object> testSubscriber = new AssertSubscriber<>( Operators.enableOnDiscard(Context.empty(), discarded::add)); MonoReduce.ReduceSubscriber<Integer> sub = new MonoReduce.ReduceSubscriber<>(testSubscriber, (current, next) -> current + next); sub.onSubscribe(Operators. emptySubscription()); sub.onNext(1); assertThat(sub.aggregate).isEqualTo(1); sub.onError(new RuntimeException("boom")); testSubscriber.assertErrorMessage("boom"); assertThat(discarded).containsExactly(1); } @Test public void noRetainValueOnComplete() { final AssertSubscriber<Object> testSubscriber = AssertSubscriber.create(); MonoReduce.ReduceSubscriber<Integer> sub = new MonoReduce.ReduceSubscriber<>(testSubscriber, (current, next) -> current + next); sub.onSubscribe(Operators.emptySubscription()); sub.onNext(1); sub.onNext(2); assertThat(sub.aggregate).isEqualTo(3); sub.request(1); sub.onComplete(); assertThat(sub.aggregate).isNull(); testSubscriber.assertNoError(); } @Test public void noRetainValueOnError() { final AssertSubscriber<Object> testSubscriber = AssertSubscriber.create(); MonoReduce.ReduceSubscriber<Integer> sub = new MonoReduce.ReduceSubscriber<>(testSubscriber, (current, next) -> current + next); sub.onSubscribe(Operators.emptySubscription()); sub.onNext(1); sub.onNext(2); assertThat(sub.aggregate).isEqualTo(3); sub.onError(new RuntimeException("boom")); assertThat(sub.aggregate).isNull(); testSubscriber.assertErrorMessage("boom"); } @Test public void scanOperator(){ MonoReduce<Integer> test = new MonoReduce<>(Flux.just(1, 2, 3), (a, b) -> a + b); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); } @Test public void scanSubscriberTerminatedScenario() { CoreSubscriber<String> actual = new LambdaMonoSubscriber<>(null, e -> {}, null, null); MonoReduce.ReduceSubscriber<String> test = new MonoReduce.ReduceSubscriber<>(actual, (s1, s2) -> s1 + s2); Subscription parent = Operators.emptySubscription(); test.onSubscribe(parent); assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(0); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent); assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse(); test.onError(new IllegalStateException("boom")); assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue(); } @Test public void scanSubscriberCancelledScenario() { CoreSubscriber<String> actual = new LambdaMonoSubscriber<>(null, e -> {}, null, null); MonoReduce.ReduceSubscriber<String> test = new MonoReduce.ReduceSubscriber<>(actual, (s1, s2) -> s1 + s2); Subscription parent = Operators.emptySubscription(); test.onSubscribe(parent); assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(0); assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent); assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse(); test.cancel(); assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue(); } }
MonoReduceTest
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/acl/AclPermissionTypeTest.java
{ "start": 992, "end": 3256 }
class ____ { private final AclPermissionType ty; private final int code; private final String name; private final boolean unknown; AclPermissionTypeTestInfo(AclPermissionType ty, int code, String name, boolean unknown) { this.ty = ty; this.code = code; this.name = name; this.unknown = unknown; } } private static final AclPermissionTypeTestInfo[] INFOS = { new AclPermissionTypeTestInfo(AclPermissionType.UNKNOWN, 0, "unknown", true), new AclPermissionTypeTestInfo(AclPermissionType.ANY, 1, "any", false), new AclPermissionTypeTestInfo(AclPermissionType.DENY, 2, "deny", false), new AclPermissionTypeTestInfo(AclPermissionType.ALLOW, 3, "allow", false) }; @Test public void testIsUnknown() { for (AclPermissionTypeTestInfo info : INFOS) { assertEquals(info.unknown, info.ty.isUnknown(), info.ty + " was supposed to have unknown == " + info.unknown); } } @Test public void testCode() { assertEquals(AclPermissionType.values().length, INFOS.length); for (AclPermissionTypeTestInfo info : INFOS) { assertEquals(info.code, info.ty.code(), info.ty + " was supposed to have code == " + info.code); assertEquals(info.ty, AclPermissionType.fromCode((byte) info.code), "AclPermissionType.fromCode(" + info.code + ") was supposed to be " + info.ty); } assertEquals(AclPermissionType.UNKNOWN, AclPermissionType.fromCode((byte) 120)); } @Test public void testName() throws Exception { for (AclPermissionTypeTestInfo info : INFOS) { assertEquals(info.ty, AclPermissionType.fromString(info.name), "AclPermissionType.fromString(" + info.name + ") was supposed to be " + info.ty); } assertEquals(AclPermissionType.UNKNOWN, AclPermissionType.fromString("something")); } @Test public void testExhaustive() { assertEquals(INFOS.length, AclPermissionType.values().length); for (int i = 0; i < INFOS.length; i++) { assertEquals(INFOS[i].ty, AclPermissionType.values()[i]); } } }
AclPermissionTypeTestInfo
java
google__dagger
javatests/dagger/hilt/android/processor/internal/GeneratorsTest.java
{ "start": 30134, "end": 30273 }
class ____ extends Service implements" + " GeneratedComponentManagerHolder {")); }); } }
Hilt_MyService
java
google__dagger
hilt-android/main/java/dagger/hilt/android/internal/lifecycle/HiltViewModelFactory.java
{ "start": 2805, "end": 7531 }
interface ____ { @Multibinds @HiltViewModelMap Map<Class<?>, ViewModel> hiltViewModelMap(); @Multibinds @HiltViewModelAssistedMap Map<Class<?>, Object> hiltViewModelAssistedMap(); } private final Map<Class<?>, Boolean> hiltViewModelKeys; private final ViewModelProvider.Factory delegateFactory; private final ViewModelProvider.Factory hiltViewModelFactory; public HiltViewModelFactory( @NonNull Map<Class<?>, Boolean> hiltViewModelKeys, @NonNull ViewModelProvider.Factory delegateFactory, @NonNull ViewModelComponentBuilder viewModelComponentBuilder) { this.hiltViewModelKeys = hiltViewModelKeys; this.delegateFactory = delegateFactory; this.hiltViewModelFactory = new ViewModelProvider.Factory() { @NonNull @Override public <T extends ViewModel> T create( @NonNull Class<T> modelClass, @NonNull CreationExtras extras) { RetainedLifecycleImpl lifecycle = new RetainedLifecycleImpl(); ViewModelComponent component = viewModelComponentBuilder .savedStateHandle(createSavedStateHandle(extras)) .viewModelLifecycle(lifecycle) .build(); T viewModel = createViewModel(component, modelClass, extras); viewModel.addCloseable(lifecycle::dispatchOnCleared); return viewModel; } @SuppressWarnings("unchecked") private <T extends ViewModel> T createViewModel( @NonNull ViewModelComponent component, @NonNull Class<T> modelClass, @NonNull CreationExtras extras) { Provider<? extends ViewModel> provider = EntryPoints.get(component, ViewModelFactoriesEntryPoint.class) .getHiltViewModelMap() .get(modelClass); Function1<Object, ViewModel> creationCallback = extras.get(CREATION_CALLBACK_KEY); Object assistedFactory = EntryPoints.get(component, ViewModelFactoriesEntryPoint.class) .getHiltViewModelAssistedMap() .get(modelClass); if (assistedFactory == null) { if (creationCallback == null) { if (provider == null) { throw new IllegalStateException( "Expected the @HiltViewModel-annotated class " + modelClass.getName() + " to be available in the multi-binding of " + "@HiltViewModelMap" + " but none was found."); } else { return (T) provider.get(); } } else { // Provider could be null or non-null. throw new IllegalStateException( "Found creation callback but class " + modelClass.getName() + " does not have an assisted factory specified in @HiltViewModel."); } } else { if (provider == null) { if (creationCallback == null) { throw new IllegalStateException( "Found @HiltViewModel-annotated class " + modelClass.getName() + " using @AssistedInject but no creation callback" + " was provided in CreationExtras."); } else { return (T) creationCallback.invoke(assistedFactory); } } else { // Creation callback could be null or non-null. throw new AssertionError( "Found the @HiltViewModel-annotated class " + modelClass.getName() + " in both the multi-bindings of " + "@HiltViewModelMap and @HiltViewModelAssistedMap."); } } } }; } @NonNull @Override public <T extends ViewModel> T create( @NonNull Class<T> modelClass, @NonNull CreationExtras extras) { if (hiltViewModelKeys.containsKey(modelClass)) { return hiltViewModelFactory.create(modelClass, extras); } else { return delegateFactory.create(modelClass, extras); } } @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { if (hiltViewModelKeys.containsKey(modelClass)) { return hiltViewModelFactory.create(modelClass); } else { return delegateFactory.create(modelClass); } } @EntryPoint @InstallIn(ActivityComponent.class)
ViewModelModule
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/converter/json/AbstractJsonHttpMessageConverter.java
{ "start": 1848, "end": 5676 }
class ____ extends AbstractGenericHttpMessageConverter<Object> { /** * The default charset used by the converter. */ public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; private @Nullable String jsonPrefix; public AbstractJsonHttpMessageConverter() { super(MediaType.APPLICATION_JSON, new MediaType("application", "*+json")); setDefaultCharset(DEFAULT_CHARSET); } /** * Specify a custom prefix to use for JSON output. Default is none. * @see #setPrefixJson */ public void setJsonPrefix(String jsonPrefix) { this.jsonPrefix = jsonPrefix; } /** * Indicate whether the JSON output by this view should be prefixed with ")]}', ". * Default is {@code false}. * <p>Prefixing the JSON string in this manner is used to help prevent JSON * Hijacking. The prefix renders the string syntactically invalid as a script * so that it cannot be hijacked. * This prefix should be stripped before parsing the string as JSON. * @see #setJsonPrefix */ public void setPrefixJson(boolean prefixJson) { this.jsonPrefix = (prefixJson ? ")]}', " : null); } @Override public final Object read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return readResolved(GenericTypeResolver.resolveType(type, contextClass), inputMessage); } @Override protected final Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return readResolved(clazz, inputMessage); } private Object readResolved(Type resolvedType, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { Reader reader = getReader(inputMessage); try { return readInternal(resolvedType, reader); } catch (Exception ex) { throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex, inputMessage); } } @Override protected final void writeInternal(Object object, @Nullable Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { Writer writer = getWriter(outputMessage); if (this.jsonPrefix != null) { writer.append(this.jsonPrefix); } try { writeInternal(object, type, writer); } catch (Exception ex) { throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); } } /** * Template method that reads the JSON-bound object from the given {@link Reader}. * @param resolvedType the resolved generic type * @param reader the {@code Reader} to use * @return the JSON-bound object * @throws Exception in case of read/parse failures */ protected abstract Object readInternal(Type resolvedType, Reader reader) throws Exception; /** * Template method that writes the JSON-bound object to the given {@link Writer}. * @param object the object to write to the output message * @param type the type of object to write (may be {@code null}) * @param writer the {@code Writer} to use * @throws Exception in case of write failures */ protected abstract void writeInternal(Object object, @Nullable Type type, Writer writer) throws Exception; private static Reader getReader(HttpInputMessage inputMessage) throws IOException { return new InputStreamReader(inputMessage.getBody(), getCharset(inputMessage.getHeaders())); } private static Writer getWriter(HttpOutputMessage outputMessage) throws IOException { return new OutputStreamWriter(outputMessage.getBody(), getCharset(outputMessage.getHeaders())); } private static Charset getCharset(HttpHeaders headers) { Charset charset = (headers.getContentType() != null ? headers.getContentType().getCharset() : null); return (charset != null ? charset : DEFAULT_CHARSET); } }
AbstractJsonHttpMessageConverter
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/creation/bytebuddy/TypeCachingMockBytecodeGeneratorTest.java
{ "start": 1132, "end": 13967 }
class ____ { @Before public void ensure_disable_gc_is_activated() throws Exception { VmArgAssumptions.assumeVmArgNotPresent("-XX:+DisableExplicitGC"); } @Test public void ensure_cache_is_cleared_if_no_reference_to_classloader_and_classes() throws Exception { // given ClassLoader classloader_with_life_shorter_than_cache = inMemoryClassLoader() .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar")) .build(); TypeCachingBytecodeGenerator cachingMockBytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true); Class<?> the_mock_type = cachingMockBytecodeGenerator.mockClass( withMockFeatures( classloader_with_life_shorter_than_cache.loadClass("foo.Bar"), Collections.<Class<?>>emptySet(), SerializableMode.NONE, false, Answers.RETURNS_DEFAULTS)); ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>(); Reference<Object> typeReference = new PhantomReference<Object>(the_mock_type, referenceQueue); // when classloader_with_life_shorter_than_cache = is_no_more_referenced(); the_mock_type = is_no_more_referenced(); System.gc(); ensure_gc_happened(); // then assertThat(referenceQueue.poll()).isEqualTo(typeReference); } @Test public void ensure_cache_returns_same_instance() throws Exception { // given ClassLoader classloader_with_life_shorter_than_cache = inMemoryClassLoader() .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar")) .build(); TypeCachingBytecodeGenerator cachingMockBytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true); Class<?> the_mock_type = cachingMockBytecodeGenerator.mockClass( withMockFeatures( classloader_with_life_shorter_than_cache.loadClass("foo.Bar"), Collections.<Class<?>>emptySet(), SerializableMode.NONE, false, Answers.RETURNS_DEFAULTS)); Class<?> other_mock_type = cachingMockBytecodeGenerator.mockClass( withMockFeatures( classloader_with_life_shorter_than_cache.loadClass("foo.Bar"), Collections.<Class<?>>emptySet(), SerializableMode.NONE, false, Answers.RETURNS_DEFAULTS)); assertThat(other_mock_type).isSameAs(the_mock_type); ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>(); Reference<Object> typeReference = new PhantomReference<Object>(the_mock_type, referenceQueue); // when classloader_with_life_shorter_than_cache = is_no_more_referenced(); the_mock_type = is_no_more_referenced(); other_mock_type = is_no_more_referenced(); System.gc(); ensure_gc_happened(); // then assertThat(referenceQueue.poll()).isEqualTo(typeReference); } @Test public void ensure_cache_returns_different_instance_serializableMode() throws Exception { // given ClassLoader classloader_with_life_shorter_than_cache = inMemoryClassLoader() .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar")) .build(); TypeCachingBytecodeGenerator cachingMockBytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true); Class<?> the_mock_type = cachingMockBytecodeGenerator.mockClass( withMockFeatures( classloader_with_life_shorter_than_cache.loadClass("foo.Bar"), Collections.<Class<?>>emptySet(), SerializableMode.NONE, false, Answers.RETURNS_DEFAULTS)); Class<?> other_mock_type = cachingMockBytecodeGenerator.mockClass( withMockFeatures( classloader_with_life_shorter_than_cache.loadClass("foo.Bar"), Collections.<Class<?>>emptySet(), SerializableMode.BASIC, false, Answers.RETURNS_DEFAULTS)); assertThat(other_mock_type).isNotSameAs(the_mock_type); } @Test public void ensure_cache_returns_same_instance_defaultAnswer() throws Exception { // given ClassLoader classloader_with_life_shorter_than_cache = inMemoryClassLoader() .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar")) .build(); TypeCachingBytecodeGenerator cachingMockBytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true); Answers[] answers = Answers.values(); Set<Class<?>> classes = Collections.newSetFromMap(new IdentityHashMap<>()); classes.add( cachingMockBytecodeGenerator.mockClass( withMockFeatures( classloader_with_life_shorter_than_cache.loadClass("foo.Bar"), Collections.<Class<?>>emptySet(), SerializableMode.NONE, false, null))); for (Answers answer : answers) { Class<?> klass = cachingMockBytecodeGenerator.mockClass( withMockFeatures( classloader_with_life_shorter_than_cache.loadClass("foo.Bar"), Collections.<Class<?>>emptySet(), SerializableMode.NONE, false, answer)); assertThat(classes.add(klass)).isFalse(); } assertThat(classes).hasSize(1); } @Test public void validate_simple_code_idea_where_weakhashmap_with_classloader_as_key_get_GCed_when_no_more_references() throws Exception { // given WeakHashMap<ClassLoader, Object> cache = new WeakHashMap<ClassLoader, Object>(); ClassLoader short_lived_classloader = inMemoryClassLoader() .withClassDefinition("foo.Bar", makeMarkerInterface("foo.Bar")) .build(); cache.put( short_lived_classloader, new HoldingAReference( new WeakReference<Class<?>>(short_lived_classloader.loadClass("foo.Bar")))); assertThat(cache).hasSize(1); // when short_lived_classloader = is_no_more_referenced(); System.gc(); ensure_gc_happened(); // then assertThat(cache).isEmpty(); } @Test public void cacheLockingStressTest_same_hashcode_different_interface() throws InterruptedException, TimeoutException { Class<?>[] classes = cacheLockingInMemClassLoaderClasses(); Class<?> ifA = classes[0]; Class<?> ifB = classes[1]; var featA = newMockFeatures(ifA, ifB); var featB = newMockFeatures(ifB, ifA); cacheLockingStressTestImpl(featA, featB); } @Test public void cacheLockingStressTest_same_hashcode_same_interface() throws InterruptedException, TimeoutException { Class<?>[] classes = cacheLockingInMemClassLoaderClasses(); Class<?> ifA = classes[0]; var featA = newMockFeatures(ifA); cacheLockingStressTestImpl(featA, featA); } @Test public void cacheLockingStressTest_different_hashcode() throws InterruptedException, TimeoutException { Class<?>[] classes = cacheLockingInMemClassLoaderClasses(); Class<?> ifA = classes[0]; Class<?> ifB = classes[1]; Class<?> ifC = classes[2]; var featA = newMockFeatures(ifA, ifB); var featB = newMockFeatures(ifB, ifC); cacheLockingStressTestImpl(featA, featB); } @Test public void cacheLockingStressTest_unrelated_classes() throws InterruptedException, TimeoutException { Class<?>[] classes = cacheLockingInMemClassLoaderClasses(); Class<?> ifA = classes[0]; Class<?> ifB = classes[1]; var featA = newMockFeatures(ifA); var featB = newMockFeatures(ifB); cacheLockingStressTestImpl(featA, featB); } private void cacheLockingStressTestImpl(MockFeatures<?> featA, MockFeatures<?> featB) throws InterruptedException, TimeoutException { int iterations = 10_000; TypeCachingBytecodeGenerator bytecodeGenerator = new TypeCachingBytecodeGenerator(new SubclassBytecodeGenerator(), true); Phaser phaser = new Phaser(4); Function<Runnable, CompletableFuture<Void>> runCode = code -> CompletableFuture.runAsync( () -> { phaser.arriveAndAwaitAdvance(); try { for (int i = 0; i < iterations; i++) { code.run(); } } finally { phaser.arrive(); } }); var mockFeatAFuture = runCode.apply( () -> { Class<?> mockClass = bytecodeGenerator.mockClass(featA); assertValidMockClass(featA, mockClass); }); var mockFeatBFuture = runCode.apply( () -> { Class<?> mockClass = bytecodeGenerator.mockClass(featB); assertValidMockClass(featB, mockClass); }); var cacheFuture = runCode.apply(bytecodeGenerator::clearAllCaches); // Start test phaser.arriveAndAwaitAdvance(); // Wait for test to end int phase = phaser.arrive(); try { phaser.awaitAdvanceInterruptibly(phase, 30, TimeUnit.SECONDS); } finally { // Collect exceptions from the futures, to make issues visible. mockFeatAFuture.getNow(null); mockFeatBFuture.getNow(null); cacheFuture.getNow(null); } } private static <T> MockFeatures<T> newMockFeatures( Class<T> mockedType, Class<?>... interfaces) { return MockFeatures.withMockFeatures( mockedType, new HashSet<>(Arrays.asList(interfaces)), SerializableMode.NONE, false, null); } private static Class<?>[] cacheLockingInMemClassLoaderClasses() { ClassLoader inMemClassLoader = inMemoryClassLoader() .withClassDefinition("foo.IfA", makeMarkerInterface("foo.IfA")) .withClassDefinition("foo.IfB", makeMarkerInterface("foo.IfB")) .withClassDefinition("foo.IfC", makeMarkerInterface("foo.IfC")) .build(); try { return new Class[] { inMemClassLoader.loadClass("foo.IfA"), inMemClassLoader.loadClass("foo.IfB"), inMemClassLoader.loadClass("foo.IfC") }; } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } private void assertValidMockClass(MockFeatures<?> mockFeature, Class<?> mockClass) { assertThat(mockClass).isAssignableTo(mockFeature.mockedType); for (Class<?> anInterface : mockFeature.interfaces) { assertThat(mockClass).isAssignableTo(anInterface); } } static
TypeCachingMockBytecodeGeneratorTest
java
quarkusio__quarkus
integration-tests/main/src/test/java/io/quarkus/it/main/SchedulerTestCase.java
{ "start": 277, "end": 734 }
class ____ { @Test public void testCount() throws InterruptedException { // Wait at least 1 second Thread.sleep(1000); Response response = given() .when().get("/scheduler/count"); String body = response.asString(); int count = Integer.valueOf(body.split(":")[1]); assertTrue(count > 0); response .then() .statusCode(200); } }
SchedulerTestCase
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/privilege/GetBuiltinPrivilegesRequest.java
{ "start": 519, "end": 729 }
class ____ extends LegacyActionRequest { public GetBuiltinPrivilegesRequest() {} @Override public ActionRequestValidationException validate() { return null; } }
GetBuiltinPrivilegesRequest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/Hamlet.java
{ "start": 473681, "end": 485271 }
class ____<T extends __> extends EImp<T> implements HamletSpec.ACRONYM { public ACRONYM(String name, T parent, EnumSet<EOpt> opts) { super(name, parent, opts); } @Override public ACRONYM<T> $id(String value) { addAttr("id", value); return this; } @Override public ACRONYM<T> $class(String value) { addAttr("class", value); return this; } @Override public ACRONYM<T> $title(String value) { addAttr("title", value); return this; } @Override public ACRONYM<T> $style(String value) { addAttr("style", value); return this; } @Override public ACRONYM<T> $lang(String value) { addAttr("lang", value); return this; } @Override public ACRONYM<T> $dir(Dir value) { addAttr("dir", value); return this; } @Override public ACRONYM<T> $onclick(String value) { addAttr("onclick", value); return this; } @Override public ACRONYM<T> $ondblclick(String value) { addAttr("ondblclick", value); return this; } @Override public ACRONYM<T> $onmousedown(String value) { addAttr("onmousedown", value); return this; } @Override public ACRONYM<T> $onmouseup(String value) { addAttr("onmouseup", value); return this; } @Override public ACRONYM<T> $onmouseover(String value) { addAttr("onmouseover", value); return this; } @Override public ACRONYM<T> $onmousemove(String value) { addAttr("onmousemove", value); return this; } @Override public ACRONYM<T> $onmouseout(String value) { addAttr("onmouseout", value); return this; } @Override public ACRONYM<T> $onkeypress(String value) { addAttr("onkeypress", value); return this; } @Override public ACRONYM<T> $onkeydown(String value) { addAttr("onkeydown", value); return this; } @Override public ACRONYM<T> $onkeyup(String value) { addAttr("onkeyup", value); return this; } @Override public ACRONYM<T> __(Object... lines) { _p(true, lines); return this; } @Override public ACRONYM<T> _r(Object... lines) { _p(false, lines); return this; } @Override public B<ACRONYM<T>> b() { closeAttrs(); return b_(this, true); } @Override public ACRONYM<T> b(String cdata) { return b().__(cdata).__(); } @Override public ACRONYM<T> b(String selector, String cdata) { return setSelector(b(), selector).__(cdata).__(); } @Override public I<ACRONYM<T>> i() { closeAttrs(); return i_(this, true); } @Override public ACRONYM<T> i(String cdata) { return i().__(cdata).__(); } @Override public ACRONYM<T> i(String selector, String cdata) { return setSelector(i(), selector).__(cdata).__(); } @Override public SMALL<ACRONYM<T>> small() { closeAttrs(); return small_(this, true); } @Override public ACRONYM<T> small(String cdata) { return small().__(cdata).__(); } @Override public ACRONYM<T> small(String selector, String cdata) { return setSelector(small(), selector).__(cdata).__(); } @Override public ACRONYM<T> em(String cdata) { return em().__(cdata).__(); } @Override public EM<ACRONYM<T>> em() { closeAttrs(); return em_(this, true); } @Override public ACRONYM<T> em(String selector, String cdata) { return setSelector(em(), selector).__(cdata).__(); } @Override public STRONG<ACRONYM<T>> strong() { closeAttrs(); return strong_(this, true); } @Override public ACRONYM<T> strong(String cdata) { return strong().__(cdata).__(); } @Override public ACRONYM<T> strong(String selector, String cdata) { return setSelector(strong(), selector).__(cdata).__(); } @Override public DFN<ACRONYM<T>> dfn() { closeAttrs(); return dfn_(this, true); } @Override public ACRONYM<T> dfn(String cdata) { return dfn().__(cdata).__(); } @Override public ACRONYM<T> dfn(String selector, String cdata) { return setSelector(dfn(), selector).__(cdata).__(); } @Override public CODE<ACRONYM<T>> code() { closeAttrs(); return code_(this, true); } @Override public ACRONYM<T> code(String cdata) { return code().__(cdata).__(); } @Override public ACRONYM<T> code(String selector, String cdata) { return setSelector(code(), selector).__(cdata).__(); } @Override public ACRONYM<T> samp(String cdata) { return samp().__(cdata).__(); } @Override public SAMP<ACRONYM<T>> samp() { closeAttrs(); return samp_(this, true); } @Override public ACRONYM<T> samp(String selector, String cdata) { return setSelector(samp(), selector).__(cdata).__(); } @Override public KBD<ACRONYM<T>> kbd() { closeAttrs(); return kbd_(this, true); } @Override public ACRONYM<T> kbd(String cdata) { return kbd().__(cdata).__(); } @Override public ACRONYM<T> kbd(String selector, String cdata) { return setSelector(kbd(), selector).__(cdata).__(); } @Override public VAR<ACRONYM<T>> var() { closeAttrs(); return var_(this, true); } @Override public ACRONYM<T> var(String cdata) { return var().__(cdata).__(); } @Override public ACRONYM<T> var(String selector, String cdata) { return setSelector(var(), selector).__(cdata).__(); } @Override public CITE<ACRONYM<T>> cite() { closeAttrs(); return cite_(this, true); } @Override public ACRONYM<T> cite(String cdata) { return cite().__(cdata).__(); } @Override public ACRONYM<T> cite(String selector, String cdata) { return setSelector(cite(), selector).__(cdata).__(); } @Override public ABBR<ACRONYM<T>> abbr() { closeAttrs(); return abbr_(this, true); } @Override public ACRONYM<T> abbr(String cdata) { return abbr().__(cdata).__(); } @Override public ACRONYM<T> abbr(String selector, String cdata) { return setSelector(abbr(), selector).__(cdata).__(); } @Override public A<ACRONYM<T>> a() { closeAttrs(); return a_(this, true); } @Override public A<ACRONYM<T>> a(String selector) { return setSelector(a(), selector); } @Override public ACRONYM<T> a(String href, String anchorText) { return a().$href(href).__(anchorText).__(); } @Override public ACRONYM<T> a(String selector, String href, String anchorText) { return setSelector(a(), selector).$href(href).__(anchorText).__(); } @Override public IMG<ACRONYM<T>> img() { closeAttrs(); return img_(this, true); } @Override public ACRONYM<T> img(String src) { return img().$src(src).__(); } @Override public OBJECT<ACRONYM<T>> object() { closeAttrs(); return object_(this, true); } @Override public OBJECT<ACRONYM<T>> object(String selector) { return setSelector(object(), selector); } @Override public SUB<ACRONYM<T>> sub() { closeAttrs(); return sub_(this, true); } @Override public ACRONYM<T> sub(String cdata) { return sub().__(cdata).__(); } @Override public ACRONYM<T> sub(String selector, String cdata) { return setSelector(sub(), selector).__(cdata).__(); } @Override public SUP<ACRONYM<T>> sup() { closeAttrs(); return sup_(this, true); } @Override public ACRONYM<T> sup(String cdata) { return sup().__(cdata).__(); } @Override public ACRONYM<T> sup(String selector, String cdata) { return setSelector(sup(), selector).__(cdata).__(); } @Override public MAP<ACRONYM<T>> map() { closeAttrs(); return map_(this, true); } @Override public MAP<ACRONYM<T>> map(String selector) { return setSelector(map(), selector); } @Override public ACRONYM<T> q(String cdata) { return q().__(cdata).__(); } @Override public ACRONYM<T> q(String selector, String cdata) { return setSelector(q(), selector).__(cdata).__(); } @Override public Q<ACRONYM<T>> q() { closeAttrs(); return q_(this, true); } @Override public BR<ACRONYM<T>> br() { closeAttrs(); return br_(this, true); } @Override public ACRONYM<T> br(String selector) { return setSelector(br(), selector).__(); } @Override public BDO<ACRONYM<T>> bdo() { closeAttrs(); return bdo_(this, true); } @Override public ACRONYM<T> bdo(Dir dir, String cdata) { return bdo().$dir(dir).__(cdata).__(); } @Override public SPAN<ACRONYM<T>> span() { closeAttrs(); return span_(this, true); } @Override public ACRONYM<T> span(String cdata) { return span().__(cdata).__(); } @Override public ACRONYM<T> span(String selector, String cdata) { return setSelector(span(), selector).__(cdata).__(); } @Override public SCRIPT<ACRONYM<T>> script() { closeAttrs(); return script_(this, true); } @Override public ACRONYM<T> script(String src) { return setScriptSrc(script(), src).__(); } @Override public INS<ACRONYM<T>> ins() { closeAttrs(); return ins_(this, true); } @Override public ACRONYM<T> ins(String cdata) { return ins().__(cdata).__(); } @Override public DEL<ACRONYM<T>> del() { closeAttrs(); return del_(this, true); } @Override public ACRONYM<T> del(String cdata) { return del().__(cdata).__(); } @Override public LABEL<ACRONYM<T>> label() { closeAttrs(); return label_(this, true); } @Override public ACRONYM<T> label(String forId, String cdata) { return label().$for(forId).__(cdata).__(); } @Override public INPUT<ACRONYM<T>> input(String selector) { return setSelector(input(), selector); } @Override public INPUT<ACRONYM<T>> input() { closeAttrs(); return input_(this, true); } @Override public SELECT<ACRONYM<T>> select() { closeAttrs(); return select_(this, true); } @Override public SELECT<ACRONYM<T>> select(String selector) { return setSelector(select(), selector); } @Override public TEXTAREA<ACRONYM<T>> textarea(String selector) { return setSelector(textarea(), selector); } @Override public TEXTAREA<ACRONYM<T>> textarea() { closeAttrs(); return textarea_(this, true); } @Override public ACRONYM<T> textarea(String selector, String cdata) { return setSelector(textarea(), selector).__(cdata).__(); } @Override public BUTTON<ACRONYM<T>> button() { closeAttrs(); return button_(this, true); } @Override public BUTTON<ACRONYM<T>> button(String selector) { return setSelector(button(), selector); } @Override public ACRONYM<T> button(String selector, String cdata) { return setSelector(button(), selector).__(cdata).__(); } } public
ACRONYM
java
grpc__grpc-java
api/src/main/java/io/grpc/MethodDescriptor.java
{ "start": 5644, "end": 5941 }
class ____ all objects produced and consumed by this marshaller */ public Class<T> getMessageClass(); } /** * A marshaller that uses a fixed instance of the type it produces. * * @since 1.1.0 */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/2222") public
for
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/DiscoverySelectors.java
{ "start": 21769, "end": 22330 }
class ____. * * @param classNames the fully qualified names of the classes to select; * never {@code null} and never containing {@code null} or blank names * @since 6.0 * @see #selectClass(String) * @see #selectClassesByName(List) * @see #selectClassesByName(ClassLoader, String...) * @see ClassSelector */ @API(status = EXPERIMENTAL, since = "6.0") public static List<ClassSelector> selectClassesByName(String... classNames) { return selectClassesByName(List.of(classNames)); } /** * Create a {@code ClassSelector} for each supplied
name
java
elastic__elasticsearch
benchmarks/src/main/java/org/elasticsearch/benchmark/bytes/PagedBytesReferenceReadVIntBenchmark.java
{ "start": 1467, "end": 2462 }
class ____ { @Param(value = { "10000000" }) int entries; private StreamInput streamInput; @Setup public void initResults() throws IOException { final BytesStreamOutput tmp = new BytesStreamOutput(); for (int i = 0; i < entries / 2; i++) { tmp.writeVInt(i); } for (int i = 0; i < entries / 2; i++) { tmp.writeVInt(Integer.MAX_VALUE - i); } BytesReference pagedBytes = tmp.bytes(); if (pagedBytes instanceof PagedBytesReference == false) { throw new AssertionError("expected PagedBytesReference but saw [" + pagedBytes.getClass() + "]"); } this.streamInput = pagedBytes.streamInput(); } @Benchmark public int readVInt() throws IOException { int res = 0; streamInput.reset(); for (int i = 0; i < entries; i++) { res = res ^ streamInput.readVInt(); } return res; } }
PagedBytesReferenceReadVIntBenchmark
java
spring-projects__spring-boot
buildSrc/src/test/java/org/springframework/boot/build/bom/bomr/version/DependencyVersionUpgradeTests.java
{ "start": 10224, "end": 10405 }
interface ____ { String current(); String candidate(); } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @ArgumentsSource(InputProvider.class) @
ReleaseTrain
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/EntryPointAssertions_fail_Test.java
{ "start": 1196, "end": 4566 }
class ____ extends EntryPointAssertionsBaseTest { @ParameterizedTest @MethodSource("failFunctions") <T> void should_fail_with_given_message(Function<String, T> failFunction) { // GIVEN String message = "boom!"; // WHEN var assertionError = expectAssertionError(() -> failFunction.apply(message)); // THEN then(assertionError).hasMessage(message); } private static <T> Stream<Function<String, T>> failFunctions() { return Stream.of(Assertions::fail, BDDAssertions::fail, withAssertions::fail); } @ParameterizedTest @MethodSource("failWithParamFunctions") <T> void should_fail_with_given_message_formatted_with_arguments(BiFunction<String, Object[], T> failWithParamFunction) { // GIVEN String message = "%sm!"; // WHEN var assertionError = expectAssertionError(() -> failWithParamFunction.apply(message, array("boo"))); // THEN then(assertionError).hasMessage("boom!"); } private static <T> Stream<BiFunction<String, Object[], T>> failWithParamFunctions() { return Stream.of(Assertions::fail, BDDAssertions::fail, withAssertions::fail); } @ParameterizedTest @MethodSource("failWithCauseFunctions") <T> void should_fail_with_given_message_with_cause(BiFunction<String, Throwable, T> failWithCauseFunction) { // GIVEN String message = "boom!"; Throwable cause = new NullPointerException(); // WHEN var assertionError = expectAssertionError(() -> failWithCauseFunction.apply(message, cause)); // THEN then(assertionError).hasMessage("boom!") .hasCause(cause); } private static <T> Stream<BiFunction<String, Throwable, T>> failWithCauseFunctions() { return Stream.of(Assertions::fail, BDDAssertions::fail, withAssertions::fail); } @ParameterizedTest @MethodSource("failFunctions") void should_return_a_value_to_allow_using_optional_orElseGet(Function<String, Integer> failFunction) { // GIVEN String message = "boom!"; Optional<Integer> empty = Optional.empty(); // WHEN var assertionError = expectAssertionError(() -> doSomethingWithInt(empty.orElseGet(() -> failFunction.apply(message)))); // THEN then(assertionError).hasMessage("boom!"); } private void doSomethingWithInt(@SuppressWarnings("unused") int parameter) { // just to illustrate the previous test } @ParameterizedTest @MethodSource void should_fail_without_message(Supplier<Void> supplier) { // WHEN var assertionError = expectAssertionError(() -> supplier.get()); // THEN then(assertionError).hasMessage(""); } private static Stream<Supplier<Void>> should_fail_without_message() { return Stream.of(Assertions::fail, BDDAssertions::fail, withAssertions::fail); } @ParameterizedTest @MethodSource <T> void should_fail_without_message_but_with_root_cause(Function<Throwable, T> failWithCauseFunction) { // GIVEN String message = "boom!"; Exception cause = new Exception(message); // WHEN var assertionError = expectAssertionError(() -> failWithCauseFunction.apply(cause)); // THEN then(assertionError).hasCause(cause); } private static <T> Stream<Function<Throwable, T>> should_fail_without_message_but_with_root_cause() { return Stream.of(Assertions::fail, BDDAssertions::fail, withAssertions::fail); } }
EntryPointAssertions_fail_Test
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/FindCoordinatorRequest.java
{ "start": 1330, "end": 1460 }
class ____ extends AbstractRequest { public static final short MIN_BATCHED_VERSION = 4; public static
FindCoordinatorRequest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/nullness/EqualsBrokenForNullTest.java
{ "start": 9701, "end": 10001 }
class ____ { @Override public boolean equals(Object other) { if (other != null && other.getClass() == NullCheckAndObjectGetClassLeftOperandDoubleEquals.class) { return true; } return false; } } private
NullCheckAndObjectGetClassLeftOperandDoubleEquals
java
google__dagger
javatests/dagger/functional/subcomponent/multibindings/MultibindingSubcomponents.java
{ "start": 997, "end": 1111 }
class ____ { /** Multibindings for this type are bound only in the parent component. */
MultibindingSubcomponents
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/JpaModelIndexBuildItem.java
{ "start": 346, "end": 605 }
class ____ extends SimpleBuildItem { private final CompositeIndex index; public JpaModelIndexBuildItem(CompositeIndex index) { this.index = index; } public CompositeIndex getIndex() { return index; } }
JpaModelIndexBuildItem
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/scalar/PrintfFunction.java
{ "start": 1321, "end": 1982 }
class ____ extends BuiltInScalarFunction { public PrintfFunction(SpecializedFunction.SpecializedContext context) { super(BuiltInFunctionDefinitions.PRINTF, context); } public @Nullable StringData eval(@Nullable StringData format, Object... obj) { if (format == null) { return null; } StringBuilder strBuf = new StringBuilder(); try (Formatter formatter = new Formatter(strBuf, Locale.US)) { formatter.format(format.toString(), obj); } catch (Throwable t) { return null; } return BinaryStringData.fromString(strBuf.toString()); } }
PrintfFunction
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client-jackson/deployment/src/test/java/io/quarkus/rest/client/reactive/jackson/test/RereadEntityInExceptionMapperTest.java
{ "start": 4003, "end": 5204 }
class ____ extends RuntimeException { public final ErrorMessage errorMessage; public final Response.Status status; public CustomException(String code, String message, Response.Status status) { this(code, message, status, null); } public CustomException(String code, String message, Response.Status status, Throwable cause) { this(new ErrorMessage(code, message), status, cause); } public CustomException(ErrorMessage errorMessage, Response.Status status, Throwable cause) { super(errorMessage.message(), cause); this.errorMessage = errorMessage; this.status = status; } public ErrorMessage getErrorMessage() { return errorMessage; } public Response.Status getStatus() { return status; } @Override public synchronized Throwable fillInStackTrace() { // we don't need the stacktrace, so let's remove the clutter from the CI logs return this; } } public record ErrorMessage(String code, String message) { } @Path("/test") public static
CustomException
java
redisson__redisson
redisson-spring-data/redisson-spring-data-16/src/main/java/org/redisson/spring/data/connection/DataTypeConvertor.java
{ "start": 822, "end": 1021 }
class ____ implements Convertor<DataType> { @Override public DataType convert(Object obj) { String val = obj.toString(); return DataType.fromCode(val); } }
DataTypeConvertor
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/DrdsCancelDDLJob.java
{ "start": 297, "end": 682 }
class ____ extends MySqlStatementImpl implements SQLStatement { private List<Long> jobIds = new ArrayList<Long>(); public void accept0(MySqlASTVisitor visitor) { visitor.visit(this); visitor.endVisit(this); } public List<Long> getJobIds() { return jobIds; } public void addJobId(long id) { jobIds.add(id); } }
DrdsCancelDDLJob
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/datastreams/UpdateDataStreamSettingsAction.java
{ "start": 5356, "end": 12047 }
class ____ extends ActionResponse implements ChunkedToXContentObject { private final List<DataStreamSettingsResponse> dataStreamSettingsResponses; public Response(List<DataStreamSettingsResponse> dataStreamSettingsResponses) { this.dataStreamSettingsResponses = dataStreamSettingsResponses; } public Response(StreamInput in) throws IOException { this(in.readCollectionAsList(DataStreamSettingsResponse::new)); } public List<DataStreamSettingsResponse> getDataStreamSettingsResponses() { return dataStreamSettingsResponses; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeCollection(dataStreamSettingsResponses, (out1, value) -> value.writeTo(out1)); } @Override public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params params) { return Iterators.concat( Iterators.single((builder, params1) -> builder.startObject().startArray("data_streams")), dataStreamSettingsResponses.stream().map(dataStreamSettingsResponse -> (ToXContent) dataStreamSettingsResponse).iterator(), Iterators.single((builder, params1) -> builder.endArray().endObject()) ); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Response response = (Response) o; return Objects.equals(dataStreamSettingsResponses, response.dataStreamSettingsResponses); } @Override public int hashCode() { return Objects.hash(dataStreamSettingsResponses); } } public record DataStreamSettingsResponse( String dataStreamName, boolean dataStreamSucceeded, String dataStreamErrorMessage, Settings settings, Settings effectiveSettings, IndicesSettingsResult indicesSettingsResult ) implements ToXContent, Writeable { public DataStreamSettingsResponse(StreamInput in) throws IOException { this( in.readString(), in.readBoolean(), in.readOptionalString(), Settings.readSettingsFromStream(in), Settings.readSettingsFromStream(in), new IndicesSettingsResult(in) ); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(dataStreamName); out.writeBoolean(dataStreamSucceeded); out.writeOptionalString(dataStreamErrorMessage); settings.writeTo(out); effectiveSettings.writeTo(out); indicesSettingsResult.writeTo(out); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("name", dataStreamName); builder.field("applied_to_data_stream", dataStreamSucceeded); if (dataStreamErrorMessage != null) { builder.field("error", dataStreamErrorMessage); } builder.startObject("settings"); settings.toXContent(builder, params); builder.endObject(); builder.startObject("effective_settings"); effectiveSettings.toXContent(builder, params); builder.endObject(); builder.startObject("index_settings_results"); indicesSettingsResult.toXContent(builder, params); builder.endObject(); builder.endObject(); return builder; } public record IndicesSettingsResult( List<String> appliedToDataStreamOnly, List<String> appliedToDataStreamAndWriteIndex, List<String> appliedToDataStreamAndBackingIndices, List<IndexSettingError> indexSettingErrors ) implements ToXContent, Writeable { public static final IndicesSettingsResult EMPTY = new IndicesSettingsResult(List.of(), List.of(), List.of(), List.of()); public IndicesSettingsResult(StreamInput in) throws IOException { this( in.readStringCollectionAsList(), in.getTransportVersion().supports(DATA_STREAM_WRITE_INDEX_ONLY_SETTINGS) ? in.readStringCollectionAsList() : List.of(), in.readStringCollectionAsList(), in.readCollectionAsList(IndexSettingError::new) ); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("applied_to_data_stream_only", appliedToDataStreamOnly); builder.field("applied_to_data_stream_and_write_indices", appliedToDataStreamAndWriteIndex); builder.field("applied_to_data_stream_and_backing_indices", appliedToDataStreamAndBackingIndices); if (indexSettingErrors.isEmpty() == false) { builder.field("errors", indexSettingErrors); } return builder; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeStringCollection(appliedToDataStreamOnly); if (out.getTransportVersion().supports(DATA_STREAM_WRITE_INDEX_ONLY_SETTINGS)) { out.writeStringCollection(appliedToDataStreamAndWriteIndex); } out.writeStringCollection(appliedToDataStreamAndBackingIndices); out.writeCollection(indexSettingErrors, (out1, value) -> value.writeTo(out1)); } } public record IndexSettingError(String indexName, String errorMessage) implements ToXContent, Writeable { public IndexSettingError(StreamInput in) throws IOException { this(in.readString(), in.readString()); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(indexName); out.writeString(errorMessage); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("index", indexName); builder.field("error", errorMessage); builder.endObject(); return builder; } } } }
Response
java
netty__netty
resolver/src/main/java/io/netty/resolver/NameResolver.java
{ "start": 901, "end": 2303 }
interface ____<T> extends Closeable { /** * Resolves the specified name into an address. * * @param inetHost the name to resolve * * @return the address as the result of the resolution */ Future<T> resolve(String inetHost); /** * Resolves the specified name into an address. * * @param inetHost the name to resolve * @param promise the {@link Promise} which will be fulfilled when the name resolution is finished * * @return the address as the result of the resolution */ Future<T> resolve(String inetHost, Promise<T> promise); /** * Resolves the specified host name and port into a list of address. * * @param inetHost the name to resolve * * @return the list of the address as the result of the resolution */ Future<List<T>> resolveAll(String inetHost); /** * Resolves the specified host name and port into a list of address. * * @param inetHost the name to resolve * @param promise the {@link Promise} which will be fulfilled when the name resolution is finished * * @return the list of the address as the result of the resolution */ Future<List<T>> resolveAll(String inetHost, Promise<List<T>> promise); /** * Closes all the resources allocated and used by this resolver. */ @Override void close(); }
NameResolver
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/planning/StageAllocatorLowCostAligned.java
{ "start": 15129, "end": 16711 }
class ____ { private long startTime; private long endTime; private double cost; private final int gangsCanFit; // Constructor public DurationInterval(long startTime, long endTime, double cost, int gangsCanfit) { this.startTime = startTime; this.endTime = endTime; this.cost = cost; this.gangsCanFit = gangsCanfit; } // canAllocate() - boolean function, returns whether requestedResources // can be allocated during the durationInterval without // violating capacity constraints public boolean canAllocate() { return (gangsCanFit > 0); } // numCanFit() - returns the maximal number of requestedResources can be // allocated during the durationInterval without violating // capacity constraints public int numCanFit() { return gangsCanFit; } public long getStartTime() { return this.startTime; } public void setStartTime(long value) { this.startTime = value; } public long getEndTime() { return this.endTime; } public void setEndTime(long value) { this.endTime = value; } public double getTotalCost() { return this.cost; } public void setTotalCost(double value) { this.cost = value; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(" start: " + startTime).append(" end: " + endTime) .append(" cost: " + cost).append(" gangsCanFit: " + gangsCanFit); return sb.toString(); } } }
DurationInterval
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/idgen/foreign/ForeignGeneratorResourceLocalTest.java
{ "start": 1478, "end": 5028 }
class ____ { private static final Logger log = Logger.getLogger( ForeignGeneratorResourceLocalTest.class ); @AfterEach void dropTestData(EntityManagerFactoryScope factoryScope) { factoryScope.dropData(); } @Test public void baseline(EntityManagerFactoryScope scope) { scope.inTransaction( (entityManager) -> { final Contract contract = new Contract(); entityManager.persist( contract ); final Customer customer = new Customer(); entityManager.persist( customer ); final CustomerContractRelation relation = new CustomerContractRelation(); relation.setContractId( customer.getId() ); customer.addContractRelation( relation ); } ); } @Test public void addRelationImplicitFlush(EntityManagerFactoryScope scope) { doIt( scope, false ); } private void doIt(EntityManagerFactoryScope scope, boolean explicitFlush) { final Long contractId = scope.fromTransaction( (entityManager) -> { var contract = new Contract(); entityManager.persist( contract ); return contract.getId(); } ); final Long customerId = scope.fromTransaction( (entityManager) -> { var customer = new Customer(); entityManager.persist( customer ); return customer.getId(); } ); scope.inTransaction( (entityManager) -> { final String qry = "SELECT c " + "FROM Customer c " + " LEFT JOIN FETCH c.contractRelations " + " WHERE c.id = :customerId"; final Customer customer = entityManager.createQuery( qry, Customer.class ) .setParameter( "customerId", customerId ) .getSingleResult(); final CustomerContractRelation relation = new CustomerContractRelation(); relation.setContractId( contractId ); customer.addContractRelation( relation ); if ( explicitFlush ) { entityManager.flush(); } } ); } @Test public void addRelationExplicitFlush(EntityManagerFactoryScope scope) { doIt( scope, true ); } @Test public void addRelationImplicitFlushCloseEntityManager(EntityManagerFactoryScope scope) { final Long contractId = scope.fromTransaction( (entityManager) -> { Contract contract = new Contract(); entityManager.persist( contract ); return contract.getId(); } ); final Long customerId = scope.fromTransaction( (entityManager) -> { Customer customer = new Customer(); entityManager.persist( customer ); return customer.getId(); } ); EntityManager entityManager = null; EntityTransaction txn = null; try { entityManager = scope.getEntityManagerFactory().createEntityManager(); txn = entityManager.getTransaction(); txn.begin(); final Customer customer = entityManager.createQuery( "SELECT c " + "FROM Customer c " + " LEFT JOIN FETCH c.contractRelations " + " WHERE c.id = :customerId", Customer.class ) .setParameter( "customerId", customerId ) .getSingleResult(); final CustomerContractRelation relation = new CustomerContractRelation(); relation.setContractId( contractId ); customer.addContractRelation( relation ); //Close the EntityManager entityManager.close(); //And, afterward commit the currently running Tx. //This might happen in JTA environments where the Tx is committed by the JTA TM. txn.commit(); } catch (Throwable t) { if ( txn != null && txn.isActive() ) { try { txn.rollback(); } catch (Exception e) { log.error( "Rollback failure", e ); } } throw t; } } @Entity(name = "Contract") @Table(name = "CONTRACT") public static
ForeignGeneratorResourceLocalTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ThrowsUncheckedExceptionTest.java
{ "start": 3831, "end": 4223 }
interface ____ { void f(); } """) .doTest(TEXT_MATCH); } @Test public void deleteLeft() { BugCheckerRefactoringTestHelper.newInstance(ThrowsUncheckedException.class, getClass()) .addInputLines( "in/Test.java", """ import java.io.IOError; import java.io.IOException;
Test
java
elastic__elasticsearch
x-pack/plugin/transform/src/test/java/org/elasticsearch/xpack/transform/action/TransformUpdaterTests.java
{ "start": 3607, "end": 4400 }
class ____ extends ESTestCase { private static final String BOB = "bob"; private final SecurityContext bobSecurityContext = newSecurityContextFor(BOB); private static final String JOHN = "john"; private final SecurityContext johnSecurityContext = newSecurityContextFor(JOHN); private final IndexNameExpressionResolver indexNameExpressionResolver = TestIndexNameExpressionResolver.newInstance(); private TestThreadPool threadPool; private Client client; private TransformAuditor auditor; private final Settings settings = Settings.builder().put(XPackSettings.SECURITY_ENABLED.getKey(), true).build(); private final Settings destIndexSettings = new DefaultTransformExtension().getTransformDestinationIndexSettings(); private static
TransformUpdaterTests
java
apache__camel
components/camel-cxf/camel-cxf-spring-soap/src/test/java/org/apache/camel/component/cxf/util/CxfEndpointUtilsWithSpringTest.java
{ "start": 1863, "end": 6596 }
class ____ extends CamelSpringTestSupport { // set up the port name and service name protected static final QName SERVICE_NAME = new QName("http://www.example.com/test", "ServiceName"); protected static final QName PORT_NAME = new QName("http://www.example.com/test", "PortName"); private static final String CXF_BASE_URI = "cxf://http://www.example.com/testaddress" + "?serviceClass=org.apache.camel.component.cxf.HelloService" + "&portName={http://www.example.com/test}PortName" + "&serviceName={http://www.example.com/test}ServiceName" + "&defaultBus=true"; private static final String NO_SERVICE_CLASS_URI = "cxf://http://www.example.com/testaddress" + "?portName={http://www.example.com/test}PortName" + "&serviceName={http://www.example.com/test}ServiceName"; @Override protected AbstractApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/component/cxf/util/CxfEndpointBeans.xml"); } protected String getEndpointURI() { return "cxf:bean:testEndpoint"; } protected String getNoServiceClassURI() { return "cxf:bean:noServiceClassEndpoint"; } @Test public void testGetServiceClass() throws Exception { CxfEndpoint endpoint = createEndpoint("cxf:bean:helloServiceEndpoint?serviceClass=#helloServiceImpl"); assertEquals("org.apache.camel.component.cxf.HelloServiceImpl", endpoint.getServiceClass().getName()); } public char sepChar() { return '?'; } @Test public void testGetProperties() throws Exception { CxfSpringEndpoint endpoint = (CxfSpringEndpoint) createEndpoint(getEndpointURI()); QName service = endpoint.getServiceNameAsQName(); assertEquals(SERVICE_NAME, service, "We should get the right service name"); assertEquals(DataFormat.RAW, endpoint.getDataFormat().dealias(), "The cxf endpoint's DataFromat should be RAW"); endpoint = (CxfSpringEndpoint) createEndpoint("cxf:bean:testPropertiesEndpoint"); service = CxfSpringEndpointUtils.getServiceName(endpoint); assertEquals(SERVICE_NAME, service, "We should get the right service name"); QName port = CxfSpringEndpointUtils.getPortName(endpoint); assertEquals(PORT_NAME, port, "We should get the right endpoint name"); } @Test public void testGetDataFormatFromCxfEndpontProperties() throws Exception { CxfEndpoint endpoint = createEndpoint(getEndpointURI() + "?dataFormat=PAYLOAD"); assertEquals(DataFormat.PAYLOAD, endpoint.getDataFormat(), "We should get the PAYLOAD DataFormat"); } @Test public void testGetDataFormatCXF() throws Exception { CxfEndpoint endpoint = createEndpoint(getEndpointURI() + sepChar() + "dataFormat=CXF_MESSAGE"); assertEquals(DataFormat.CXF_MESSAGE, endpoint.getDataFormat(), "We should get the Message DataFormat"); } @Test public void testGetDataFormatRAW() throws Exception { CxfEndpoint endpoint = createEndpoint(getEndpointURI() + sepChar() + "dataFormat=RAW"); assertEquals(DataFormat.RAW, endpoint.getDataFormat(), "We should get the Message DataFormat"); } @Test public void testCheckServiceClassWithTheEndpoint() throws Exception { CxfEndpoint endpoint = createEndpoint(getNoServiceClassURI()); assertNull(endpoint.getServiceClass()); } @Test public void testCheckServiceClassProcedure() throws Exception { CxfEndpoint endpoint = createEndpoint(getNoServiceClassURI()); assertNotNull(endpoint.createProducer()); } @Test public void testCheckServiceClassConsumer() throws Exception { CxfEndpoint endpoint = createEndpoint(getNoServiceClassURI()); Consumer cxfConsumer = endpoint.createConsumer(new Processor() { @Override public void process(Exchange exchange) throws Exception { // noop } }); Exception ex = assertThrows(IllegalArgumentException.class, () -> cxfConsumer.start()); assertNotNull(ex, "Should get a CamelException here"); assertTrue(ex.getMessage().startsWith("serviceClass must be specified")); } protected CxfEndpoint createEndpoint(String uri) throws Exception { return (CxfEndpoint) new CxfComponent(context).createEndpoint(uri); } }
CxfEndpointUtilsWithSpringTest
java
apache__rocketmq
store/src/main/java/org/apache/rocketmq/store/ha/io/HAWriter.java
{ "start": 1168, "end": 2256 }
class ____ { private static final Logger LOGGER = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME); protected final List<HAWriteHook> writeHookList = new ArrayList<>(); public boolean write(SocketChannel socketChannel, ByteBuffer byteBufferWrite) throws IOException { int writeSizeZeroTimes = 0; while (byteBufferWrite.hasRemaining()) { int writeSize = socketChannel.write(byteBufferWrite); for (HAWriteHook writeHook : writeHookList) { writeHook.afterWrite(writeSize); } if (writeSize > 0) { writeSizeZeroTimes = 0; } else if (writeSize == 0) { if (++writeSizeZeroTimes >= 3) { break; } } else { LOGGER.info("Write socket < 0"); } } return !byteBufferWrite.hasRemaining(); } public void registerHook(HAWriteHook writeHook) { writeHookList.add(writeHook); } public void clearHook() { writeHookList.clear(); } }
HAWriter
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/objectid/TestObjectIdSerialization.java
{ "start": 3624, "end": 3773 }
class ____ { public int x = 3; } @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") static
Value