language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__camel | components/camel-clickup/src/main/java/org/apache/camel/component/clickup/model/TimeSpentHistoryItemState.java | {
"start": 1367,
"end": 3063
} | class ____ implements Serializable {
@Serial
private static final long serialVersionUID = 0L;
@JsonProperty("id")
private String id; // example: "4207094451598598611",
@JsonProperty("start")
@JsonDeserialize(using = UnixTimestampDeserializer.class)
@JsonSerialize(using = UnixTimestampSerializer.class)
private Instant start; // example: "1726529707994",
@JsonProperty("end")
@JsonDeserialize(using = UnixTimestampDeserializer.class)
@JsonSerialize(using = UnixTimestampSerializer.class)
private Instant end; // example: "1726558507994",
@JsonProperty("time")
private String time; // example: "28800000",
@JsonProperty("source")
private String source; // example: "clickup",
@JsonProperty("date_added")
@JsonDeserialize(using = UnixTimestampDeserializer.class)
@JsonSerialize(using = UnixTimestampSerializer.class)
private Instant dateAdded; // example: "1726558509952"
public String getId() {
return id;
}
public Instant getStart() {
return start;
}
public Instant getEnd() {
return end;
}
public String getTime() {
return time;
}
public String getSource() {
return source;
}
public Instant getDateAdded() {
return dateAdded;
}
@Override
public String toString() {
return "TimeSpentHistoryItemState{" +
"id='" + id + '\'' +
", start=" + start +
", end=" + end +
", time='" + time + '\'' +
", source='" + source + '\'' +
", dateAdded=" + dateAdded +
'}';
}
}
| TimeSpentHistoryItemState |
java | apache__dubbo | dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/Transporters.java | {
"start": 1074,
"end": 2809
} | class ____ {
private Transporters() {}
public static RemotingServer bind(String url, ChannelHandler... handler) throws RemotingException {
return bind(URL.valueOf(url), handler);
}
public static RemotingServer bind(URL url, ChannelHandler... handlers) throws RemotingException {
if (url == null) {
throw new IllegalArgumentException("url == null");
}
if (handlers == null || handlers.length == 0) {
throw new IllegalArgumentException("handlers == null");
}
ChannelHandler handler;
if (handlers.length == 1) {
handler = handlers[0];
} else {
handler = new ChannelHandlerDispatcher(handlers);
}
return getTransporter(url).bind(url, handler);
}
public static Client connect(String url, ChannelHandler... handler) throws RemotingException {
return connect(URL.valueOf(url), handler);
}
public static Client connect(URL url, ChannelHandler... handlers) throws RemotingException {
if (url == null) {
throw new IllegalArgumentException("url == null");
}
ChannelHandler handler;
if (handlers == null || handlers.length == 0) {
handler = new ChannelHandlerAdapter();
} else if (handlers.length == 1) {
handler = handlers[0];
} else {
handler = new ChannelHandlerDispatcher(handlers);
}
return getTransporter(url).connect(url, handler);
}
public static Transporter getTransporter(URL url) {
return url.getOrDefaultFrameworkModel()
.getExtensionLoader(Transporter.class)
.getAdaptiveExtension();
}
}
| Transporters |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/store/DeprecationRoleDescriptorConsumer.java | {
"start": 3629,
"end": 14199
} | class ____ implements Consumer<Collection<RoleDescriptor>> {
private static final String ROLE_PERMISSION_DEPRECATION_STANZA = "Role [%s] contains index privileges covering the [%s] alias but"
+ " which do not cover some of the indices that it points to [%s]. Granting privileges over an alias and hence granting"
+ " privileges over all the indices that the alias points to is deprecated and will be removed in a future version of"
+ " Elasticsearch. Instead define permissions exclusively on index names or index name patterns.";
private static final Logger logger = LogManager.getLogger(DeprecationRoleDescriptorConsumer.class);
private final DeprecationLogger deprecationLogger;
private final ClusterService clusterService;
private final ProjectResolver projectResolver;
private final ThreadPool threadPool;
private final Object mutex;
private final Queue<RoleDescriptor> workQueue;
private boolean workerBusy;
private final Set<String> dailyRoleCache;
public DeprecationRoleDescriptorConsumer(ClusterService clusterService, ProjectResolver projectResolver, ThreadPool threadPool) {
this(clusterService, projectResolver, threadPool, DeprecationLogger.getLogger(DeprecationRoleDescriptorConsumer.class));
}
// package-private for testing
DeprecationRoleDescriptorConsumer(
ClusterService clusterService,
ProjectResolver projectResolver,
ThreadPool threadPool,
DeprecationLogger deprecationLogger
) {
this.clusterService = clusterService;
this.projectResolver = projectResolver;
this.threadPool = threadPool;
this.deprecationLogger = deprecationLogger;
this.mutex = new Object();
this.workQueue = new LinkedList<>();
this.workerBusy = false;
// this String Set keeps "<date>-<role>" pairs so that we only log a role once a day.
this.dailyRoleCache = Collections.newSetFromMap(new LinkedHashMap<String, Boolean>() {
@Override
protected boolean removeEldestEntry(final Map.Entry<String, Boolean> eldest) {
return false == eldest.getKey().startsWith(todayISODate());
}
});
}
@Override
public void accept(Collection<RoleDescriptor> effectiveRoleDescriptors) {
synchronized (mutex) {
for (RoleDescriptor roleDescriptor : effectiveRoleDescriptors) {
if (dailyRoleCache.add(buildCacheKey(roleDescriptor))) {
workQueue.add(roleDescriptor);
}
}
if (false == workerBusy) {
workerBusy = true;
try {
// spawn another worker on the generic thread pool
threadPool.generic().execute(new AbstractRunnable() {
@Override
public void onFailure(Exception e) {
logger.warn("Failed to produce role deprecation messages", e);
synchronized (mutex) {
final boolean hasMoreWork = workQueue.peek() != null;
if (hasMoreWork) {
workerBusy = true; // just being paranoid :)
try {
threadPool.generic().execute(this);
} catch (RejectedExecutionException e1) {
workerBusy = false;
logger.warn("Failed to start working on role alias permisssion deprecation messages", e1);
}
} else {
workerBusy = false;
}
}
}
@Override
protected void doRun() throws Exception {
while (true) {
final RoleDescriptor workItem;
synchronized (mutex) {
workItem = workQueue.poll();
if (workItem == null) {
workerBusy = false;
break;
}
}
logger.trace("Begin role [" + workItem.getName() + "] check for alias permission deprecation");
// executing the check asynchronously will not conserve the generated deprecation response headers (which is
// what we want, because it's not the request that uses deprecated features, but rather the role definition.
// Furthermore, due to caching, we can't reliably associate response headers to every request).
logDeprecatedPermission(workItem);
logger.trace("Completed role [" + workItem.getName() + "] check for alias permission deprecation");
}
}
});
} catch (RejectedExecutionException e) {
workerBusy = false;
logger.warn("Failed to start working on role alias permisssion deprecation messages", e);
}
}
}
}
private void logDeprecatedPermission(RoleDescriptor roleDescriptor) {
final ProjectMetadata metadata = projectResolver.getProjectMetadata(clusterService.state());
final SortedMap<String, IndexAbstraction> aliasOrIndexMap = metadata.getIndicesLookup();
final Map<String, Set<String>> privilegesByAliasMap = new HashMap<>();
// sort answer by alias for tests
final SortedMap<String, Set<String>> privilegesByIndexMap = new TreeMap<>();
// collate privileges by index and by alias separately
for (final IndicesPrivileges indexPrivilege : roleDescriptor.getIndicesPrivileges()) {
final StringMatcher matcher = StringMatcher.of(Arrays.asList(indexPrivilege.getIndices()));
for (final Map.Entry<String, IndexAbstraction> aliasOrIndex : aliasOrIndexMap.entrySet()) {
final String aliasOrIndexName = aliasOrIndex.getKey();
if (matcher.test(aliasOrIndexName)) {
if (aliasOrIndex.getValue().getType() == IndexAbstraction.Type.ALIAS) {
final Set<String> privilegesByAlias = privilegesByAliasMap.computeIfAbsent(aliasOrIndexName, k -> new HashSet<>());
privilegesByAlias.addAll(Arrays.asList(indexPrivilege.getPrivileges()));
} else {
final Set<String> privilegesByIndex = privilegesByIndexMap.computeIfAbsent(aliasOrIndexName, k -> new HashSet<>());
privilegesByIndex.addAll(Arrays.asList(indexPrivilege.getPrivileges()));
}
}
}
}
// compute privileges Automaton for each alias and for each of the indices it points to
final Map<String, Set<IndexPrivilege>> indexPrivilegeMap = new HashMap<>();
for (Map.Entry<String, Set<String>> privilegesByAlias : privilegesByAliasMap.entrySet()) {
final String aliasName = privilegesByAlias.getKey();
final Set<String> aliasPrivilegeNames = privilegesByAlias.getValue();
final Set<IndexPrivilege> aliasPrivileges = IndexPrivilege.resolveBySelectorAccess(aliasPrivilegeNames);
final SortedSet<String> inferiorIndexNames = new TreeSet<>();
for (var aliasPrivilege : aliasPrivileges) {
// TODO implement failures handling in a follow-up
if (aliasPrivilege.getSelectorPredicate() == IndexComponentSelectorPredicate.FAILURES) {
continue;
}
final Automaton aliasPrivilegeAutomaton = aliasPrivilege.getAutomaton();
// check if the alias grants superiors privileges than the indices it points to
for (Index index : aliasOrIndexMap.get(aliasName).getIndices()) {
final Set<String> indexPrivileges = privilegesByIndexMap.get(index.getName());
// null iff the index does not have *any* privilege
if (indexPrivileges != null) {
// compute privilege set once per index no matter how many times it is pointed to
final Set<IndexPrivilege> indexPrivilegeSet = indexPrivilegeMap.computeIfAbsent(
index.getName(),
i -> IndexPrivilege.resolveBySelectorAccess(indexPrivileges)
);
for (var indexPrivilege : indexPrivilegeSet) {
// TODO implement failures handling in a follow-up
if (indexPrivilege.getSelectorPredicate() == IndexComponentSelectorPredicate.FAILURES) {
continue;
}
if (false == Automatons.subsetOf(indexPrivilege.getAutomaton(), aliasPrivilegeAutomaton)) {
inferiorIndexNames.add(index.getName());
}
}
} else {
inferiorIndexNames.add(index.getName());
}
}
}
// log inferior indices for this role, for this alias
if (false == inferiorIndexNames.isEmpty()) {
final String logMessage = String.format(
Locale.ROOT,
ROLE_PERMISSION_DEPRECATION_STANZA,
roleDescriptor.getName(),
aliasName,
String.join(", ", inferiorIndexNames)
);
deprecationLogger.warn(DeprecationCategory.SECURITY, "index_permissions_on_alias", logMessage);
}
}
}
private static String todayISODate() {
return ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.BASIC_ISO_DATE);
}
// package-private for testing
static String buildCacheKey(RoleDescriptor roleDescriptor) {
return todayISODate() + "-" + roleDescriptor.getName();
}
}
| DeprecationRoleDescriptorConsumer |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/proxy/concrete/ConcreteProxyTest.java | {
"start": 2206,
"end": 12396
} | class ____ {
@Test
public void testSingleTable(SessionFactoryScope scope) {
final SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class );
inspector.clear();
// test find and association
scope.inSession( session -> {
//tag::entity-concrete-proxy-find[]
final SingleParent parent1 = session.find( SingleParent.class, 1L );
assertThat( parent1.getSingle(), instanceOf( SingleSubChild1.class ) );
assertThat( Hibernate.isInitialized( parent1.getSingle() ), is( false ) );
final SingleSubChild1 proxy = (SingleSubChild1) parent1.getSingle();
assertThat( Hibernate.isInitialized( proxy ), is( false ) );
//end::entity-concrete-proxy-find[]
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 1 );
inspector.assertNumberOfOccurrenceInQueryNoSpace( 0, "disc_col", 1 );
} );
inspector.clear();
// test query and association
scope.inSession( session -> {
final SingleParent parent2 = session.createQuery(
"from SingleParent where id = 2",
SingleParent.class
).getSingleResult();
assertThat( parent2.getSingle(), instanceOf( SingleChild2.class ) );
assertThat( Hibernate.isInitialized( parent2.getSingle() ), is( false ) );
final SingleChild2 proxy = (SingleChild2) parent2.getSingle();
assertThat( Hibernate.isInitialized( proxy ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 1 );
inspector.assertNumberOfOccurrenceInQueryNoSpace( 0, "disc_col", 1 );
} );
inspector.clear();
// test get reference
scope.inSession( session -> {
//tag::entity-concrete-proxy-reference[]
final SingleChild1 proxy1 = session.getReference( SingleChild1.class, 1L );
assertThat( proxy1, instanceOf( SingleSubChild1.class ) );
assertThat( Hibernate.isInitialized( proxy1 ), is( false ) );
final SingleSubChild1 subChild1 = (SingleSubChild1) proxy1;
assertThat( Hibernate.isInitialized( subChild1 ), is( false ) );
//end::entity-concrete-proxy-reference[]
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfOccurrenceInQueryNoSpace( 0, "disc_col", 2 );
inspector.clear();
final SingleBase proxy2 = session.byId( SingleBase.class ).getReference( 2L );
assertThat( proxy2, instanceOf( SingleChild2.class ) );
assertThat( Hibernate.isInitialized( proxy2 ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfOccurrenceInQueryNoSpace( 0, "disc_col", 1 );
} );
}
@Test
public void testJoined(SessionFactoryScope scope) {
final SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class );
inspector.clear();
// test find and association
scope.inSession( session -> {
final JoinedParent parent1 = session.find( JoinedParent.class, 1L );
assertThat( Hibernate.isInitialized( parent1.getJoined() ), is( false ) );
assertThat( parent1.getJoined(), instanceOf( JoinedSubChild1.class ) );
final JoinedSubChild1 proxy = (JoinedSubChild1) parent1.getJoined();
assertThat( Hibernate.isInitialized( proxy ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 4 );
} );
inspector.clear();
// test query and association
scope.inSession( session -> {
final JoinedParent parent2 = session.createQuery(
"from JoinedParent where id = 2",
JoinedParent.class
).getSingleResult();
assertThat( Hibernate.isInitialized( parent2.getJoined() ), is( false ) );
assertThat( parent2.getJoined(), instanceOf( JoinedChild2.class ) );
final JoinedChild2 proxy = (JoinedChild2) parent2.getJoined();
assertThat( Hibernate.isInitialized( proxy ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 4 );
} );
inspector.clear();
// test get reference
scope.inSession( session -> {
final JoinedChild1 proxy1 = session.getReference( JoinedChild1.class, 1L );
assertThat( proxy1, instanceOf( JoinedSubChild1.class ) );
assertThat( Hibernate.isInitialized( proxy1 ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 1 );
inspector.clear();
final JoinedBase proxy2 = session.byId( JoinedBase.class ).getReference( 2L );
assertThat( proxy2, instanceOf( JoinedChild2.class ) );
assertThat( Hibernate.isInitialized( proxy2 ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 3 );
} );
}
@Test
public void testJoinedDisc(SessionFactoryScope scope) {
final SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class );
inspector.clear();
// test find and association
scope.inSession( session -> {
final JoinedDiscParent parent1 = session.find( JoinedDiscParent.class, 1L );
assertThat( Hibernate.isInitialized( parent1.getJoinedDisc() ), is( false ) );
assertThat( parent1.getJoinedDisc(), instanceOf( JoinedDiscSubChild1.class ) );
final JoinedDiscSubChild1 proxy = (JoinedDiscSubChild1) parent1.getJoinedDisc();
assertThat( Hibernate.isInitialized( proxy ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 1 );
inspector.assertNumberOfOccurrenceInQueryNoSpace( 0, "disc_col", 1 );
} );
inspector.clear();
// test query and association
scope.inSession( session -> {
final JoinedDiscParent parent2 = session.createQuery(
"from JoinedDiscParent where id = 2",
JoinedDiscParent.class
).getSingleResult();
assertThat( Hibernate.isInitialized( parent2.getJoinedDisc() ), is( false ) );
assertThat( parent2.getJoinedDisc(), instanceOf( JoinedDiscChild2.class ) );
final JoinedDiscChild2 proxy = (JoinedDiscChild2) parent2.getJoinedDisc();
assertThat( Hibernate.isInitialized( proxy ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 1 );
inspector.assertNumberOfOccurrenceInQueryNoSpace( 0, "disc_col", 1 );
} );
inspector.clear();
// test get reference
scope.inSession( session -> {
final JoinedDiscChild1 proxy1 = session.getReference( JoinedDiscChild1.class, 1L );
assertThat( proxy1, instanceOf( JoinedDiscSubChild1.class ) );
assertThat( Hibernate.isInitialized( proxy1 ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 0 );
inspector.assertNumberOfOccurrenceInQueryNoSpace( 0, "disc_col", 1 );
inspector.clear();
final JoinedDiscBase proxy2 = session.byId( JoinedDiscBase.class ).getReference( 2L );
assertThat( proxy2, instanceOf( JoinedDiscChild2.class ) );
assertThat( Hibernate.isInitialized( proxy2 ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, 0 );
inspector.assertNumberOfOccurrenceInQueryNoSpace( 0, "disc_col", 1 );
} );
}
@Test
public void testUnion(SessionFactoryScope scope) {
final SQLStatementInspector inspector = scope.getStatementInspector( SQLStatementInspector.class );
inspector.clear();
// test find and association
scope.inSession( session -> {
final UnionParent parent1 = session.find( UnionParent.class, 1L );
assertThat( Hibernate.isInitialized( parent1.getUnion() ), is( false ) );
assertThat( parent1.getUnion(), instanceOf( UnionSubChild1.class ) );
final UnionSubChild1 proxy = (UnionSubChild1) parent1.getUnion();
assertThat( Hibernate.isInitialized( proxy ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 1 );
inspector.assertNumberOfOccurrenceInQuery( 0, "union", 3 );
} );
inspector.clear();
// test query and association
scope.inSession( session -> {
final UnionParent parent2 = session.createQuery(
"from UnionParent where id = 2",
UnionParent.class
).getSingleResult();
assertThat( Hibernate.isInitialized( parent2.getUnion() ), is( false ) );
assertThat( parent2.getUnion(), instanceOf( UnionChild2.class ) );
final UnionChild2 proxy = (UnionChild2) parent2.getUnion();
assertThat( Hibernate.isInitialized( proxy ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfJoins( 0, SqlAstJoinType.LEFT, 1 );
inspector.assertNumberOfOccurrenceInQuery( 0, "union", 3 );
} );
inspector.clear();
// test get reference
scope.inSession( session -> {
final UnionChild1 proxy1 = session.getReference( UnionChild1.class, 1L );
assertThat( proxy1, instanceOf( UnionSubChild1.class ) );
assertThat( Hibernate.isInitialized( proxy1 ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfOccurrenceInQuery( 0, "union", 1 );
inspector.clear();
final UnionBase proxy2 = session.byId( UnionBase.class ).getReference( 2L );
assertThat( proxy2, instanceOf( UnionChild2.class ) );
assertThat( Hibernate.isInitialized( proxy2 ), is( false ) );
inspector.assertExecutedCount( 1 );
inspector.assertNumberOfOccurrenceInQuery( 0, "union", 3 );
} );
}
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
session.persist( new SingleParent( 1L, new SingleSubChild1( 1L, "1", "1" ) ) );
session.persist( new JoinedParent( 1L, new JoinedSubChild1( 1L, "1", "1" ) ) );
session.persist( new JoinedDiscParent( 1L, new JoinedDiscSubChild1( 1L, "1", "1" ) ) );
session.persist( new UnionParent( 1L, new UnionSubChild1( 1L, "1", "1" ) ) );
session.persist( new SingleParent( 2L, new SingleChild2( 2L, 2 ) ) );
session.persist( new JoinedParent( 2L, new JoinedChild2( 2L, 2 ) ) );
session.persist( new JoinedDiscParent( 2L, new JoinedDiscChild2( 2L, 2 ) ) );
session.persist( new UnionParent( 2L, new UnionChild2( 2L, 2 ) ) );
} );
}
@AfterAll
public void tearDown(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncateMappedObjects();
}
// InheritanceType.SINGLE_TABLE
//tag::entity-concrete-proxy-mapping[]
@Entity(name = "SingleParent")
public static | ConcreteProxyTest |
java | apache__camel | test-infra/camel-test-infra-openldap/src/main/java/org/apache/camel/test/infra/openldap/services/OpenldapInfraService.java | {
"start": 984,
"end": 1123
} | interface ____ extends InfrastructureService {
Integer getPort();
Integer getSslPort();
String getHost();
}
| OpenldapInfraService |
java | google__dagger | dagger-android/main/java/dagger/android/DaggerBroadcastReceiver.java | {
"start": 933,
"end": 1162
} | class ____ only be used for {@link BroadcastReceiver}s that are declared in an {@code
* AndroidManifest.xml}. If, instead, the {@link BroadcastReceiver} is created in code, prefer
* constructor injection.
*
* <p>Note: this | should |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlBaseBaseVisitor.java | {
"start": 154,
"end": 485
} | class ____ an empty implementation of {@link SqlBaseVisitor},
* which can be extended to create a visitor which only needs to handle a subset
* of the available methods.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
@SuppressWarnings("CheckReturnValue")
| provides |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/blobstore/OperationPurpose.java | {
"start": 770,
"end": 1579
} | enum ____ {
SNAPSHOT_DATA("SnapshotData"),
SNAPSHOT_METADATA("SnapshotMetadata"),
REPOSITORY_ANALYSIS("RepositoryAnalysis"),
CLUSTER_STATE("ClusterState"),
INDICES("Indices"),
TRANSLOG("Translog");
private final String key;
OperationPurpose(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public static OperationPurpose parse(String s) {
for (OperationPurpose purpose : OperationPurpose.values()) {
if (purpose.key.equals(s)) {
return purpose;
}
}
throw new IllegalArgumentException(
Strings.format("invalid purpose [%s] expected one of [%s]", s, Strings.arrayToCommaDelimitedString(OperationPurpose.values()))
);
}
}
| OperationPurpose |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/formulajoin/FormulaJoinTest.java | {
"start": 868,
"end": 3406
} | class ____ {
@Test
public void testFormulaJoin(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Root root = new Root();
root.setName( "root 1" );
Detail current = new Detail();
current.setCurrentVersion( true );
current.setVersion( 2 );
current.setDetails( "details of root 1 blah blah" );
current.setRoot( root );
root.setDetail( current );
Detail past = new Detail();
past.setCurrentVersion( false );
past.setVersion( 1 );
past.setDetails( "old details of root 1 yada yada" );
past.setRoot( root );
session.persist( root );
session.persist( past );
session.persist( current );
}
);
if ( scope.getSessionFactory().getJdbcServices().getDialect() instanceof PostgreSQLDialect ) {
return;
}
scope.inTransaction(
session -> {
List<Object[]> l = session.createQuery( "from Root m left join m.detail d", Object[].class ).list();
assertThat( l ).hasSize( 1 );
}
);
scope.inTransaction(
session -> {
List<Root> l = session.createQuery( "from Root m left join fetch m.detail", Root.class ).list();
assertThat( l ).hasSize( 1 );
Root m = l.get( 0 );
assertThat( m.getDetail().getRoot().getName() ).isEqualTo( "root 1" );
assertThat( m.getDetail().getRoot() ).isEqualTo( m );
}
);
scope.inTransaction(
session -> {
List<Root> l = session.createQuery( "from Root m join fetch m.detail", Root.class ).list();
assertThat( l ).hasSize( 1 );
}
);
scope.inTransaction(
session -> {
List<Detail> l = session.createQuery( "from Detail d join fetch d.currentRoot.root", Detail.class )
.list();
assertThat( l ).hasSize( 2 );
}
);
scope.inTransaction(
session -> {
List<Detail> l = session.createQuery( "from Detail d join fetch d.root", Detail.class ).list();
assertThat( l ).hasSize( 2 );
}
);
scope.inTransaction(
session -> {
List<Detail> l = session.createQuery( "from Detail d join fetch d.currentRoot.root m join fetch m.detail",
Detail.class ).list();
assertThat( l ).hasSize( 2 );
}
);
scope.inTransaction(
session -> {
List<Detail> l = session.createQuery( "from Detail d join fetch d.root m join fetch m.detail",
Detail.class ).list();
assertThat( l ).hasSize( 2 );
session.createMutationQuery( "delete from Detail" ).executeUpdate();
session.createMutationQuery( "delete from Root" ).executeUpdate();
}
);
}
}
| FormulaJoinTest |
java | apache__camel | components/camel-huawei/camel-huaweicloud-imagerecognition/src/main/java/org/apache/camel/component/huaweicloud/image/models/ClientConfigurations.java | {
"start": 872,
"end": 3685
} | class ____ {
private String accessKey;
private String secretKey;
private String projectId;
private String proxyHost;
private int proxyPort;
private String proxyUser;
private String proxyPassword;
private boolean ignoreSslVerification;
private String endpoint;
private String imageContent;
private String imageUrl;
private String tagLanguage;
private int tagLimit;
private float threshold;
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getProxyHost() {
return proxyHost;
}
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
public int getProxyPort() {
return proxyPort;
}
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
public String getProxyUser() {
return proxyUser;
}
public void setProxyUser(String proxyUser) {
this.proxyUser = proxyUser;
}
public String getProxyPassword() {
return proxyPassword;
}
public void setProxyPassword(String proxyPassword) {
this.proxyPassword = proxyPassword;
}
public boolean isIgnoreSslVerification() {
return ignoreSslVerification;
}
public void setIgnoreSslVerification(boolean ignoreSslVerification) {
this.ignoreSslVerification = ignoreSslVerification;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getImageContent() {
return imageContent;
}
public void setImageContent(String imageContent) {
this.imageContent = imageContent;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getTagLanguage() {
return tagLanguage;
}
public void setTagLanguage(String tagLanguage) {
this.tagLanguage = tagLanguage;
}
public float getThreshold() {
return threshold;
}
public void setThreshold(float threshold) {
this.threshold = threshold;
}
public int getTagLimit() {
return tagLimit;
}
public void setTagLimit(int tagLimit) {
this.tagLimit = tagLimit;
}
}
| ClientConfigurations |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/aggregator/CustomAggregationStrategyTest.java | {
"start": 1177,
"end": 2785
} | class ____ extends ContextTestSupport {
@Test
public void testCustomAggregationStrategy() throws Exception {
// START SNIPPET: e2
MockEndpoint result = getMockEndpoint("mock:result");
// we expect to find the two winners with the highest bid
result.expectedBodiesReceivedInAnyOrder("200", "150");
// then we sent all the message at once
template.sendBodyAndHeader("direct:start", "100", "id", "1");
template.sendBodyAndHeader("direct:start", "150", "id", "2");
template.sendBodyAndHeader("direct:start", "130", "id", "2");
template.sendBodyAndHeader("direct:start", "200", "id", "1");
template.sendBodyAndHeader("direct:start", "190", "id", "1");
assertMockEndpointsSatisfied();
// END SNIPPET: e2
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// START SNIPPET: e1
// our route is aggregating from the direct queue and sending
// the response to the mock
from("direct:start")
// aggregated by header id and use our own strategy how to
// aggregate
.aggregate(new MyAggregationStrategy()).header("id")
// wait for 1 seconds to aggregate
.completionTimeout(1000L).to("mock:result");
// END SNIPPET: e1
}
};
}
// START SNIPPET: e3
private static | CustomAggregationStrategyTest |
java | google__dagger | javatests/dagger/internal/codegen/BindsOptionalOfMethodValidationTest.java | {
"start": 1485,
"end": 4431
} | class ____ {
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
return ImmutableList.copyOf(new Object[][] {{Module.class}, {ProducerModule.class}});
}
private final String moduleDeclaration;
public BindsOptionalOfMethodValidationTest(Class<? extends Annotation> moduleAnnotation) {
moduleDeclaration = "@" + moduleAnnotation.getCanonicalName() + " abstract class %s { %s }";
}
@Test
public void nonAbstract() {
assertThatMethod("@BindsOptionalOf Object concrete() { return null; }")
.hasError("must be abstract");
}
@Test
public void hasParameters() {
assertThatMethod("@BindsOptionalOf abstract Object hasParameters(String s1);")
.hasError("parameters");
}
@Test
public void typeParameters() {
assertThatMethod("@BindsOptionalOf abstract <S> S generic();").hasError("type parameters");
}
@Test
public void notInModule() {
assertThatMethodInUnannotatedClass("@BindsOptionalOf abstract Object notInModule();")
.hasError("within a @Module or @ProducerModule");
}
@Test
public void throwsException() {
assertThatMethod("@BindsOptionalOf abstract Object throwsException() throws RuntimeException;")
.hasError("may not throw");
}
@Test
public void returnsVoid() {
assertThatMethod("@BindsOptionalOf abstract void returnsVoid();").hasError("void");
}
@Test
public void returnsMembersInjector() {
assertThatMethod("@BindsOptionalOf abstract MembersInjector<Object> returnsMembersInjector();")
.hasError("framework");
}
@Test
public void tooManyQualifiers() {
assertThatMethod(
"@BindsOptionalOf @Qualifier1 @Qualifier2 abstract String tooManyQualifiers();")
.importing(Qualifier1.class, Qualifier2.class)
.hasError("more than one @Qualifier");
}
@Test
public void intoSet() {
assertThatMethod("@BindsOptionalOf @IntoSet abstract String intoSet();")
.hasError("cannot have multibinding annotations");
}
@Test
public void elementsIntoSet() {
assertThatMethod("@BindsOptionalOf @ElementsIntoSet abstract Set<String> elementsIntoSet();")
.hasError("cannot have multibinding annotations");
}
@Test
public void intoMap() {
assertThatMethod("@BindsOptionalOf @IntoMap abstract String intoMap();")
.hasError("cannot have multibinding annotations");
}
/**
* Tests that @BindsOptionalOf @IntoMap actually causes module validation to fail.
*
* @see <a href="http://b/118434447">bug 118434447</a>
*/
@Test
public void intoMapWithComponent() {
Source module =
CompilerTests.javaSource(
"test.TestModule",
"package test;",
"",
"import dagger.BindsOptionalOf;",
"import dagger.Module;",
"import dagger.multibindings.IntoMap;",
"",
"@Module",
" | BindsOptionalOfMethodValidationTest |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/access/PathPatternRequestTransformer.java | {
"start": 1192,
"end": 1582
} | class ____
implements AuthorizationManagerWebInvocationPrivilegeEvaluator.HttpServletRequestTransformer {
@Override
public HttpServletRequest transform(HttpServletRequest request) {
HttpServletRequest wrapped = new AttributesSupportingHttpServletRequest(request);
ServletRequestPathUtils.parseAndCache(wrapped);
return wrapped;
}
private static final | PathPatternRequestTransformer |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest100.java | {
"start": 329,
"end": 2238
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "CREATE TABLE IF NOT EXISTS ttable\n" +
"(\n" +
"`id` BIGINT(20) NOT NULL AUTO_INCREMENT,\n" +
"`queue_id` varchar(20) NOT NULL DEFAULT '-1',\n" +
"`status` TINYINT(4) NOT NULL DEFAULT '1',\n" +
"`geometry` geometry not null,\n" +
"CONSTRAINT PRIMARY KEY (`id`),\n" +
"CONSTRAINT UNIQUE KEY `uk_queue_id` USING BTREE (`queue_id`) KEY_BLOCK_SIZE=10,\n" +
"FULLTEXT KEY `ft_status` (`queue_id`),\n" +
"spatial index `spatial` (`geometry`),\n" +
"CONSTRAINT FOREIGN KEY `fk_test`(`queue_id`) REFERENCES `test`(`id`)\n" +
") ENGINE=INNODB";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0);
assertEquals(1, statementList.size());
assertEquals(9, stmt.getTableElementList().size());
assertEquals("CREATE TABLE IF NOT EXISTS ttable (\n" +
"\t`id` BIGINT(20) NOT NULL AUTO_INCREMENT,\n" +
"\t`queue_id` varchar(20) NOT NULL DEFAULT '-1',\n" +
"\t`status` TINYINT(4) NOT NULL DEFAULT '1',\n" +
"\t`geometry` geometry NOT NULL,\n" +
"\tPRIMARY KEY (`id`),\n" +
"\tUNIQUE KEY `uk_queue_id` USING BTREE (`queue_id`) KEY_BLOCK_SIZE = 10,\n" +
"\tFULLTEXT KEY `ft_status` (`queue_id`),\n" +
"\tSPATIAL INDEX `spatial`(`geometry`),\n" +
"\tCONSTRAINT FOREIGN KEY `fk_test` (`queue_id`) REFERENCES `test` (`id`)\n" +
") ENGINE = INNODB", stmt.toString());
}
}
| MySqlCreateTableTest100 |
java | spring-projects__spring-boot | module/spring-boot-cache/src/main/java/org/springframework/boot/cache/autoconfigure/CacheAutoConfiguration.java | {
"start": 3364,
"end": 4135
} | class ____ {
@Bean
@ConditionalOnMissingBean
CacheManagerCustomizers cacheManagerCustomizers(ObjectProvider<CacheManagerCustomizer<?>> customizers) {
return new CacheManagerCustomizers(customizers.orderedStream().toList());
}
@Bean
CacheManagerValidator cacheAutoConfigurationValidator(CacheProperties cacheProperties,
ObjectProvider<CacheManager> cacheManager) {
return new CacheManagerValidator(cacheProperties, cacheManager);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ EntityManagerFactoryDependsOnPostProcessor.class,
LocalContainerEntityManagerFactoryBean.class })
@ConditionalOnBean(AbstractEntityManagerFactoryBean.class)
@Import(CacheManagerEntityManagerFactoryDependsOnPostProcessor.class)
static | CacheAutoConfiguration |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_1200/Issue1278.java | {
"start": 1793,
"end": 1931
} | class ____ {
@JSONField(alternateNames = {"name", "user"})
public String name;
public int id;
}
}
| AlternateNames |
java | apache__camel | components/camel-stomp/src/test/java/org/apache/camel/component/stomp/StompProducerTest.java | {
"start": 1782,
"end": 4197
} | class ____ extends StompBaseTest {
private static final Logger LOG = LoggerFactory.getLogger(StompProducerTest.class);
private static final String HEADER = "testheader1";
private static final String HEADER_VALUE = "testheader1";
@Test
public void testProduce() throws Exception {
context.addRoutes(createRouteBuilder());
context.start();
Stomp stomp = createStompClient();
final BlockingConnection subscribeConnection = stomp.connectBlocking();
StompFrame frame = new StompFrame(SUBSCRIBE);
frame.addHeader(DESTINATION, StompFrame.encodeHeader("test"));
frame.addHeader(ID, subscribeConnection.nextId());
subscribeConnection.request(frame);
final CountDownLatch latch = new CountDownLatch(numberOfMessages);
Thread thread = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < numberOfMessages; i++) {
try {
StompFrame frame = subscribeConnection.receive();
assertTrue(frame.contentAsString().startsWith("test message "));
assertTrue(frame.getHeader(new AsciiBuffer(HEADER)).ascii().toString().startsWith(HEADER_VALUE));
latch.countDown();
} catch (Exception e) {
LOG.warn("Unhandled exception receiving STOMP data: {}", e.getMessage(), e);
break;
}
}
}
});
thread.start();
Endpoint endpoint = context.getEndpoint("direct:foo");
Producer producer = endpoint.createProducer();
for (int i = 0; i < numberOfMessages; i++) {
Exchange exchange = endpoint.createExchange();
exchange.getIn().setBody(("test message " + i).getBytes("UTF-8"));
exchange.getIn().setHeader(HEADER, HEADER_VALUE);
producer.process(exchange);
}
latch.await(20, TimeUnit.SECONDS);
assertEquals(0, latch.getCount(), "Messages not consumed = " + latch.getCount());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:foo").toF("stomp:test?brokerURL=tcp://localhost:%s", servicePort);
}
};
}
}
| StompProducerTest |
java | apache__flink | flink-end-to-end-tests/flink-failure-enricher-test/src/main/java/org/apache/flink/runtime/enricher/CustomTestFailureEnricherFactory.java | {
"start": 1084,
"end": 1301
} | class ____ implements FailureEnricherFactory {
@Override
public FailureEnricher createFailureEnricher(Configuration conf) {
return new CustomTestFailureEnricher();
}
}
| CustomTestFailureEnricherFactory |
java | apache__kafka | connect/runtime/src/main/java/org/apache/kafka/connect/runtime/SubmittedRecords.java | {
"start": 1999,
"end": 8284
} | class ____ {
private static final Logger log = LoggerFactory.getLogger(SubmittedRecords.class);
// Visible for testing
final Map<Map<String, Object>, Deque<SubmittedRecord>> records = new HashMap<>();
private int numUnackedMessages = 0;
private CountDownLatch messageDrainLatch;
public SubmittedRecords() {
}
/**
* Enqueue a new source record before dispatching it to a producer.
* The returned {@link SubmittedRecord} should either be {@link SubmittedRecord#ack() acknowledged} in the
* producer callback, or {@link SubmittedRecord#drop() dropped} if the record could not be successfully
* sent to the producer.
*
* @param record the record about to be dispatched; may not be null but may have a null
* {@link SourceRecord#sourcePartition()} and/or {@link SourceRecord#sourceOffset()}
* @return a {@link SubmittedRecord} that can be either {@link SubmittedRecord#ack() acknowledged} once ack'd by
* the producer, or {@link SubmittedRecord#drop() dropped} if synchronously rejected by the producer
*/
@SuppressWarnings("unchecked")
public SubmittedRecord submit(SourceRecord record) {
return submit((Map<String, Object>) record.sourcePartition(), (Map<String, Object>) record.sourceOffset());
}
// Convenience method for testing
SubmittedRecord submit(Map<String, Object> partition, Map<String, Object> offset) {
SubmittedRecord result = new SubmittedRecord(partition, offset);
records.computeIfAbsent(result.partition(), p -> new LinkedList<>())
.add(result);
synchronized (this) {
numUnackedMessages++;
}
return result;
}
/**
* Clear out any acknowledged records at the head of the deques and return a {@link CommittableOffsets snapshot} of the offsets and offset metadata
* accrued between the last time this method was invoked and now. This snapshot can be {@link CommittableOffsets#updatedWith(CommittableOffsets) combined}
* with an existing snapshot if desired.
* Note that this may take some time to complete if a large number of records has built up, which may occur if a
* Kafka partition is offline and all records targeting that partition go unacknowledged while records targeting
* other partitions continue to be dispatched to the producer and sent successfully
* @return a fresh offset snapshot; never null
*/
public CommittableOffsets committableOffsets() {
Map<Map<String, Object>, Map<String, Object>> offsets = new HashMap<>();
int totalCommittableMessages = 0;
int totalUncommittableMessages = 0;
int largestDequeSize = 0;
Map<String, Object> largestDequePartition = null;
for (Map.Entry<Map<String, Object>, Deque<SubmittedRecord>> entry : records.entrySet()) {
Map<String, Object> partition = entry.getKey();
Deque<SubmittedRecord> queuedRecords = entry.getValue();
int initialDequeSize = queuedRecords.size();
if (canCommitHead(queuedRecords)) {
Map<String, Object> offset = committableOffset(queuedRecords);
offsets.put(partition, offset);
}
int uncommittableMessages = queuedRecords.size();
int committableMessages = initialDequeSize - uncommittableMessages;
totalCommittableMessages += committableMessages;
totalUncommittableMessages += uncommittableMessages;
if (uncommittableMessages > largestDequeSize) {
largestDequeSize = uncommittableMessages;
largestDequePartition = partition;
}
}
// Clear out all empty deques from the map to keep it from growing indefinitely
records.values().removeIf(Deque::isEmpty);
return new CommittableOffsets(offsets, totalCommittableMessages, totalUncommittableMessages, records.size(), largestDequeSize, largestDequePartition);
}
/**
* Wait for all currently in-flight messages to be acknowledged, up to the requested timeout.
* This method is expected to be called from the same thread that calls {@link #committableOffsets()}.
* @param timeout the maximum time to wait
* @param timeUnit the time unit of the timeout argument
* @return whether all in-flight messages were acknowledged before the timeout elapsed
*/
public boolean awaitAllMessages(long timeout, TimeUnit timeUnit) {
// Create a new message drain latch as a local variable to avoid SpotBugs warnings about inconsistent synchronization
// on an instance variable when invoking CountDownLatch::await outside a synchronized block
CountDownLatch messageDrainLatch;
synchronized (this) {
messageDrainLatch = new CountDownLatch(numUnackedMessages);
this.messageDrainLatch = messageDrainLatch;
}
try {
return messageDrainLatch.await(timeout, timeUnit);
} catch (InterruptedException e) {
return false;
}
}
// Note that this will return null if either there are no committable offsets for the given deque, or the latest
// committable offset is itself null. The caller is responsible for distinguishing between the two cases.
private Map<String, Object> committableOffset(Deque<SubmittedRecord> queuedRecords) {
Map<String, Object> result = null;
while (canCommitHead(queuedRecords)) {
result = queuedRecords.poll().offset();
}
return result;
}
private boolean canCommitHead(Deque<SubmittedRecord> queuedRecords) {
return queuedRecords.peek() != null && queuedRecords.peek().acked();
}
// Synchronize in order to ensure that the number of unacknowledged messages isn't modified in the middle of a call
// to awaitAllMessages (which might cause us to decrement first, then create a new message drain latch, then count down
// that latch here, effectively double-acking the message)
private synchronized void messageAcked() {
numUnackedMessages--;
if (messageDrainLatch != null) {
messageDrainLatch.countDown();
}
}
public | SubmittedRecords |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/SignalLogger.java | {
"start": 999,
"end": 1356
} | class ____ a message whenever we're about to exit on a UNIX signal.
* This is helpful for determining the root cause of a process' exit.
* For example, if the process exited because the system administrator
* ran a standard "kill," you would see 'EXITING ON SIGNAL SIGTERM' in the log.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public | logs |
java | apache__camel | core/camel-util/src/test/java/org/apache/camel/util/backoff/BackOffTest.java | {
"start": 987,
"end": 3968
} | class ____ {
@Test
public void testSimpleBackOff() {
final BackOff backOff = BackOff.builder().build();
final BackOffTimerTask context = new BackOffTimerTask(null, backOff, null, t -> true);
long delay;
for (int i = 1; i <= 5; i++) {
delay = context.next();
assertEquals(i, context.getCurrentAttempts());
assertEquals(BackOff.DEFAULT_DELAY.toMillis(), delay);
assertEquals(BackOff.DEFAULT_DELAY.toMillis(), context.getCurrentDelay());
assertEquals(BackOff.DEFAULT_DELAY.toMillis() * i, context.getCurrentElapsedTime());
}
}
@Test
public void testBackOffWithMultiplier() {
final BackOff backOff = BackOff.builder().multiplier(1.5).build();
final BackOffTimerTask context = new BackOffTimerTask(null, backOff, null, t -> true);
long delay = BackOff.DEFAULT_DELAY.toMillis();
long oldDelay;
long elapsed = 0;
for (int i = 1; i <= 5; i++) {
oldDelay = delay;
delay = context.next();
elapsed += delay;
assertEquals(i, context.getCurrentAttempts());
assertEquals((long) (oldDelay * 1.5), delay);
assertEquals((long) (oldDelay * 1.5), context.getCurrentDelay());
assertEquals(elapsed, context.getCurrentElapsedTime(), 0);
}
}
@Test
public void testBackOffWithMaxAttempts() {
final BackOff backOff = BackOff.builder().maxAttempts(5L).build();
final BackOffTimerTask context = new BackOffTimerTask(null, backOff, null, t -> true);
long delay;
for (int i = 1; i <= 5; i++) {
delay = context.next();
assertEquals(i, context.getCurrentAttempts());
assertEquals(BackOff.DEFAULT_DELAY.toMillis(), delay);
assertEquals(BackOff.DEFAULT_DELAY.toMillis(), context.getCurrentDelay());
assertEquals(BackOff.DEFAULT_DELAY.toMillis() * i, context.getCurrentElapsedTime());
}
delay = context.next();
assertEquals(6, context.getCurrentAttempts());
assertEquals(BackOff.NEVER, delay);
}
@Test
public void testBackOffWithMaxTime() {
final BackOff backOff = BackOff.builder().maxElapsedTime(9, TimeUnit.SECONDS).build();
final BackOffTimerTask context = new BackOffTimerTask(null, backOff, null, t -> true);
long delay;
for (int i = 1; i <= 5; i++) {
delay = context.next();
assertEquals(i, context.getCurrentAttempts());
assertEquals(BackOff.DEFAULT_DELAY.toMillis(), delay);
assertEquals(BackOff.DEFAULT_DELAY.toMillis(), context.getCurrentDelay());
assertEquals(BackOff.DEFAULT_DELAY.toMillis() * i, context.getCurrentElapsedTime());
}
delay = context.next();
assertEquals(6, context.getCurrentAttempts());
assertEquals(BackOff.NEVER, delay);
}
}
| BackOffTest |
java | elastic__elasticsearch | x-pack/plugin/rank-rrf/src/internalClusterTest/java/org/elasticsearch/xpack/rank/rrf/RRFRankCoordinatorCanMatchIT.java | {
"start": 2982,
"end": 10912
} | class ____ extends Plugin implements EnginePlugin {
@Override
public Optional<EngineFactory> getEngineFactory(IndexSettings indexSettings) {
return Optional.of(EngineWithExposingTimestamp::new);
}
}
@Override
protected boolean addMockInternalEngine() {
return false;
}
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return List.of(RRFRankPlugin.class, ExposingTimestampEnginePlugin.class);
}
@Override
protected int minimumNumberOfShards() {
return 5;
}
@Override
protected int maximumNumberOfShards() {
return 5;
}
@Override
protected int maximumNumberOfReplicas() {
return 0;
}
public void testCanMatchCoordinator() throws Exception {
// setup the cluster
XContentBuilder builder = XContentFactory.jsonBuilder()
.startObject()
.startObject("properties")
.startObject("@timestamp")
.field("type", "date")
.endObject()
.endObject()
.endObject();
assertAcked(prepareCreate("time_index").setMapping(builder));
ensureGreen("time_index");
for (int i = 0; i < 500; i++) {
prepareIndex("time_index").setSource("@timestamp", i).setRouting("a").get();
}
for (int i = 500; i < 1000; i++) {
prepareIndex("time_index").setSource("@timestamp", i).setRouting("b").get();
}
client().admin().indices().prepareRefresh("time_index").get();
client().admin().indices().prepareClose("time_index").get();
client().admin().indices().prepareOpen("time_index").get();
assertBusy(() -> {
IndexLongFieldRange timestampRange = clusterService().state().metadata().getProject().index("time_index").getTimestampRange();
assertTrue(Strings.toString(timestampRange), timestampRange.containsAllShardRanges());
});
// match 2 separate shard with no overlap in queries
assertResponse(
prepareSearch("time_index").setSearchType(SearchType.QUERY_THEN_FETCH)
.setPreFilterShardSize(1)
.setRankBuilder(new RRFRankBuilder(20, 1))
.setTrackTotalHits(false)
.setSubSearches(
List.of(
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gt(495).lte(499)),
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gte(500).lt(505))
)
)
.setSize(5),
response -> {
assertNull(response.getHits().getTotalHits());
assertEquals(5, response.getHits().getHits().length);
assertEquals(5, response.getSuccessfulShards());
assertEquals(3, response.getSkippedShards());
}
);
// match 2 shards with overlap in queries
assertResponse(
prepareSearch("time_index").setSearchType(SearchType.QUERY_THEN_FETCH)
.setPreFilterShardSize(1)
.setRankBuilder(new RRFRankBuilder(20, 1))
.setTrackTotalHits(false)
.setSubSearches(
List.of(
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gt(495).lte(505)),
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gte(497).lt(507))
)
)
.setSize(5),
response -> {
assertNull(response.getHits().getTotalHits());
assertEquals(5, response.getHits().getHits().length);
assertEquals(5, response.getSuccessfulShards());
assertEquals(3, response.getSkippedShards());
}
);
// match one shard with one query in range and one query out of range
assertResponse(
prepareSearch("time_index").setSearchType(SearchType.QUERY_THEN_FETCH)
.setPreFilterShardSize(1)
.setRankBuilder(new RRFRankBuilder(20, 1))
.setTrackTotalHits(false)
.setSubSearches(
List.of(
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gt(501).lte(505)),
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gte(10000).lt(10005))
)
)
.setSize(5),
response -> {
assertNull(response.getHits().getTotalHits());
assertEquals(4, response.getHits().getHits().length);
assertEquals(5, response.getSuccessfulShards());
assertEquals(4, response.getSkippedShards());
}
);
// match no shards, but still use one to generate a search response
assertResponse(
prepareSearch("time_index").setSearchType(SearchType.QUERY_THEN_FETCH)
.setPreFilterShardSize(1)
.setRankBuilder(new RRFRankBuilder(20, 1))
.setTrackTotalHits(false)
.setSubSearches(
List.of(
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gt(4000).lte(5000)),
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gte(10000).lt(10005))
)
)
.setSize(5),
response -> {
assertEquals(new TotalHits(0, TotalHits.Relation.EQUAL_TO), response.getHits().getTotalHits());
assertEquals(0, response.getHits().getHits().length);
assertEquals(5, response.getSuccessfulShards());
assertEquals(5, response.getSkippedShards());
}
);
// match one shard with with no overlap in queries
assertResponse(
prepareSearch("time_index").setSearchType(SearchType.QUERY_THEN_FETCH)
.setPreFilterShardSize(1)
.setRankBuilder(new RRFRankBuilder(20, 1))
.setTrackTotalHits(false)
.setSubSearches(
List.of(
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gt(600).lte(605)),
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gte(700).lt(705))
)
)
.setSize(5),
response -> {
assertNull(response.getHits().getTotalHits());
assertEquals(5, response.getHits().getHits().length);
assertEquals(5, response.getSuccessfulShards());
assertEquals(4, response.getSkippedShards());
}
);
// match one shard with exact overlap in queries
assertResponse(
prepareSearch("time_index").setSearchType(SearchType.QUERY_THEN_FETCH)
.setPreFilterShardSize(1)
.setRankBuilder(new RRFRankBuilder(20, 1))
.setTrackTotalHits(false)
.setSubSearches(
List.of(
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gt(600).lte(605)),
new SubSearchSourceBuilder(QueryBuilders.rangeQuery("@timestamp").gte(600).lt(605))
)
)
.setSize(5),
response -> {
assertNull(response.getHits().getTotalHits());
assertEquals(5, response.getHits().getHits().length);
assertEquals(5, response.getSuccessfulShards());
assertEquals(4, response.getSkippedShards());
}
);
}
}
| ExposingTimestampEnginePlugin |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/json/JsonValueFunction.java | {
"start": 1839,
"end": 8251
} | class ____ extends AbstractSqmSelfRenderingFunctionDescriptor {
protected final boolean supportsJsonPathExpression;
protected final boolean supportsJsonPathPassingClause;
public JsonValueFunction(
TypeConfiguration typeConfiguration,
boolean supportsJsonPathExpression,
boolean supportsJsonPathPassingClause) {
super(
"json_value",
FunctionKind.NORMAL,
StandardArgumentsValidators.composite(
new ArgumentTypesValidator( StandardArgumentsValidators.between( 2, 3 ), IMPLICIT_JSON, STRING, ANY )
),
new CastTargetReturnTypeResolver( typeConfiguration ),
StandardFunctionArgumentTypeResolvers.invariant( typeConfiguration, JSON, STRING )
);
this.supportsJsonPathExpression = supportsJsonPathExpression;
this.supportsJsonPathPassingClause = supportsJsonPathPassingClause;
}
@Override
protected <T> SelfRenderingSqmFunction<T> generateSqmFunctionExpression(
List<? extends SqmTypedNode<?>> arguments,
ReturnableType<T> impliedResultType,
QueryEngine queryEngine) {
return new SqmJsonValueExpression<>(
this,
this,
arguments,
impliedResultType,
getArgumentsValidator(),
getReturnTypeResolver(),
queryEngine.getCriteriaBuilder(),
getName()
);
}
@Override
public void render(
SqlAppender sqlAppender,
List<? extends SqlAstNode> sqlAstArguments,
ReturnableType<?> returnType,
SqlAstTranslator<?> walker) {
render( sqlAppender, JsonValueArguments.extract( sqlAstArguments ), returnType, walker );
}
protected void render(
SqlAppender sqlAppender,
JsonValueArguments arguments,
ReturnableType<?> returnType,
SqlAstTranslator<?> walker) {
sqlAppender.appendSql( "json_value(" );
arguments.jsonDocument().accept( walker );
sqlAppender.appendSql( ',' );
final JsonPathPassingClause passingClause = arguments.passingClause();
if ( supportsJsonPathPassingClause || passingClause == null ) {
if ( supportsJsonPathExpression ) {
arguments.jsonPath().accept( walker );
}
else {
walker.getSessionFactory().getJdbcServices().getDialect().appendLiteral(
sqlAppender,
walker.getLiteralValue( arguments.jsonPath() )
);
}
if ( passingClause != null ) {
sqlAppender.appendSql( " passing " );
final Map<String, Expression> passingExpressions = passingClause.getPassingExpressions();
final Iterator<Map.Entry<String, Expression>> iterator = passingExpressions.entrySet().iterator();
Map.Entry<String, Expression> entry = iterator.next();
entry.getValue().accept( walker );
sqlAppender.appendSql( " as " );
sqlAppender.appendDoubleQuoteEscapedString( entry.getKey() );
while ( iterator.hasNext() ) {
entry = iterator.next();
sqlAppender.appendSql( ',' );
entry.getValue().accept( walker );
sqlAppender.appendSql( " as " );
sqlAppender.appendDoubleQuoteEscapedString( entry.getKey() );
}
}
}
else {
JsonPathHelper.appendInlinedJsonPathIncludingPassingClause(
sqlAppender,
"",
arguments.jsonPath(),
passingClause,
walker
);
}
renderReturningClause( sqlAppender, arguments, walker );
if ( arguments.errorBehavior() != null ) {
if ( arguments.errorBehavior() == JsonValueErrorBehavior.ERROR ) {
sqlAppender.appendSql( " error on error" );
}
else if ( arguments.errorBehavior() != JsonValueErrorBehavior.NULL ) {
final Expression defaultExpression = arguments.errorBehavior().getDefaultExpression();
assert defaultExpression != null;
sqlAppender.appendSql( " default " );
defaultExpression.accept( walker );
sqlAppender.appendSql( " on error" );
}
}
if ( arguments.emptyBehavior() != null ) {
if ( arguments.emptyBehavior() == JsonValueEmptyBehavior.ERROR ) {
sqlAppender.appendSql( " error on empty" );
}
else if ( arguments.emptyBehavior() != JsonValueEmptyBehavior.NULL ) {
final Expression defaultExpression = arguments.emptyBehavior().getDefaultExpression();
assert defaultExpression != null;
sqlAppender.appendSql( " default " );
defaultExpression.accept( walker );
sqlAppender.appendSql( " on empty" );
}
}
sqlAppender.appendSql( ')' );
}
protected void renderReturningClause(SqlAppender sqlAppender, JsonValueArguments arguments, SqlAstTranslator<?> walker) {
if ( arguments.returningType() != null ) {
sqlAppender.appendSql( " returning " );
arguments.returningType().accept( walker );
}
}
protected record JsonValueArguments(
Expression jsonDocument,
Expression jsonPath,
boolean isJsonType,
@Nullable JsonPathPassingClause passingClause,
@Nullable CastTarget returningType,
@Nullable JsonValueErrorBehavior errorBehavior,
@Nullable JsonValueEmptyBehavior emptyBehavior) {
public static JsonValueArguments extract(List<? extends SqlAstNode> sqlAstArguments) {
int nextIndex = 2;
JsonPathPassingClause passingClause = null;
CastTarget castTarget = null;
JsonValueErrorBehavior errorBehavior = null;
JsonValueEmptyBehavior emptyBehavior = null;
if ( nextIndex < sqlAstArguments.size() ) {
final SqlAstNode node = sqlAstArguments.get( nextIndex );
if ( node instanceof CastTarget cast ) {
castTarget = cast;
nextIndex++;
}
}
if ( nextIndex < sqlAstArguments.size() ) {
final SqlAstNode node = sqlAstArguments.get( nextIndex );
if ( node instanceof JsonPathPassingClause jsonPathPassingClause ) {
passingClause = jsonPathPassingClause;
nextIndex++;
}
}
if ( nextIndex < sqlAstArguments.size() ) {
final SqlAstNode node = sqlAstArguments.get( nextIndex );
if ( node instanceof JsonValueErrorBehavior jsonValueErrorBehavior ) {
errorBehavior = jsonValueErrorBehavior;
nextIndex++;
}
}
if ( nextIndex < sqlAstArguments.size() ) {
final SqlAstNode node = sqlAstArguments.get( nextIndex );
if ( node instanceof JsonValueEmptyBehavior jsonValueEmptyBehavior ) {
emptyBehavior = jsonValueEmptyBehavior;
}
}
final Expression jsonDocument = (Expression) sqlAstArguments.get( 0 );
return new JsonValueArguments(
jsonDocument,
(Expression) sqlAstArguments.get( 1 ),
jsonDocument.getExpressionType() != null
&& jsonDocument.getExpressionType().getSingleJdbcMapping().getJdbcType().isJson(),
passingClause,
castTarget,
errorBehavior,
emptyBehavior
);
}
}
}
| JsonValueFunction |
java | square__retrofit | retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java | {
"start": 79335,
"end": 80159
} | class ____ {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part("ping") String ping, @Part("fizz") String fizz) {
return null;
}
}
Request request = buildRequest(Example.class, "pong", null);
assertThat(request.method()).isEqualTo("POST");
assertThat(request.headers().size()).isEqualTo(0);
assertThat(request.url().toString()).isEqualTo("http://example.com/foo/bar/");
RequestBody body = request.body();
Buffer buffer = new Buffer();
body.writeTo(buffer);
String bodyString = buffer.readUtf8();
assertThat(bodyString).contains("Content-Disposition: form-data;");
assertThat(bodyString).contains("name=\"ping\"");
assertThat(bodyString).contains("\r\npong\r\n--");
}
@Test
public void multipartPartOptional() {
| Example |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java | {
"start": 3537,
"end": 5424
} | class ____ {
private static final Log logger = LogFactory.getLog(ConfigurationClassBeanDefinitionReader.class);
private static final ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();
private final BeanDefinitionRegistry registry;
private final SourceExtractor sourceExtractor;
private final ResourceLoader resourceLoader;
private final Environment environment;
private final BeanNameGenerator importBeanNameGenerator;
private final ImportRegistry importRegistry;
private final ConditionEvaluator conditionEvaluator;
/**
* Create a new {@link ConfigurationClassBeanDefinitionReader} instance
* that will be used to populate the given {@link BeanDefinitionRegistry}.
*/
ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
ResourceLoader resourceLoader, Environment environment, BeanNameGenerator importBeanNameGenerator,
ImportRegistry importRegistry) {
this.registry = registry;
this.sourceExtractor = sourceExtractor;
this.resourceLoader = resourceLoader;
this.environment = environment;
this.importBeanNameGenerator = importBeanNameGenerator;
this.importRegistry = importRegistry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}
/**
* Read {@code configurationModel}, registering bean definitions
* with the registry based on its contents.
*/
public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator();
for (ConfigurationClass configClass : configurationModel) {
loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);
}
}
/**
* Read a particular {@link ConfigurationClass}, registering bean definitions
* for the | ConfigurationClassBeanDefinitionReader |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/access/FieldAccessTest.java | {
"start": 449,
"end": 833
} | class ____ {
@Test
public void test(EntityManagerFactoryScope scope) {
scope.inTransaction(entityManager -> {
Book book = new Book();
book.setId(1L);
book.setTitle("High-Performance Java Persistence");
book.setAuthor("Vlad Mihalcea");
entityManager.persist(book);
});
}
//tag::access-field-mapping-example[]
@Entity(name = "Book")
public static | FieldAccessTest |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/SQLPartitionOf.java | {
"start": 827,
"end": 4415
} | class ____ extends SQLObjectImpl {
protected SQLExprTableSource parentTable;
private boolean useDefault;
private SQLName columnName;
private SQLName constraintName;
private SQLExpr checkExpr;
private SQLExpr defaultExpr;
private List<SQLExpr> forValuesFrom;
private List<SQLExpr> forValuesTo;
private List<SQLExpr> forValuesIn;
private SQLExpr forValuesModulus;
private SQLExpr forValuesRemainder;
public SQLExprTableSource getParentTable() {
return parentTable;
}
public void setParentTable(SQLExprTableSource parentTable) {
this.parentTable = parentTable;
}
public boolean isUseDefault() {
return useDefault;
}
public void setUseDefault(boolean useDefault) {
this.useDefault = useDefault;
}
public List<SQLExpr> getForValuesFrom() {
return forValuesFrom;
}
public void setForValuesFrom(List<SQLExpr> forValuesFrom) {
this.forValuesFrom = forValuesFrom;
}
public List<SQLExpr> getForValuesTo() {
return forValuesTo;
}
public void setForValuesTo(List<SQLExpr> forValuesTo) {
this.forValuesTo = forValuesTo;
}
public List<SQLExpr> getForValuesIn() {
return forValuesIn;
}
public void setForValuesIn(List<SQLExpr> forValuesIn) {
this.forValuesIn = forValuesIn;
}
public SQLName getColumnName() {
return columnName;
}
public void setColumnName(SQLName columnName) {
this.columnName = columnName;
}
public SQLName getConstraintName() {
return constraintName;
}
public void setConstraintName(SQLName constraintName) {
this.constraintName = constraintName;
}
public SQLExpr getCheckExpr() {
return checkExpr;
}
public void setCheckExpr(SQLExpr checkExpr) {
this.checkExpr = checkExpr;
}
public SQLExpr getDefaultExpr() {
return defaultExpr;
}
public void setDefaultExpr(SQLExpr defaultExpr) {
this.defaultExpr = defaultExpr;
}
public SQLExpr getForValuesModulus() {
return forValuesModulus;
}
public void setForValuesModulus(SQLExpr forValuesModulus) {
this.forValuesModulus = forValuesModulus;
}
public SQLExpr getForValuesRemainder() {
return forValuesRemainder;
}
public void setForValuesRemainder(SQLExpr forValuesRemainder) {
this.forValuesRemainder = forValuesRemainder;
}
@Override
protected void accept0(SQLASTVisitor v) {
if (v.visit(this)) {
acceptChild(v, parentTable);
if (columnName != null) {
acceptChild(v, columnName);
}
if (constraintName != null) {
acceptChild(v, constraintName);
}
if (checkExpr != null) {
acceptChild(v, checkExpr);
}
if (defaultExpr != null) {
acceptChild(v, defaultExpr);
}
if (forValuesFrom != null) {
acceptChild(v, forValuesFrom);
}
if (forValuesTo != null) {
acceptChild(v, forValuesTo);
}
if (forValuesIn != null) {
acceptChild(v, forValuesIn);
}
if (forValuesModulus != null) {
acceptChild(v, forValuesModulus);
}
if (forValuesRemainder != null) {
acceptChild(v, forValuesRemainder);
}
}
v.endVisit(this);
}
}
| SQLPartitionOf |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/verification/argumentmatching/ArgumentMatchingToolTest.java | {
"start": 588,
"end": 3408
} | class ____ extends TestBase {
@Test
public void shouldNotFindAnySuspiciousMatchersWhenNumberOfArgumentsDoesntMatch() {
// given
List<ArgumentMatcher> matchers = (List) Arrays.asList(new Equals(1));
// when
Integer[] suspicious =
ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes(
matchers, new Object[] {10, 20});
// then
assertEquals(0, suspicious.length);
}
@Test
public void shouldNotFindAnySuspiciousMatchersWhenArgumentsMatch() {
// given
List<ArgumentMatcher> matchers = (List) Arrays.asList(new Equals(10), new Equals(20));
// when
Integer[] suspicious =
ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes(
matchers, new Object[] {10, 20});
// then
assertEquals(0, suspicious.length);
}
@Test
public void shouldFindSuspiciousMatchers() {
// given
Equals matcherInt20 = new Equals(20);
Long longPretendingAnInt = 20L;
// when
List<ArgumentMatcher> matchers = (List) Arrays.asList(new Equals(10), matcherInt20);
Integer[] suspicious =
ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes(
matchers, new Object[] {10, longPretendingAnInt});
// then
assertEquals(1, suspicious.length);
assertEquals(new Integer(1), suspicious[0]);
}
@Test
public void shouldNotFindSuspiciousMatchersWhenTypesAreTheSame() {
// given
Equals matcherWithBadDescription =
new Equals(20) {
public String toString() {
return "10";
}
};
Integer argument = 10;
// when
Integer[] suspicious =
ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes(
(List) Arrays.asList(matcherWithBadDescription), new Object[] {argument});
// then
assertEquals(0, suspicious.length);
}
@Test
public void shouldWorkFineWhenGivenArgIsNull() {
// when
Integer[] suspicious =
ArgumentMatchingTool.getSuspiciouslyNotMatchingArgsIndexes(
(List) Arrays.asList(new Equals(20)), new Object[] {null});
// then
assertEquals(0, suspicious.length);
}
@Test
public void shouldUseMatchersSafely() {
// This matcher is evil cause typeMatches(Object) returns true for every passed type but
// matches(T)
// method accepts only Strings. When a Integer is passed (thru the matches(Object) bridge
// method ) a
// ClassCastException will be thrown.
| ArgumentMatchingToolTest |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/eventtime/WatermarkStrategy.java | {
"start": 1444,
"end": 1817
} | interface ____ split into three parts: 1) methods that an implementor of this interface
* needs to implement, 2) builder methods for building a {@code WatermarkStrategy} on a base
* strategy, 3) convenience methods for constructing a {@code WatermarkStrategy} for common built-in
* strategies or based on a {@link WatermarkGeneratorSupplier}
*
* <p>Implementors of this | is |
java | elastic__elasticsearch | plugins/examples/rescore/src/main/java/org/elasticsearch/example/rescore/ExampleRescorePlugin.java | {
"start": 685,
"end": 985
} | class ____ extends Plugin implements SearchPlugin {
@Override
public List<RescorerSpec<?>> getRescorers() {
return singletonList(
new RescorerSpec<>(ExampleRescoreBuilder.NAME, ExampleRescoreBuilder::new, ExampleRescoreBuilder::fromXContent));
}
}
| ExampleRescorePlugin |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/Metadata.java | {
"start": 2892,
"end": 36574
} | class ____ implements Closeable {
private final Logger log;
private final ExponentialBackoff refreshBackoff;
private final long metadataExpireMs;
private int updateVersion; // bumped on every metadata response
private int requestVersion; // bumped on every new topic addition
private long lastRefreshMs;
private long lastSuccessfulRefreshMs;
private long attempts;
private KafkaException fatalException;
private Set<String> invalidTopics;
private Set<String> unauthorizedTopics;
private volatile MetadataSnapshot metadataSnapshot = MetadataSnapshot.empty();
private boolean needFullUpdate;
private boolean needPartialUpdate;
private long equivalentResponseCount;
private final ClusterResourceListeners clusterResourceListeners;
private boolean isClosed;
private final Map<TopicPartition, Integer> lastSeenLeaderEpochs;
/** Addresses with which the metadata was originally bootstrapped. */
private List<InetSocketAddress> bootstrapAddresses;
/**
* Create a new Metadata instance
*
* @param refreshBackoffMs The minimum amount of time that must expire between metadata refreshes to avoid busy
* polling
* @param refreshBackoffMaxMs The maximum amount of time to wait between metadata refreshes
* @param metadataExpireMs The maximum amount of time that metadata can be retained without refresh
* @param logContext Log context corresponding to the containing client
* @param clusterResourceListeners List of ClusterResourceListeners which will receive metadata updates.
*/
public Metadata(long refreshBackoffMs,
long refreshBackoffMaxMs,
long metadataExpireMs,
LogContext logContext,
ClusterResourceListeners clusterResourceListeners) {
this.log = logContext.logger(Metadata.class);
this.refreshBackoff = new ExponentialBackoff(
refreshBackoffMs,
CommonClientConfigs.RETRY_BACKOFF_EXP_BASE,
refreshBackoffMaxMs,
CommonClientConfigs.RETRY_BACKOFF_JITTER);
this.metadataExpireMs = metadataExpireMs;
this.lastRefreshMs = 0L;
this.lastSuccessfulRefreshMs = 0L;
this.attempts = 0L;
this.requestVersion = 0;
this.updateVersion = 0;
this.needFullUpdate = false;
this.needPartialUpdate = false;
this.equivalentResponseCount = 0;
this.clusterResourceListeners = clusterResourceListeners;
this.isClosed = false;
this.lastSeenLeaderEpochs = new HashMap<>();
this.invalidTopics = Collections.emptySet();
this.unauthorizedTopics = Collections.emptySet();
}
/**
* Get the current cluster info without blocking
*/
public Cluster fetch() {
return metadataSnapshot.cluster();
}
/**
* Get the current metadata cache.
*/
public MetadataSnapshot fetchMetadataSnapshot() {
return metadataSnapshot;
}
/**
* Return the next time when the current cluster info can be updated (i.e., backoff time has elapsed).
* There are two calculations for backing off based on how many attempts to retrieve metadata have been made
* since the last successful response, and how many equivalent metadata responses have been received.
* The second of these allows backing off when there are errors to do with stale metadata, even though the
* metadata responses are clean.
* <p>
* This can be used to check whether it's worth requesting an update in the knowledge that it will
* not be delayed if this method returns 0.
*
* @param nowMs current time in ms
* @return remaining time in ms till the cluster info can be updated again
*/
public synchronized long timeToAllowUpdate(long nowMs) {
// Calculate the backoff for attempts which acts when metadata responses fail
long backoffForAttempts = Math.max(this.lastRefreshMs +
this.refreshBackoff.backoff(this.attempts > 0 ? this.attempts - 1 : 0) - nowMs, 0);
// Periodic updates based on expiration resets the equivalent response count so exponential backoff is not used
if (Math.max(this.lastSuccessfulRefreshMs + this.metadataExpireMs - nowMs, 0) == 0) {
this.equivalentResponseCount = 0;
}
// Calculate the backoff for equivalent responses which acts when metadata responses are not making progress
long backoffForEquivalentResponseCount = Math.max(this.lastRefreshMs +
(this.equivalentResponseCount > 0 ? this.refreshBackoff.backoff(this.equivalentResponseCount - 1) : 0) - nowMs, 0);
return Math.max(backoffForAttempts, backoffForEquivalentResponseCount);
}
/**
* The next time to update the cluster info is the maximum of the time the current info will expire and the time the
* current info can be updated (i.e. backoff time has elapsed). If an update has been requested, the metadata
* expiry time is now.
*
* @param nowMs current time in ms
* @return remaining time in ms till updating the cluster info
*/
public synchronized long timeToNextUpdate(long nowMs) {
long timeToExpire = updateRequested() ? 0 : Math.max(this.lastSuccessfulRefreshMs + this.metadataExpireMs - nowMs, 0);
return Math.max(timeToExpire, timeToAllowUpdate(nowMs));
}
public long metadataExpireMs() {
return this.metadataExpireMs;
}
/**
* Request an update of the current cluster metadata info, permitting backoff based on the number of
* equivalent metadata responses, which indicates that responses did not make progress and may be stale.
*
* @param resetEquivalentResponseBackoff Whether to reset backing off based on consecutive equivalent responses.
* This should be set to <i>false</i> in situations where the update is
* being requested to retry an operation, such as when the leader has
* changed. It should be set to <i>true</i> in situations where new
* metadata is being requested, such as adding a topic to a subscription.
* In situations where it's not clear, it's best to use <i>true</i>.
*
* @return The current updateVersion before the update
*/
public synchronized int requestUpdate(final boolean resetEquivalentResponseBackoff) {
this.needFullUpdate = true;
if (resetEquivalentResponseBackoff) {
this.equivalentResponseCount = 0;
}
return this.updateVersion;
}
/**
* Request an immediate update of the current cluster metadata info, because the caller is interested in
* metadata that is being newly requested.
* @return The current updateVersion before the update
*/
public synchronized int requestUpdateForNewTopics() {
// Override the timestamp of last refresh to let immediate update.
this.lastRefreshMs = 0;
this.needPartialUpdate = true;
this.equivalentResponseCount = 0;
this.requestVersion++;
return this.updateVersion;
}
/**
* Request an update for the partition metadata iff we have seen a newer leader epoch. This is called by the client
* any time it handles a response from the broker that includes leader epoch, except for update via Metadata RPC which
* follows a different code path ({@link #update}).
*
* @param topicPartition
* @param leaderEpoch
* @return true if we updated the last seen epoch, false otherwise
*/
public synchronized boolean updateLastSeenEpochIfNewer(TopicPartition topicPartition, int leaderEpoch) {
Objects.requireNonNull(topicPartition, "TopicPartition cannot be null");
if (leaderEpoch < 0)
throw new IllegalArgumentException("Invalid leader epoch " + leaderEpoch + " (must be non-negative)");
Integer oldEpoch = lastSeenLeaderEpochs.get(topicPartition);
log.trace("Determining if we should replace existing epoch {} with new epoch {} for partition {}", oldEpoch, leaderEpoch, topicPartition);
final boolean updated;
if (oldEpoch == null) {
log.debug("Not replacing null epoch with new epoch {} for partition {}", leaderEpoch, topicPartition);
updated = false;
} else if (leaderEpoch > oldEpoch) {
log.debug("Updating last seen epoch from {} to {} for partition {}", oldEpoch, leaderEpoch, topicPartition);
lastSeenLeaderEpochs.put(topicPartition, leaderEpoch);
updated = true;
} else {
log.debug("Not replacing existing epoch {} with new epoch {} for partition {}", oldEpoch, leaderEpoch, topicPartition);
updated = false;
}
this.needFullUpdate = this.needFullUpdate || updated;
return updated;
}
public Optional<Integer> lastSeenLeaderEpoch(TopicPartition topicPartition) {
return Optional.ofNullable(lastSeenLeaderEpochs.get(topicPartition));
}
/**
* Check whether an update has been explicitly requested.
*
* @return true if an update was requested, false otherwise
*/
public synchronized boolean updateRequested() {
return this.needFullUpdate || this.needPartialUpdate;
}
public synchronized void addClusterUpdateListener(ClusterResourceListener listener) {
this.clusterResourceListeners.maybeAdd(listener);
}
/**
* Return the cached partition info if it exists and a newer leader epoch isn't known about.
*/
public synchronized Optional<MetadataResponse.PartitionMetadata> partitionMetadataIfCurrent(TopicPartition topicPartition) {
Integer epoch = lastSeenLeaderEpochs.get(topicPartition);
Optional<MetadataResponse.PartitionMetadata> partitionMetadata = metadataSnapshot.partitionMetadata(topicPartition);
if (epoch == null) {
// old cluster format (no epochs)
return partitionMetadata;
} else {
return partitionMetadata.filter(metadata ->
metadata.leaderEpoch.orElse(NO_PARTITION_LEADER_EPOCH).equals(epoch));
}
}
/**
* @return a mapping from topic names to topic IDs for all topics with valid IDs in the cache
*/
public Map<String, Uuid> topicIds() {
return metadataSnapshot.topicIds();
}
public synchronized LeaderAndEpoch currentLeader(TopicPartition topicPartition) {
Optional<MetadataResponse.PartitionMetadata> maybeMetadata = partitionMetadataIfCurrent(topicPartition);
if (maybeMetadata.isEmpty())
return new LeaderAndEpoch(Optional.empty(), Optional.ofNullable(lastSeenLeaderEpochs.get(topicPartition)));
MetadataResponse.PartitionMetadata partitionMetadata = maybeMetadata.get();
Optional<Integer> leaderEpochOpt = partitionMetadata.leaderEpoch;
Optional<Node> leaderNodeOpt = partitionMetadata.leaderId.flatMap(metadataSnapshot::nodeById);
return new LeaderAndEpoch(leaderNodeOpt, leaderEpochOpt);
}
public synchronized void bootstrap(List<InetSocketAddress> addresses) {
this.needFullUpdate = true;
this.updateVersion += 1;
this.metadataSnapshot = MetadataSnapshot.bootstrap(addresses);
this.bootstrapAddresses = addresses;
}
public synchronized void rebootstrap() {
log.info("Rebootstrapping with {}", this.bootstrapAddresses);
this.bootstrap(this.bootstrapAddresses);
}
/**
* Update metadata assuming the current request version.
*
* For testing only.
*/
public synchronized void updateWithCurrentRequestVersion(MetadataResponse response, boolean isPartialUpdate, long nowMs) {
this.update(this.requestVersion, response, isPartialUpdate, nowMs);
}
/**
* Updates the cluster metadata. If topic expiry is enabled, expiry time
* is set for topics if required and expired topics are removed from the metadata.
*
* @param requestVersion The request version corresponding to the update response, as provided by
* {@link #newMetadataRequestAndVersion(long)}.
* @param response metadata response received from the broker
* @param isPartialUpdate whether the metadata request was for a subset of the active topics
* @param nowMs current time in milliseconds
*/
public synchronized void update(int requestVersion, MetadataResponse response, boolean isPartialUpdate, long nowMs) {
Objects.requireNonNull(response, "Metadata response cannot be null");
if (isClosed())
throw new IllegalStateException("Update requested after metadata close");
this.needPartialUpdate = requestVersion < this.requestVersion;
this.lastRefreshMs = nowMs;
this.attempts = 0;
this.updateVersion += 1;
if (!isPartialUpdate) {
this.needFullUpdate = false;
this.lastSuccessfulRefreshMs = nowMs;
}
// If we subsequently find that the metadata response is not equivalent to the metadata already known,
// this count is reset to 0 in updateLatestMetadata()
this.equivalentResponseCount++;
String previousClusterId = metadataSnapshot.clusterResource().clusterId();
this.metadataSnapshot = handleMetadataResponse(response, isPartialUpdate, nowMs);
Cluster cluster = metadataSnapshot.cluster();
maybeSetMetadataError(cluster);
this.lastSeenLeaderEpochs.keySet().removeIf(tp -> !retainTopic(tp.topic(), false, nowMs));
String newClusterId = metadataSnapshot.clusterResource().clusterId();
if (!Objects.equals(previousClusterId, newClusterId)) {
log.info("Cluster ID: {}", newClusterId);
}
clusterResourceListeners.onUpdate(metadataSnapshot.clusterResource());
log.debug("Updated cluster metadata updateVersion {} to {}", this.updateVersion, this.metadataSnapshot);
}
/**
* Updates the partition-leadership info in the metadata. Update is done by merging existing metadata with the input leader information and nodes.
* This is called whenever partition-leadership updates are returned in a response from broker(ex - ProduceResponse & FetchResponse).
* Note that the updates via Metadata RPC are handled separately in ({@link #update}).
* Both partitionLeader and leaderNodes override the existing metadata. Non-overlapping metadata is kept as it is.
* @param partitionLeaders map of new leadership information for partitions.
* @param leaderNodes a list of nodes for leaders in the above map.
* @return a set of partitions, for which leaders were updated.
*/
public synchronized Set<TopicPartition> updatePartitionLeadership(Map<TopicPartition, LeaderIdAndEpoch> partitionLeaders, List<Node> leaderNodes) {
Map<Integer, Node> newNodes = leaderNodes.stream().collect(Collectors.toMap(Node::id, node -> node));
// Insert non-overlapping nodes from existing-nodes into new-nodes.
this.metadataSnapshot.cluster().nodes().forEach(node -> newNodes.putIfAbsent(node.id(), node));
// Create partition-metadata for all updated partitions. Exclude updates for partitions -
// 1. for which the corresponding partition has newer leader in existing metadata.
// 2. for which corresponding leader's node is missing in the new-nodes.
// 3. for which the existing metadata doesn't know about the partition.
List<PartitionMetadata> updatePartitionMetadata = new ArrayList<>();
for (Entry<TopicPartition, Metadata.LeaderIdAndEpoch> partitionLeader: partitionLeaders.entrySet()) {
TopicPartition partition = partitionLeader.getKey();
Metadata.LeaderAndEpoch currentLeader = currentLeader(partition);
Metadata.LeaderIdAndEpoch newLeader = partitionLeader.getValue();
if (newLeader.epoch.isEmpty() || newLeader.leaderId.isEmpty()) {
log.debug("For {}, incoming leader information is incomplete {}", partition, newLeader);
continue;
}
if (currentLeader.epoch.isPresent() && newLeader.epoch.get() <= currentLeader.epoch.get()) {
log.debug("For {}, incoming leader({}) is not-newer than the one in the existing metadata {}, so ignoring.", partition, newLeader, currentLeader);
continue;
}
if (!newNodes.containsKey(newLeader.leaderId.get())) {
log.debug("For {}, incoming leader({}), the corresponding node information for node-id {} is missing, so ignoring.", partition, newLeader, newLeader.leaderId.get());
continue;
}
if (this.metadataSnapshot.partitionMetadata(partition).isEmpty()) {
log.debug("For {}, incoming leader({}), partition metadata is no longer cached, ignoring.", partition, newLeader);
continue;
}
MetadataResponse.PartitionMetadata existingMetadata = this.metadataSnapshot.partitionMetadata(partition).get();
MetadataResponse.PartitionMetadata updatedMetadata = new MetadataResponse.PartitionMetadata(
existingMetadata.error,
partition,
newLeader.leaderId,
newLeader.epoch,
existingMetadata.replicaIds,
existingMetadata.inSyncReplicaIds,
existingMetadata.offlineReplicaIds
);
updatePartitionMetadata.add(updatedMetadata);
lastSeenLeaderEpochs.put(partition, newLeader.epoch.get());
}
if (updatePartitionMetadata.isEmpty()) {
log.debug("No relevant metadata updates.");
return new HashSet<>();
}
Set<String> updatedTopics = updatePartitionMetadata.stream().map(MetadataResponse.PartitionMetadata::topic).collect(Collectors.toSet());
// Get topic-ids for updated topics from existing topic-ids.
Map<String, Uuid> existingTopicIds = this.metadataSnapshot.topicIds();
Map<String, Uuid> topicIdsForUpdatedTopics = updatedTopics.stream()
.filter(existingTopicIds::containsKey)
.collect(Collectors.toMap(e -> e, existingTopicIds::get));
if (log.isDebugEnabled()) {
updatePartitionMetadata.forEach(
partMetadata -> log.debug("For {} updating leader information, updated metadata is {}.", partMetadata.topicPartition, partMetadata)
);
}
// Fetch responses can include partition level leader changes, when this happens, we perform a partial
// metadata update, by keeping the unchanged partition and update the changed partitions.
this.metadataSnapshot = metadataSnapshot.mergeWith(
metadataSnapshot.clusterResource().clusterId(),
newNodes,
updatePartitionMetadata,
Collections.emptySet(), Collections.emptySet(), Collections.emptySet(),
metadataSnapshot.cluster().controller(),
topicIdsForUpdatedTopics,
(topic, isInternal) -> true);
clusterResourceListeners.onUpdate(metadataSnapshot.clusterResource());
return updatePartitionMetadata.stream()
.map(metadata -> metadata.topicPartition)
.collect(Collectors.toSet());
}
private void maybeSetMetadataError(Cluster cluster) {
clearRecoverableErrors();
checkInvalidTopics(cluster);
checkUnauthorizedTopics(cluster);
}
private void checkInvalidTopics(Cluster cluster) {
if (!cluster.invalidTopics().isEmpty()) {
log.error("Metadata response reported invalid topics {}", cluster.invalidTopics());
invalidTopics = new HashSet<>(cluster.invalidTopics());
}
}
private void checkUnauthorizedTopics(Cluster cluster) {
if (!cluster.unauthorizedTopics().isEmpty()) {
log.error("Topic authorization failed for topics {}", cluster.unauthorizedTopics());
unauthorizedTopics = new HashSet<>(cluster.unauthorizedTopics());
}
}
/**
* Transform a MetadataResponse into a new MetadataCache instance.
*/
private MetadataSnapshot handleMetadataResponse(MetadataResponse metadataResponse, boolean isPartialUpdate, long nowMs) {
// All encountered topics.
Set<String> topics = new HashSet<>();
// Retained topics to be passed to the metadata cache.
Set<String> internalTopics = new HashSet<>();
Set<String> unauthorizedTopics = new HashSet<>();
Set<String> invalidTopics = new HashSet<>();
List<MetadataResponse.PartitionMetadata> partitions = new ArrayList<>();
Map<String, Uuid> topicIds = new HashMap<>();
Map<String, Uuid> oldTopicIds = metadataSnapshot.topicIds();
for (MetadataResponse.TopicMetadata metadata : metadataResponse.topicMetadata()) {
String topicName = metadata.topic();
Uuid topicId = metadata.topicId();
topics.add(topicName);
// We can only reason about topic ID changes when both IDs are valid, so keep oldId null unless the new metadata contains a topic ID
Uuid oldTopicId = null;
if (!Uuid.ZERO_UUID.equals(topicId)) {
topicIds.put(topicName, topicId);
oldTopicId = oldTopicIds.get(topicName);
} else {
topicId = null;
}
if (!retainTopic(topicName, topicId, metadata.isInternal(), nowMs))
continue;
if (metadata.isInternal())
internalTopics.add(topicName);
if (metadata.error() == Errors.NONE) {
for (MetadataResponse.PartitionMetadata partitionMetadata : metadata.partitionMetadata()) {
// Even if the partition's metadata includes an error, we need to handle
// the update to catch new epochs
updateLatestMetadata(partitionMetadata, metadataResponse.hasReliableLeaderEpochs(), topicId, oldTopicId)
.ifPresent(partitions::add);
if (partitionMetadata.error.exception() instanceof InvalidMetadataException) {
log.debug("Requesting metadata update for partition {} due to error {}",
partitionMetadata.topicPartition, partitionMetadata.error);
requestUpdate(false);
}
}
} else {
if (metadata.error().exception() instanceof InvalidMetadataException) {
log.debug("Requesting metadata update for topic {} due to error {}", topicName, metadata.error());
requestUpdate(false);
}
if (metadata.error() == Errors.INVALID_TOPIC_EXCEPTION)
invalidTopics.add(topicName);
else if (metadata.error() == Errors.TOPIC_AUTHORIZATION_FAILED)
unauthorizedTopics.add(topicName);
}
}
Map<Integer, Node> nodes = metadataResponse.brokersById();
if (isPartialUpdate)
return this.metadataSnapshot.mergeWith(metadataResponse.clusterId(), nodes, partitions,
unauthorizedTopics, invalidTopics, internalTopics, metadataResponse.controller(), topicIds,
(topic, isInternal) -> !topics.contains(topic) && retainTopic(topic, isInternal, nowMs));
else
return new MetadataSnapshot(metadataResponse.clusterId(), nodes, partitions,
unauthorizedTopics, invalidTopics, internalTopics, metadataResponse.controller(), topicIds);
}
/**
* Compute the latest partition metadata to cache given ordering by leader epochs (if both
* available and reliable) and whether the topic ID changed.
*/
private Optional<MetadataResponse.PartitionMetadata> updateLatestMetadata(
MetadataResponse.PartitionMetadata partitionMetadata,
boolean hasReliableLeaderEpoch,
Uuid topicId,
Uuid oldTopicId) {
TopicPartition tp = partitionMetadata.topicPartition;
if (hasReliableLeaderEpoch && partitionMetadata.leaderEpoch.isPresent()) {
int newEpoch = partitionMetadata.leaderEpoch.get();
Integer currentEpoch = lastSeenLeaderEpochs.get(tp);
if (currentEpoch == null) {
// We have no previous info, so we can just insert the new epoch info
log.debug("Setting the last seen epoch of partition {} to {} since the last known epoch was undefined.",
tp, newEpoch);
lastSeenLeaderEpochs.put(tp, newEpoch);
this.equivalentResponseCount = 0;
return Optional.of(partitionMetadata);
} else if (topicId != null && !topicId.equals(oldTopicId)) {
// If the new topic ID is valid and different from the last seen topic ID, update the metadata.
// Between the time that a topic is deleted and re-created, the client may lose track of the
// corresponding topicId (i.e. `oldTopicId` will be null). In this case, when we discover the new
// topicId, we allow the corresponding leader epoch to override the last seen value.
log.info("Resetting the last seen epoch of partition {} to {} since the associated topicId changed from {} to {}",
tp, newEpoch, oldTopicId, topicId);
lastSeenLeaderEpochs.put(tp, newEpoch);
this.equivalentResponseCount = 0;
return Optional.of(partitionMetadata);
} else if (newEpoch >= currentEpoch) {
// If the received leader epoch is at least the same as the previous one, update the metadata
log.debug("Updating last seen epoch for partition {} from {} to epoch {} from new metadata", tp, currentEpoch, newEpoch);
lastSeenLeaderEpochs.put(tp, newEpoch);
if (newEpoch > currentEpoch) {
this.equivalentResponseCount = 0;
}
return Optional.of(partitionMetadata);
} else {
// Otherwise ignore the new metadata and use the previously cached info
log.debug("Got metadata for an older epoch {} (current is {}) for partition {}, not updating", newEpoch, currentEpoch, tp);
return metadataSnapshot.partitionMetadata(tp);
}
} else {
// Handle old cluster formats as well as error responses where leader and epoch are missing
lastSeenLeaderEpochs.remove(tp);
this.equivalentResponseCount = 0;
return Optional.of(partitionMetadata.withoutLeaderEpoch());
}
}
/**
* If any non-retriable exceptions were encountered during metadata update, clear and throw the exception.
* This is used by the consumer to propagate any fatal exceptions or topic exceptions for any of the topics
* in the consumer's Metadata.
*/
public synchronized void maybeThrowAnyException() {
clearErrorsAndMaybeThrowException(this::recoverableException);
}
/**
* If any fatal exceptions were encountered during metadata update, throw the exception. This is used by
* the producer to abort waiting for metadata if there were fatal exceptions (e.g. authentication failures)
* in the last metadata update.
*/
protected synchronized void maybeThrowFatalException() {
KafkaException metadataException = this.fatalException;
if (metadataException != null) {
fatalException = null;
throw metadataException;
}
}
/**
* If any non-retriable exceptions were encountered during metadata update, throw exception if the exception
* is fatal or related to the specified topic. All exceptions from the last metadata update are cleared.
* This is used by the producer to propagate topic metadata errors for send requests.
*/
public synchronized void maybeThrowExceptionForTopic(String topic) {
clearErrorsAndMaybeThrowException(() -> recoverableExceptionForTopic(topic));
}
private void clearErrorsAndMaybeThrowException(Supplier<KafkaException> recoverableExceptionSupplier) {
KafkaException metadataException = Optional.ofNullable(fatalException).orElseGet(recoverableExceptionSupplier);
fatalException = null;
clearRecoverableErrors();
if (metadataException != null)
throw metadataException;
}
// We may be able to recover from this exception if metadata for this topic is no longer needed
private KafkaException recoverableException() {
if (!unauthorizedTopics.isEmpty())
return new TopicAuthorizationException(unauthorizedTopics);
else if (!invalidTopics.isEmpty())
return new InvalidTopicException(invalidTopics);
else
return null;
}
private KafkaException recoverableExceptionForTopic(String topic) {
if (unauthorizedTopics.contains(topic))
return new TopicAuthorizationException(Collections.singleton(topic));
else if (invalidTopics.contains(topic))
return new InvalidTopicException(Collections.singleton(topic));
else
return null;
}
private void clearRecoverableErrors() {
invalidTopics = Collections.emptySet();
unauthorizedTopics = Collections.emptySet();
}
/**
* Record an attempt to update the metadata that failed. We need to keep track of this
* to avoid retrying immediately.
*/
public synchronized void failedUpdate(long now) {
this.lastRefreshMs = now;
this.attempts++;
this.equivalentResponseCount = 0;
}
/**
* Propagate a fatal error which affects the ability to fetch metadata for the cluster.
* Two examples are authentication and unsupported version exceptions.
*
* @param exception The fatal exception
*/
public synchronized void fatalError(KafkaException exception) {
this.fatalException = exception;
}
/**
* @return The current metadata updateVersion
*/
public synchronized int updateVersion() {
return this.updateVersion;
}
/**
* The last time metadata was successfully updated.
*/
public synchronized long lastSuccessfulUpdate() {
return this.lastSuccessfulRefreshMs;
}
/**
* Close this metadata instance to indicate that metadata updates are no longer possible.
*/
@Override
public synchronized void close() {
this.isClosed = true;
}
/**
* Check if this metadata instance has been closed. See {@link #close()} for more information.
*
* @return True if this instance has been closed; false otherwise
*/
public synchronized boolean isClosed() {
return this.isClosed;
}
public synchronized MetadataRequestAndVersion newMetadataRequestAndVersion(long nowMs) {
MetadataRequest.Builder request = null;
boolean isPartialUpdate = false;
// Perform a partial update only if a full update hasn't been requested, and the last successful
// hasn't exceeded the metadata refresh time.
if (!this.needFullUpdate && this.lastSuccessfulRefreshMs + this.metadataExpireMs > nowMs) {
request = newMetadataRequestBuilderForNewTopics();
isPartialUpdate = true;
}
if (request == null) {
request = newMetadataRequestBuilder();
isPartialUpdate = false;
}
return new MetadataRequestAndVersion(request, requestVersion, isPartialUpdate);
}
/**
* Constructs and returns a metadata request builder for fetching cluster data and all active topics.
*
* @return the constructed non-null metadata builder
*/
protected MetadataRequest.Builder newMetadataRequestBuilder() {
return MetadataRequest.Builder.allTopics();
}
/**
* Constructs and returns a metadata request builder for fetching cluster data and any uncached topics,
* otherwise null if the functionality is not supported.
*
* @return the constructed metadata builder, or null if not supported
*/
protected MetadataRequest.Builder newMetadataRequestBuilderForNewTopics() {
return null;
}
/**
* @return Mapping from topic IDs to topic names for all topics in the cache.
*/
public Map<Uuid, String> topicNames() {
return metadataSnapshot.topicNames();
}
/**
* Based on the topic name, check if the topic metadata should be kept when received in a metadata response.
*/
protected boolean retainTopic(String topic, boolean isInternal, long nowMs) {
return true;
}
/**
* Based on the topic name and topic ID, check if the topic metadata should be kept when received in a metadata response.
*/
protected boolean retainTopic(String topicName, Uuid topicId, boolean isInternal, long nowMs) {
return retainTopic(topicName, isInternal, nowMs);
}
public static | Metadata |
java | google__dagger | javatests/dagger/internal/codegen/DependencyCycleValidationTest.java | {
"start": 19895,
"end": 20227
} | interface ____");
});
}
@Test
public void cyclicDependencyInSubcomponentsWithChildren() {
Source parent =
CompilerTests.javaSource(
"test.Parent",
"package test;",
"",
"import dagger.Component;",
"",
"@Component",
" | Parent |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/join/CompositeInputFormat.java | {
"start": 2760,
"end": 6660
} | class ____.
* @see #compose(java.lang.String, java.lang.Class, java.lang.String...)
*/
public void setFormat(JobConf job) throws IOException {
addDefaults();
addUserIdentifiers(job);
root = Parser.parse(job.get("mapred.join.expr", null), job);
}
/**
* Adds the default set of identifiers to the parser.
*/
protected void addDefaults() {
try {
Parser.CNode.addIdentifier("inner", InnerJoinRecordReader.class);
Parser.CNode.addIdentifier("outer", OuterJoinRecordReader.class);
Parser.CNode.addIdentifier("override", OverrideRecordReader.class);
Parser.WNode.addIdentifier("tbl", WrappedRecordReader.class);
} catch (NoSuchMethodException e) {
throw new RuntimeException("FATAL: Failed to init defaults", e);
}
}
/**
* Inform the parser of user-defined types.
*/
private void addUserIdentifiers(JobConf job) throws IOException {
Pattern x = Pattern.compile("^mapred\\.join\\.define\\.(\\w+)$");
for (Map.Entry<String,String> kv : job) {
Matcher m = x.matcher(kv.getKey());
if (m.matches()) {
try {
Parser.CNode.addIdentifier(m.group(1),
job.getClass(m.group(0), null, ComposableRecordReader.class));
} catch (NoSuchMethodException e) {
throw (IOException)new IOException(
"Invalid define for " + m.group(1)).initCause(e);
}
}
}
}
/**
* Build a CompositeInputSplit from the child InputFormats by assigning the
* ith split from each child to the ith composite split.
*/
public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException {
setFormat(job);
job.setLong("mapred.min.split.size", Long.MAX_VALUE);
return root.getSplits(job, numSplits);
}
/**
* Construct a CompositeRecordReader for the children of this InputFormat
* as defined in the init expression.
* The outermost join need only be composable, not necessarily a composite.
* Mandating TupleWritable isn't strictly correct.
*/
@SuppressWarnings("unchecked") // child types unknown
public ComposableRecordReader<K,TupleWritable> getRecordReader(
InputSplit split, JobConf job, Reporter reporter) throws IOException {
setFormat(job);
return root.getRecordReader(split, job, reporter);
}
/**
* Convenience method for constructing composite formats.
* Given InputFormat class (inf), path (p) return:
* {@code tbl(<inf>, <p>) }
*/
public static String compose(Class<? extends InputFormat> inf, String path) {
return compose(inf.getName().intern(), path, new StringBuffer()).toString();
}
/**
* Convenience method for constructing composite formats.
* Given operation (op), Object class (inf), set of paths (p) return:
* {@code <op>(tbl(<inf>,<p1>),tbl(<inf>,<p2>),...,tbl(<inf>,<pn>)) }
*/
public static String compose(String op, Class<? extends InputFormat> inf,
String... path) {
final String infname = inf.getName();
StringBuffer ret = new StringBuffer(op + '(');
for (String p : path) {
compose(infname, p, ret);
ret.append(',');
}
ret.setCharAt(ret.length() - 1, ')');
return ret.toString();
}
/**
* Convenience method for constructing composite formats.
* Given operation (op), Object class (inf), set of paths (p) return:
* {@code <op>(tbl(<inf>,<p1>),tbl(<inf>,<p2>),...,tbl(<inf>,<pn>)) }
*/
public static String compose(String op, Class<? extends InputFormat> inf,
Path... path) {
ArrayList<String> tmp = new ArrayList<String>(path.length);
for (Path p : path) {
tmp.add(p.toString());
}
return compose(op, inf, tmp.toArray(new String[0]));
}
private static StringBuffer compose(String inf, String path,
StringBuffer sb) {
sb.append("tbl(" + inf + ",\"");
sb.append(path);
sb.append("\")");
return sb;
}
}
| listed |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/common/operators/base/PartitionMapOperatorTest.java | {
"start": 1874,
"end": 5181
} | class ____ implements java.io.Serializable {
@Test
void testMapPartitionWithRuntimeContext() throws Exception {
final String taskName = "Test Task";
final AtomicBoolean opened = new AtomicBoolean();
final AtomicBoolean closed = new AtomicBoolean();
final MapPartitionFunction<String, Integer> parser =
new RichMapPartitionFunction<String, Integer>() {
@Override
public void open(OpenContext openContext) {
opened.set(true);
RuntimeContext ctx = getRuntimeContext();
assertThat(ctx.getTaskInfo().getIndexOfThisSubtask()).isZero();
assertThat(ctx.getTaskInfo().getNumberOfParallelSubtasks()).isOne();
assertThat(ctx.getTaskInfo().getTaskName()).isEqualTo(taskName);
}
@Override
public void mapPartition(Iterable<String> values, Collector<Integer> out) {
for (String s : values) {
out.collect(Integer.parseInt(s));
}
}
@Override
public void close() {
closed.set(true);
}
};
MapPartitionOperatorBase<String, Integer, MapPartitionFunction<String, Integer>> op =
new MapPartitionOperatorBase<>(
parser,
new UnaryOperatorInformation<>(
BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.INT_TYPE_INFO),
taskName);
List<String> input = new ArrayList<>(asList("1", "2", "3", "4", "5", "6"));
final TaskInfo taskInfo = new TaskInfoImpl(taskName, 1, 0, 1, 0);
ExecutionConfig executionConfig = new ExecutionConfig();
executionConfig.disableObjectReuse();
List<Integer> resultMutableSafe =
op.executeOnCollections(
input,
new RuntimeUDFContext(
taskInfo,
null,
executionConfig,
new HashMap<>(),
new HashMap<>(),
UnregisteredMetricsGroup.createOperatorMetricGroup()),
executionConfig);
executionConfig.enableObjectReuse();
List<Integer> resultRegular =
op.executeOnCollections(
input,
new RuntimeUDFContext(
taskInfo,
null,
executionConfig,
new HashMap<>(),
new HashMap<>(),
UnregisteredMetricsGroup.createOperatorMetricGroup()),
executionConfig);
assertThat(resultMutableSafe).isEqualTo(asList(1, 2, 3, 4, 5, 6));
assertThat(resultRegular).isEqualTo(asList(1, 2, 3, 4, 5, 6));
assertThat(opened).isTrue();
assertThat(closed).isTrue();
}
}
| PartitionMapOperatorTest |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/AutowiredLifecycleStrategy.java | {
"start": 969,
"end": 1036
} | interface ____ extends LifecycleStrategy {
}
| AutowiredLifecycleStrategy |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/SplitterParallelAggregateManualTest.java | {
"start": 1429,
"end": 3479
} | class ____ extends ContextTestSupport {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:splitSynchronizedAggregation")
.split(method(new MySplitter(), "rowIterator"), new MyAggregationStrategy())
.to("log:someSplitProcessing?groupSize=500");
from("direct:splitUnsynchronizedAggregation")
.split(method(new MySplitter(), "rowIterator"), new MyAggregationStrategy()).parallelAggregate()
.to("log:someSplitProcessing?groupSize=500");
}
};
}
@Test
public void test1() throws Exception {
int numberOfRequests = 1;
timeSplitRoutes(numberOfRequests);
}
@Test
public void test2() throws Exception {
int numberOfRequests = 2;
timeSplitRoutes(numberOfRequests);
}
@Test
public void test4() throws Exception {
int numberOfRequests = 4;
timeSplitRoutes(numberOfRequests);
}
protected void timeSplitRoutes(int numberOfRequests) throws Exception {
String[] endpoints = new String[] { "direct:splitSynchronizedAggregation", "direct:splitUnsynchronizedAggregation" };
List<Future<String>> futures = new ArrayList<>();
StopWatch stopWatch = new StopWatch(false);
for (String endpoint : endpoints) {
stopWatch.restart();
for (int requestIndex = 0; requestIndex < numberOfRequests; requestIndex++) {
futures.add(template.asyncRequestBody(endpoint, null, String.class));
}
for (int i = 0; i < futures.size(); i++) {
Future<String> future = futures.get(i);
future.get();
}
stopWatch.taken();
log.info("test{}.{}={}\n", numberOfRequests, endpoint, stopWatch.taken());
}
}
public static | SplitterParallelAggregateManualTest |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/NameNodeProxies.java | {
"start": 7801,
"end": 15512
} | interface ____ should be created
* @param ugi the user who is making the calls on the proxy object
* @param withRetries certain interfaces have a non-standard retry policy
* @param fallbackToSimpleAuth - set to true or false during this method to
* indicate if a secure client falls back to simple auth
* @return an object containing both the proxy and the associated
* delegation token service it corresponds to
* @throws IOException
*/
@SuppressWarnings("unchecked")
public static <T> ProxyAndInfo<T> createNonHAProxy(
Configuration conf, InetSocketAddress nnAddr, Class<T> xface,
UserGroupInformation ugi, boolean withRetries,
AtomicBoolean fallbackToSimpleAuth, AlignmentContext alignmentContext)
throws IOException {
Text dtService = SecurityUtil.buildTokenService(nnAddr);
T proxy;
if (xface == ClientProtocol.class) {
proxy = (T) NameNodeProxiesClient.createProxyWithAlignmentContext(
nnAddr, conf, ugi, withRetries, fallbackToSimpleAuth,
alignmentContext);
} else if (xface == JournalProtocol.class) {
proxy = (T) createNNProxyWithJournalProtocol(nnAddr, conf, ugi,
alignmentContext);
} else if (xface == NamenodeProtocol.class) {
proxy = (T) createNNProxyWithNamenodeProtocol(nnAddr, conf, ugi,
withRetries, alignmentContext);
} else if (xface == GetUserMappingsProtocol.class) {
proxy = (T) createNNProxyWithGetUserMappingsProtocol(nnAddr, conf, ugi,
alignmentContext);
} else if (xface == RefreshUserMappingsProtocol.class) {
proxy = (T) createNNProxyWithRefreshUserMappingsProtocol(nnAddr, conf,
ugi, alignmentContext);
} else if (xface == RefreshAuthorizationPolicyProtocol.class) {
proxy = (T) createNNProxyWithRefreshAuthorizationPolicyProtocol(nnAddr,
conf, ugi, alignmentContext);
} else if (xface == RefreshCallQueueProtocol.class) {
proxy = (T) createNNProxyWithRefreshCallQueueProtocol(nnAddr, conf, ugi,
alignmentContext);
} else if (xface == InMemoryAliasMapProtocol.class) {
proxy = (T) createNNProxyWithInMemoryAliasMapProtocol(nnAddr, conf, ugi,
alignmentContext);
} else if (xface == BalancerProtocols.class) {
proxy = (T) createNNProxyWithBalancerProtocol(nnAddr, conf, ugi,
withRetries, fallbackToSimpleAuth, alignmentContext);
} else {
String message = "Unsupported protocol found when creating the proxy " +
"connection to NameNode: " +
((xface != null) ? xface.getClass().getName() : "null");
LOG.error(message);
throw new IllegalStateException(message);
}
return new ProxyAndInfo<T>(proxy, dtService, nnAddr);
}
private static InMemoryAliasMapProtocol createNNProxyWithInMemoryAliasMapProtocol(
InetSocketAddress address, Configuration conf, UserGroupInformation ugi,
AlignmentContext alignmentContext) throws IOException {
AliasMapProtocolPB proxy = createNameNodeProxy(
address, conf, ugi, AliasMapProtocolPB.class, 30000, alignmentContext);
return new InMemoryAliasMapProtocolClientSideTranslatorPB(proxy);
}
private static JournalProtocol createNNProxyWithJournalProtocol(
InetSocketAddress address, Configuration conf, UserGroupInformation ugi,
AlignmentContext alignmentContext) throws IOException {
JournalProtocolPB proxy = createNameNodeProxy(address,
conf, ugi, JournalProtocolPB.class, 30000, alignmentContext);
return new JournalProtocolTranslatorPB(proxy);
}
private static RefreshAuthorizationPolicyProtocol
createNNProxyWithRefreshAuthorizationPolicyProtocol(InetSocketAddress address,
Configuration conf, UserGroupInformation ugi,
AlignmentContext alignmentContext) throws IOException {
RefreshAuthorizationPolicyProtocolPB proxy = createNameNodeProxy(address,
conf, ugi, RefreshAuthorizationPolicyProtocolPB.class, 0,
alignmentContext);
return new RefreshAuthorizationPolicyProtocolClientSideTranslatorPB(proxy);
}
private static RefreshUserMappingsProtocol
createNNProxyWithRefreshUserMappingsProtocol(InetSocketAddress address,
Configuration conf, UserGroupInformation ugi,
AlignmentContext alignmentContext) throws IOException {
RefreshUserMappingsProtocolPB proxy = createNameNodeProxy(address, conf,
ugi, RefreshUserMappingsProtocolPB.class, 0, alignmentContext);
return new RefreshUserMappingsProtocolClientSideTranslatorPB(proxy);
}
private static RefreshCallQueueProtocol
createNNProxyWithRefreshCallQueueProtocol(InetSocketAddress address,
Configuration conf, UserGroupInformation ugi,
AlignmentContext alignmentContext) throws IOException {
RefreshCallQueueProtocolPB proxy = createNameNodeProxy(address, conf, ugi,
RefreshCallQueueProtocolPB.class, 0, alignmentContext);
return new RefreshCallQueueProtocolClientSideTranslatorPB(proxy);
}
private static GetUserMappingsProtocol createNNProxyWithGetUserMappingsProtocol(
InetSocketAddress address, Configuration conf, UserGroupInformation ugi,
AlignmentContext alignmentContext) throws IOException {
GetUserMappingsProtocolPB proxy = createNameNodeProxy(address, conf, ugi,
GetUserMappingsProtocolPB.class, 0, alignmentContext);
return new GetUserMappingsProtocolClientSideTranslatorPB(proxy);
}
private static NamenodeProtocol createNNProxyWithNamenodeProtocol(
InetSocketAddress address, Configuration conf, UserGroupInformation ugi,
boolean withRetries, AlignmentContext alignmentContext)
throws IOException {
NamenodeProtocolPB proxy = createNameNodeProxy(
address, conf, ugi, NamenodeProtocolPB.class, 0, alignmentContext);
if (withRetries) { // create the proxy with retries
RetryPolicy timeoutPolicy = RetryPolicies.exponentialBackoffRetry(5, 200,
TimeUnit.MILLISECONDS);
Map<String, RetryPolicy> methodNameToPolicyMap
= new HashMap<String, RetryPolicy>();
methodNameToPolicyMap.put("getBlocks", timeoutPolicy);
methodNameToPolicyMap.put("getAccessKeys", timeoutPolicy);
NamenodeProtocol translatorProxy =
new NamenodeProtocolTranslatorPB(proxy);
return (NamenodeProtocol) RetryProxy.create(
NamenodeProtocol.class, translatorProxy, methodNameToPolicyMap);
} else {
return new NamenodeProtocolTranslatorPB(proxy);
}
}
private static BalancerProtocols createNNProxyWithBalancerProtocol(
InetSocketAddress address, Configuration conf, UserGroupInformation ugi,
boolean withRetries, AtomicBoolean fallbackToSimpleAuth,
AlignmentContext alignmentContext) throws IOException {
NamenodeProtocol namenodeProtocol = createNNProxyWithNamenodeProtocol(
address, conf, ugi, withRetries, alignmentContext);
ClientProtocol clientProtocol =
NameNodeProxiesClient.createProxyWithAlignmentContext(address,
conf, ugi, withRetries, fallbackToSimpleAuth, alignmentContext);
return ProxyCombiner.combine(BalancerProtocols.class,
namenodeProtocol, clientProtocol);
}
private static <T> T createNameNodeProxy(InetSocketAddress address,
Configuration conf, UserGroupInformation ugi, Class<T> xface,
int rpcTimeout, AlignmentContext alignmentContext) throws IOException {
RPC.setProtocolEngine(conf, xface, ProtobufRpcEngine2.class);
return RPC.getProtocolProxy(xface,
RPC.getProtocolVersion(xface), address, ugi, conf,
NetUtils.getDefaultSocketFactory(conf), rpcTimeout, null, null,
alignmentContext).getProxy();
}
}
| which |
java | alibaba__nacos | test/naming-test/src/test/java/com/alibaba/nacos/test/naming/ServiceListTestNamingITCase.java | {
"start": 1820,
"end": 4476
} | class ____ {
private static int listenseCount = 0;
private NamingService naming;
private volatile List<Instance> instances = Collections.emptyList();
@LocalServerPort
private int port;
@BeforeEach
void init() throws Exception {
if (naming == null) {
naming = NamingFactory.createNamingService("127.0.0.1" + ":" + port);
}
}
@Test
void serviceList() throws NacosException {
naming.getServicesOfServer(1, 10);
}
/**
* @throws NacosException
* @description 获取当前订阅的所有服务
*/
@Test
void getSubscribeServices() throws NacosException, InterruptedException {
ListView<String> listView = naming.getServicesOfServer(1, 10);
if (listView != null && listView.getCount() > 0) {
naming.getAllInstances(listView.getData().get(0));
}
List<ServiceInfo> serviceInfoList = naming.getSubscribeServices();
int count = serviceInfoList.size();
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
naming.subscribe(serviceName, new EventListener() {
@Override
public void onEvent(Event event) {
}
});
serviceInfoList = naming.getSubscribeServices();
assertEquals(count + 1, serviceInfoList.size());
}
/**
* @throws NacosException
* @description 删除注册,获取当前订阅的所有服务
*/
@Test
void getSubscribeServices_deregisterInstance() throws NacosException, InterruptedException {
listenseCount = 0;
EventListener listener = new EventListener() {
@Override
public void onEvent(Event event) {
System.out.println(((NamingEvent) event).getServiceName());
System.out.println(((NamingEvent) event).getInstances());
listenseCount++;
}
};
List<ServiceInfo> serviceInfoList = naming.getSubscribeServices();
int count = serviceInfoList.size();
String serviceName = randomDomainName();
naming.registerInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
naming.subscribe(serviceName, listener);
serviceInfoList = naming.getSubscribeServices();
assertEquals(count + 1, serviceInfoList.size());
naming.deregisterInstance(serviceName, "127.0.0.1", TEST_PORT, "c1");
assertEquals(count + 1, serviceInfoList.size());
}
}
| ServiceListTestNamingITCase |
java | grpc__grpc-java | api/src/main/java/io/grpc/Contexts.java | {
"start": 794,
"end": 2185
} | class ____ {
private Contexts() {
}
/**
* Make the provided {@link Context} {@link Context#current()} for the creation of a listener
* to a received call and for all events received by that listener.
*
* <p>This utility is expected to be used by {@link ServerInterceptor} implementations that need
* to augment the {@link Context} in which the application does work when receiving events from
* the client.
*
* @param context to make {@link Context#current()}.
* @param call used to send responses to client.
* @param headers received from client.
* @param next handler used to create the listener to be wrapped.
* @return listener that will receive events in the scope of the provided context.
*/
public static <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
Context context,
ServerCall<ReqT, RespT> call,
Metadata headers,
ServerCallHandler<ReqT, RespT> next) {
Context previous = context.attach();
try {
return new ContextualizedServerCallListener<>(
next.startCall(call, headers),
context);
} finally {
context.detach(previous);
}
}
/**
* Implementation of {@link io.grpc.ForwardingServerCallListener} that attaches a context before
* dispatching calls to the delegate and detaches them after the call completes.
*/
private static | Contexts |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/persister/collection/mutation/UpdateRowsCoordinatorStandard.java | {
"start": 991,
"end": 4319
} | class ____ extends AbstractUpdateRowsCoordinator implements UpdateRowsCoordinator {
private final RowMutationOperations rowMutationOperations;
private MutationOperationGroup operationGroup;
public UpdateRowsCoordinatorStandard(
CollectionMutationTarget mutationTarget,
RowMutationOperations rowMutationOperations,
SessionFactoryImplementor sessionFactory) {
super( mutationTarget, sessionFactory );
this.rowMutationOperations = rowMutationOperations;
}
@Override
protected int doUpdate(Object key, PersistentCollection<?> collection, SharedSessionContractImplementor session) {
final var operationGroup = getOperationGroup();
final var mutationExecutor = mutationExecutorService.createExecutor(
() -> new BasicBatchKey( getMutationTarget().getRolePath() + "#UPDATE" ),
operationGroup,
session
);
try {
final var entries =
collection.entries( getMutationTarget().getTargetPart().getCollectionDescriptor() );
int count = 0;
if ( collection.isElementRemoved() ) {
// the update should be done starting from the end of the elements
// - make a copy so that we can go in reverse
final List<Object> elements = new ArrayList<>();
while ( entries.hasNext() ) {
elements.add( entries.next() );
}
for ( int i = elements.size() - 1; i >= 0; i-- ) {
final Object entry = elements.get( i );
final boolean updated = processRow(
key,
collection,
entry,
i,
mutationExecutor,
session
);
if ( updated ) {
count++;
}
}
}
else {
int position = 0;
while ( entries.hasNext() ) {
final Object entry = entries.next();
final boolean updated = processRow(
key,
collection,
entry,
position++,
mutationExecutor,
session
);
if ( updated ) {
count++;
}
}
}
return count;
}
finally {
mutationExecutor.release();
}
}
private boolean processRow(
Object key,
PersistentCollection<?> collection,
Object entry,
int entryPosition,
MutationExecutor mutationExecutor,
SharedSessionContractImplementor session) {
if ( rowMutationOperations.getUpdateRowOperation() != null ) {
final var attribute = getMutationTarget().getTargetPart();
if ( !collection.needsUpdating( entry, entryPosition, attribute ) ) {
return false;
}
rowMutationOperations.getUpdateRowValues().applyValues(
collection,
key,
entry,
entryPosition,
session,
mutationExecutor.getJdbcValueBindings()
);
rowMutationOperations.getUpdateRowRestrictions().applyRestrictions(
collection,
key,
entry,
entryPosition,
session,
mutationExecutor.getJdbcValueBindings()
);
mutationExecutor.execute( collection, null, null, null, session );
return true;
}
else {
return false;
}
}
protected MutationOperationGroup getOperationGroup() {
if ( operationGroup == null ) {
final var updateRowOperation = rowMutationOperations.getUpdateRowOperation();
operationGroup = updateRowOperation == null
? noOperations( MutationType.UPDATE, getMutationTarget() )
: singleOperation( MutationType.UPDATE, getMutationTarget(), updateRowOperation );
}
return operationGroup;
}
}
| UpdateRowsCoordinatorStandard |
java | apache__maven | impl/maven-core/src/main/java/org/apache/maven/plugin/MavenPluginManager.java | {
"start": 1600,
"end": 4100
} | interface ____ {
/**
* Retrieves the descriptor for the specified plugin from its main artifact.
*
* @param plugin The plugin whose descriptor should be retrieved, must not be {@code null}.
* @param repositories The plugin repositories to use for resolving the plugin's main artifact, must not be {@code
* null}.
* @param session The repository session to use for resolving the plugin's main artifact, must not be {@code null}.
* @return The plugin descriptor, never {@code null}.
*/
PluginDescriptor getPluginDescriptor(
Plugin plugin, List<RemoteRepository> repositories, RepositorySystemSession session)
throws PluginResolutionException, PluginDescriptorParsingException, InvalidPluginDescriptorException;
/**
* Retrieves the descriptor for the specified plugin goal from the plugin's main artifact.
*
* @param plugin The plugin whose mojo descriptor should be retrieved, must not be {@code null}.
* @param goal The simple name of the mojo whose descriptor should be retrieved, must not be {@code null}.
* @param repositories The plugin repositories to use for resolving the plugin's main artifact, must not be {@code
* null}.
* @param session The repository session to use for resolving the plugin's main artifact, must not be {@code null}.
* @return The mojo descriptor, never {@code null}.
*/
MojoDescriptor getMojoDescriptor(
Plugin plugin, String goal, List<RemoteRepository> repositories, RepositorySystemSession session)
throws MojoNotFoundException, PluginResolutionException, PluginDescriptorParsingException,
InvalidPluginDescriptorException;
/**
* Verifies the specified plugin is compatible with the current Maven runtime.
*
* @param pluginDescriptor The descriptor of the plugin to check, must not be {@code null}.
* @deprecated Use {@link #checkPrerequisites(PluginDescriptor)} instead.
*/
@Deprecated
void checkRequiredMavenVersion(PluginDescriptor pluginDescriptor) throws PluginIncompatibleException;
/**
* Verifies that the specified plugin's prerequisites are met.
*
* @param pluginDescriptor The descriptor of the plugin to check, must not be {@code null}.
* @since 4.0.0
*/
void checkPrerequisites(PluginDescriptor pluginDescriptor) throws PluginIncompatibleException;
/**
* Sets up the | MavenPluginManager |
java | quarkusio__quarkus | integration-tests/hibernate-validator/src/main/java/io/quarkus/it/hibernate/validator/injection/InjectedConstraintValidator.java | {
"start": 265,
"end": 622
} | class ____ implements ConstraintValidator<InjectedConstraintValidatorConstraint, String> {
@Inject
MyService service;
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
return service.validate(value);
}
}
| InjectedConstraintValidator |
java | elastic__elasticsearch | modules/ingest-otel/src/test/java/org/elasticsearch/ingest/otel/OTelSemConvCrawler.java | {
"start": 1730,
"end": 7347
} | class ____ {
public static final String SEM_CONV_GITHUB_REPO_ZIP_URL =
"https://github.com/open-telemetry/semantic-conventions/archive/refs/heads/main.zip";
private static final Logger logger = LogManager.getLogger(OTelSemConvCrawler.class);
@SuppressForbidden(reason = "writing the GitHub repo zip file to the test's runtime temp directory and deleting on exit")
static Set<String> collectOTelSemConvResourceAttributes() {
Path semConvZipFilePath = null;
Path semConvExtractedTmpDirPath = null;
Set<String> resourceAttributes = new HashSet<>();
try (HttpClient httpClient = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build()) {
semConvZipFilePath = Files.createTempFile("otel-semconv-", ".zip");
// Download zip
HttpResponse<Path> response = httpClient.send(
HttpRequest.newBuilder(URI.create(SEM_CONV_GITHUB_REPO_ZIP_URL)).build(),
HttpResponse.BodyHandlers.ofFile(semConvZipFilePath)
);
if (response.statusCode() != 200) {
logger.error("failed to download semantic conventions zip file");
return resourceAttributes;
}
// Unzip
semConvExtractedTmpDirPath = Files.createTempDirectory("otel-semconv-extracted-");
try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(semConvZipFilePath))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory() == false) {
Path outPath = semConvExtractedTmpDirPath.resolve(entry.getName());
Files.createDirectories(outPath.getParent());
Files.copy(zis, outPath, StandardCopyOption.REPLACE_EXISTING);
}
}
}
// look for the model root at semantic-conventions-main/model
Path semConvModelRootDir = semConvExtractedTmpDirPath.resolve("semantic-conventions-main/model");
if (Files.exists(semConvModelRootDir) == false) {
logger.error("model directory not found in the extracted zip");
return resourceAttributes;
}
try (Stream<Path> semConvFileStream = Files.walk(semConvModelRootDir)) {
semConvFileStream.filter(path -> path.toString().endsWith(".yaml") || path.toString().endsWith(".yml"))
.parallel()
.forEach(path -> {
try (
InputStream inputStream = Files.newInputStream(path);
XContentParser parser = XContentFactory.xContent(XContentType.YAML)
.createParser(XContentParserConfiguration.EMPTY, inputStream)
) {
Map<String, Object> yamlData = parser.map();
Object groupsObj = yamlData.get("groups");
if (groupsObj instanceof List<?> groups) {
for (Object group : groups) {
if (group instanceof Map<?, ?> groupMap && "entity".equals(groupMap.get("type"))) {
Object attrs = groupMap.get("attributes");
if (attrs instanceof List<?> attrList) {
for (Object attr : attrList) {
if (attr instanceof Map<?, ?> attrMap) {
String refVal = (String) attrMap.get("ref");
if (refVal != null) {
resourceAttributes.add(refVal);
}
}
}
}
}
}
}
} catch (IOException e) {
logger.error("error parsing yaml file", e);
}
});
}
} catch (InterruptedException e) {
logger.error("interrupted", e);
} catch (IOException e) {
logger.error("IO exception", e);
} finally {
if (semConvZipFilePath != null) {
try {
Files.deleteIfExists(semConvZipFilePath);
} catch (IOException e) {
logger.warn("failed to delete semconv zip file", e);
}
}
if (semConvExtractedTmpDirPath != null) {
try (Stream<Path> semConvFileStream = Files.walk(semConvExtractedTmpDirPath)) {
semConvFileStream.sorted(Comparator.reverseOrder()) // delete files first
.forEach(path -> {
try {
Files.delete(path);
} catch (IOException e) {
logger.warn("failed to delete file: " + path, e);
}
});
} catch (IOException e) {
logger.warn("failed to delete semconv zip file", e);
}
}
}
return resourceAttributes;
}
}
| OTelSemConvCrawler |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/stereotype/Repository.java | {
"start": 958,
"end": 1569
} | class ____ a "Repository", originally defined by
* Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage,
* retrieval, and search behavior which emulates a collection of objects".
*
* <p>Teams implementing traditional Jakarta EE patterns such as "Data Access Object"
* may also apply this stereotype to DAO classes, though care should be taken to
* understand the distinction between Data Access Object and DDD-style repositories
* before doing so. This annotation is a general-purpose stereotype and individual teams
* may narrow their semantics and use as appropriate.
*
* <p>A | is |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/byte_/ByteAssert_isGreaterThanOrEqualTo_byte_Test.java | {
"start": 894,
"end": 1255
} | class ____ extends ByteAssertBaseTest {
@Override
protected ByteAssert invoke_api_method() {
return assertions.isGreaterThanOrEqualTo((byte) 6);
}
@Override
protected void verify_internal_effects() {
verify(bytes).assertGreaterThanOrEqualTo(getInfo(assertions), getActual(assertions), (byte) 6);
}
}
| ByteAssert_isGreaterThanOrEqualTo_byte_Test |
java | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/AfterFilterFunctions.java | {
"start": 8123,
"end": 8383
} | enum ____ {
/**
* Default: Retain the first value only.
*/
RETAIN_FIRST,
/**
* Retain the last value only.
*/
RETAIN_LAST,
/**
* Retain all unique values in the order of their first encounter.
*/
RETAIN_UNIQUE
}
}
| DedupeStrategy |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/TwitterSearchEndpointBuilderFactory.java | {
"start": 46150,
"end": 51493
} | interface ____
extends
EndpointProducerBuilder {
default AdvancedTwitterSearchEndpointProducerBuilder advanced() {
return (AdvancedTwitterSearchEndpointProducerBuilder) this;
}
/**
* The http proxy host which can be used for the camel-twitter. Can also
* be configured on the TwitterComponent level instead.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param httpProxyHost the value to set
* @return the dsl builder
*/
default TwitterSearchEndpointProducerBuilder httpProxyHost(String httpProxyHost) {
doSetProperty("httpProxyHost", httpProxyHost);
return this;
}
/**
* The http proxy password which can be used for the camel-twitter. Can
* also be configured on the TwitterComponent level instead.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param httpProxyPassword the value to set
* @return the dsl builder
*/
default TwitterSearchEndpointProducerBuilder httpProxyPassword(String httpProxyPassword) {
doSetProperty("httpProxyPassword", httpProxyPassword);
return this;
}
/**
* The http proxy port which can be used for the camel-twitter. Can also
* be configured on the TwitterComponent level instead.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: proxy
*
* @param httpProxyPort the value to set
* @return the dsl builder
*/
default TwitterSearchEndpointProducerBuilder httpProxyPort(Integer httpProxyPort) {
doSetProperty("httpProxyPort", httpProxyPort);
return this;
}
/**
* The http proxy port which can be used for the camel-twitter. Can also
* be configured on the TwitterComponent level instead.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Group: proxy
*
* @param httpProxyPort the value to set
* @return the dsl builder
*/
default TwitterSearchEndpointProducerBuilder httpProxyPort(String httpProxyPort) {
doSetProperty("httpProxyPort", httpProxyPort);
return this;
}
/**
* The http proxy user which can be used for the camel-twitter. Can also
* be configured on the TwitterComponent level instead.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param httpProxyUser the value to set
* @return the dsl builder
*/
default TwitterSearchEndpointProducerBuilder httpProxyUser(String httpProxyUser) {
doSetProperty("httpProxyUser", httpProxyUser);
return this;
}
/**
* The access token. Can also be configured on the TwitterComponent
* level instead.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessToken the value to set
* @return the dsl builder
*/
default TwitterSearchEndpointProducerBuilder accessToken(String accessToken) {
doSetProperty("accessToken", accessToken);
return this;
}
/**
* The access secret. Can also be configured on the TwitterComponent
* level instead.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param accessTokenSecret the value to set
* @return the dsl builder
*/
default TwitterSearchEndpointProducerBuilder accessTokenSecret(String accessTokenSecret) {
doSetProperty("accessTokenSecret", accessTokenSecret);
return this;
}
/**
* The consumer key. Can also be configured on the TwitterComponent
* level instead.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param consumerKey the value to set
* @return the dsl builder
*/
default TwitterSearchEndpointProducerBuilder consumerKey(String consumerKey) {
doSetProperty("consumerKey", consumerKey);
return this;
}
/**
* The consumer secret. Can also be configured on the TwitterComponent
* level instead.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param consumerSecret the value to set
* @return the dsl builder
*/
default TwitterSearchEndpointProducerBuilder consumerSecret(String consumerSecret) {
doSetProperty("consumerSecret", consumerSecret);
return this;
}
}
/**
* Advanced builder for endpoint producers for the Twitter Search component.
*/
public | TwitterSearchEndpointProducerBuilder |
java | spring-projects__spring-framework | spring-websocket/src/main/java/org/springframework/web/socket/messaging/SessionConnectEvent.java | {
"start": 1259,
"end": 1720
} | class ____ extends AbstractSubProtocolEvent {
/**
* Create a new SessionConnectEvent.
* @param source the component that published the event (never {@code null})
* @param message the connect message
*/
public SessionConnectEvent(Object source, Message<byte[]> message) {
super(source, message);
}
public SessionConnectEvent(Object source, Message<byte[]> message, @Nullable Principal user) {
super(source, message, user);
}
}
| SessionConnectEvent |
java | google__guava | android/guava-tests/test/com/google/common/base/JoinerTest.java | {
"start": 3592,
"end": 12971
} | class ____<E extends @Nullable Object>
extends ForwardingList<E> {
final List<E> delegate;
final int delta;
MisleadingSizeList(List<E> delegate, int delta) {
this.delegate = delegate;
this.delta = delta;
}
@Override
protected List<E> delegate() {
return delegate;
}
@Override
public int size() {
return delegate.size() + delta;
}
}
@SuppressWarnings("JoinIterableIterator") // explicitly testing iterator overload, too
public void testNoSpecialNullBehavior() {
checkNoOutput(J, iterable);
checkResult(J, iterable1, "1");
checkResult(J, iterable12, "1-2");
checkResult(J, iterable123, "1-2-3");
checkResult(J, UNDERREPORTING_SIZE_LIST, "1-2-3");
checkResult(J, OVERREPORTING_SIZE_LIST, "1-2-3");
assertThrows(NullPointerException.class, () -> J.join(iterableNull));
assertThrows(NullPointerException.class, () -> J.join(iterable1Null2));
assertThrows(NullPointerException.class, () -> J.join(iterableNull.iterator()));
assertThrows(NullPointerException.class, () -> J.join(iterable1Null2.iterator()));
}
public void testOnCharOverride() {
Joiner onChar = Joiner.on('-');
checkNoOutput(onChar, iterable);
checkResult(onChar, iterable1, "1");
checkResult(onChar, iterable12, "1-2");
checkResult(onChar, iterable123, "1-2-3");
checkResult(J, UNDERREPORTING_SIZE_LIST, "1-2-3");
checkResult(J, OVERREPORTING_SIZE_LIST, "1-2-3");
}
public void testSkipNulls() {
Joiner skipNulls = J.skipNulls();
checkNoOutput(skipNulls, iterable);
checkNoOutput(skipNulls, iterableNull);
checkNoOutput(skipNulls, iterableNullNull);
checkNoOutput(skipNulls, iterableFourNulls);
checkResult(skipNulls, iterable1, "1");
checkResult(skipNulls, iterable12, "1-2");
checkResult(skipNulls, iterable123, "1-2-3");
checkResult(J, UNDERREPORTING_SIZE_LIST, "1-2-3");
checkResult(J, OVERREPORTING_SIZE_LIST, "1-2-3");
checkResult(skipNulls, iterableNull1, "1");
checkResult(skipNulls, iterable1Null, "1");
checkResult(skipNulls, iterable1Null2, "1-2");
}
public void testUseForNull() {
Joiner zeroForNull = J.useForNull("0");
checkNoOutput(zeroForNull, iterable);
checkResult(zeroForNull, iterable1, "1");
checkResult(zeroForNull, iterable12, "1-2");
checkResult(zeroForNull, iterable123, "1-2-3");
checkResult(J, UNDERREPORTING_SIZE_LIST, "1-2-3");
checkResult(J, OVERREPORTING_SIZE_LIST, "1-2-3");
checkResult(zeroForNull, iterableNull, "0");
checkResult(zeroForNull, iterableNullNull, "0-0");
checkResult(zeroForNull, iterableNull1, "0-1");
checkResult(zeroForNull, iterable1Null, "1-0");
checkResult(zeroForNull, iterable1Null2, "1-0-2");
checkResult(zeroForNull, iterableFourNulls, "0-0-0-0");
}
private static void checkNoOutput(Joiner joiner, Iterable<Integer> set) {
assertEquals("", joiner.join(set));
assertEquals("", joiner.join(set.iterator()));
Object[] array = newArrayList(set).toArray(new Integer[0]);
assertEquals("", joiner.join(array));
StringBuilder sb1FromIterable = new StringBuilder();
assertSame(sb1FromIterable, joiner.appendTo(sb1FromIterable, set));
assertEquals(0, sb1FromIterable.length());
StringBuilder sb1FromIterator = new StringBuilder();
assertSame(sb1FromIterator, joiner.appendTo(sb1FromIterator, set));
assertEquals(0, sb1FromIterator.length());
StringBuilder sb2 = new StringBuilder();
assertSame(sb2, joiner.appendTo(sb2, array));
assertEquals(0, sb2.length());
try {
joiner.appendTo(NASTY_APPENDABLE, set);
} catch (IOException e) {
throw new AssertionError(e);
}
try {
joiner.appendTo(NASTY_APPENDABLE, set.iterator());
} catch (IOException e) {
throw new AssertionError(e);
}
try {
joiner.appendTo(NASTY_APPENDABLE, array);
} catch (IOException e) {
throw new AssertionError(e);
}
}
private static final Appendable NASTY_APPENDABLE =
new Appendable() {
@Override
public Appendable append(@Nullable CharSequence csq) throws IOException {
throw new IOException();
}
@Override
public Appendable append(@Nullable CharSequence csq, int start, int end)
throws IOException {
throw new IOException();
}
@Override
public Appendable append(char c) throws IOException {
throw new IOException();
}
};
private static void checkResult(Joiner joiner, Iterable<Integer> parts, String expected) {
assertEquals(expected, joiner.join(parts));
assertEquals(expected, joiner.join(parts.iterator()));
StringBuilder sb1FromIterable = new StringBuilder().append('x');
joiner.appendTo(sb1FromIterable, parts);
assertEquals("x" + expected, sb1FromIterable.toString());
StringBuilder sb1FromIterator = new StringBuilder().append('x');
joiner.appendTo(sb1FromIterator, parts.iterator());
assertEquals("x" + expected, sb1FromIterator.toString());
// The use of iterator() works around J2KT b/381065164.
Integer[] partsArray = newArrayList(parts.iterator()).toArray(new Integer[0]);
assertEquals(expected, joiner.join(partsArray));
StringBuilder sb2 = new StringBuilder().append('x');
joiner.appendTo(sb2, partsArray);
assertEquals("x" + expected, sb2.toString());
int num = partsArray.length - 2;
if (num >= 0) {
Object[] rest = new Integer[num];
for (int i = 0; i < num; i++) {
rest[i] = partsArray[i + 2];
}
assertEquals(expected, joiner.join(partsArray[0], partsArray[1], rest));
StringBuilder sb3 = new StringBuilder().append('x');
joiner.appendTo(sb3, partsArray[0], partsArray[1], rest);
assertEquals("x" + expected, sb3.toString());
}
}
public void test_useForNull_skipNulls() {
Joiner j = Joiner.on("x").useForNull("y");
assertThrows(UnsupportedOperationException.class, j::skipNulls);
}
public void test_skipNulls_useForNull() {
Joiner j = Joiner.on("x").skipNulls();
assertThrows(UnsupportedOperationException.class, () -> j.useForNull("y"));
}
public void test_useForNull_twice() {
Joiner j = Joiner.on("x").useForNull("y");
assertThrows(UnsupportedOperationException.class, () -> j.useForNull("y"));
}
public void testMap() {
MapJoiner j = Joiner.on(';').withKeyValueSeparator(':');
assertEquals("", j.join(ImmutableMap.of()));
assertEquals(":", j.join(ImmutableMap.of("", "")));
Map<@Nullable String, @Nullable String> mapWithNulls = new LinkedHashMap<>();
mapWithNulls.put("a", null);
mapWithNulls.put(null, "b");
assertThrows(NullPointerException.class, () -> j.join(mapWithNulls));
assertEquals("a:00;00:b", j.useForNull("00").join(mapWithNulls));
StringBuilder sb = new StringBuilder();
j.appendTo(sb, ImmutableMap.of(1, 2, 3, 4, 5, 6));
assertEquals("1:2;3:4;5:6", sb.toString());
}
public void testEntries() {
MapJoiner j = Joiner.on(";").withKeyValueSeparator(":");
assertEquals("", j.join(ImmutableMultimap.of().entries()));
assertEquals("", j.join(ImmutableMultimap.of().entries().iterator()));
assertEquals(":", j.join(ImmutableMultimap.of("", "").entries()));
assertEquals(":", j.join(ImmutableMultimap.of("", "").entries().iterator()));
assertEquals("1:a;1:b", j.join(ImmutableMultimap.of("1", "a", "1", "b").entries()));
assertEquals("1:a;1:b", j.join(ImmutableMultimap.of("1", "a", "1", "b").entries().iterator()));
Map<@Nullable String, @Nullable String> mapWithNulls = new LinkedHashMap<>();
mapWithNulls.put("a", null);
mapWithNulls.put(null, "b");
Set<Entry<String, String>> entriesWithNulls = mapWithNulls.entrySet();
assertThrows(NullPointerException.class, () -> j.join(entriesWithNulls));
assertThrows(NullPointerException.class, () -> j.join(entriesWithNulls.iterator()));
assertEquals("a:00;00:b", j.useForNull("00").join(entriesWithNulls));
assertEquals("a:00;00:b", j.useForNull("00").join(entriesWithNulls.iterator()));
StringBuilder sb1 = new StringBuilder();
j.appendTo(sb1, ImmutableMultimap.of(1, 2, 3, 4, 5, 6, 1, 3, 5, 10).entries());
assertEquals("1:2;1:3;3:4;5:6;5:10", sb1.toString());
StringBuilder sb2 = new StringBuilder();
j.appendTo(sb2, ImmutableMultimap.of(1, 2, 3, 4, 5, 6, 1, 3, 5, 10).entries().iterator());
assertEquals("1:2;1:3;3:4;5:6;5:10", sb2.toString());
}
public void test_skipNulls_onMap() {
Joiner j = Joiner.on(",").skipNulls();
assertThrows(UnsupportedOperationException.class, () -> j.withKeyValueSeparator("/"));
}
@J2ktIncompatible
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
NullPointerTester tester = new NullPointerTester();
tester.testAllPublicStaticMethods(Joiner.class);
tester.testInstanceMethods(Joiner.on(","), NullPointerTester.Visibility.PACKAGE);
tester.testInstanceMethods(Joiner.on(",").skipNulls(), NullPointerTester.Visibility.PACKAGE);
tester.testInstanceMethods(
Joiner.on(",").useForNull("x"), NullPointerTester.Visibility.PACKAGE);
tester.testInstanceMethods(
Joiner.on(",").withKeyValueSeparator("="), NullPointerTester.Visibility.PACKAGE);
}
}
| MisleadingSizeList |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/inference/strategies/SymbolArgumentTypeStrategy.java | {
"start": 1541,
"end": 4464
} | class ____<T extends Enum<? extends TableSymbol>>
implements ArgumentTypeStrategy {
private final Class<T> symbolClass;
private final Set<T> allowedVariants;
public SymbolArgumentTypeStrategy(Class<T> symbolClass) {
this(symbolClass, new HashSet<>(Arrays.asList(symbolClass.getEnumConstants())));
}
public SymbolArgumentTypeStrategy(Class<T> symbolClass, Set<T> allowedVariants) {
this.symbolClass = symbolClass;
this.allowedVariants = allowedVariants;
}
@Override
public Optional<DataType> inferArgumentType(
CallContext callContext, int argumentPos, boolean throwOnFailure) {
final DataType argumentType = callContext.getArgumentDataTypes().get(argumentPos);
if (argumentType.getLogicalType().getTypeRoot() != LogicalTypeRoot.SYMBOL
|| !callContext.isArgumentLiteral(argumentPos)) {
return callContext.fail(
throwOnFailure,
"Unsupported argument type. Expected symbol type '%s' but actual type was '%s'.",
symbolClass.getSimpleName(),
argumentType);
}
Optional<T> val = callContext.getArgumentValue(argumentPos, symbolClass);
if (!val.isPresent()) {
return callContext.fail(
throwOnFailure,
"Unsupported argument symbol type. Expected symbol '%s' but actual symbol was %s.",
symbolClass.getSimpleName(),
callContext
.getArgumentValue(argumentPos, Enum.class)
.map(e -> "'" + e.getClass().getSimpleName() + "'")
.orElse("invalid"));
}
if (!this.allowedVariants.contains(val.get())) {
return callContext.fail(
throwOnFailure,
"Unsupported argument symbol variant. Expected one of the following variants %s but actual symbol was %s.",
this.allowedVariants,
val.get());
}
return Optional.of(argumentType);
}
@Override
public Signature.Argument getExpectedArgument(
FunctionDefinition functionDefinition, int argumentPos) {
return Signature.Argument.ofGroup(symbolClass);
}
// ---------------------------------------------------------------------------------------------
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
SymbolArgumentTypeStrategy that = (SymbolArgumentTypeStrategy) other;
return Objects.equals(symbolClass, that.symbolClass);
}
@Override
public int hashCode() {
return Objects.hash(symbolClass);
}
}
| SymbolArgumentTypeStrategy |
java | google__dagger | dagger-producers/main/java/dagger/producers/Producers.java | {
"start": 950,
"end": 1496
} | class ____ {
/** Returns a producer that succeeds with the given value. */
public static <T> Producer<T> immediateProducer(final T value) {
return new ImmediateProducer<>(Futures.immediateFuture(value));
}
/** Returns a producer that fails with the given exception. */
public static <T> Producer<T> immediateFailedProducer(final Throwable throwable) {
return new ImmediateProducer<>(Futures.<T>immediateFailedFuture(throwable));
}
/** A {@link CancellableProducer} with an immediate result. */
private static final | Producers |
java | netty__netty | codec-redis/src/main/java/io/netty/handler/codec/redis/BulkStringRedisContent.java | {
"start": 1294,
"end": 1833
} | interface ____ extends RedisMessage, ByteBufHolder {
@Override
BulkStringRedisContent copy();
@Override
BulkStringRedisContent duplicate();
@Override
BulkStringRedisContent retainedDuplicate();
@Override
BulkStringRedisContent replace(ByteBuf content);
@Override
BulkStringRedisContent retain();
@Override
BulkStringRedisContent retain(int increment);
@Override
BulkStringRedisContent touch();
@Override
BulkStringRedisContent touch(Object hint);
}
| BulkStringRedisContent |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/OnBeanConditionTypeDeductionFailureTests.java | {
"start": 2960,
"end": 3194
} | class ____ implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[] { OnMissingBeanConfiguration.class.getName() };
}
}
}
| OnMissingBeanImportSelector |
java | alibaba__nacos | client-basic/src/main/java/com/alibaba/nacos/client/auth/impl/NacosClientAuthServiceImpl.java | {
"start": 1376,
"end": 5146
} | class ____ extends AbstractClientAuthService {
private static final Logger SECURITY_LOGGER = LoggerFactory.getLogger(NacosClientAuthServiceImpl.class);
/**
* TTL of token in seconds.
*/
private long tokenTtl;
/**
* Last timestamp refresh security info from server.
*/
private long lastRefreshTime;
/**
* time window to refresh security info in seconds.
*/
private long tokenRefreshWindow;
/**
* A context to take with when sending request to Nacos server.
*/
private volatile LoginIdentityContext loginIdentityContext = new LoginIdentityContext();
/**
* Re-login window in milliseconds.
*/
private final long reLoginWindow = 60000;
/**
* Login to servers.
*
* @return true if login successfully
*/
@Override
public Boolean login(Properties properties) {
try {
boolean reLoginFlag = Boolean.parseBoolean(loginIdentityContext.getParameter(NacosAuthLoginConstant.RELOGINFLAG, "false"));
if (reLoginFlag) {
if ((System.currentTimeMillis() - lastRefreshTime) < reLoginWindow) {
return true;
}
} else {
if ((System.currentTimeMillis() - lastRefreshTime) < TimeUnit.SECONDS
.toMillis(tokenTtl - tokenRefreshWindow)) {
return true;
}
}
if (StringUtils.isBlank(properties.getProperty(PropertyKeyConst.USERNAME))) {
lastRefreshTime = System.currentTimeMillis();
return true;
}
for (String server : this.serverList) {
HttpLoginProcessor httpLoginProcessor = new HttpLoginProcessor(nacosRestTemplate);
properties.setProperty(NacosAuthLoginConstant.SERVER, server);
LoginIdentityContext identityContext = httpLoginProcessor.getResponse(properties);
if (identityContext != null) {
if (identityContext.getAllKey().contains(NacosAuthLoginConstant.ACCESSTOKEN)) {
tokenTtl = Long.parseLong(identityContext.getParameter(NacosAuthLoginConstant.TOKENTTL));
tokenRefreshWindow = generateTokenRefreshWindow(tokenTtl);
lastRefreshTime = System.currentTimeMillis();
LoginIdentityContext newCtx = new LoginIdentityContext();
newCtx.setParameter(NacosAuthLoginConstant.ACCESSTOKEN,
identityContext.getParameter(NacosAuthLoginConstant.ACCESSTOKEN));
this.loginIdentityContext = newCtx;
}
return true;
}
}
} catch (Throwable throwable) {
SECURITY_LOGGER.warn("[SecurityProxy] login failed, error: ", throwable);
return false;
}
return false;
}
@Override
public LoginIdentityContext getLoginIdentityContext(RequestResource resource) {
return this.loginIdentityContext;
}
@Override
public void shutdown() throws NacosException {
}
/**
* Randomly generate TokenRefreshWindow, Avoid a large number of logins causing pressure on the Nacos server.
* @param tokenTtl TTL of token in seconds.
* @return tokenRefreshWindow, numerical range [tokenTtl/15 ~ tokenTtl/10]
*/
public long generateTokenRefreshWindow(long tokenTtl) {
long startNumber = tokenTtl / 15;
long endNumber = tokenTtl / 10;
return RandomUtils.nextLong(startNumber, endNumber);
}
}
| NacosClientAuthServiceImpl |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/mapping/BasicValuedModelPart.java | {
"start": 409,
"end": 1467
} | interface ____ extends BasicValuedMapping, ValuedModelPart, Fetchable, SelectableMapping {
@Override
default MappingType getPartMappingType() {
return this::getJavaType;
}
@Override
default int getJdbcTypeCount() {
return 1;
}
@Override
default JdbcMapping getJdbcMapping(int index) {
return BasicValuedMapping.super.getJdbcMapping( index );
}
@Override
default JdbcMapping getSingleJdbcMapping() {
return BasicValuedMapping.super.getSingleJdbcMapping();
}
@Override
default SelectableMapping getSelectable(int columnIndex) {
return this;
}
@Override
default int forEachSelectable(int offset, SelectableConsumer consumer) {
consumer.accept( offset, this );
return getJdbcTypeCount();
}
@Override
default int forEachSelectable(SelectableConsumer consumer) {
consumer.accept( 0, this );
return getJdbcTypeCount();
}
@Override
default boolean hasPartitionedSelectionMapping() {
return isPartitioned();
}
@Override
default BasicValuedModelPart asBasicValuedModelPart() {
return this;
}
}
| BasicValuedModelPart |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectorySessionFactory.java | {
"start": 20807,
"end": 20901
} | class ____ the logic necessary to authenticate this form of a username
*/
static | contains |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/registrations/Thing1.java | {
"start": 240,
"end": 445
} | class ____ implements Thing, Serializable {
private final String content;
public Thing1(String content) {
this.content = content;
}
@Override
public String getContent() {
return content;
}
}
| Thing1 |
java | junit-team__junit5 | junit-jupiter-api/src/main/java/org/junit/jupiter/api/TestClassOrder.java | {
"start": 1992,
"end": 2129
} | class ____ {
* // {@literal @}Test methods ...
* }
*
* {@literal @}Nested
* {@literal @}Order(2)
* | PrimaryTests |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/api/AtomicStampedReferenceAssert.java | {
"start": 1026,
"end": 2906
} | class ____<VALUE>
extends AbstractAtomicReferenceAssert<AtomicStampedReferenceAssert<VALUE>, VALUE, AtomicStampedReference<VALUE>> {
public AtomicStampedReferenceAssert(AtomicStampedReference<VALUE> actual) {
super(actual, AtomicStampedReferenceAssert.class);
}
/**
* Verifies that the actual {@link AtomicStampedReference} contains the given value.
* <p>
* Example:
* <pre><code class='java'> AtomicStampedReferenceAssert<String> ref = new AtomicStampedReferenceAssert<>("foo", 123);
*
* // this assertion succeeds:
* assertThat(ref).hasValue("foo");
*
* // this assertion fails:
* assertThat(ref).hasValue("bar");</code></pre>
*
* @param expectedValue the expected value inside the {@link AtomicStampedReference}.
* @return this assertion object.
* @since 2.7.0 / 3.7.0
*/
@Override
public AtomicStampedReferenceAssert<VALUE> hasReference(VALUE expectedValue) {
return super.hasReference(expectedValue);
}
@Override
protected VALUE getReference() {
return actual.getReference();
}
/**
* Verifies that the actual {@link AtomicStampedReference} has the given stamp.
*
* Examples:
* <pre><code class='java'> // this assertion succeeds:
* assertThat(new AtomicStampedReference<>("actual", 1234)).hasStamp(1234);
*
* // this assertion fails:
* assertThat(new AtomicStampedReference<>("actual", 1234)).hasStamp(5678);</code></pre>
*
* @param expectedStamp the expected stamp inside the {@link AtomicStampedReference}.
* @return this assertion object.
* @since 2.7.0 / 3.7.0
*/
public AtomicStampedReferenceAssert<VALUE> hasStamp(int expectedStamp) {
int timestamp = actual.getStamp();
if (timestamp != expectedStamp) throwAssertionError(shouldHaveStamp(actual, expectedStamp));
return this;
}
}
| AtomicStampedReferenceAssert |
java | apache__camel | components/camel-dns/src/test/java/org/apache/camel/component/dns/DnsDigEndpointSpringTest.java | {
"start": 1524,
"end": 3200
} | class ____ extends CamelSpringTestSupport {
private static final String RESPONSE_MONKEY = "\"A monkey is a nonhuman "
+ "primate mammal with the exception usually of the lemurs and tarsiers. More specifically, the term monkey refers to a subset "
+ "of monkeys: any of the smaller longer-tailed catarrhine or "
+ "platyrrhine primates as contrasted with the apes.\" "
+ "\" http://en.wikipedia.org/wiki/Monkey\"";
@EndpointInject("mock:result")
protected MockEndpoint resultEndpoint;
@Produce("direct:start")
protected ProducerTemplate template;
@Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("DNSDig.xml");
}
@Test
@Disabled("Testing behind nat produces timeouts")
void testDigForMonkey() throws Exception {
resultEndpoint.expectedMessageCount(1);
resultEndpoint.expectedMessagesMatches(new Predicate() {
public boolean matches(Exchange exchange) {
String str = ((Message) exchange.getIn().getBody()).getSectionArray(Section.ANSWER)[0].rdataToString();
return RESPONSE_MONKEY.equals(str);
}
});
Map<String, Object> headers = new HashMap<>();
headers.put("dns.name", "monkey.wp.dg.cx");
headers.put("dns.type", "TXT");
template.sendBodyAndHeaders(null, headers);
resultEndpoint.assertIsSatisfied();
}
}
| DnsDigEndpointSpringTest |
java | elastic__elasticsearch | server/src/internalClusterTest/java/org/elasticsearch/versioning/ConcurrentSeqNoVersioningIT.java | {
"start": 6789,
"end": 10218
} | class ____ extends AbstractDisruptionTestCase {
private static final Pattern EXTRACT_VERSION = Pattern.compile("current document has seqNo \\[(\\d+)\\] and primary term \\[(\\d+)\\]");
// Test info: disrupt network for up to 8s in a number of rounds and check that we only get true positive CAS results when running
// multiple threads doing CAS updates.
// Wait up to 1 minute (+10s in thread to ensure it does not time out) for threads to complete previous round before initiating next
// round.
public void testSeqNoCASLinearizability() {
final int disruptTimeSeconds = scaledRandomIntBetween(1, 8);
assertAcked(
prepareCreate("test").setSettings(
Settings.builder()
.put(indexSettings())
.put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1 + randomInt(2))
.put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, randomInt(3))
)
);
ensureGreen();
int numberOfKeys = randomIntBetween(1, 10);
logger.info("--> Indexing initial doc for {} keys", numberOfKeys);
List<Partition> partitions = IntStream.range(0, numberOfKeys)
.mapToObj(i -> prepareIndex("test").setId("ID:" + i).setSource("value", -1).get())
.map(response -> new Partition(response.getId(), new Version(response.getPrimaryTerm(), response.getSeqNo())))
.toList();
int threadCount = randomIntBetween(3, 20);
CyclicBarrier roundBarrier = new CyclicBarrier(threadCount + 1); // +1 for main thread.
List<CASUpdateThread> threads = IntStream.range(0, threadCount)
.mapToObj(i -> new CASUpdateThread(i, roundBarrier, partitions, disruptTimeSeconds + 1))
.toList();
logger.info("--> Starting {} threads", threadCount);
threads.forEach(Thread::start);
try {
int rounds = randomIntBetween(2, 5);
logger.info("--> Running {} rounds", rounds);
for (int i = 0; i < rounds; ++i) {
ServiceDisruptionScheme disruptionScheme = addRandomDisruptionScheme();
roundBarrier.await(1, TimeUnit.MINUTES);
disruptionScheme.startDisrupting();
logger.info("--> round {}", i);
try {
roundBarrier.await(disruptTimeSeconds, TimeUnit.SECONDS);
} catch (TimeoutException e) {
roundBarrier.reset();
}
internalCluster().clearDisruptionScheme(false);
// heal cluster faster to reduce test time.
ensureFullyConnectedCluster();
}
} catch (InterruptedException | BrokenBarrierException | TimeoutException e) {
logger.error("Timed out, dumping stack traces of all threads:");
threads.forEach(thread -> logger.info(thread.toString() + ":\n" + ExceptionsHelper.formatStackTrace(thread.getStackTrace())));
throw new RuntimeException(e);
} finally {
logger.info("--> terminating test");
threads.forEach(CASUpdateThread::terminate);
threads.forEach(CASUpdateThread::await);
threads.stream().filter(Thread::isAlive).forEach(t -> fail("Thread still alive: " + t));
}
partitions.forEach(Partition::assertLinearizable);
}
private | ConcurrentSeqNoVersioningIT |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/stateless/StatelessSessionNativeQueryInsertTest.java | {
"start": 793,
"end": 1500
} | class ____ {
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
@JiraKey(value = "HHH-12141")
public void testInsertInStatelessSession(SessionFactoryScope scope) {
scope.inSession(
session ->
session.doWork(
connection -> {
StatelessSession sls = scope.getSessionFactory().openStatelessSession( connection );
NativeQuery q = sls.createNativeQuery(
"INSERT INTO TEST_ENTITY (ID,SIMPLE_ATTRIBUTE) values (1,'red')" );
q.executeUpdate();
} )
);
}
@Entity(name = "TestEntity")
@Table(name = "TEST_ENTITY")
public static | StatelessSessionNativeQueryInsertTest |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/authz/privilege/ClusterPrivilegeTests.java | {
"start": 850,
"end": 1634
} | class ____ extends ESTestCase {
public void testMonitorPrivilegeWillGrantActions() {
assertGranted(ClusterPrivilegeResolver.MONITOR, EnrichStatsAction.INSTANCE);
}
public void testMonitorPrivilegeGrantsGetTemplateActions() {
for (var action : List.of(
GetComponentTemplateAction.INSTANCE,
GetComposableIndexTemplateAction.INSTANCE,
GetIndexTemplatesAction.INSTANCE
)) {
assertGranted(ClusterPrivilegeResolver.MONITOR, action);
}
}
public static void assertGranted(ClusterPrivilege clusterPrivilege, ActionType<?> actionType) {
assertTrue(clusterPrivilege.buildPermission(ClusterPermission.builder()).build().check(actionType.name(), null, null));
}
}
| ClusterPrivilegeTests |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/IndexedSortable.java | {
"start": 871,
"end": 2836
} | interface ____ {
/**
* Compare items at the given addresses consistent with the semantics of {@link
* java.util.Comparator#compare(Object, Object)}.
*/
int compare(int i, int j);
/**
* Compare records at the given addresses consistent with the semantics of {@link
* java.util.Comparator#compare(Object, Object)}.
*
* @param segmentNumberI index of memory segment containing first record
* @param segmentOffsetI offset into memory segment containing first record
* @param segmentNumberJ index of memory segment containing second record
* @param segmentOffsetJ offset into memory segment containing second record
* @return a negative integer, zero, or a positive integer as the first argument is less than,
* equal to, or greater than the second.
*/
int compare(int segmentNumberI, int segmentOffsetI, int segmentNumberJ, int segmentOffsetJ);
/** Swap items at the given addresses. */
void swap(int i, int j);
/**
* Swap records at the given addresses.
*
* @param segmentNumberI index of memory segment containing first record
* @param segmentOffsetI offset into memory segment containing first record
* @param segmentNumberJ index of memory segment containing second record
* @param segmentOffsetJ offset into memory segment containing second record
*/
void swap(int segmentNumberI, int segmentOffsetI, int segmentNumberJ, int segmentOffsetJ);
/**
* Gets the number of elements in the sortable.
*
* @return The number of elements.
*/
int size();
/**
* Gets the size of each record, the number of bytes separating the head of successive records.
*
* @return The record size
*/
int recordSize();
/**
* Gets the number of elements in each memory segment.
*
* @return The number of records per segment
*/
int recordsPerSegment();
}
| IndexedSortable |
java | spring-projects__spring-framework | integration-tests/src/test/java/org/springframework/context/annotation/jsr330/ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java | {
"start": 13863,
"end": 14098
} | class ____ extends ScopedTestBean implements AnotherScopeTestInterface {
}
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@jakarta.inject.Scope
public @ | SessionScopedTestBean |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java | {
"start": 16486,
"end": 20125
} | class ____ {
@Test
void withEmptyArgumentList() {
assertThatIllegalArgumentException().isThrownBy(environment::matchesProfiles);
}
@Test
void withNullArgumentList() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles((String[]) null));
}
@Test
void withNullArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles((String) null));
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1", null));
}
@Test
void withEmptyArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles(""));
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1", ""));
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1", " "));
}
@Test
void withInvalidNotOperator() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1", "!"));
}
@Test
void withInvalidCompoundExpressionGrouping() {
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1 | p2 & p3"));
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1 & p2 | p3"));
assertThatIllegalArgumentException().isThrownBy(() -> environment.matchesProfiles("p1 & (p2 | p3) | p4"));
}
@Test
void activeProfileSetProgrammatically() {
assertThat(environment.matchesProfiles("p1", "p2")).isFalse();
environment.setActiveProfiles("p1");
assertThat(environment.matchesProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p2");
assertThat(environment.matchesProfiles("p1", "p2")).isTrue();
environment.setActiveProfiles("p1", "p2");
assertThat(environment.matchesProfiles("p1", "p2")).isTrue();
}
@Test
void activeProfileSetViaProperty() {
assertThat(environment.matchesProfiles("p1")).isFalse();
environment.getPropertySources().addFirst(new MockPropertySource().withProperty(ACTIVE_PROFILES_PROPERTY_NAME, "p1"));
assertThat(environment.matchesProfiles("p1")).isTrue();
}
@Test
void defaultProfile() {
assertThat(environment.matchesProfiles("pd")).isFalse();
environment.setDefaultProfiles("pd");
assertThat(environment.matchesProfiles("pd")).isTrue();
environment.setActiveProfiles("p1");
assertThat(environment.matchesProfiles("pd")).isFalse();
assertThat(environment.matchesProfiles("p1")).isTrue();
}
@Test
void withNotOperator() {
assertThat(environment.matchesProfiles("p1")).isFalse();
assertThat(environment.matchesProfiles("!p1")).isTrue();
environment.addActiveProfile("p1");
assertThat(environment.matchesProfiles("p1")).isTrue();
assertThat(environment.matchesProfiles("!p1")).isFalse();
}
@Test
void withProfileExpressions() {
assertThat(environment.matchesProfiles("p1 & p2")).isFalse();
environment.addActiveProfile("p1");
assertThat(environment.matchesProfiles("p1 | p2")).isTrue();
assertThat(environment.matchesProfiles("p1 & p2")).isFalse();
environment.addActiveProfile("p2");
assertThat(environment.matchesProfiles("p1 & p2")).isTrue();
assertThat(environment.matchesProfiles("p1 | p2")).isTrue();
assertThat(environment.matchesProfiles("foo | p1", "p2")).isTrue();
assertThat(environment.matchesProfiles("foo | p2", "p1")).isTrue();
assertThat(environment.matchesProfiles("foo | (p2 & p1)")).isTrue();
assertThat(environment.matchesProfiles("p2 & (foo | p1)")).isTrue();
assertThat(environment.matchesProfiles("foo", "(p2 & p1)")).isTrue();
}
}
}
| MatchesProfilesTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/registry/classloading/spi/ClassLoaderService.java | {
"start": 3032,
"end": 3137
} | interface ____<T> {
T doWork(ClassLoader classLoader);
}
<T> T workWithClassLoader(Work<T> work);
}
| Work |
java | google__truth | core/src/test/java/com/google/common/truth/IntStreamSubjectTest.java | {
"start": 1225,
"end": 10137
} | class ____ {
@Test
@SuppressWarnings("TruthSelfEquals")
public void isEqualTo() {
IntStream stream = IntStream.of(42);
assertThat(stream).isEqualTo(stream);
}
@Test
public void isEqualToList() {
IntStream stream = IntStream.of(42);
List<Integer> list = asList(42);
expectFailure(whenTesting -> whenTesting.that(stream).isEqualTo(list));
}
@Test
public void nullStream_fails() {
expectFailure(whenTesting -> whenTesting.that((IntStream) null).isEmpty());
}
@Test
public void nullStreamIsNull() {
assertThat((IntStream) null).isNull();
}
@Test
@SuppressWarnings("TruthSelfEquals")
public void isSameInstanceAs() {
IntStream stream = IntStream.of(1);
assertThat(stream).isSameInstanceAs(stream);
}
@Test
public void isEmpty() {
assertThat(IntStream.of()).isEmpty();
}
@Test
public void isEmpty_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(42)).isEmpty());
}
@Test
public void isNotEmpty() {
assertThat(IntStream.of(42)).isNotEmpty();
}
@Test
public void isNotEmpty_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of()).isNotEmpty());
}
@Test
public void hasSize() {
assertThat(IntStream.of(42)).hasSize(1);
}
@Test
public void hasSize_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(42)).hasSize(2));
}
@Test
public void containsNoDuplicates() {
assertThat(IntStream.of(42)).containsNoDuplicates();
}
@Test
public void containsNoDuplicates_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(42, 42)).containsNoDuplicates());
}
@Test
public void contains() {
assertThat(IntStream.of(42)).contains(42);
}
@Test
public void contains_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(42)).contains(100));
}
@Test
public void containsAnyOf() {
assertThat(IntStream.of(42)).containsAnyOf(42, 43);
}
@Test
public void containsAnyOf_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(42)).containsAnyOf(43, 44));
}
@Test
public void containsAnyIn() {
assertThat(IntStream.of(42)).containsAnyIn(asList(42, 43));
}
@Test
public void containsAnyIn_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(42)).containsAnyIn(asList(43, 44)));
}
@Test
public void doesNotContain() {
assertThat(IntStream.of(42)).doesNotContain(43);
}
@Test
public void doesNotContain_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(42)).doesNotContain(42));
}
@Test
public void containsNoneOf() {
assertThat(IntStream.of(42)).containsNoneOf(43, 44);
}
@Test
public void containsNoneOf_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(42)).containsNoneOf(42, 43));
}
@Test
public void containsNoneIn() {
assertThat(IntStream.of(42)).containsNoneIn(asList(43, 44));
}
@Test
public void containsNoneIn_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(42)).containsNoneIn(asList(42, 43)));
}
@Test
public void containsAtLeast() {
assertThat(IntStream.of(42, 43)).containsAtLeast(42, 43);
}
@Test
public void containsAtLeast_fails() {
expectFailure(
whenTesting -> whenTesting.that(IntStream.of(42, 43)).containsAtLeast(42, 43, 44));
}
@Test
public void containsAtLeast_inOrder() {
assertThat(IntStream.of(42, 43)).containsAtLeast(42, 43).inOrder();
}
@Test
public void containsAtLeast_inOrder_fails() {
AssertionError e =
expectFailure(
whenTesting ->
whenTesting.that(IntStream.of(42, 43)).containsAtLeast(43, 42).inOrder());
assertFailureKeys(
e,
"required elements were all found, but order was wrong",
"expected order for required elements",
"but was");
assertFailureValue(e, "expected order for required elements", "[43, 42]");
}
@Test
public void containsAtLeastElementsIn() {
assertThat(IntStream.of(42, 43)).containsAtLeastElementsIn(asList(42, 43));
}
@Test
public void containsAtLeastElementsIn_fails() {
expectFailure(
whenTesting ->
whenTesting.that(IntStream.of(42, 43)).containsAtLeastElementsIn(asList(42, 43, 44)));
}
@Test
public void containsAtLeastElementsIn_inOrder() {
assertThat(IntStream.of(42, 43)).containsAtLeastElementsIn(asList(42, 43)).inOrder();
}
@Test
public void containsAtLeastElementsIn_inOrder_fails() {
AssertionError e =
expectFailure(
whenTesting ->
whenTesting
.that(IntStream.of(42, 43))
.containsAtLeastElementsIn(asList(43, 42))
.inOrder());
assertFailureKeys(
e,
"required elements were all found, but order was wrong",
"expected order for required elements",
"but was");
assertFailureValue(e, "expected order for required elements", "[43, 42]");
}
@Test
public void containsExactly() {
assertThat(IntStream.of(42, 43)).containsExactly(42, 43);
}
@Test
public void containsExactly_fails() {
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(IntStream.of(42, 43)).containsExactly(42));
assertFailureKeys(e, "unexpected (1)", "---", "expected", "but was");
assertFailureValue(e, "expected", "[42]");
}
@Test
@J2ktIncompatible // Kotlin can't pass a null array for a varargs parameter
@GwtIncompatible // j2cl doesn't throw NPE for a null originally-Kotlin varargs parameter below
public void testContainsExactly_nullExpected() {
// Do nothing if the implementation throws an exception for a null varargs parameter.
// The try/catch here doesn't work with j2cl, hence the @GwtIncompatible annotation.
try {
assertThat(IntStream.of(42, 43)).containsExactly((int[]) null);
} catch (NullPointerException e) {
return;
} catch (AssertionError e) {
// expected
}
AssertionError expected =
expectFailure(
whenTesting -> whenTesting.that(IntStream.of(42, 43)).containsExactly((int[]) null));
assertFailureKeys(
expected,
"could not perform containment check because expected array was null",
"actual contents");
}
@Test
public void containsExactly_inOrder() {
assertThat(IntStream.of(42, 43)).containsExactly(42, 43).inOrder();
}
@Test
public void containsExactly_inOrder_fails() {
AssertionError e =
expectFailure(
whenTesting ->
whenTesting.that(IntStream.of(42, 43)).containsExactly(43, 42).inOrder());
assertFailureKeys(e, "contents match, but order was wrong", "expected", "but was");
assertFailureValue(e, "expected", "[43, 42]");
}
@Test
public void containsExactlyElementsIn() {
assertThat(IntStream.of(42, 43)).containsExactlyElementsIn(asList(42, 43));
assertThat(IntStream.of(42, 43)).containsExactlyElementsIn(asList(43, 42));
}
@Test
public void containsExactlyElementsIn_fails() {
AssertionError e =
expectFailure(
whenTesting ->
whenTesting.that(IntStream.of(42, 43)).containsExactlyElementsIn(asList(42)));
assertFailureKeys(e, "unexpected (1)", "---", "expected", "but was");
assertFailureValue(e, "expected", "[42]");
}
@Test
public void containsExactlyElementsIn_inOrder() {
assertThat(IntStream.of(42, 43)).containsExactlyElementsIn(asList(42, 43)).inOrder();
}
@Test
public void containsExactlyElementsIn_inOrder_fails() {
AssertionError e =
expectFailure(
whenTesting ->
whenTesting
.that(IntStream.of(42, 43))
.containsExactlyElementsIn(asList(43, 42))
.inOrder());
assertFailureKeys(e, "contents match, but order was wrong", "expected", "but was");
assertFailureValue(e, "expected", "[43, 42]");
}
@Test
public void containsExactlyElementsIn_inOrder_intStream() {
assertThat(IntStream.of(1, 2, 3, 4)).containsExactly(1, 2, 3, 4).inOrder();
}
@Test
public void isInOrder() {
assertThat(IntStream.of()).isInOrder();
assertThat(IntStream.of(1)).isInOrder();
assertThat(IntStream.of(1, 1, 2, 3, 3, 3, 4)).isInOrder();
}
@Test
public void isInOrder_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(1, 3, 2, 4)).isInOrder());
}
@Test
public void isInStrictOrder() {
assertThat(IntStream.of()).isInStrictOrder();
assertThat(IntStream.of(1)).isInStrictOrder();
assertThat(IntStream.of(1, 2, 3, 4)).isInStrictOrder();
}
@Test
public void isInStrictOrder_fails() {
expectFailure(whenTesting -> whenTesting.that(IntStream.of(1, 2, 2, 4)).isInStrictOrder());
}
}
| IntStreamSubjectTest |
java | apache__kafka | storage/src/test/java/org/apache/kafka/server/log/remote/metadata/storage/RemoteLogMetadataManagerTestUtils.java | {
"start": 2374,
"end": 5380
} | class ____ {
private String bootstrapServers;
private Map<String, Object> overrideRemoteLogMetadataManagerProps = Map.of();
private Supplier<RemotePartitionMetadataStore> remotePartitionMetadataStore = RemotePartitionMetadataStore::new;
private Function<Integer, RemoteLogMetadataTopicPartitioner> remoteLogMetadataTopicPartitioner = RemoteLogMetadataTopicPartitioner::new;
private Builder() {
}
public Builder bootstrapServers(String bootstrapServers) {
this.bootstrapServers = Objects.requireNonNull(bootstrapServers);
return this;
}
public Builder remotePartitionMetadataStore(Supplier<RemotePartitionMetadataStore> remotePartitionMetadataStore) {
this.remotePartitionMetadataStore = remotePartitionMetadataStore;
return this;
}
public Builder remoteLogMetadataTopicPartitioner(Function<Integer, RemoteLogMetadataTopicPartitioner> remoteLogMetadataTopicPartitioner) {
this.remoteLogMetadataTopicPartitioner = Objects.requireNonNull(remoteLogMetadataTopicPartitioner);
return this;
}
public Builder overrideRemoteLogMetadataManagerProps(Map<String, Object> overrideRemoteLogMetadataManagerProps) {
this.overrideRemoteLogMetadataManagerProps = Objects.requireNonNull(overrideRemoteLogMetadataManagerProps);
return this;
}
public TopicBasedRemoteLogMetadataManager build() {
Objects.requireNonNull(bootstrapServers);
String logDir = TestUtils.tempDirectory("rlmm_segs_").getAbsolutePath();
TopicBasedRemoteLogMetadataManager topicBasedRemoteLogMetadataManager =
new TopicBasedRemoteLogMetadataManager(remoteLogMetadataTopicPartitioner, remotePartitionMetadataStore);
// Initialize TopicBasedRemoteLogMetadataManager.
Map<String, Object> configs = new HashMap<>();
configs.put(REMOTE_LOG_METADATA_COMMON_CLIENT_PREFIX + CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
configs.put(BROKER_ID, 0);
configs.put(LOG_DIR, logDir);
configs.put(REMOTE_LOG_METADATA_TOPIC_PARTITIONS_PROP, METADATA_TOPIC_PARTITIONS_COUNT);
configs.put(REMOTE_LOG_METADATA_TOPIC_REPLICATION_FACTOR_PROP, METADATA_TOPIC_REPLICATION_FACTOR);
configs.put(REMOTE_LOG_METADATA_TOPIC_RETENTION_MS_PROP, METADATA_TOPIC_RETENTION_MS);
// Add override properties.
configs.putAll(overrideRemoteLogMetadataManagerProps);
topicBasedRemoteLogMetadataManager.configure(configs);
topicBasedRemoteLogMetadataManager.onBrokerReady();
assertDoesNotThrow(() -> TestUtils.waitForCondition(topicBasedRemoteLogMetadataManager::isInitialized, 60_000L,
"Time out reached before it is initialized successfully"));
return topicBasedRemoteLogMetadataManager;
}
}
}
| Builder |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/permission/ScopedAclEntries.java | {
"start": 1328,
"end": 3268
} | class ____ {
private static final int PIVOT_NOT_FOUND = -1;
private final List<AclEntry> accessEntries;
private final List<AclEntry> defaultEntries;
/**
* Creates a new ScopedAclEntries from the given list. It is assumed that the
* list is already sorted such that all access entries precede all default
* entries.
*
* @param aclEntries List<AclEntry> to separate
*/
public ScopedAclEntries(List<AclEntry> aclEntries) {
int pivot = calculatePivotOnDefaultEntries(aclEntries);
if (pivot != PIVOT_NOT_FOUND) {
accessEntries = pivot != 0 ? aclEntries.subList(0, pivot) :
Collections.<AclEntry>emptyList();
defaultEntries = aclEntries.subList(pivot, aclEntries.size());
} else {
accessEntries = aclEntries;
defaultEntries = Collections.emptyList();
}
}
/**
* Returns access entries.
*
* @return List<AclEntry> containing just access entries, or an empty
* list if there are no access entries
*/
public List<AclEntry> getAccessEntries() {
return accessEntries;
}
/**
* Returns default entries.
*
* @return List<AclEntry> containing just default entries, or an empty
* list if there are no default entries
*/
public List<AclEntry> getDefaultEntries() {
return defaultEntries;
}
/**
* Returns the pivot point in the list between the access entries and the
* default entries. This is the index of the first element in the list that
* is a default entry.
*
* @param aclBuilder ArrayList<AclEntry> containing entries to build
* @return int pivot point, or -1 if list contains no default entries
*/
private static int calculatePivotOnDefaultEntries(List<AclEntry> aclBuilder) {
for (int i = 0; i < aclBuilder.size(); ++i) {
if (aclBuilder.get(i).getScope() == AclEntryScope.DEFAULT) {
return i;
}
}
return PIVOT_NOT_FOUND;
}
}
| ScopedAclEntries |
java | apache__flink | flink-core-api/src/main/java/org/apache/flink/api/common/watermark/BoolWatermarkDeclaration.java | {
"start": 976,
"end": 1232
} | class ____ the {@link WatermarkDeclaration} interface
* and provides additional functionality specific to boolean-type watermarks. It includes methods
* for obtaining combination semantics and creating new bool watermarks.
*/
@Experimental
public | implements |
java | spring-projects__spring-framework | spring-websocket/src/test/java/org/springframework/web/socket/server/DefaultHandshakeHandlerTests.java | {
"start": 1565,
"end": 4923
} | class ____ extends AbstractHttpRequestTests {
private RequestUpgradeStrategy upgradeStrategy = mock();
private DefaultHandshakeHandler handshakeHandler = new DefaultHandshakeHandler(this.upgradeStrategy);
@Test
void supportedSubProtocols() {
this.handshakeHandler.setSupportedProtocols("stomp", "mqtt");
given(this.upgradeStrategy.getSupportedVersions()).willReturn(new String[] {"13"});
this.servletRequest.setMethod("GET");
initHeaders(this.request.getHeaders()).setSecWebSocketProtocol("STOMP");
WebSocketHandler handler = new TextWebSocketHandler();
Map<String, Object> attributes = Collections.emptyMap();
this.handshakeHandler.doHandshake(this.request, this.response, handler, attributes);
verify(this.upgradeStrategy).upgrade(this.request, this.response, "STOMP",
Collections.emptyList(), null, handler, attributes);
}
@Test
void supportedExtensions() {
WebSocketExtension extension1 = new WebSocketExtension("ext1");
WebSocketExtension extension2 = new WebSocketExtension("ext2");
given(this.upgradeStrategy.getSupportedVersions()).willReturn(new String[] {"13"});
given(this.upgradeStrategy.getSupportedExtensions(this.request)).willReturn(Collections.singletonList(extension1));
this.servletRequest.setMethod("GET");
initHeaders(this.request.getHeaders()).setSecWebSocketExtensions(Arrays.asList(extension1, extension2));
WebSocketHandler handler = new TextWebSocketHandler();
Map<String, Object> attributes = Collections.emptyMap();
this.handshakeHandler.doHandshake(this.request, this.response, handler, attributes);
verify(this.upgradeStrategy).upgrade(this.request, this.response, null,
Collections.singletonList(extension1), null, handler, attributes);
}
@Test
void subProtocolCapableHandler() {
given(this.upgradeStrategy.getSupportedVersions()).willReturn(new String[] {"13"});
this.servletRequest.setMethod("GET");
initHeaders(this.request.getHeaders()).setSecWebSocketProtocol("v11.stomp");
WebSocketHandler handler = new SubProtocolCapableHandler("v12.stomp", "v11.stomp");
Map<String, Object> attributes = Collections.emptyMap();
this.handshakeHandler.doHandshake(this.request, this.response, handler, attributes);
verify(this.upgradeStrategy).upgrade(this.request, this.response, "v11.stomp",
Collections.emptyList(), null, handler, attributes);
}
@Test
void subProtocolCapableHandlerNoMatch() {
given(this.upgradeStrategy.getSupportedVersions()).willReturn(new String[] {"13"});
this.servletRequest.setMethod("GET");
initHeaders(this.request.getHeaders()).setSecWebSocketProtocol("v10.stomp");
WebSocketHandler handler = new SubProtocolCapableHandler("v12.stomp", "v11.stomp");
Map<String, Object> attributes = Collections.emptyMap();
this.handshakeHandler.doHandshake(this.request, this.response, handler, attributes);
verify(this.upgradeStrategy).upgrade(this.request, this.response, null,
Collections.emptyList(), null, handler, attributes);
}
private WebSocketHttpHeaders initHeaders(HttpHeaders httpHeaders) {
WebSocketHttpHeaders headers = new WebSocketHttpHeaders(httpHeaders);
headers.setUpgrade("WebSocket");
headers.setConnection("Upgrade");
headers.setSecWebSocketVersion("13");
headers.setSecWebSocketKey("82/ZS2YHjEnUN97HLL8tbw==");
return headers;
}
private static | DefaultHandshakeHandlerTests |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/FetchSessionHandler.java | {
"start": 2399,
"end": 3379
} | class ____ {
private final Logger log;
private final int node;
/**
* The metadata for the next fetch request.
*/
private FetchMetadata nextMetadata = FetchMetadata.INITIAL;
public FetchSessionHandler(LogContext logContext, int node) {
this.log = logContext.logger(FetchSessionHandler.class);
this.node = node;
}
// visible for testing
public int sessionId() {
return nextMetadata.sessionId();
}
/**
* All of the partitions which exist in the fetch request session.
*/
private LinkedHashMap<TopicPartition, PartitionData> sessionPartitions =
new LinkedHashMap<>(0);
/**
* All of the topic names mapped to topic ids for topics which exist in the fetch request session.
*/
private Map<Uuid, String> sessionTopicNames = new HashMap<>(0);
public Map<Uuid, String> sessionTopicNames() {
return sessionTopicNames;
}
public static | FetchSessionHandler |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/TestInitStringFieldAsEmpty.java | {
"start": 640,
"end": 872
} | class ____ {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public static | VO1 |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/RecipientListBeanSubUnitOfWorkTest.java | {
"start": 3105,
"end": 3304
} | class ____ {
@org.apache.camel.RecipientList(shareUnitOfWork = true)
public String whereToGo() {
return "direct:a,direct:b";
}
}
public static | WhereToGoBean |
java | dropwizard__dropwizard | dropwizard-lifecycle/src/test/java/io/dropwizard/lifecycle/setup/ExecutorServiceBuilderTest.java | {
"start": 1028,
"end": 6952
} | class ____ {
private static final String WARNING = "Parameter 'maximumPoolSize' is conflicting with unbounded work queues";
private final MetricRegistry metricRegistry = new MetricRegistry();
private ExecutorServiceBuilder executorServiceBuilder;
@SuppressWarnings("Slf4jLoggerShouldBeFinal")
private Logger log;
@BeforeEach
void setUp() {
executorServiceBuilder = new ExecutorServiceBuilder(new LifecycleEnvironment(metricRegistry), "test-%d");
log = mock(Logger.class);
ExecutorServiceBuilder.setLog(log);
}
@Test
void testGiveAWarningAboutMaximumPoolSizeAndUnboundedQueue() {
executorServiceBuilder
.minThreads(4)
.maxThreads(8)
.build();
verify(log).warn(WARNING);
assertThat(metricRegistry.getMetrics())
.containsOnlyKeys("test.created", "test.terminated", "test.running");
}
@Test
@SuppressWarnings("Slf4jFormatShouldBeConst")
void testGiveNoWarningAboutMaximumPoolSizeAndBoundedQueue() {
ExecutorService exe = executorServiceBuilder
.minThreads(4)
.maxThreads(8)
.workQueue(new ArrayBlockingQueue<>(16))
.build();
verify(log, never()).warn(WARNING);
assertCanExecuteAtLeast2ConcurrentTasks(exe);
}
/**
* There should be no warning about using an Executors.newSingleThreadExecutor() equivalent
* @see java.util.concurrent.Executors#newSingleThreadExecutor()
*/
@Test
@SuppressWarnings("Slf4jFormatShouldBeConst")
void shouldNotWarnWhenSettingUpSingleThreadedPool() {
executorServiceBuilder
.minThreads(1)
.maxThreads(1)
.keepAliveTime(Duration.milliseconds(0))
.workQueue(new LinkedBlockingQueue<>())
.build();
verify(log, never()).warn(anyString());
}
/**
* There should be no warning about using an Executors.newCachedThreadPool() equivalent
* @see java.util.concurrent.Executors#newCachedThreadPool()
*/
@Test
@SuppressWarnings("Slf4jFormatShouldBeConst")
void shouldNotWarnWhenSettingUpCachedThreadPool() {
ExecutorService exe = executorServiceBuilder
.minThreads(0)
.maxThreads(Integer.MAX_VALUE)
.keepAliveTime(Duration.seconds(60))
.workQueue(new SynchronousQueue<>())
.build();
verify(log, never()).warn(anyString());
assertCanExecuteAtLeast2ConcurrentTasks(exe); // cached thread pools work right?
}
@Test
@SuppressWarnings("Slf4jFormatShouldBeConst")
void shouldNotWarnWhenUsingTheDefaultConfiguration() {
executorServiceBuilder.build();
verify(log, never()).warn(anyString());
}
/**
* Setting large max threads without large min threads is misleading on the default queue implementation
* It should warn or work
*/
@Test
@SuppressWarnings("Slf4jFormatShouldBeConst")
void shouldBeAbleToExecute2TasksAtOnceWithLargeMaxThreadsOrBeWarnedOtherwise() {
ExecutorService exe = executorServiceBuilder
.maxThreads(Integer.MAX_VALUE)
.build();
try {
verify(log).warn(anyString());
} catch (WantedButNotInvoked error) {
// no warning has been given so we should be able to execute at least 2 things at once
assertCanExecuteAtLeast2ConcurrentTasks(exe);
}
}
@Test
void shouldUseInstrumentedThreadFactory() {
assertThat(executorServiceBuilder.build())
.isInstanceOfSatisfying(ThreadPoolExecutor.class, castedExec ->
assertThat(castedExec.getThreadFactory()).isInstanceOf(InstrumentedThreadFactory.class));
}
@CsvSource(value = {
"my-client-%d,my-client",
"my-client--%d,my-client-",
"my-client-%d-abc,my-client-abc",
"my-client%d,my-client",
"my-client%d-abc,my-client-abc",
"my-client%s,my-client",
"my-client%sabc,my-clientabc",
"my-client%10d,my-client",
"my-client%10d0,my-client0",
"my-client%-10d,my-client",
"my-client%-10d0,my-client0",
"my-client-%10d,my-client",
"my-client-%10dabc,my-clientabc",
"my-client-%1$d,my-client",
"my-client-%1$d-abc,my-client-abc",
"-%d,''",
"%d,''",
"%d-abc,-abc",
"%10d,''",
"%10dabc,abc",
"%-10d,''",
"%-10dabc,abc",
"%10s,''" ,
"%10sabc,abc",
})
@ParameterizedTest
void nameWithoutFormat(String format, String name) {
assertThat(ExecutorServiceBuilder.getNameWithoutFormat(format))
.describedAs("%s -> %s", format, name)
.isEqualTo(name);
}
/**
* Tries to run 2 tasks that on the executor that rely on each others side effect to complete. If they fail to
* complete within a short time then we can assume they are not running concurrently
* @param exe an executor to try to run 2 tasks on
*/
private void assertCanExecuteAtLeast2ConcurrentTasks(Executor exe) {
CountDownLatch latch = new CountDownLatch(2);
Runnable concurrentLatchCountDownAndWait = () -> {
latch.countDown();
try {
latch.await();
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
};
exe.execute(concurrentLatchCountDownAndWait);
exe.execute(concurrentLatchCountDownAndWait);
try {
// 1 second is ages even on a slow VM
assertThat(latch.await(1, TimeUnit.SECONDS))
.as("2 tasks executed concurrently on " + exe)
.isTrue();
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
| ExecutorServiceBuilderTest |
java | apache__flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/extraction/DataTypeExtractorTest.java | {
"start": 38350,
"end": 38667
} | class ____ extends TableFunction<List<List<String>>> {}
// --------------------------------------------------------------------------------------------
/** Complex POJO with raw types. */
@SuppressWarnings("unused")
@DataTypeHint(allowRawGlobally = HintFlag.TRUE)
public static | TableFunctionWithList |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/cache/SimpleLRUCache.java | {
"start": 16515,
"end": 17314
} | class ____<V> {
private final long revision;
private final V value;
ValueHolder(long revision, V value) {
this.revision = revision;
this.value = value;
}
V get() {
return value;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass())
return false;
ValueHolder<?> that = (ValueHolder<?>) o;
return revision == that.revision;
}
@Override
public int hashCode() {
return Objects.hashCode(revision);
}
}
/**
* A modifiable cache entry.
*
* @param <K> the type of the key
* @param <V> the type of the value
*/
private static | ValueHolder |
java | spring-projects__spring-framework | spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java | {
"start": 33565,
"end": 37989
} | class ____ extends RelayConnectionHandler {
public SystemSessionConnectionHandler(StompHeaderAccessor connectHeaders) {
super(SYSTEM_SESSION_ID, connectHeaders, false);
}
@Override
protected void afterStompConnected(StompHeaderAccessor connectedHeaders) {
if (logger.isInfoEnabled()) {
logger.info("\"System\" session connected.");
}
super.afterStompConnected(connectedHeaders);
publishBrokerAvailableEvent();
sendSystemSubscriptions();
}
@Override
protected void initHeartbeats(StompHeaderAccessor connectedHeaders) {
TcpConnection<byte[]> con = getTcpConnection();
Assert.state(con != null, "No TcpConnection available");
long clientSendInterval = getConnectHeaders().getHeartbeat()[0];
long clientReceiveInterval = getConnectHeaders().getHeartbeat()[1];
long serverSendInterval = connectedHeaders.getHeartbeat()[0];
long serverReceiveInterval = connectedHeaders.getHeartbeat()[1];
if (clientSendInterval > 0 && serverReceiveInterval > 0) {
long interval = Math.max(clientSendInterval, serverReceiveInterval);
con.onWriteInactivity(() ->
con.sendAsync(HEARTBEAT_MESSAGE).whenComplete((unused, ex) -> {
if (ex != null) {
handleTcpConnectionFailure("Failed to forward heartbeat: " + ex.getMessage(), ex);
}
}), interval);
}
if (clientReceiveInterval > 0 && serverSendInterval > 0) {
final long interval = Math.max(clientReceiveInterval, serverSendInterval) * HEARTBEAT_MULTIPLIER;
con.onReadInactivity(
() -> handleTcpConnectionFailure("No messages received in " + interval + " ms.", null), interval);
}
}
private void sendSystemSubscriptions() {
int i = 0;
for (String destination : getSystemSubscriptions().keySet()) {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
accessor.setSubscriptionId(String.valueOf(i++));
accessor.setDestination(destination);
if (logger.isDebugEnabled()) {
logger.debug("Subscribing to " + destination + " on \"system\" connection.");
}
TcpConnection<byte[]> conn = getTcpConnection();
if (conn != null) {
MessageHeaders headers = accessor.getMessageHeaders();
conn.sendAsync(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers)).whenComplete((unused, ex) -> {
if (ex != null) {
handleTcpConnectionFailure("Failed to subscribe in \"system\" session.", ex);
}
});
}
}
}
@Override
protected void handleInboundMessage(Message<?> message) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (accessor != null && StompCommand.MESSAGE.equals(accessor.getCommand())) {
String destination = accessor.getDestination();
if (destination == null) {
if (logger.isDebugEnabled()) {
logger.debug("Got message on \"system\" connection, with no destination: " +
accessor.getDetailedLogMessage(message.getPayload()));
}
return;
}
if (!getSystemSubscriptions().containsKey(destination)) {
if (logger.isDebugEnabled()) {
logger.debug("Got message on \"system\" connection with no handler: " +
accessor.getDetailedLogMessage(message.getPayload()));
}
return;
}
try {
MessageHandler handler = getSystemSubscriptions().get(destination);
handler.handleMessage(message);
}
catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Error while handling message on \"system\" connection.", ex);
}
}
}
}
@Override
protected void handleTcpConnectionFailure(String errorMessage, @Nullable Throwable ex) {
super.handleTcpConnectionFailure(errorMessage, ex);
publishBrokerUnavailableEvent();
}
@Override
public void afterConnectionClosed() {
super.afterConnectionClosed();
publishBrokerUnavailableEvent();
}
@Override
public CompletableFuture<Void> forward(Message<?> message, StompHeaderAccessor accessor) {
try {
CompletableFuture<Void> future = super.forward(message, accessor);
if (message.getHeaders().get(SimpMessageHeaderAccessor.IGNORE_ERROR) == null) {
future.get();
}
return future;
}
catch (Throwable ex) {
throw new MessageDeliveryException(message, ex);
}
}
@Override
protected boolean shouldSendHeartbeatForIgnoredMessage() {
return false;
}
}
private | SystemSessionConnectionHandler |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/proxy/narrow/BidirectionalManyToOneNarrowingTest.java | {
"start": 4508,
"end": 4936
} | class ____ {
@Id
private Long id;
@ManyToOne( fetch = FetchType.LAZY )
@JoinColumn( name = "receiver_address_id" )
private Address receiverAddress;
public Message() {
}
public Message(Long id, Address receiverAddress) {
this.id = id;
this.receiverAddress = receiverAddress;
}
public Address getReceiverAddress() {
return receiverAddress;
}
}
@Entity( name = "MyAddress" )
public static | Message |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java | {
"start": 80997,
"end": 81087
} | enum ____ {
ABORT,
COMPLETE,
SUBSUME
}
}
| NotifyCheckpointOperation |
java | alibaba__nacos | core/src/main/java/com/alibaba/nacos/core/remote/grpc/ConnectionGeneratorService.java | {
"start": 930,
"end": 1348
} | interface ____ {
/**
* get connection by metaInfo.
* @param metaInfo not null
* @param streamObserver not null
* @param channel not null
* @return connection
*/
Connection getConnection(ConnectionMeta metaInfo, StreamObserver streamObserver, Channel channel);
/**
* get connection type.
* @return type
*/
String getType();
}
| ConnectionGeneratorService |
java | redisson__redisson | redisson/src/test/java/org/redisson/BaseMapTest.java | {
"start": 19794,
"end": 55258
} | class ____ {
private String testField;
SimpleObjectWithoutDefaultConstructor(String testField) {
this.testField = testField;
}
public String getTestField() {
return testField;
}
public void setTestField(String testField) {
this.testField = testField;
}
}
@Test
public void testReplaceOldValueFail() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.replace(new SimpleKey("1"), new SimpleValue("43"), new SimpleValue("31"));
assertThat(res).isFalse();
SimpleValue val1 = map.get(new SimpleKey("1"));
assertThat(val1.getValue()).isEqualTo("2");
destroy(map);
}
@Test
public void testReplaceOldValueSuccess() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.replace(new SimpleKey("1"), new SimpleValue("2"), new SimpleValue("3"));
assertThat(res).isTrue();
boolean res1 = map.replace(new SimpleKey("1"), new SimpleValue("2"), new SimpleValue("3"));
assertThat(res1).isFalse();
SimpleValue val1 = map.get(new SimpleKey("1"));
assertThat(val1.getValue()).isEqualTo("3");
destroy(map);
}
@Test
public void testReplaceValue() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
SimpleValue res = map.replace(new SimpleKey("1"), new SimpleValue("3"));
assertThat(res.getValue()).isEqualTo("2");
SimpleValue val1 = map.get(new SimpleKey("1"));
assertThat(val1.getValue()).isEqualTo("3");
destroy(map);
}
@Test
public void testReplace() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
SimpleValue val1 = map.get(new SimpleKey("33"));
assertThat(val1.getValue()).isEqualTo("44");
map.put(new SimpleKey("33"), new SimpleValue("abc"));
SimpleValue val2 = map.get(new SimpleKey("33"));
assertThat(val2.getValue()).isEqualTo("abc");
destroy(map);
}
@Test
public void testContainsValue() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
assertThat(map.containsValue(new SimpleValue("2"))).isTrue();
assertThat(map.containsValue(new SimpleValue("441"))).isFalse();
assertThat(map.containsValue(new SimpleKey("5"))).isFalse();
destroy(map);
}
@Test
public void testContainsKey() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
assertThat(map.containsKey(new SimpleKey("33"))).isTrue();
assertThat(map.containsKey(new SimpleKey("34"))).isFalse();
destroy(map);
}
@Test
public void testRemoveValueFail() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.remove(new SimpleKey("2"), new SimpleValue("1"));
assertThat(res).isFalse();
boolean res1 = map.remove(new SimpleKey("1"), new SimpleValue("3"));
assertThat(res1).isFalse();
SimpleValue val1 = map.get(new SimpleKey("1"));
assertThat(val1.getValue()).isEqualTo("2");
destroy(map);
}
@Test
public void testRemoveValue() throws InterruptedException {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
boolean res = map.remove(new SimpleKey("1"), new SimpleValue("2"));
assertThat(res).isTrue();
SimpleValue val1 = map.get(new SimpleKey("1"));
assertThat(val1).isNull();
assertThat(map.size()).isZero();
destroy(map);
}
@Test
public void testRemoveObject() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
assertThat(map.remove(new SimpleKey("33"))).isEqualTo(new SimpleValue("44"));
assertThat(map.remove(new SimpleKey("5"))).isEqualTo(new SimpleValue("6"));
assertThat(map.remove(new SimpleKey("11"))).isNull();
assertThat(map.size()).isEqualTo(1);
destroy(map);
}
@Test
public void testRemove() {
RMap<Integer, Integer> map = getMap("simple");
map.put(1, 3);
map.put(3, 5);
map.put(7, 8);
assertThat(map.remove(1)).isEqualTo(3);
assertThat(map.remove(3)).isEqualTo(5);
assertThat(map.remove(10)).isNull();
assertThat(map.remove(7)).isEqualTo(8);
destroy(map);
}
@Test
public void testFastRemove() throws InterruptedException, ExecutionException {
RMap<Integer, Integer> map = getMap("simple");
map.put(1, 3);
map.put(3, 5);
map.put(4, 6);
map.put(7, 8);
assertThat(map.fastRemove(1, 3, 7)).isEqualTo(3);
Thread.sleep(1);
assertThat(map.size()).isEqualTo(1);
destroy(map);
}
@Test
public void testValueIterator() {
RMap<Integer, Integer> map = getMap("simple");
map.put(1, 0);
map.put(3, 5);
map.put(4, 6);
map.put(7, 8);
Collection<Integer> values = map.values();
assertThat(values).containsOnly(0, 5, 6, 8);
for (Iterator<Integer> iterator = map.values().iterator(); iterator.hasNext();) {
Integer value = iterator.next();
if (!values.remove(value)) {
Assertions.fail("unable to remove value " + value);
}
}
assertThat(values.size()).isEqualTo(0);
destroy(map);
}
@Test
public void testFastPut() throws Exception {
RMap<Integer, Integer> map = getMap("simple");
assertThat(map.fastPut(1, 2)).isTrue();
assertThat(map.get(1)).isEqualTo(2);
assertThat(map.fastPut(1, 3)).isFalse();
assertThat(map.get(1)).isEqualTo(3);
assertThat(map.size()).isEqualTo(1);
destroy(map);
}
@Test
public void testFastReplace() throws Exception {
RMap<Integer, Integer> map = getMap("simple");
map.put(1, 2);
assertThat(map.fastReplace(1, 3)).isTrue();
assertThat(map.fastReplace(2, 0)).isFalse();
assertThat(map.size()).isEqualTo(1);
assertThat(map.get(1)).isEqualTo(3);
destroy(map);
}
@Test
public void testEquals() {
RMap<String, String> map = getMap("simple");
map.put("1", "7");
map.put("2", "4");
map.put("3", "5");
Map<String, String> testMap = new HashMap<String, String>();
testMap.put("1", "7");
testMap.put("2", "4");
testMap.put("3", "5");
assertThat(map).isEqualTo(testMap);
assertThat(testMap.hashCode()).isEqualTo(map.hashCode());
destroy(map);
}
@Test
public void testFastRemoveEmpty() throws Exception {
RMap<Integer, Integer> map = getMap("simple");
map.put(1, 3);
assertThat(map.fastRemove()).isZero();
assertThat(map.size()).isEqualTo(1);
destroy(map);
}
@Test
public void testKeySetByPatternCodec() {
RMap<String, String> map = getMap("test", new CompositeCodec(StringCodec.INSTANCE, JsonJacksonCodec.INSTANCE));
map.put("1-1", "test1");
Set<String> set = map.keySet("1-*");
assertThat(set).containsOnly("1-1");
}
@Test
public void testKeySetByPattern() {
RMap<String, String> map = getMap("simple", StringCodec.INSTANCE);
map.put("10", "100");
map.put("20", "200");
map.put("30", "300");
assertThat(map.keySet("?0")).containsExactly("10", "20", "30");
assertThat(map.keySet("1")).isEmpty();
assertThat(map.keySet("10")).containsExactly("10");
destroy(map);
}
@Test
public void testValuesByPattern() {
RMap<String, String> map = getMap("simple", StringCodec.INSTANCE);
map.put("10", "100");
map.put("20", "200");
map.put("30", "300");
assertThat(map.values("?0")).containsExactlyInAnyOrder("100", "200", "300");
assertThat(map.values("1")).isEmpty();
assertThat(map.values("10")).containsExactlyInAnyOrder("100");
destroy(map);
}
@Test
public void testEntrySetByPattern() {
RMap<String, String> map = getMap("simple", StringCodec.INSTANCE);
map.put("10", "100");
map.put("20", "200");
map.put("30", "300");
assertThat(map.entrySet("?0")).containsExactlyInAnyOrder(new AbstractMap.SimpleEntry("10", "100"), new AbstractMap.SimpleEntry("20", "200"), new AbstractMap.SimpleEntry("30", "300"));
assertThat(map.entrySet("1")).isEmpty();
assertThat(map.entrySet("10")).containsExactlyInAnyOrder(new AbstractMap.SimpleEntry("10", "100"));
destroy(map);
}
@Test
public void testReadAllKeySet() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
assertThat(map.readAllKeySet().size()).isEqualTo(3);
Map<SimpleKey, SimpleValue> testMap = new HashMap<>(map);
assertThat(map.readAllKeySet()).isSubsetOf(testMap.keySet());
destroy(map);
}
@Test
public void testEntrySetIteratorRemoveHighVolume() throws InterruptedException {
RMap<Integer, Integer> map = getMap("simpleMap");
for (int i = 0; i < 10000; i++) {
map.put(i, i*10);
}
int cnt = 0;
Iterator<Entry<Integer, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Integer, Integer> entry = iterator.next();
iterator.remove();
cnt++;
}
assertThat(cnt).isEqualTo(10000);
assertThat(map).isEmpty();
assertThat(map.size()).isEqualTo(0);
destroy(map);
}
@Test
public void testEntrySetIteratorRandomRemoveHighVolume() throws InterruptedException {
RMap<Integer, Integer> map = getMap("simpleMap");
for (int i = 0; i < 10000; i++) {
map.put(i, i*10);
}
int cnt = 0;
int removed = 0;
Iterator<Entry<Integer, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Entry<Integer, Integer> entry = iterator.next();
if (ThreadLocalRandom.current().nextBoolean()) {
iterator.remove();
removed++;
}
cnt++;
}
assertThat(cnt).isEqualTo(10000);
assertThat(map.size()).isEqualTo(cnt - removed);
destroy(map);
}
@Test
public void testKeySetIteratorRemoveHighVolume() throws InterruptedException {
RMap<Integer, Integer> map = getMap("simpleMap");
for (int i = 0; i < 10000; i++) {
map.put(i, i*10);
}
int cnt = 0;
Iterator<Integer> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
Integer integer = iterator.next();
iterator.remove();
cnt++;
}
assertThat(cnt).isEqualTo(10000);
assertThat(map).isEmpty();
assertThat(map.size()).isEqualTo(0);
destroy(map);
}
@Test
public void testReadAllKeySetHighAmount() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
for (int i = 0; i < 1000; i++) {
map.put(new SimpleKey("" + i), new SimpleValue("" + i));
}
assertThat(map.readAllKeySet().size()).isEqualTo(1000);
Map<SimpleKey, SimpleValue> testMap = new HashMap<>(map);
assertThat(map.readAllKeySet()).isSubsetOf(testMap.keySet());
destroy(map);
}
@Test
public void testReadAllValues() {
RMap<SimpleKey, SimpleValue> map = getMap("simple");
map.put(new SimpleKey("1"), new SimpleValue("2"));
map.put(new SimpleKey("33"), new SimpleValue("44"));
map.put(new SimpleKey("5"), new SimpleValue("6"));
assertThat(map.readAllValues().size()).isEqualTo(3);
Map<SimpleKey, SimpleValue> testMap = new HashMap<>(map);
assertThat(map.readAllValues()).isSubsetOf(testMap.values());
destroy(map);
}
@Test
public void testGetAllBig() {
Map<Integer, String> joinMap = new HashMap<Integer, String>();
for (int i = 0; i < 10000; i++) {
joinMap.put(i, "" + i);
}
RMap<Integer, String> map = getMap("simple");
map.putAll(joinMap);
Map<Integer, String> s = map.getAll(joinMap.keySet());
assertThat(s).isEqualTo(joinMap);
assertThat(map.size()).isEqualTo(joinMap.size());
destroy(map);
}
@Test
public void testGetAll() {
RMap<Integer, Integer> map = getMap("getAll");
map.put(1, 100);
map.put(2, 200);
map.put(3, 300);
map.put(4, 400);
Map<Integer, Integer> filtered = map.getAll(new HashSet<Integer>(Arrays.asList(2, 3, 5)));
Map<Integer, Integer> expectedMap = new HashMap<Integer, Integer>();
expectedMap.put(2, 200);
expectedMap.put(3, 300);
assertThat(filtered).isEqualTo(expectedMap);
destroy(map);
}
@Test
public void testValueSize() {
RMap<String, String> map = getMap("getAll");
Assumptions.assumeTrue(!(map instanceof RMapCache));
map.put("1", "1234");
assertThat(map.valueSize("4")).isZero();
assertThat(map.valueSize("1")).isEqualTo(5);
destroy(map);
}
@Test
public void testCopy() {
RMap<String, String> map = getMap("test");
map.put("1", "2");
map.copy("test2");
RMap<String, String> mapCopy = getMap("test2");
assertThat(mapCopy.get("1")).isEqualTo("2");
}
@Test
public void testAddAndGet() throws InterruptedException {
RMap<Integer, Integer> map = getMap("getAll", new CompositeCodec(redisson.getConfig().getCodec(), IntegerCodec.INSTANCE));
map.put(1, 100);
Integer res = map.addAndGet(1, 12);
assertThat(res).isEqualTo(112);
res = map.get(1);
assertThat(res).isEqualTo(112);
RMap<Integer, Double> map2 = getMap("getAll2", new CompositeCodec(redisson.getConfig().getCodec(), DoubleCodec.INSTANCE));
map2.put(1, 100.2);
Double res2 = map2.addAndGet(1, 12.1);
assertThat(res2).isEqualTo(112.3);
res2 = map2.get(1);
assertThat(res2).isEqualTo(112.3);
RMap<String, Integer> mapStr = getMap("mapStr", new CompositeCodec(redisson.getConfig().getCodec(), IntegerCodec.INSTANCE));
assertThat(mapStr.put("1", 100)).isNull();
assertThat(mapStr.addAndGet("1", 12)).isEqualTo(112);
assertThat(mapStr.get("1")).isEqualTo(112);
destroy(map);
}
protected abstract <K, V> RMap<K, V> getMap(String name);
protected abstract <K, V> RMap<K, V> getMap(String name, Codec codec);
protected abstract <K, V> RMap<K, V> getWriterTestMap(String name, Map<K, V> map);
protected abstract <K, V> RMap<K, V> getWriteBehindTestMap(String name, Map<K, V> map);
protected abstract <K, V> RMap<K, V> getWriteBehindAsyncTestMap(String name, Map<K, V> map);
protected abstract <K, V, M extends RMap<K, V>> M getLoaderTestMap(String name, Map<K, V> map);
protected abstract <K, V> RMap<K, V> getLoaderAsyncTestMap(String name, Map<K, V> map);
@Test
public void testMapLoaderGetMulipleNulls() {
Map<String, String> cache = new HashMap<String, String>();
cache.put("1", "11");
cache.put("2", "22");
cache.put("3", "33");
RMap<String, String> map = getLoaderTestMap("test", cache);
assertThat(map.get("0")).isNull();
assertThat(map.get("1")).isEqualTo("11");
assertThat(map.get("0")).isNull(); // This line will never return anything and the test will hang
destroy(map);
}
@Test
public void testWriterAddAndGet() throws InterruptedException {
Map<String, Integer> store = new HashMap<>();
RMap<String, Integer> map = getWriterTestMap("test", store);
assertThat(map.addAndGet("1", 11)).isEqualTo(11);
assertThat(map.addAndGet("1", 7)).isEqualTo(18);
Map<String, Integer> expected = new HashMap<>();
expected.put("1", 18);
assertThat(store).isEqualTo(expected);
destroy(map);
}
@Test
public void testWriteBehindFastRemove() throws InterruptedException {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriteBehindTestMap("test", store);
map.put("1", "11");
map.put("2", "22");
map.put("3", "33");
Thread.sleep(1400);
map.fastRemove("1", "2", "4");
Map<String, String> expected = new HashMap<>();
expected.put("3", "33");
Thread.sleep(1400);
assertThat(store).isEqualTo(expected);
destroy(map);
}
@Test
public void testLoaderGetAsync() {
Map<String, String> cache = new HashMap<String, String>();
cache.put("1", "11");
cache.put("2", "22");
cache.put("3", "33");
RMap<String, String> map = getLoaderAsyncTestMap("test", cache);
assertThat(map.size()).isEqualTo(0);
assertThat(map.get("1")).isEqualTo("11");
assertThat(map.size()).isEqualTo(1);
assertThat(map.get("0")).isNull();
map.put("0", "00");
assertThat(map.get("0")).isEqualTo("00");
assertThat(map.size()).isEqualTo(2);
assertThat(map.containsKey("2")).isTrue();
assertThat(map.size()).isEqualTo(3);
Map<String, String> s = map.getAll(new HashSet<>(Arrays.asList("1", "2", "9", "3")));
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("1", "11");
expectedMap.put("2", "22");
expectedMap.put("3", "33");
assertThat(s).isEqualTo(expectedMap);
assertThat(map.size()).isEqualTo(4);
destroy(map);
}
@Test
public void testWriteBehindAsyncFastRemove() throws InterruptedException {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriteBehindAsyncTestMap("test", store);
map.put("1", "11");
map.put("2", "22");
map.put("3", "33");
Thread.sleep(1400);
map.fastRemove("1", "2", "4");
Map<String, String> expected = new HashMap<>();
expected.put("3", "33");
Thread.sleep(1400);
assertThat(store).isEqualTo(expected);
destroy(map);
}
@Test
public void testWriterFastRemove() {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriterTestMap("test", store);
map.put("1", "11");
map.put("2", "22");
map.put("3", "33");
map.fastRemove("1", "2", "4");
Map<String, String> expected = new HashMap<>();
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
destroy(map);
}
@Test
public void testWriterFastPut() {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriterTestMap("test", store);
map.fastPut("1", "11");
map.fastPut("2", "22");
map.fastPut("3", "33");
Map<String, String> expected = new HashMap<>();
expected.put("1", "11");
expected.put("2", "22");
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
destroy(map);
}
@Test
public void testWriterRemove() {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriterTestMap("test", store);
map.put("1", "11");
map.remove("1");
map.put("3", "33");
Map<String, String> expected = new HashMap<>();
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
}
@Test
public void testWriterReplaceKeyValue() {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriterTestMap("test", store);
map.put("1", "11");
map.replace("1", "00");
map.replace("2", "22");
map.put("3", "33");
Map<String, String> expected = new HashMap<>();
expected.put("1", "00");
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
}
@Test
public void testWriterReplaceKeyOldNewValue() {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriterTestMap("test", store);
map.put("1", "11");
map.replace("1", "11", "00");
map.put("3", "33");
Map<String, String> expected = new HashMap<>();
expected.put("1", "00");
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
destroy(map);
}
@Test
public void testWriterRemoveKeyValue() {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriterTestMap("test", store);
map.put("1", "11");
map.put("2", "22");
map.put("3", "33");
Map<String, String> expected = new HashMap<>();
expected.put("1", "11");
expected.put("2", "22");
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
map.remove("1", "11");
Map<String, String> expected2 = new HashMap<>();
expected2.put("2", "22");
expected2.put("3", "33");
assertThat(store).isEqualTo(expected2);
destroy(map);
}
@Test
public void testWriterFastPutIfAbsent() {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriterTestMap("test", store);
map.fastPutIfAbsent("1", "11");
map.fastPutIfAbsent("1", "00");
map.fastPutIfAbsent("2", "22");
Map<String, String> expected = new HashMap<>();
expected.put("1", "11");
expected.put("2", "22");
assertThat(store).isEqualTo(expected);
destroy(map);
}
@Test
public void testWriterPutIfAbsent() {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriterTestMap("test", store);
map.putIfAbsent("1", "11");
map.putIfAbsent("1", "00");
map.putIfAbsent("2", "22");
Map<String, String> expected = new HashMap<>();
expected.put("1", "11");
expected.put("2", "22");
assertThat(store).isEqualTo(expected);
destroy(map);
}
@Test
public void testWriterPutAll() {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriterTestMap("test", store);
Map<String, String> newMap = new HashMap<>();
newMap.put("1", "11");
newMap.put("2", "22");
newMap.put("3", "33");
map.putAll(newMap);
Map<String, String> expected = new HashMap<>();
expected.put("1", "11");
expected.put("2", "22");
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
destroy(map);
}
@Test
public void testWriterPut() {
Map<String, String> store = new HashMap<>();
RMap<String, String> map = getWriterTestMap("test", store);
map.put("1", "11");
map.put("2", "22");
map.put("3", "33");
Map<String, String> expected = new HashMap<>();
expected.put("1", "11");
expected.put("2", "22");
expected.put("3", "33");
assertThat(store).isEqualTo(expected);
destroy(map);
}
@Test
public void testRetryableWriterAsyncSuccessAtLastRetry() throws InterruptedException {
//success at last retry
int expectedRetryAttempts = 3;
AtomicInteger actualRetryTimes = new AtomicInteger(0);
Map<String, String> store = new HashMap<>();
MapOptions<String, String> options = MapOptions.<String, String>defaults()
.writerRetryAttempts(expectedRetryAttempts)
.writerAsync(new MapWriterAsync<String, String>() {
@Override
public CompletionStage<Void> write(Map<String, String> map) {
return CompletableFuture.runAsync(()->{
//throws until last chance
if (actualRetryTimes.incrementAndGet() < expectedRetryAttempts) {
throw new IllegalStateException("retry");
}
store.putAll(map);
});
}
@Override
public CompletionStage<Void> delete(Collection<String> keys) {
return CompletableFuture.runAsync(()->{
if (actualRetryTimes.incrementAndGet() < expectedRetryAttempts) {
throw new IllegalStateException("retry");
}
keys.forEach(store::remove);
});
}
})
.writeMode(MapOptions.WriteMode.WRITE_BEHIND)
.writerRetryInterval(Duration.ofMillis(100));
final RMap<String, String> map = redisson.getMap("test", options);
//do add
map.put("1", "11");
Thread.sleep(2400);
//assert add
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("1", "11");
assertThat(store).isEqualTo(expectedMap);
//assert add retry times
assertThat(actualRetryTimes.get()).isEqualTo(expectedRetryAttempts);
//do delete
actualRetryTimes.set(0);
map.remove("1");
Thread.sleep(2400);
//assert delete
expectedMap.clear();
assertThat(store).isEqualTo(expectedMap);
//assert delete retry times
assertThat(actualRetryTimes.get()).isEqualTo(expectedRetryAttempts);
destroy(map);
}
@Test
public void testRetryableWriterSuccessAtLastRetry() throws InterruptedException {
//success at last retry
int expectedRetryAttempts = 3;
AtomicInteger actualRetryTimes = new AtomicInteger(0);
Map<String, String> store = new HashMap<>();
MapOptions<String, String> options = MapOptions.<String, String>defaults()
.writerRetryAttempts(expectedRetryAttempts)
.writer(new MapWriter<String, String>() {
@Override
public void write(Map<String, String> map) {
if (actualRetryTimes.incrementAndGet() < expectedRetryAttempts) {
throw new IllegalStateException("retry");
}
store.putAll(map);
}
@Override
public void delete(Collection<String> keys) {
if (actualRetryTimes.incrementAndGet() < expectedRetryAttempts) {
throw new IllegalStateException("retry");
}
keys.forEach(store::remove);
}
})
.writeMode(MapOptions.WriteMode.WRITE_THROUGH);
final RMap<String, String> map = redisson.getMap("test", options);
//do add
map.put("1", "11");
Thread.sleep(1400);
//assert add
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("1", "11");
assertThat(store).isEqualTo(expectedMap);
//assert add retry times
assertThat(actualRetryTimes.get()).isEqualTo(expectedRetryAttempts);
//do delete
actualRetryTimes.set(0);
map.remove("1");
Thread.sleep(1400);
//assert delete
expectedMap.clear();
assertThat(store).isEqualTo(expectedMap);
//assert delete retry times
assertThat(actualRetryTimes.get()).isEqualTo(expectedRetryAttempts);
destroy(map);
}
@Test
public void testLoadAllReplaceValues() {
Map<String, String> cache = new HashMap<>();
for (int i = 0; i < 10; i++) {
cache.put("" + i, "" + i + "" + i);
}
RMap<String, String> map = getLoaderTestMap("test", cache);
map.put("0", "010");
map.put("5", "555");
map.loadAll(false, 2);
assertThat(map.size()).isEqualTo(10);
assertThat(map.get("0")).isEqualTo("010");
assertThat(map.get("5")).isEqualTo("555");
map.clear();
map.put("0", "010");
map.put("5", "555");
map.loadAll(true, 2);
assertThat(map.size()).isEqualTo(10);
assertThat(map.get("0")).isEqualTo("00");
assertThat(map.get("5")).isEqualTo("55");
destroy(map);
}
@Test
public void testLoadAll() {
Map<String, String> cache = new HashMap<String, String>();
for (int i = 0; i < 100; i++) {
cache.put("" + i, "" + (i*10 + i));
}
RMap<String, String> map = getLoaderTestMap("test", cache);
assertThat(map.size()).isEqualTo(0);
map.loadAll(false, 2);
assertThat(map.size()).isEqualTo(100);
for (int i = 0; i < 100; i++) {
assertThat(map.containsKey("" + i)).isTrue();
}
destroy(map);
}
@Test
public void testLoadAllAsync() {
Map<String, String> cache = new HashMap<String, String>();
for (int i = 0; i < 100; i++) {
cache.put("" + i, "" + (i*10 + i));
}
RMap<String, String> map = getLoaderAsyncTestMap("test", cache);
assertThat(map.size()).isEqualTo(0);
map.loadAll(false, 2);
assertThat(map.size()).isEqualTo(100);
for (int i = 0; i < 100; i++) {
assertThat(map.containsKey("" + i)).isTrue();
}
destroy(map);
}
protected <K, V> MapWriterAsync<K, V> createMapWriterAsync(Map<K, V> map) {
return new MapWriterAsync<K, V>() {
@Override
public CompletionStage<Void> write(Map<K, V> values) {
map.putAll(values);
return CompletableFuture.completedFuture(null);
}
@Override
public CompletionStage<Void> delete(Collection<K> keys) {
for (K key : keys) {
map.remove(key);
}
return CompletableFuture.completedFuture(null);
}
};
}
protected <K, V> MapWriter<K, V> createMapWriter(Map<K, V> map) {
return new MapWriter<K, V>() {
@Override
public void write(Map<K, V> values) {
map.putAll(values);
System.out.println("map " + map);
}
@Override
public void delete(Collection<K> keys) {
for (K key : keys) {
map.remove(key);
}
System.out.println("delete " + keys + " map " + map);
}
};
}
protected <K, V> MapLoaderAsync<K, V> createMapLoaderAsync(Map<K, V> map) {
MapLoaderAsync<K, V> loaderAsync = new MapLoaderAsync<K, V>() {
@Override
public CompletionStage<V> load(Object key) {
return CompletableFuture.completedFuture(map.get(key));
}
@Override
public AsyncIterator<K> loadAllKeys() {
Iterator<K> iter = map.keySet().iterator();
return new AsyncIterator<K>() {
@Override
public CompletionStage<Boolean> hasNext() {
return CompletableFuture.completedFuture(iter.hasNext());
}
@Override
public CompletionStage<K> next() {
return CompletableFuture.completedFuture(iter.next());
}
};
}
};
return loaderAsync;
}
protected <K, V> MapLoader<K, V> createMapLoader(Map<K, V> map) {
return new MapLoader<K, V>() {
@Override
public V load(K key) {
return map.get(key);
}
@Override
public Iterable<K> loadAllKeys() {
return map.keySet();
}
};
}
@Test
public void testMapLoaderGetWithException() {
Map<String, String> cache = new HashMap<String, String>() {
@Override
public String get(Object key) {
throw new RuntimeException();
};
};
RMap<String, String> map = getLoaderTestMap("test", cache);
assertThat(map.get("1")).isNull();
}
@Test
public void testMapLoaderGet() {
Map<String, String> cache = new HashMap<String, String>();
cache.put("1", "11");
cache.put("2", "22");
cache.put("3", "33");
RMap<String, String> map = getLoaderTestMap("test", cache);
assertThat(map.size()).isEqualTo(0);
assertThat(map.get("1")).isEqualTo("11");
assertThat(map.size()).isEqualTo(1);
assertThat(map.get("0")).isNull();
map.put("0", "00");
assertThat(map.get("0")).isEqualTo("00");
assertThat(map.size()).isEqualTo(2);
assertThat(map.containsKey("2")).isTrue();
assertThat(map.size()).isEqualTo(3);
Map<String, String> s = map.getAll(new HashSet<>(Arrays.asList("1", "2", "9", "3")));
Map<String, String> expectedMap = new HashMap<>();
expectedMap.put("1", "11");
expectedMap.put("2", "22");
expectedMap.put("3", "33");
assertThat(s).isEqualTo(expectedMap);
assertThat(map.size()).isEqualTo(4);
destroy(map);
}
}
| SimpleObjectWithoutDefaultConstructor |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/converter/json/MappingJacksonInputMessage.java | {
"start": 1216,
"end": 2098
} | class ____ implements HttpInputMessage {
private final InputStream body;
private final HttpHeaders headers;
private @Nullable Class<?> deserializationView;
public MappingJacksonInputMessage(InputStream body, HttpHeaders headers) {
this.body = body;
this.headers = headers;
}
public MappingJacksonInputMessage(InputStream body, HttpHeaders headers, Class<?> deserializationView) {
this(body, headers);
this.deserializationView = deserializationView;
}
@Override
public InputStream getBody() throws IOException {
return this.body;
}
@Override
public HttpHeaders getHeaders() {
return this.headers;
}
public void setDeserializationView(@Nullable Class<?> deserializationView) {
this.deserializationView = deserializationView;
}
public @Nullable Class<?> getDeserializationView() {
return this.deserializationView;
}
}
| MappingJacksonInputMessage |
java | quarkusio__quarkus | integration-tests/jfr-blocking/src/main/java/io/quarkus/jfr/it/JfrResource.java | {
"start": 828,
"end": 4690
} | class ____ {
final Configuration c = Configuration.create(Paths.get("src/main/resources/quarkus-jfr.jfc"));
public JfrResource() throws IOException, ParseException {
}
@GET
@Path("/start/{name}")
public void startJfr(@PathParam("name") String name) {
Recording recording = new Recording(c);
recording.setName(name);
recording.start();
}
@GET
@Path("/stop/{name}")
public void stopJfr(@PathParam("name") String name) throws IOException {
Recording recording = getRecording(name);
recording.stop();
}
@GET
@Path("check/{name}/{traceId}")
@Produces(MediaType.APPLICATION_JSON)
public JfrRestEventResponse check(@PathParam("name") String name, @PathParam("traceId") String traceId) throws IOException {
java.nio.file.Path dumpFile = Files.createTempFile("dump", "jfr");
Recording recording = getRecording(name);
recording.dump(dumpFile);
recording.close();
List<RecordedEvent> recordedEvents = RecordingFile.readAllEvents(dumpFile);
if (Log.isDebugEnabled()) {
Log.debug(recordedEvents.size() + " events were recorded");
}
RecordedEvent periodEvent = null;
RecordedEvent startEvent = null;
RecordedEvent endEvent = null;
for (RecordedEvent e : recordedEvents) {
if (Log.isDebugEnabled()) {
if (e.getEventType().getCategoryNames().contains("Quarkus")) {
Log.debug(e);
}
}
if (e.hasField("traceId") && e.getString("traceId").equals(traceId)) {
if (RestPeriodEvent.class.getAnnotation(Name.class).value().equals(e.getEventType().getName())) {
periodEvent = e;
} else if (RestStartEvent.class.getAnnotation(Name.class).value().equals(e.getEventType().getName())) {
startEvent = e;
} else if (RestEndEvent.class.getAnnotation(Name.class).value().equals(e.getEventType().getName())) {
endEvent = e;
}
}
}
return new JfrRestEventResponse(createRestEvent(periodEvent), createRestEvent(startEvent),
createRestEvent(endEvent));
}
@GET
@Path("count/{name}")
@Produces(MediaType.APPLICATION_JSON)
public long count(@PathParam("name") String name) throws IOException {
java.nio.file.Path dumpFile = Files.createTempFile("dump", "jfr");
Recording recording = getRecording(name);
recording.dump(dumpFile);
recording.close();
List<RecordedEvent> recordedEvents = RecordingFile.readAllEvents(dumpFile);
return recordedEvents.stream().filter(r -> r.getEventType().getCategoryNames().contains("quarkus")).count();
}
private Recording getRecording(String name) {
List<Recording> recordings = FlightRecorder.getFlightRecorder().getRecordings();
Optional<Recording> recording = recordings.stream().filter(r -> r.getName().equals(name)).findFirst();
return recording.get();
}
private RestEvent createRestEvent(RecordedEvent event) {
if (event == null) {
return null;
}
RestEvent restEvent = new RestEvent();
setHttpInfo(restEvent, event);
return restEvent;
}
private void setHttpInfo(RestEvent response, RecordedEvent event) {
response.traceId = event.getString("traceId");
response.spanId = event.getString("spanId");
response.httpMethod = event.getString("httpMethod");
response.uri = event.getString("uri");
response.resourceClass = event.getString("resourceClass");
response.resourceMethod = event.getString("resourceMethod");
response.client = event.getString("client");
}
| JfrResource |
java | elastic__elasticsearch | libs/exponential-histogram/src/main/java/org/elasticsearch/exponentialhistogram/ExponentialHistogram.java | {
"start": 1360,
"end": 2426
} | interface ____ sparse implementations, allowing iteration over buckets without requiring direct index access.<br>
* The most important properties are:
* <ul>
* <li>The histogram has a scale parameter, which defines the accuracy. A higher scale implies a higher accuracy.
* The {@code base} for the buckets is defined as {@code base = 2^(2^-scale)}.</li>
* <li>The histogram bucket at index {@code i} has the range {@code (base^i, base^(i+1)]}</li>
* <li>Negative values are represented by a separate negative range of buckets with the boundaries {@code (-base^(i+1), -base^i]}</li>
* <li>Histograms are perfectly subsetting: increasing the scale by one merges each pair of neighboring buckets</li>
* <li>A special {@link ZeroBucket} is used to handle zero and close-to-zero values</li>
* </ul>
*
* <br>
* Additionally, all algorithms assume that samples within a bucket are located at a single point: the point of least relative error
* (see {@link ExponentialScaleUtils#getPointOfLeastRelativeError(long, int)}).
*/
public | supports |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java | {
"start": 3087,
"end": 3181
} | class ____ details.
*
* @author Sam Brannen
* @author Phillip Webb
* @since 3.2
*/
public | for |
java | elastic__elasticsearch | modules/aggregations/src/test/java/org/elasticsearch/aggregations/pipeline/DerivativeResultTests.java | {
"start": 854,
"end": 3181
} | class ____ extends InternalAggregationTestCase<Derivative> {
@Override
protected SearchPlugin registerPlugin() {
return new AggregationsPlugin();
}
@Override
protected Derivative createTestInstance(String name, Map<String, Object> metadata) {
DocValueFormat formatter = randomNumericDocValueFormat();
double value = frequently()
? randomDoubleBetween(-100000, 100000, true)
: randomFrom(new Double[] { Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NaN });
double normalizationFactor = frequently() ? randomDoubleBetween(0, 100000, true) : 0;
return new Derivative(name, value, normalizationFactor, formatter, metadata);
}
@Override
public void testReduceRandom() {
expectThrows(UnsupportedOperationException.class, () -> createTestInstance("name", null).getReducer(null, 0));
}
@Override
protected void assertReduced(Derivative reduced, List<Derivative> inputs) {
// no test since reduce operation is unsupported
}
@Override
protected Derivative mutateInstance(Derivative instance) {
String name = instance.getName();
double value = instance.getValue();
double normalizationFactor = instance.getNormalizationFactor();
DocValueFormat formatter = instance.formatter();
Map<String, Object> metadata = instance.getMetadata();
switch (between(0, 3)) {
case 0 -> name += randomAlphaOfLength(5);
case 1 -> {
if (Double.isFinite(value)) {
value += between(1, 100);
} else {
value = randomDoubleBetween(0, 100000, true);
}
}
case 2 -> normalizationFactor += between(1, 100);
case 3 -> {
if (metadata == null) {
metadata = Maps.newMapWithExpectedSize(1);
} else {
metadata = new HashMap<>(instance.getMetadata());
}
metadata.put(randomAlphaOfLength(15), randomInt());
}
default -> throw new AssertionError("Illegal randomisation branch");
}
return new Derivative(name, value, normalizationFactor, formatter, metadata);
}
}
| DerivativeResultTests |
java | google__guava | android/guava-tests/test/com/google/common/eventbus/PackageSanityTests.java | {
"start": 1383,
"end": 2031
} | class ____ {
private final EventBus eventBus = new EventBus();
@Subscribe
public void handle(@Nullable Object unused) {}
Subscriber toSubscriber() throws Exception {
return Subscriber.create(eventBus, this, subscriberMethod());
}
SubscriberExceptionContext toContext() {
return new SubscriberExceptionContext(eventBus, new Object(), this, subscriberMethod());
}
private static Method subscriberMethod() {
try {
return DummySubscriber.class.getMethod("handle", Object.class);
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
}
}
}
| DummySubscriber |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/security/oauthbearer/FileJwtRetriever.java | {
"start": 1672,
"end": 2511
} | class ____ implements JwtRetriever {
private CachedFile<String> jwtFile;
@Override
public void configure(Map<String, ?> configs, String saslMechanism, List<AppConfigurationEntry> jaasConfigEntries) {
ConfigurationUtils cu = new ConfigurationUtils(configs, saslMechanism);
File file = cu.validateFileUrl(SASL_OAUTHBEARER_TOKEN_ENDPOINT_URL);
jwtFile = new CachedFile<>(file, STRING_JSON_VALIDATING_TRANSFORMER, lastModifiedPolicy());
}
@Override
public String retrieve() throws JwtRetrieverException {
if (jwtFile == null)
throw new IllegalStateException("JWT is null; please call configure() first");
try {
return jwtFile.transformed();
} catch (Exception e) {
throw new JwtRetrieverException(e);
}
}
}
| FileJwtRetriever |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/TimeUnitMismatchTest.java | {
"start": 5293,
"end": 6294
} | class ____ {
static final int THE_MILLIS = 0;
int startMillis;
int stopMillis;
void fields() {
startMillis = THE_MILLIS;
startMillis = stopMillis;
}
void memberSelect() {
this.startMillis = this.stopMillis;
}
void locals() {
int millis = 0;
startMillis = millis;
}
long getMicros() {
return 0;
}
void returns() {
long fooUs = getMicros();
}
void doSomething(double startSec, double endSec) {}
void args() {
double seconds = 0;
doSomething(seconds, seconds);
}
void timeUnit() {
int nanos = 0;
NANOSECONDS.toMillis(nanos);
}
| TimeUnitMismatchNegativeCases |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/MapWithParamConverterTest.java | {
"start": 1749,
"end": 2160
} | class ____ {
@GET
@Produces("text/plain")
public String hello(@RestQuery("param") Map<String, Integer> names) {
return Optional.ofNullable(names)
.orElse(Map.of())
.entrySet().stream().map(e -> e.getKey() + ":" + e.getValue())
.collect(Collectors.joining("-"));
}
}
@Provider
static | HelloResource |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/tree/domain/SqmCteRoot.java | {
"start": 762,
"end": 3051
} | class ____<T> extends SqmRoot<T> implements JpaRoot<T> {
private final SqmCteStatement<T> cte;
public SqmCteRoot(
SqmCteStatement<T> cte,
@Nullable String alias) {
this(
SqmCreationHelper.buildRootNavigablePath( "<<cte>>", alias ),
cte,
(SqmPathSource<T>) cte.getCteTable().getTupleType(),
alias
);
}
protected SqmCteRoot(
NavigablePath navigablePath,
SqmCteStatement<T> cte,
SqmPathSource<T> pathSource,
@Nullable String alias) {
super(
navigablePath,
pathSource,
alias,
true,
cte.nodeBuilder()
);
this.cte = cte;
}
@Override
public SqmCteRoot<T> copy(SqmCopyContext context) {
final SqmCteRoot<T> existing = context.getCopy( this );
if ( existing != null ) {
return existing;
}
final SqmCteRoot<T> path = context.registerCopy(
this,
new SqmCteRoot<>(
getNavigablePath(),
getCte().copy( context ),
getReferencedPathSource(),
getExplicitAlias()
)
);
copyTo( path, context );
return path;
}
public SqmCteStatement<T> getCte() {
return cte;
}
@Override
public <X> X accept(SemanticQueryWalker<X> walker) {
return walker.visitRootCte( this );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// JPA
@Override
public SqmEntityDomainType<T> getModel() {
throw new UnsupportedOperationException( "Cte root does not have an entity type. Use getReferencedPathSource() instead." );
}
@Override
public String getEntityName() {
throw new UnsupportedOperationException( "Cte root does not have an entity type. Use getReferencedPathSource() instead." );
}
@Override
public SqmPathSource<T> getResolvedModel() {
return getReferencedPathSource();
}
@Override
public SqmCorrelatedRoot<T> createCorrelation() {
return new SqmCorrelatedDerivedRoot<>( this );
}
@Override
public boolean deepEquals(SqmFrom<?, ?> object) {
return super.deepEquals( object )
&& Objects.equals( cte.getCteTable().getCteName(), ((SqmCteRoot<?>) object).cte.getCteTable().getCteName() );
}
@Override
public boolean isDeepCompatible(SqmFrom<?, ?> object) {
return super.isDeepCompatible( object )
&& Objects.equals( cte.getCteTable().getCteName(), ((SqmCteRoot<?>) object).cte.getCteTable().getCteName() );
}
}
| SqmCteRoot |
java | elastic__elasticsearch | x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/NotificationsIndexIT.java | {
"start": 1118,
"end": 3514
} | class ____ extends MlSingleNodeTestCase {
@Override
protected Settings nodeSettings() {
Settings.Builder newSettings = Settings.builder();
newSettings.put(super.nodeSettings());
newSettings.put(XPackSettings.SECURITY_ENABLED.getKey(), false);
newSettings.put(XPackSettings.WATCHER_ENABLED.getKey(), false);
return newSettings.build();
}
public void testAliasCreated() throws Exception {
// Auditing a notification should create the .ml-notifications-000002 index
// and write alias
createNotification(true);
assertBusy(() -> {
assertNotificationsIndexExists();
assertNotificationsWriteAliasCreated();
});
}
private void assertNotificationsIndexExists() {
GetIndexResponse getIndexResponse = indicesAdmin().prepareGetIndex(TEST_REQUEST_TIMEOUT)
.setIndices(NotificationsIndex.NOTIFICATIONS_INDEX)
.setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN)
.get();
assertThat(Arrays.asList(getIndexResponse.getIndices()), contains(NotificationsIndex.NOTIFICATIONS_INDEX));
}
private void assertNotificationsWriteAliasCreated() {
Map<String, List<AliasMetadata>> aliases = indicesAdmin().prepareGetAliases(
TimeValue.timeValueSeconds(10L),
NotificationsIndex.NOTIFICATIONS_INDEX_WRITE_ALIAS
).setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN_CLOSED_HIDDEN).get().getAliases();
assertThat(aliases.size(), is(1));
List<AliasMetadata> indexAliases = aliases.get(NotificationsIndex.NOTIFICATIONS_INDEX);
assertNotNull(aliases.toString(), indexAliases);
assertThat(indexAliases.size(), is(1));
var writeAlias = indexAliases.get(0);
assertThat(writeAlias.alias(), is(NotificationsIndex.NOTIFICATIONS_INDEX_WRITE_ALIAS));
assertThat("notification write alias should be hidden but is not: " + aliases, writeAlias.isHidden(), is(true));
}
private void createNotification(boolean includeNodeInfo) {
AnomalyDetectionAuditor auditor = new AnomalyDetectionAuditor(
client(),
getInstanceFromNode(ClusterService.class),
TestIndexNameExpressionResolver.newInstance(),
includeNodeInfo
);
auditor.info("whatever", "blah");
}
}
| NotificationsIndexIT |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/RemoteControl.java | {
"start": 475,
"end": 928
} | class ____ {
private Integer id;
private Date creationDate;
@Basic
@Temporal(TemporalType.TIMESTAMP)
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
@Id
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@PrePersist
private void init() {
creationDate = new Date();
}
}
| RemoteControl |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/common/TestHostRestrictingAuthorizationFilter.java | {
"start": 1632,
"end": 9818
} | class ____ {
private Logger log =
LoggerFactory.getLogger(TestHostRestrictingAuthorizationFilter.class);
/*
* Test running in unrestricted mode
*/
@Test
public void testAcceptAll() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn(null);
Mockito.when(request.getMethod()).thenReturn("GET");
Mockito.when(request.getRequestURI())
.thenReturn(new StringBuffer(WebHdfsFileSystem.PATH_PREFIX + "/user" +
"/ubuntu/foo").toString());
Mockito.when(request.getQueryString()).thenReturn("op=OPEN");
Mockito.when(request.getRemoteAddr()).thenReturn("192.168.1.2");
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse)
throws IOException, ServletException {
}
};
Filter filter = new HostRestrictingAuthorizationFilter();
HashMap<String, String> configs = new HashMap<String, String>() {
};
String allowRule = "*,*,/";
log.trace("Passing configs:\n{}", allowRule);
configs.put("host.allow.rules", allowRule);
configs.put(AuthenticationFilter.AUTH_TYPE, "simple");
FilterConfig fc = new DummyFilterConfig(configs);
filter.init(fc);
filter.doFilter(request, response, chain);
Mockito.verify(response, Mockito.times(0)).sendError(Mockito.eq(HttpServletResponse.SC_FORBIDDEN),
Mockito.anyString());
filter.destroy();
}
/*
* Test accepting a GET request for the file checksum when prohibited from
* doing
* a GET open call
*/
@Test
public void testAcceptGETFILECHECKSUM() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn(null);
Mockito.when(request.getMethod()).thenReturn("GET");
Mockito.when(request.getRequestURI())
.thenReturn(new StringBuffer(WebHdfsFileSystem.PATH_PREFIX + "/user" +
"/ubuntu/").toString());
Mockito.when(request.getQueryString()).thenReturn("op=GETFILECHECKSUM ");
Mockito.when(request.getRemoteAddr()).thenReturn("192.168.1.2");
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse)
throws IOException, ServletException {
}
};
Filter filter = new HostRestrictingAuthorizationFilter();
HashMap<String, String> configs = new HashMap<String, String>() {
};
configs.put(AuthenticationFilter.AUTH_TYPE, "simple");
FilterConfig fc = new DummyFilterConfig(configs);
filter.init(fc);
filter.doFilter(request, response, chain);
Mockito.verify(response, Mockito.times(0)).sendError(Mockito.eq(HttpServletResponse.SC_FORBIDDEN),
Mockito.anyString());
filter.destroy();
}
/*
* Test accepting a GET request for reading a file via an open call
*/
@Test
public void testRuleAllowedGet() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn(null);
Mockito.when(request.getMethod()).thenReturn("GET");
String queryString = "op=OPEN";
Mockito.when(request.getRequestURI())
.thenReturn(new StringBuffer(WebHdfsFileSystem.PATH_PREFIX + "/user" +
"/ubuntu/foo?" + queryString).toString());
Mockito.when(request.getQueryString()).thenReturn(queryString);
Mockito.when(request.getRemoteAddr()).thenReturn("192.168.1.2");
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse)
throws IOException, ServletException {
}
};
Filter filter = new HostRestrictingAuthorizationFilter();
HashMap<String, String> configs = new HashMap<String, String>() {
};
String allowRule = "ubuntu,127.0.0.1/32,/localbits/*|*,192.168.0.1/22," +
"/user/ubuntu/*";
log.trace("Passing configs:\n{}", allowRule);
configs.put("host.allow.rules", allowRule);
configs.put(AuthenticationFilter.AUTH_TYPE, "simple");
FilterConfig fc = new DummyFilterConfig(configs);
filter.init(fc);
filter.doFilter(request, response, chain);
filter.destroy();
}
/*
* Test by default we deny an open call GET request
*/
@Test
public void testRejectsGETs() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn(null);
Mockito.when(request.getMethod()).thenReturn("GET");
String queryString = "bar=foo&delegationToken=dt&op=OPEN";
Mockito.when(request.getRequestURI())
.thenReturn(new StringBuffer(WebHdfsFileSystem.PATH_PREFIX + "/user" +
"/ubuntu/?" + queryString).toString());
Mockito.when(request.getQueryString()).thenReturn(queryString);
Mockito.when(request.getRemoteAddr()).thenReturn("192.168.1.2");
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse)
throws IOException, ServletException {
}
};
Filter filter = new HostRestrictingAuthorizationFilter();
HashMap<String, String> configs = new HashMap<String, String>() {
};
configs.put(AuthenticationFilter.AUTH_TYPE, "simple");
FilterConfig fc = new DummyFilterConfig(configs);
filter.init(fc);
filter.doFilter(request, response, chain);
filter.destroy();
}
/*
* Test acceptable behavior to malformed requests
* Case: no operation (op parameter) specified
*/
@Test
public void testUnexpectedInputMissingOpParameter() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn(null);
Mockito.when(request.getMethod()).thenReturn("GET");
Mockito.when(request.getRequestURI())
.thenReturn(new StringBuffer(WebHdfsFileSystem.PATH_PREFIX +
"/IAmARandomRequest/").toString());
Mockito.when(request.getQueryString()).thenReturn(null);
Mockito.when(request.getRemoteAddr()).thenReturn("192.168.1.2");
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse)
throws IOException, ServletException {
}
};
Filter filter = new HostRestrictingAuthorizationFilter();
HashMap<String, String> configs = new HashMap<String, String>() {
};
configs.put(AuthenticationFilter.AUTH_TYPE, "simple");
FilterConfig fc = new DummyFilterConfig(configs);
filter.init(fc);
filter.doFilter(request, response, chain);
log.error("XXX {}", response.getStatus());
filter.destroy();
}
/**
* A request that don't access WebHDFS API should pass through.
*/
@Test
public void testNotWebhdfsAPIRequest() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getMethod()).thenReturn("GET");
Mockito.when(request.getRequestURI()).thenReturn("/conf");
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Filter filter = new HostRestrictingAuthorizationFilter();
HashMap<String, String> configs = new HashMap<String, String>() {};
configs.put(AuthenticationFilter.AUTH_TYPE, "simple");
FilterConfig fc = new DummyFilterConfig(configs);
filter.init(fc);
filter.doFilter(request, response, (servletRequest, servletResponse) -> {});
filter.destroy();
}
private static | TestHostRestrictingAuthorizationFilter |
java | micronaut-projects__micronaut-core | http/src/main/java/io/micronaut/http/HttpAttributes.java | {
"start": 1063,
"end": 5280
} | enum ____ implements CharSequence {
/**
* Attribute used to store the {@link java.security.Principal}.
*
* @deprecated Use {@link HttpRequest#getUserPrincipal()} and {@link HttpRequest#setUserPrincipal(Principal)}
*/
@Deprecated(forRemoval = true, since = "4.8.0")
PRINCIPAL("micronaut.AUTHENTICATION"),
/**
* Attribute used to store any exception that may have occurred during request processing.
*/
@Deprecated(forRemoval = true, since = "4.8.0")
ERROR(Constants.PREFIX + ".error"),
/**
* Attribute used to store the object that represents the Route match.
*
* @deprecated Please use the accessors in RouteAttributes
*/
@Deprecated(forRemoval = true, since = "4.8.0")
ROUTE_MATCH(Constants.PREFIX + ".route.match"),
/**
* Attribute used to store the object that represents the Route.
*
* @deprecated Please use the accessors in RouteAttributes
*/
@Deprecated(forRemoval = true, since = "4.8.0")
ROUTE_INFO(Constants.PREFIX + ".route.info"),
/**
* Attribute used to store the URI template defined by the route.
*
* @deprecated Use {@link BasicHttpAttributes#getUriTemplate} instead
*/
@Deprecated(forRemoval = true, since = "4.8.0")
URI_TEMPLATE(Constants.PREFIX + ".route.template"),
/**
* Attribute used to store the HTTP method name, if required within the response.
*
* @deprecated No replacement. Use your own attribute if necessary
*/
@Deprecated(forRemoval = true, since = "4.8.0")
METHOD_NAME(Constants.PREFIX + ".method.name"),
/**
* Attribute used to store the service ID a client request is being sent to. Used for tracing purposes.
*
* @deprecated Use {@link BasicHttpAttributes#getServiceId}
*/
@Deprecated(forRemoval = true, since = "4.8.0")
SERVICE_ID(Constants.PREFIX + ".serviceId"),
/**
* Attribute used to store the MediaTypeCodec. Used to override the registered codec per-request.
*
* @deprecated Unused
*/
@Deprecated(forRemoval = true, since = "4.8.0")
MEDIA_TYPE_CODEC(Constants.PREFIX + ".mediaType.codec"),
/**
* Attribute used to store the MethodInvocationContext by declarative client.
*
* @deprecated Please use accessors in ClientAttributes instead
*/
@Deprecated(forRemoval = true, since = "4.8.0")
INVOCATION_CONTEXT(Constants.PREFIX + ".invocationContext"),
/**
* Attribute used to store the cause of an error response.
*
* @deprecated Please use the accessors in RouteAttributes
*/
@Deprecated(forRemoval = true, since = "4.8.0")
EXCEPTION(Constants.PREFIX + ".exception"),
/**
* Attribute used to store a client Certificate (mutual authentication).
*
* @deprecated Use {@link HttpRequest#getCertificate()} instead
*/
@Deprecated(forRemoval = true, since = "4.8.0")
X509_CERTIFICATE("javax.servlet.request.X509Certificate"),
/**
* Attribute used to store Available HTTP methods on the OPTIONS request.
* @deprecated Not used anymore
*/
@Deprecated(forRemoval = true, since = "4.7")
AVAILABLE_HTTP_METHODS(Constants.PREFIX + ".route.availableHttpMethods"),
/**
* The message body writer.
*
* @deprecated Use accessors in {@link HttpMessage} instead
*/
@Deprecated(forRemoval = true, since = "4.8.0")
MESSAGE_BODY_WRITER(Constants.PREFIX + ".messageBodyWriter"),
/**
* Body that was discarded because this is a HEAD response.
*/
HEAD_BODY(Constants.PREFIX + ".headBody");
private final String name;
/**
* @param name The name
*/
HttpAttributes(String name) {
this.name = name;
}
@Override
public int length() {
return name.length();
}
@Override
public char charAt(int index) {
return name.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return name.subSequence(start, end);
}
@Override
public String toString() {
return name;
}
/**
* Constants.
*/
private static final | HttpAttributes |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/resource/ScanProxy.java | {
"start": 182,
"end": 334
} | interface ____ {
@Path("/subrsource")
ScanSubresource doit();
@Path("/doit")
@GET
@Produces("text/plain")
String get();
}
| ScanProxy |
java | alibaba__nacos | common/src/main/java/com/alibaba/nacos/common/task/engine/NacosExecuteTaskExecuteEngine.java | {
"start": 1018,
"end": 3438
} | class ____ extends AbstractNacosTaskExecuteEngine<AbstractExecuteTask> {
private final TaskExecuteWorker[] executeWorkers;
public NacosExecuteTaskExecuteEngine(String name, Logger logger) {
this(name, logger, ThreadUtils.getSuitableThreadCount(1));
}
public NacosExecuteTaskExecuteEngine(String name, Logger logger, int dispatchWorkerCount) {
super(logger);
executeWorkers = new TaskExecuteWorker[dispatchWorkerCount];
for (int mod = 0; mod < dispatchWorkerCount; ++mod) {
executeWorkers[mod] = new TaskExecuteWorker(name, mod, dispatchWorkerCount, getEngineLog());
}
}
@Override
public int size() {
int result = 0;
for (TaskExecuteWorker each : executeWorkers) {
result += each.pendingTaskCount();
}
return result;
}
@Override
public boolean isEmpty() {
return 0 == size();
}
@Override
public void addTask(Object tag, AbstractExecuteTask task) {
NacosTaskProcessor processor = getProcessor(tag);
if (null != processor) {
processor.process(task);
return;
}
TaskExecuteWorker worker = getWorker(tag);
worker.process(task);
}
private TaskExecuteWorker getWorker(Object tag) {
int idx = (tag.hashCode() & Integer.MAX_VALUE) % workersCount();
return executeWorkers[idx];
}
private int workersCount() {
return executeWorkers.length;
}
@Override
public AbstractExecuteTask removeTask(Object key) {
throw new UnsupportedOperationException("ExecuteTaskEngine do not support remove task");
}
@Override
public Collection<Object> getAllTaskKeys() {
throw new UnsupportedOperationException("ExecuteTaskEngine do not support get all task keys");
}
@Override
public void shutdown() throws NacosException {
for (TaskExecuteWorker each : executeWorkers) {
each.shutdown();
}
}
/**
* Get workers status.
*
* @return workers status string
*/
public String workersStatus() {
StringBuilder sb = new StringBuilder();
for (TaskExecuteWorker worker : executeWorkers) {
sb.append(worker.status()).append('\n');
}
return sb.toString();
}
}
| NacosExecuteTaskExecuteEngine |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/InstrumentedWriteLock.java | {
"start": 1126,
"end": 1460
} | class ____ a <code>WriteLock</code>.
* It extends the class {@link InstrumentedLock}, and can be used to track
* whether a specific write lock is being held for too long and log
* warnings if so.
*
* The logged warnings are throttled so that logs are not spammed.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public | of |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.