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 | core/camel-core/src/test/java/org/apache/camel/component/timer/TimerMultipleConsumerTest.java | {
"start": 990,
"end": 1643
} | class ____ extends ContextTestSupport {
@Test
public void testMultipleConsumers() throws Exception {
getMockEndpoint("mock:foo").expectedMinimumMessageCount(1);
getMockEndpoint("mock:bar").expectedMinimumMessageCount(1);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("timer:mytimer?period=0&delay=10").to("mock:foo");
from("timer:mytimer?period=0&delay=10").to("mock:bar");
}
};
}
}
| TimerMultipleConsumerTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/collapse/CollapseBuilder.java | {
"start": 1512,
"end": 8972
} | class ____ implements Writeable, ToXContentObject {
public static final ParseField FIELD_FIELD = new ParseField("field");
public static final ParseField INNER_HITS_FIELD = new ParseField("inner_hits");
public static final ParseField MAX_CONCURRENT_GROUP_REQUESTS_FIELD = new ParseField("max_concurrent_group_searches");
private static final ObjectParser<CollapseBuilder, Void> PARSER = new ObjectParser<>("collapse", CollapseBuilder::new);
static {
PARSER.declareString(CollapseBuilder::setField, FIELD_FIELD);
PARSER.declareInt(CollapseBuilder::setMaxConcurrentGroupRequests, MAX_CONCURRENT_GROUP_REQUESTS_FIELD);
PARSER.declareField((parser, builder, context) -> {
XContentParser.Token currentToken = parser.currentToken();
if (currentToken == XContentParser.Token.START_OBJECT) {
builder.setInnerHits(InnerHitBuilder.fromXContent(parser));
} else if (currentToken == XContentParser.Token.START_ARRAY) {
List<InnerHitBuilder> innerHitBuilders = new ArrayList<>();
for (currentToken = parser.nextToken(); currentToken != XContentParser.Token.END_ARRAY; currentToken = parser.nextToken()) {
if (currentToken == XContentParser.Token.START_OBJECT) {
innerHitBuilders.add(InnerHitBuilder.fromXContent(parser));
} else {
throw new ParsingException(parser.getTokenLocation(), "Invalid token in inner_hits array");
}
}
builder.setInnerHits(innerHitBuilders);
}
}, INNER_HITS_FIELD, ObjectParser.ValueType.OBJECT_ARRAY);
}
private String field;
private List<InnerHitBuilder> innerHits = Collections.emptyList();
private int maxConcurrentGroupRequests = 0;
private CollapseBuilder() {}
/**
* Public constructor
* @param field The name of the field to collapse on
*/
public CollapseBuilder(String field) {
Objects.requireNonNull(field, "field must be non-null");
this.field = field;
}
public CollapseBuilder(StreamInput in) throws IOException {
this.field = in.readString();
this.maxConcurrentGroupRequests = in.readVInt();
this.innerHits = in.readCollectionAsList(InnerHitBuilder::new);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(field);
out.writeVInt(maxConcurrentGroupRequests);
out.writeCollection(innerHits);
}
public static CollapseBuilder fromXContent(XContentParser parser) {
return PARSER.apply(parser, null);
}
// for object parser only
private CollapseBuilder setField(String field) {
if (Strings.isEmpty(field)) {
throw new IllegalArgumentException("field name is null or empty");
}
this.field = field;
return this;
}
public CollapseBuilder setInnerHits(InnerHitBuilder innerHit) {
if (innerHit.getName() == null) {
throw new IllegalArgumentException("inner_hits must have a [name]; set the [name] field in the inner_hits definition");
}
this.innerHits = Collections.singletonList(innerHit);
return this;
}
public CollapseBuilder setInnerHits(List<InnerHitBuilder> innerHits) {
if (innerHits != null) {
for (InnerHitBuilder innerHit : innerHits) {
if (innerHit.getName() == null) {
throw new IllegalArgumentException("inner_hits must have a [name]; set the [name] field in the inner_hits definition");
}
}
}
this.innerHits = innerHits;
return this;
}
public CollapseBuilder setMaxConcurrentGroupRequests(int num) {
if (num < 1) {
throw new IllegalArgumentException("maxConcurrentGroupRequests` must be positive");
}
this.maxConcurrentGroupRequests = num;
return this;
}
/**
* The name of the field to collapse against
*/
public String getField() {
return this.field;
}
/**
* The inner hit options to expand the collapsed results
*/
public List<InnerHitBuilder> getInnerHits() {
return this.innerHits;
}
/**
* Returns the amount of group requests that are allowed to be ran concurrently in the inner_hits phase.
*/
public int getMaxConcurrentGroupRequests() {
return maxConcurrentGroupRequests;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
builder.startObject();
innerToXContent(builder);
builder.endObject();
return builder;
}
private void innerToXContent(XContentBuilder builder) throws IOException {
builder.field(FIELD_FIELD.getPreferredName(), field);
if (maxConcurrentGroupRequests > 0) {
builder.field(MAX_CONCURRENT_GROUP_REQUESTS_FIELD.getPreferredName(), maxConcurrentGroupRequests);
}
if (innerHits.isEmpty() == false) {
if (innerHits.size() == 1) {
builder.field(INNER_HITS_FIELD.getPreferredName(), innerHits.get(0));
} else {
builder.startArray(INNER_HITS_FIELD.getPreferredName());
for (InnerHitBuilder innerHit : innerHits) {
innerHit.toXContent(builder, ToXContent.EMPTY_PARAMS);
}
builder.endArray();
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CollapseBuilder that = (CollapseBuilder) o;
if (maxConcurrentGroupRequests != that.maxConcurrentGroupRequests) return false;
if (field.equals(that.field) == false) return false;
return Objects.equals(innerHits, that.innerHits);
}
@Override
public int hashCode() {
int result = Objects.hash(field, innerHits);
result = 31 * result + maxConcurrentGroupRequests;
return result;
}
@Override
public String toString() {
return Strings.toString(this, true, true);
}
public CollapseContext build(SearchExecutionContext searchExecutionContext) {
MappedFieldType fieldType = searchExecutionContext.getFieldType(field);
if (fieldType == null) {
throw new IllegalArgumentException("no mapping found for `" + field + "` in order to collapse on");
}
if (fieldType.collapseType() == CollapseType.NONE) {
throw new IllegalArgumentException(
"collapse is not supported for the field [" + fieldType.name() + "] of the type [" + fieldType.typeName() + "]"
);
}
if (fieldType.hasDocValues() == false) {
throw new IllegalArgumentException("cannot collapse on field `" + field + "` without `doc_values`");
}
if (fieldType.indexType().hasDenseIndex() == false && (innerHits != null && innerHits.isEmpty() == false)) {
throw new IllegalArgumentException(
"cannot expand `inner_hits` for collapse field `" + field + "`, " + "only indexed field can retrieve `inner_hits`"
);
}
return new CollapseContext(field, fieldType);
}
}
| CollapseBuilder |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/LoopOverCharArrayTest.java | {
"start": 872,
"end": 1099
} | class ____ {
@Test
public void refactor() {
BugCheckerRefactoringTestHelper.newInstance(LoopOverCharArray.class, getClass())
.addInputLines(
"Test.java",
"""
| LoopOverCharArrayTest |
java | elastic__elasticsearch | x-pack/plugin/searchable-snapshots/src/main/java/org/elasticsearch/xpack/searchablesnapshots/action/SearchableSnapshotsStatsResponse.java | {
"start": 1275,
"end": 6229
} | class ____ extends BroadcastResponse {
private final List<SearchableSnapshotShardStats> stats;
private volatile List<CacheIndexInputStats> total;
SearchableSnapshotsStatsResponse(StreamInput in) throws IOException {
super(in);
this.stats = in.readCollectionAsList(SearchableSnapshotShardStats::new);
}
SearchableSnapshotsStatsResponse(
List<SearchableSnapshotShardStats> stats,
int totalShards,
int successfulShards,
int failedShards,
List<DefaultShardOperationFailedException> shardFailures
) {
super(totalShards, successfulShards, failedShards, shardFailures);
this.stats = Objects.requireNonNull(stats);
}
public List<SearchableSnapshotShardStats> getStats() {
return stats;
}
private List<CacheIndexInputStats> getTotal() {
if (total != null) {
return total;
}
return total = computeCompound(getStats().stream().flatMap(stat -> stat.getStats().stream()));
}
private static List<CacheIndexInputStats> computeCompound(Stream<CacheIndexInputStats> statsStream) {
return statsStream.collect(groupingBy(CacheIndexInputStats::getFileExt, Collectors.reducing(CacheIndexInputStats::combine)))
.values()
.stream()
.filter(o -> o.isEmpty() == false)
.map(Optional::get)
.sorted(Comparator.comparing(CacheIndexInputStats::getFileExt))
.collect(toList());
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeCollection(stats);
}
@Override
protected void addCustomXContentFields(XContentBuilder builder, Params params) throws IOException {
final ClusterStatsLevel level = ClusterStatsLevel.of(params, ClusterStatsLevel.INDICES);
builder.startArray("total");
for (CacheIndexInputStats cis : getTotal()) {
cis.toXContent(builder, params);
}
builder.endArray();
if (level == ClusterStatsLevel.INDICES || level == ClusterStatsLevel.SHARDS) {
builder.startObject("indices");
final List<Index> indices = getStats().stream()
.filter(shardStats -> shardStats.getStats().isEmpty() == false)
.map(SearchableSnapshotShardStats::getShardRouting)
.map(ShardRouting::index)
.sorted(Index.COMPARE_BY_NAME)
.distinct()
.toList();
for (Index index : indices) {
builder.startObject(index.getName());
{
builder.startArray("total");
List<CacheIndexInputStats> indexStats = computeCompound(
getStats().stream()
.filter(dirStats -> dirStats.getShardRouting().index().equals(index))
.flatMap(dirStats -> dirStats.getStats().stream())
);
for (CacheIndexInputStats cis : indexStats) {
cis.toXContent(builder, params);
}
builder.endArray();
if (level == ClusterStatsLevel.SHARDS) {
builder.startObject("shards");
{
List<SearchableSnapshotShardStats> listOfStats = getStats().stream()
.filter(dirStats -> dirStats.getShardRouting().index().equals(index))
.sorted(Comparator.comparingInt(dir -> dir.getShardRouting().getId()))
.toList();
int minShard = listOfStats.stream()
.map(stat -> stat.getShardRouting().getId())
.min(Integer::compareTo)
.orElse(0);
int maxShard = listOfStats.stream()
.map(stat -> stat.getShardRouting().getId())
.max(Integer::compareTo)
.orElse(0);
for (int i = minShard; i <= maxShard; i++) {
builder.startArray(Integer.toString(i));
for (SearchableSnapshotShardStats stat : listOfStats) {
if (stat.getShardRouting().getId() == i) {
stat.toXContent(builder, params);
}
}
builder.endArray();
}
}
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
}
| SearchableSnapshotsStatsResponse |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/clickhouse/parser/CKLexer.java | {
"start": 487,
"end": 2324
} | class ____ extends Lexer {
static final Keywords CK_KEYWORDS;
static final DialectFeature CK_FEATURE = new DialectFeature(
Arrays.asList(
AsofJoin,
GlobalJoin,
JoinRightTableAlias,
ParseLimitBy,
TableAliasAsof
),
null
);
static {
Map<String, Token> map = new HashMap<>();
map.putAll(Keywords.DEFAULT_KEYWORDS.getKeywords());
map.put("IF", Token.IF);
map.put("OF", Token.OF);
map.put("CONCAT", Token.CONCAT);
map.put("CONTINUE", Token.CONTINUE);
map.put("MERGE", Token.MERGE);
map.put("USING", Token.USING);
map.put("ROW", Token.ROW);
map.put("LIMIT", Token.LIMIT);
map.put("SHOW", Token.SHOW);
map.put("ALL", Token.ALL);
map.put("GLOBAL", Token.GLOBAL);
map.put("PARTITION", Token.PARTITION);
map.put("ILIKE", Token.ILIKE);
map.put("PREWHERE", Token.PREWHERE);
map.put("QUALIFY", Token.QUALIFY);
map.put("FORMAT", Token.FORMAT);
map.put("SETTINGS", Token.SETTINGS);
map.put("FINAL", Token.FINAL);
map.put("TTL", Token.TTL);
map.put("CODEC", Token.CODEC);
map.remove("ANY");
CK_KEYWORDS = new Keywords(map);
}
@Override
protected Keywords loadKeywords() {
return CK_KEYWORDS;
}
public CKLexer(String input, SQLParserFeature... features) {
super(input, DbType.clickhouse);
this.skipComment = true;
this.keepComments = true;
for (SQLParserFeature feature : features) {
config(feature, true);
}
}
@Override
protected void initDialectFeature() {
this.dialectFeature = CK_FEATURE;
}
}
| CKLexer |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2ClientRegistrationAuthenticationProvider.java | {
"start": 3351,
"end": 13326
} | class ____ implements AuthenticationProvider {
private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc7591#section-3.2.2";
private static final String DEFAULT_CLIENT_REGISTRATION_AUTHORIZED_SCOPE = "client.create";
private final Log logger = LogFactory.getLog(getClass());
private final RegisteredClientRepository registeredClientRepository;
private final OAuth2AuthorizationService authorizationService;
private Converter<RegisteredClient, OAuth2ClientRegistration> clientRegistrationConverter;
private Converter<OAuth2ClientRegistration, RegisteredClient> registeredClientConverter;
private PasswordEncoder passwordEncoder;
private boolean openRegistrationAllowed;
/**
* Constructs an {@code OAuth2ClientRegistrationAuthenticationProvider} using the
* provided parameters.
* @param registeredClientRepository the repository of registered clients
*/
public OAuth2ClientRegistrationAuthenticationProvider(RegisteredClientRepository registeredClientRepository,
OAuth2AuthorizationService authorizationService) {
Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null");
Assert.notNull(authorizationService, "authorizationService cannot be null");
this.registeredClientRepository = registeredClientRepository;
this.authorizationService = authorizationService;
this.clientRegistrationConverter = new RegisteredClientOAuth2ClientRegistrationConverter();
this.registeredClientConverter = new OAuth2ClientRegistrationRegisteredClientConverter();
this.passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
OAuth2ClientRegistrationAuthenticationToken clientRegistrationAuthentication = (OAuth2ClientRegistrationAuthenticationToken) authentication;
// Check if "initial" access token is not provided
AbstractOAuth2TokenAuthenticationToken<?> accessTokenAuthentication = null;
if (clientRegistrationAuthentication.getPrincipal() != null && AbstractOAuth2TokenAuthenticationToken.class
.isAssignableFrom(clientRegistrationAuthentication.getPrincipal().getClass())) {
accessTokenAuthentication = (AbstractOAuth2TokenAuthenticationToken<?>) clientRegistrationAuthentication
.getPrincipal();
}
if (accessTokenAuthentication == null) {
if (this.openRegistrationAllowed) {
return registerClient(clientRegistrationAuthentication, null);
}
else {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN);
}
}
// Validate the "initial" access token
if (!accessTokenAuthentication.isAuthenticated()) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN);
}
String accessTokenValue = accessTokenAuthentication.getToken().getTokenValue();
OAuth2Authorization authorization = this.authorizationService.findByToken(accessTokenValue,
OAuth2TokenType.ACCESS_TOKEN);
if (authorization == null) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN);
}
if (this.logger.isTraceEnabled()) {
this.logger.trace("Retrieved authorization with initial access token");
}
OAuth2Authorization.Token<OAuth2AccessToken> authorizedAccessToken = authorization.getAccessToken();
if (!authorizedAccessToken.isActive()) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN);
}
checkScope(authorizedAccessToken, Collections.singleton(DEFAULT_CLIENT_REGISTRATION_AUTHORIZED_SCOPE));
return registerClient(clientRegistrationAuthentication, authorization);
}
@Override
public boolean supports(Class<?> authentication) {
return OAuth2ClientRegistrationAuthenticationToken.class.isAssignableFrom(authentication);
}
/**
* Sets the {@link Converter} used for converting an {@link OAuth2ClientRegistration}
* to a {@link RegisteredClient}.
* @param registeredClientConverter the {@link Converter} used for converting an
* {@link OAuth2ClientRegistration} to a {@link RegisteredClient}
*/
public void setRegisteredClientConverter(
Converter<OAuth2ClientRegistration, RegisteredClient> registeredClientConverter) {
Assert.notNull(registeredClientConverter, "registeredClientConverter cannot be null");
this.registeredClientConverter = registeredClientConverter;
}
/**
* Sets the {@link Converter} used for converting a {@link RegisteredClient} to an
* {@link OAuth2ClientRegistration}.
* @param clientRegistrationConverter the {@link Converter} used for converting a
* {@link RegisteredClient} to an {@link OAuth2ClientRegistration}
*/
public void setClientRegistrationConverter(
Converter<RegisteredClient, OAuth2ClientRegistration> clientRegistrationConverter) {
Assert.notNull(clientRegistrationConverter, "clientRegistrationConverter cannot be null");
this.clientRegistrationConverter = clientRegistrationConverter;
}
/**
* Sets the {@link PasswordEncoder} used to encode the
* {@link RegisteredClient#getClientSecret() client secret}. If not set, the client
* secret will be encoded using
* {@link PasswordEncoderFactories#createDelegatingPasswordEncoder()}.
* @param passwordEncoder the {@link PasswordEncoder} used to encode the client secret
*/
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
this.passwordEncoder = passwordEncoder;
}
/**
* Set to {@code true} if open client registration (with no initial access token) is
* allowed. The default is {@code false}.
* @param openRegistrationAllowed {@code true} if open client registration is allowed,
* {@code false} otherwise
*/
public void setOpenRegistrationAllowed(boolean openRegistrationAllowed) {
this.openRegistrationAllowed = openRegistrationAllowed;
}
private OAuth2ClientRegistrationAuthenticationToken registerClient(
OAuth2ClientRegistrationAuthenticationToken clientRegistrationAuthentication,
OAuth2Authorization authorization) {
if (!isValidRedirectUris(clientRegistrationAuthentication.getClientRegistration().getRedirectUris())) {
throwInvalidClientRegistration(OAuth2ErrorCodes.INVALID_REDIRECT_URI,
OAuth2ClientMetadataClaimNames.REDIRECT_URIS);
}
if (this.logger.isTraceEnabled()) {
this.logger.trace("Validated client registration request parameters");
}
RegisteredClient registeredClient = this.registeredClientConverter
.convert(clientRegistrationAuthentication.getClientRegistration());
if (StringUtils.hasText(registeredClient.getClientSecret())) {
// Encode the client secret
RegisteredClient updatedRegisteredClient = RegisteredClient.from(registeredClient)
.clientSecret(this.passwordEncoder.encode(registeredClient.getClientSecret()))
.build();
this.registeredClientRepository.save(updatedRegisteredClient);
if (ClientAuthenticationMethod.CLIENT_SECRET_JWT.getValue()
.equals(clientRegistrationAuthentication.getClientRegistration()
.getTokenEndpointAuthenticationMethod())) {
// Return the hashed client_secret
registeredClient = updatedRegisteredClient;
}
}
else {
this.registeredClientRepository.save(registeredClient);
}
if (this.logger.isTraceEnabled()) {
this.logger.trace("Saved registered client");
}
if (authorization != null) {
// Invalidate the "initial" access token as it can only be used once
OAuth2Authorization.Builder builder = OAuth2Authorization.from(authorization)
.invalidate(authorization.getAccessToken().getToken());
if (authorization.getRefreshToken() != null) {
builder.invalidate(authorization.getRefreshToken().getToken());
}
authorization = builder.build();
this.authorizationService.save(authorization);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Saved authorization with invalidated initial access token");
}
}
OAuth2ClientRegistration clientRegistration = this.clientRegistrationConverter.convert(registeredClient);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Authenticated client registration request");
}
OAuth2ClientRegistrationAuthenticationToken clientRegistrationAuthenticationResult = new OAuth2ClientRegistrationAuthenticationToken(
(Authentication) clientRegistrationAuthentication.getPrincipal(), clientRegistration);
clientRegistrationAuthenticationResult.setDetails(clientRegistrationAuthentication.getDetails());
return clientRegistrationAuthenticationResult;
}
@SuppressWarnings("unchecked")
private static void checkScope(OAuth2Authorization.Token<OAuth2AccessToken> authorizedAccessToken,
Set<String> requiredScope) {
Collection<String> authorizedScope = Collections.emptySet();
if (authorizedAccessToken.getClaims().containsKey(OAuth2ParameterNames.SCOPE)) {
authorizedScope = (Collection<String>) authorizedAccessToken.getClaims().get(OAuth2ParameterNames.SCOPE);
}
if (!authorizedScope.containsAll(requiredScope)) {
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
}
else if (authorizedScope.size() != requiredScope.size()) {
// Restrict the access token to only contain the required scope
throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_TOKEN);
}
}
private static boolean isValidRedirectUris(List<String> redirectUris) {
if (CollectionUtils.isEmpty(redirectUris)) {
return true;
}
for (String redirectUri : redirectUris) {
try {
URI validRedirectUri = new URI(redirectUri);
if (validRedirectUri.getFragment() != null) {
return false;
}
}
catch (URISyntaxException ex) {
return false;
}
}
return true;
}
private static void throwInvalidClientRegistration(String errorCode, String fieldName) {
OAuth2Error error = new OAuth2Error(errorCode, "Invalid Client Registration: " + fieldName, ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
}
| OAuth2ClientRegistrationAuthenticationProvider |
java | spring-projects__spring-security | webauthn/src/main/java/org/springframework/security/web/webauthn/api/AuthenticatorTransport.java | {
"start": 1050,
"end": 4080
} | class ____ implements Serializable {
@Serial
private static final long serialVersionUID = -5617945441117386982L;
/**
* <a href="https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-usb">usbc</a>
* indicates the respective authenticator can be contacted over removable USB.
*/
public static final AuthenticatorTransport USB = new AuthenticatorTransport("usb");
/**
* <a href="https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-nfc">nfc</a>
* indicates the respective authenticator can be contacted over Near Field
* Communication (NFC).
*/
public static final AuthenticatorTransport NFC = new AuthenticatorTransport("nfc");
/**
* <a href="https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-ble">ble</a>
* Indicates the respective authenticator can be contacted over Bluetooth Smart
* (Bluetooth Low Energy / BLE).
*/
public static final AuthenticatorTransport BLE = new AuthenticatorTransport("ble");
/**
* <a href=
* "https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-smart-card">smart-card</a>
* indicates the respective authenticator can be contacted over ISO/IEC 7816 smart
* card with contacts.
*/
public static final AuthenticatorTransport SMART_CARD = new AuthenticatorTransport("smart-card");
/**
* <a href=
* "https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-hybrid">hybrid</a>
* indicates the respective authenticator can be contacted using a combination of
* (often separate) data-transport and proximity mechanisms. This supports, for
* example, authentication on a desktop computer using a smartphone.
*/
public static final AuthenticatorTransport HYBRID = new AuthenticatorTransport("hybrid");
/**
* <a href=
* "https://www.w3.org/TR/webauthn-3/#dom-authenticatortransport-internal">internal</a>
* indicates the respective authenticator is contacted using a client device-specific
* transport, i.e., it is a platform authenticator. These authenticators are not
* removable from the client device.
*/
public static final AuthenticatorTransport INTERNAL = new AuthenticatorTransport("internal");
private final String value;
AuthenticatorTransport(String value) {
this.value = value;
}
/**
* Get's the value.
* @return the value.
*/
public String getValue() {
return this.value;
}
/**
* Gets an instance of {@link AuthenticatorTransport}.
* @param value the value of the {@link AuthenticatorTransport}
* @return the {@link AuthenticatorTransport}
*/
public static AuthenticatorTransport valueOf(String value) {
switch (value) {
case "usb":
return USB;
case "nfc":
return NFC;
case "ble":
return BLE;
case "smart-card":
return SMART_CARD;
case "hybrid":
return HYBRID;
case "internal":
return INTERNAL;
default:
return new AuthenticatorTransport(value);
}
}
public static AuthenticatorTransport[] values() {
return new AuthenticatorTransport[] { USB, NFC, BLE, HYBRID, INTERNAL };
}
}
| AuthenticatorTransport |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/UTF8ByteArrayParseTest.java | {
"start": 154,
"end": 401
} | class ____ extends TestCase {
public void test_utf8() throws Exception {
byte[] bytes = "{'name':'xxx', age:3, birthday:\"2009-09-05\"}".getBytes("UTF-8");
JSON.parseObject(bytes, JSONObject.class);
}
}
| UTF8ByteArrayParseTest |
java | grpc__grpc-java | xds/src/test/java/io/grpc/xds/XdsDependencyManagerTest.java | {
"start": 43416,
"end": 44046
} | class ____ implements XdsDependencyManager.XdsConfigWatcher {
XdsConfig lastConfig;
int numUpdates = 0;
int numError = 0;
@Override
public void onUpdate(StatusOr<XdsConfig> update) {
log.fine("Config update: " + update);
if (update.hasValue()) {
lastConfig = update.getValue();
numUpdates++;
} else {
numError++;
}
}
private List<Integer> getStats() {
return Arrays.asList(numUpdates, numError);
}
private void verifyStats(int updt, int err) {
assertThat(getStats()).isEqualTo(Arrays.asList(updt, err));
}
}
static | TestWatcher |
java | quarkusio__quarkus | test-framework/junit5/src/main/java/io/quarkus/test/junit/DisableIfBuiltWithGraalVMOlderThan.java | {
"start": 280,
"end": 756
} | class ____ method should be disabled if the version of GraalVM used to build the native binary
* under test was older than the supplied version.
*
* This annotation should only be used on a test classes annotated with {@link QuarkusIntegrationTest}.
* If it is used on other test classes, it will have no effect.
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@ExtendWith(DisableIfBuiltWithGraalVMOlderThanCondition.class)
public @ | or |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/state/v2/AbstractValueState.java | {
"start": 1560,
"end": 2373
} | class ____<K, N, V> extends AbstractKeyedState<K, N, V>
implements InternalValueState<K, N, V> {
public AbstractValueState(
StateRequestHandler stateRequestHandler, TypeSerializer<V> valueSerializer) {
super(stateRequestHandler, valueSerializer);
}
@Override
public final StateFuture<V> asyncValue() {
return handleRequest(StateRequestType.VALUE_GET, null);
}
@Override
public final StateFuture<Void> asyncUpdate(V value) {
return handleRequest(StateRequestType.VALUE_UPDATE, value);
}
@Override
public V value() {
return handleRequestSync(StateRequestType.VALUE_GET, null);
}
@Override
public void update(V value) {
handleRequestSync(StateRequestType.VALUE_UPDATE, value);
}
}
| AbstractValueState |
java | elastic__elasticsearch | x-pack/plugin/esql/arrow/src/test/java/org/elasticsearch/xpack/esql/arrow/ArrowResponseTests.java | {
"start": 22000,
"end": 27272
} | class ____ implements Iterator<Object> {
private final ValueType type;
private ValueVector vector;
private int position;
ArrowValuesIterator(TestCase testCase, VectorSchemaRoot root, int column) {
this(root.getVector(column), testCase.columns.get(column).valueType);
}
ArrowValuesIterator(ValueVector vector, ValueType type) {
this.vector = vector;
this.type = type;
}
@Override
public boolean hasNext() {
return vector != null;
}
@Override
public Object next() {
if (vector == null) {
throw new NoSuchElementException();
}
Object result = vector.isNull(position) ? null : type.valueAt(vector, position);
position++;
if (position >= vector.getValueCount()) {
vector = null;
}
return result;
}
}
private BytesReference serializeBlocksDirectly(ArrowResponse body) throws IOException {
// Ensure there's a single part, this will fail if we ever change it.
assertTrue(body.isLastPart());
List<BytesReference> ourEncoding = new ArrayList<>();
int page = 0;
while (body.isPartComplete() == false) {
ourEncoding.add(body.encodeChunk(1500, BytesRefRecycler.NON_RECYCLING_INSTANCE));
page++;
}
return CompositeBytesReference.of(ourEncoding.toArray(BytesReference[]::new));
}
record TestCase(List<TestColumn> columns, List<TestPage> pages) {
@Override
public String toString() {
return pages.size() + " pages of " + columns.stream().map(TestColumn::type).collect(Collectors.joining("|"));
}
}
record TestColumn(String name, String type, ValueType valueType, boolean multivalue) {
static TestColumn create(String name, String type) {
return create(name, type, randomBoolean());
}
static TestColumn create(String name, String type, boolean multivalue) {
return new TestColumn(name, type, VALUE_TYPES.get(type), multivalue);
}
}
record TestPage(List<TestBlock> blocks) {
static TestPage create(BlockFactory factory, List<TestColumn> columns) {
int size = randomIntBetween(1, 1000);
return new TestPage(columns.stream().map(column -> TestBlock.create(factory, column, size)).toList());
}
@Override
public String toString() {
return blocks.get(0).block.getPositionCount()
+ " items - "
+ blocks.stream().map(b -> b.density.toString()).collect(Collectors.joining("|"));
}
}
record TestBlock(TestColumn column, Block block, Density density) {
static TestBlock create(TestColumn column, Block block) {
Density density;
if (block.areAllValuesNull()) {
density = Density.Empty;
} else if (block.mayHaveNulls()) {
density = Density.Sparse;
} else {
density = Density.Dense;
}
return new TestBlock(column, block, density);
}
static TestBlock create(BlockFactory factory, TestColumn column, int positions) {
return create(factory, column, randomFrom(Density.values()), positions);
}
static TestBlock create(BlockFactory factory, TestColumn column, Density density, int positions) {
ValueType valueType = column.valueType();
Block block;
if (density == Density.Empty) {
block = factory.newConstantNullBlock(positions);
} else {
Block.Builder builder = valueType.createBlockBuilder(factory);
int start = 0;
if (density == Density.Sparse && positions >= 2) {
// Make sure it's really sparse even if randomness of values may decide otherwise
valueType.addValue(builder, Density.Dense);
valueType.addValue(builder, Density.Empty);
start = 2;
}
for (int i = start; i < positions; i++) {
// If multivalued, randomly insert a series of values if the type isn't null (nulls are not allowed in multivalues)
if (column.multivalue && column.valueType != NULL_VALUES && randomBoolean()) {
builder.beginPositionEntry();
int numEntries = randomIntBetween(2, 5);
for (int j = 0; j < numEntries; j++) {
valueType.addValue(builder, Density.Dense);
}
builder.endPositionEntry();
} else {
valueType.addValue(builder, density);
}
}
// Will create an ArrayBlock if there are null values, VectorBlock otherwise
block = builder.build();
assertEquals(positions, block.getPositionCount());
}
return new TestBlock(column, block, density);
}
}
public | ArrowValuesIterator |
java | spring-projects__spring-framework | framework-docs/src/main/java/org/springframework/docs/web/webmvc/mvcconfig/mvcconfigcontentnegotiation/WebConfiguration.java | {
"start": 1017,
"end": 1306
} | class ____ implements WebMvcConfigurer {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.mediaType("json", MediaType.APPLICATION_JSON);
configurer.mediaType("xml", MediaType.APPLICATION_XML);
}
}
// end::snippet[] | WebConfiguration |
java | apache__flink | flink-metrics/flink-metrics-jmx/src/main/java/org/apache/flink/metrics/jmx/JMXReporter.java | {
"start": 10908,
"end": 10990
} | interface ____ an exposed histogram. */
@SuppressWarnings("unused")
public | for |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/xcontent/XContentHelper.java | {
"start": 25454,
"end": 36934
} | interface ____ {
/**
* Based on the provided arguments, compute a value to use for the given key as a merge result.
* If this method returns a non-{@code null} value, then the merge result will replace the original value of the provided key in
* the base map.
* If this method returns {@code null}, then:
* <ul>
* <li> if the values are of map type, the old and new values will be merged recursively
* <li> otherwise, the original value will be maintained
* </ul>
* This method doesn't throw a checked exception, but it is expected that illegal merges will result in a {@link RuntimeException}.
* @param parent merged field's parent
* @param key merged field's name
* @param oldValue original value of the provided key
* @param newValue the new value of the provided key which is to be merged with the original
* @return the merged value to use for the given key, or {@code null} if there is no custom merge result for it. If {@code null}
* is returned, the algorithm will live the original value as is, unless it is a map, in which case the new map will be merged
* into the old map recursively.
*/
@Nullable
Object merge(String parent, String key, Object oldValue, Object newValue);
}
/**
* Writes a "raw" (bytes) field, handling cases where the bytes are compressed, and tries to optimize writing using
* {@link XContentBuilder#rawField(String, InputStream)}.
* @deprecated use {@link #writeRawField(String, BytesReference, XContentType, XContentBuilder, Params)} to avoid content type
* auto-detection
*/
@Deprecated
public static void writeRawField(String field, BytesReference source, XContentBuilder builder, ToXContent.Params params)
throws IOException {
Compressor compressor = CompressorFactory.compressorForUnknownXContentType(source);
if (compressor != null) {
try (InputStream compressedStreamInput = compressor.threadLocalInputStream(source.streamInput())) {
builder.rawField(field, compressedStreamInput);
}
} else {
try (InputStream stream = source.streamInput()) {
builder.rawField(field, stream);
}
}
}
/**
* Writes a "raw" (bytes) field, handling cases where the bytes are compressed, and tries to optimize writing using
* {@link XContentBuilder#rawField(String, InputStream, XContentType)}.
*/
public static void writeRawField(
String field,
BytesReference source,
XContentType xContentType,
XContentBuilder builder,
ToXContent.Params params
) throws IOException {
Objects.requireNonNull(xContentType);
Compressor compressor = CompressorFactory.compressorForUnknownXContentType(source);
if (compressor != null) {
try (InputStream compressedStreamInput = compressor.threadLocalInputStream(source.streamInput())) {
builder.rawField(field, compressedStreamInput, xContentType);
}
} else {
try (InputStream stream = source.streamInput()) {
builder.rawField(field, stream, xContentType);
}
}
}
/**
* Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided
* {@link XContentType}. Wraps the output into a new anonymous object according to the value returned
* by the {@link ToXContent#isFragment()} method returns.
*/
public static BytesReference toXContent(ToXContent toXContent, XContentType xContentType, boolean humanReadable) throws IOException {
return toXContent(toXContent, xContentType, ToXContent.EMPTY_PARAMS, humanReadable);
}
/**
* Returns the bytes that represent the XContent output of the provided {@link ChunkedToXContent} object, using the provided
* {@link XContentType}. Wraps the output into a new anonymous object according to the value returned
* by the {@link ToXContent#isFragment()} method returns.
*/
public static BytesReference toXContent(ChunkedToXContent toXContent, XContentType xContentType, boolean humanReadable)
throws IOException {
return toXContent(ChunkedToXContent.wrapAsToXContent(toXContent), xContentType, humanReadable);
}
/**
* Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided
* {@link XContentType}. Wraps the output into a new anonymous object according to the value returned
* by the {@link ToXContent#isFragment()} method returns.
*/
public static BytesReference toXContent(ToXContent toXContent, XContentType xContentType, Params params, boolean humanReadable)
throws IOException {
return toXContent(toXContent, xContentType, RestApiVersion.current(), params, humanReadable);
}
/**
* Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided
* {@link XContentType}. Wraps the output into a new anonymous object according to the value returned
* by the {@link ToXContent#isFragment()} method returns.
*/
public static BytesReference toXContent(
ToXContent toXContent,
XContentType xContentType,
RestApiVersion restApiVersion,
Params params,
boolean humanReadable
) throws IOException {
try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent(), restApiVersion)) {
builder.humanReadable(humanReadable);
if (toXContent.isFragment()) {
builder.startObject();
}
toXContent.toXContent(builder, params);
if (toXContent.isFragment()) {
builder.endObject();
}
return BytesReference.bytes(builder);
}
}
/**
* Returns the bytes that represent the XContent output of the provided {@link ChunkedToXContent} object, using the provided
* {@link XContentType}. Wraps the output into a new anonymous object according to the value returned
* by the {@link ToXContent#isFragment()} method returns.
*/
public static BytesReference toXContent(ChunkedToXContent toXContent, XContentType xContentType, Params params, boolean humanReadable)
throws IOException {
return toXContent(ChunkedToXContent.wrapAsToXContent(toXContent), xContentType, params, humanReadable);
}
/**
* Guesses the content type based on the provided bytes which may be compressed.
*
* @deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
* The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
* This method is deprecated to prevent usages of it from spreading further without specific reasons.
*/
@Deprecated
public static XContentType xContentTypeMayCompressed(BytesReference bytes) {
Compressor compressor = CompressorFactory.compressorForUnknownXContentType(bytes);
if (compressor != null) {
try {
InputStream compressedStreamInput = compressor.threadLocalInputStream(bytes.streamInput());
if (compressedStreamInput.markSupported() == false) {
compressedStreamInput = new BufferedInputStream(compressedStreamInput);
}
return XContentFactory.xContentType(compressedStreamInput);
} catch (IOException e) {
assert false : "Should not happen, we're just reading bytes from memory";
throw new UncheckedIOException(e);
}
} else {
return XContentHelper.xContentType(bytes);
}
}
/**
* Guesses the content type based on the provided bytes.
*
* @deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
* The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
* This method is deprecated to prevent usages of it from spreading further without specific reasons.
*/
@Deprecated
public static XContentType xContentType(BytesReference bytes) {
if (bytes.hasArray()) {
return XContentFactory.xContentType(bytes.array(), bytes.arrayOffset(), bytes.length());
}
try {
final InputStream inputStream = bytes.streamInput();
assert inputStream.markSupported();
return XContentFactory.xContentType(inputStream);
} catch (IOException e) {
assert false : "Should not happen, we're just reading bytes from memory";
throw new UncheckedIOException(e);
}
}
/**
* Returns the contents of an object as an unparsed BytesReference
*
* This is useful for things like mappings where we're copying bytes around but don't
* actually need to parse their contents, and so avoids building large maps of maps
* unnecessarily
*/
public static BytesReference childBytes(XContentParser parser) throws IOException {
if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
throw new XContentParseException(
parser.getTokenLocation(),
"Expected [START_OBJECT] but got [" + parser.currentToken() + "]"
);
}
}
XContentBuilder builder = XContentBuilder.builder(parser.contentType().xContent());
builder.copyCurrentStructure(parser);
return BytesReference.bytes(builder);
}
/**
* Serialises new XContentType VND_ values in a bwc manner
* TODO remove in ES v9
* @param out stream output of the destination node
* @param xContentType an instance to serialize
*/
public static void writeTo(StreamOutput out, XContentType xContentType) throws IOException {
if (out.getTransportVersion().before(TransportVersions.V_8_0_0)) {
// when sending an enumeration to <v8 node it does not have new VND_ XContentType instances
out.writeVInt(xContentType.canonical().ordinal());
} else {
out.writeVInt(xContentType.ordinal());
}
}
/**
* Convenience method that creates a {@link XContentParser} from a content map so that it can be passed to
* existing REST based code for input parsing.
*
* @param config XContentParserConfiguration for this mapper
* @param source the operator content as a map
* @return
*/
public static XContentParser mapToXContentParser(XContentParserConfiguration config, Map<String, ?> source) {
try (XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON)) {
builder.map(source);
return createParserNotCompressed(config, BytesReference.bytes(builder), builder.contentType());
} catch (IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
}
}
}
| CustomMerge |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ClassNewInstanceTest.java | {
"start": 8457,
"end": 8886
} | class ____ {
void f() throws IOException {
try {
getClass().getDeclaredConstructor().newInstance();
} catch (ReflectiveOperationException e) {
}
}
}
""")
.doTest();
}
@Test
public void negativeThrows() {
testHelper
.addInputLines(
"Test.java",
"""
| Test |
java | quarkusio__quarkus | extensions/undertow/deployment/src/test/java/io/quarkus/undertow/test/sessioncontext/ObservingBean.java | {
"start": 364,
"end": 1341
} | class ____ {
int timesInitObserved = 0;
int timesBeforeDestroyedObserved = 0;
int timesDestroyedObserved = 0;
public int getTimesInitObserved() {
return timesInitObserved;
}
public int getTimesBeforeDestroyedObserved() {
return timesBeforeDestroyedObserved;
}
public int getTimesDestroyedObserved() {
return timesDestroyedObserved;
}
public void observeInit(@Observes @Initialized(SessionScoped.class) Object event) {
timesInitObserved++;
}
public void observeBeforeDestroyed(@Observes @BeforeDestroyed(SessionScoped.class) Object event) {
timesBeforeDestroyedObserved++;
}
public void observeDestroyed(@Observes @Destroyed(SessionScoped.class) Object event) {
timesDestroyedObserved++;
}
public void resetState() {
this.timesInitObserved = 0;
this.timesBeforeDestroyedObserved = 0;
this.timesDestroyedObserved = 0;
}
}
| ObservingBean |
java | google__gson | gson/src/test/java/com/google/gson/JsonObjectAsMapTest.java | {
"start": 1118,
"end": 9291
} | class ____ {
@Test
public void testSize() {
JsonObject o = new JsonObject();
assertThat(o.asMap().size()).isEqualTo(0);
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
assertThat(map).hasSize(1);
map.clear();
assertThat(map).hasSize(0);
assertThat(o.size()).isEqualTo(0);
}
@Test
public void testContainsKey() {
JsonObject o = new JsonObject();
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
assertThat(map.containsKey("a")).isTrue();
assertThat(map.containsKey("b")).isFalse();
assertThat(map.containsKey(null)).isFalse();
}
@Test
public void testContainsValue() {
JsonObject o = new JsonObject();
o.addProperty("a", 1);
o.add("b", JsonNull.INSTANCE);
Map<String, JsonElement> map = o.asMap();
assertThat(map.containsValue(new JsonPrimitive(1))).isTrue();
assertThat(map.containsValue(new JsonPrimitive(2))).isFalse();
assertThat(map.containsValue(null)).isFalse();
@SuppressWarnings({"unlikely-arg-type", "CollectionIncompatibleType"})
boolean containsInt = map.containsValue(1); // should only contain JsonPrimitive(1)
assertThat(containsInt).isFalse();
}
@Test
public void testGet() {
JsonObject o = new JsonObject();
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(1));
assertThat(map.get("b")).isNull();
assertThat(map.get(null)).isNull();
}
@Test
public void testPut() {
JsonObject o = new JsonObject();
Map<String, JsonElement> map = o.asMap();
assertThat(map.put("a", new JsonPrimitive(1))).isNull();
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(1));
JsonElement old = map.put("a", new JsonPrimitive(2));
assertThat(old).isEqualTo(new JsonPrimitive(1));
assertThat(map).hasSize(1);
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(2));
assertThat(o.get("a")).isEqualTo(new JsonPrimitive(2));
assertThat(map.put("b", JsonNull.INSTANCE)).isNull();
assertThat(map.get("b")).isEqualTo(JsonNull.INSTANCE);
var e = assertThrows(NullPointerException.class, () -> map.put(null, new JsonPrimitive(1)));
assertThat(e).hasMessageThat().isEqualTo("key == null");
e = assertThrows(NullPointerException.class, () -> map.put("a", null));
assertThat(e).hasMessageThat().isEqualTo("value == null");
}
@Test
public void testRemove() {
JsonObject o = new JsonObject();
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
assertThat(map.remove("b")).isNull();
assertThat(map).hasSize(1);
JsonElement old = map.remove("a");
assertThat(old).isEqualTo(new JsonPrimitive(1));
assertThat(map).hasSize(0);
assertThat(map.remove("a")).isNull();
assertThat(map).hasSize(0);
assertThat(o.size()).isEqualTo(0);
assertThat(map.remove(null)).isNull();
}
@Test
public void testPutAll() {
JsonObject o = new JsonObject();
o.addProperty("a", 1);
Map<String, JsonElement> otherMap = new HashMap<>();
otherMap.put("a", new JsonPrimitive(2));
otherMap.put("b", new JsonPrimitive(3));
Map<String, JsonElement> map = o.asMap();
map.putAll(otherMap);
assertThat(map).hasSize(2);
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(2));
assertThat(map.get("b")).isEqualTo(new JsonPrimitive(3));
var e =
assertThrows(
NullPointerException.class,
() -> map.putAll(Collections.singletonMap(null, new JsonPrimitive(1))));
assertThat(e).hasMessageThat().isEqualTo("key == null");
e =
assertThrows(
NullPointerException.class, () -> map.putAll(Collections.singletonMap("a", null)));
assertThat(e).hasMessageThat().isEqualTo("value == null");
}
@Test
public void testClear() {
JsonObject o = new JsonObject();
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
map.clear();
assertThat(map).hasSize(0);
assertThat(o.size()).isEqualTo(0);
}
@Test
public void testKeySet() {
JsonObject o = new JsonObject();
o.addProperty("b", 1);
o.addProperty("a", 2);
Map<String, JsonElement> map = o.asMap();
Set<String> keySet = map.keySet();
// Should contain keys in same order
assertThat(keySet).containsExactly("b", "a").inOrder();
// Key set doesn't support insertions
assertThrows(UnsupportedOperationException.class, () -> keySet.add("c"));
assertThat(keySet.remove("a")).isTrue();
assertThat(map.keySet()).isEqualTo(Collections.singleton("b"));
assertThat(o.keySet()).isEqualTo(Collections.singleton("b"));
}
@Test
public void testValues() {
JsonObject o = new JsonObject();
o.addProperty("a", 2);
o.addProperty("b", 1);
Map<String, JsonElement> map = o.asMap();
Collection<JsonElement> values = map.values();
// Should contain values in same order
assertThat(values).containsExactly(new JsonPrimitive(2), new JsonPrimitive(1)).inOrder();
// Values collection doesn't support insertions
assertThrows(UnsupportedOperationException.class, () -> values.add(new JsonPrimitive(3)));
assertThat(values.remove(new JsonPrimitive(2))).isTrue();
assertThat(new ArrayList<>(map.values()))
.isEqualTo(Collections.singletonList(new JsonPrimitive(1)));
assertThat(o.size()).isEqualTo(1);
assertThat(o.get("b")).isEqualTo(new JsonPrimitive(1));
}
@Test
public void testEntrySet() {
JsonObject o = new JsonObject();
o.addProperty("b", 2);
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
Set<Entry<String, JsonElement>> entrySet = map.entrySet();
List<Entry<?, ?>> expectedEntrySet =
Arrays.asList(
new SimpleEntry<>("b", new JsonPrimitive(2)),
new SimpleEntry<>("a", new JsonPrimitive(1)));
// Should contain entries in same order
assertThat(new ArrayList<>(entrySet)).isEqualTo(expectedEntrySet);
// Entry set doesn't support insertions
assertThrows(
UnsupportedOperationException.class,
() -> entrySet.add(new SimpleEntry<>("c", new JsonPrimitive(3))));
assertThat(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1)))).isTrue();
assertThat(map.entrySet())
.isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(2))));
assertThat(o.entrySet())
.isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(2))));
// Should return false because entry has already been removed
assertThat(entrySet.remove(new SimpleEntry<>("a", new JsonPrimitive(1)))).isFalse();
Entry<String, JsonElement> entry = entrySet.iterator().next();
JsonElement old = entry.setValue(new JsonPrimitive(3));
assertThat(old).isEqualTo(new JsonPrimitive(2));
assertThat(map.entrySet())
.isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3))));
assertThat(o.entrySet())
.isEqualTo(Collections.singleton(new SimpleEntry<>("b", new JsonPrimitive(3))));
var e = assertThrows(NullPointerException.class, () -> entry.setValue(null));
assertThat(e).hasMessageThat().isEqualTo("value == null");
}
@Test
public void testEqualsHashCode() {
JsonObject o = new JsonObject();
o.addProperty("a", 1);
Map<String, JsonElement> map = o.asMap();
MoreAsserts.assertEqualsAndHashCode(map, Collections.singletonMap("a", new JsonPrimitive(1)));
assertThat(map.equals(Collections.emptyMap())).isFalse();
assertThat(map.equals(Collections.singletonMap("a", new JsonPrimitive(2)))).isFalse();
}
/** Verify that {@code JsonObject} updates are visible to view and vice versa */
@Test
public void testViewUpdates() {
JsonObject o = new JsonObject();
Map<String, JsonElement> map = o.asMap();
o.addProperty("a", 1);
assertThat(map).hasSize(1);
assertThat(map.get("a")).isEqualTo(new JsonPrimitive(1));
map.put("b", new JsonPrimitive(2));
assertThat(o.size()).isEqualTo(2);
assertThat(map.get("b")).isEqualTo(new JsonPrimitive(2));
}
}
| JsonObjectAsMapTest |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/commit/LocalTempDir.java | {
"start": 1140,
"end": 1282
} | class ____ manages access to a temporary directory store, uses the
* directories listed in {@link Constants#BUFFER_DIR} for this.
*/
final | which |
java | apache__camel | dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/ThymeleafComponentBuilderFactory.java | {
"start": 5661,
"end": 6714
} | class ____
extends AbstractComponentBuilder<ThymeleafComponent>
implements ThymeleafComponentBuilder {
@Override
protected ThymeleafComponent buildConcreteComponent() {
return new ThymeleafComponent();
}
@Override
protected boolean setPropertyOnComponent(
Component component,
String name,
Object value) {
switch (name) {
case "allowContextMapAll": ((ThymeleafComponent) component).setAllowContextMapAll((boolean) value); return true;
case "allowTemplateFromHeader": ((ThymeleafComponent) component).setAllowTemplateFromHeader((boolean) value); return true;
case "lazyStartProducer": ((ThymeleafComponent) component).setLazyStartProducer((boolean) value); return true;
case "autowiredEnabled": ((ThymeleafComponent) component).setAutowiredEnabled((boolean) value); return true;
default: return false;
}
}
}
} | ThymeleafComponentBuilderImpl |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/grant/MySqlGrantTest_2.java | {
"start": 969,
"end": 2401
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "GRANT USAGE ON *.* TO 'jeffrey'@'localhost' WITH MAX_QUERIES_PER_HOUR 90";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
// print(statementList);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
String output = SQLUtils.toMySqlString(stmt);
assertEquals("GRANT USAGE ON *.* TO 'jeffrey'@'localhost' WITH MAX_QUERIES_PER_HOUR 90", //
output);
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(0, visitor.getColumns().size());
assertEquals(0, visitor.getConditions().size());
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("City")));
// assertTrue(visitor.getTables().containsKey(new TableStat.Name("t2")));
// assertTrue(visitor.getColumns().contains(new Column("t2", "id")));
}
}
| MySqlGrantTest_2 |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/catalog/CatalogView.java | {
"start": 1447,
"end": 1544
} | class ____ allows passing
* catalog-specific objects (if necessary).
*/
@PublicEvolving
public | that |
java | alibaba__nacos | plugin/control/src/main/java/com/alibaba/nacos/plugin/control/tps/response/TpsCheckResponse.java | {
"start": 725,
"end": 1465
} | class ____ {
private boolean success;
private int code;
private String message;
public TpsCheckResponse(boolean success, int code, String message) {
this.success = success;
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public void setSuccess(boolean success) {
this.success = success;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSuccess() {
return success;
}
public String getMessage() {
return message;
}
}
| TpsCheckResponse |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/ParallelThen.java | {
"start": 6350,
"end": 7805
} | class ____ implements InnerConsumer<Object> {
final ThenMain parent;
@SuppressWarnings("NotNullFieldNotInitialized") // s initialized in onSubscribe
volatile Subscription s;
// https://github.com/uber/NullAway/issues/1157
@SuppressWarnings({"rawtypes", "DataFlowIssue"})
static final AtomicReferenceFieldUpdater<ThenInner, @Nullable Subscription>
S = AtomicReferenceFieldUpdater.newUpdater(
ThenInner.class,
Subscription.class,
"s");
ThenInner(ThenMain parent) {
this.parent = parent;
}
@Override
public Context currentContext() {
return parent.actual.currentContext();
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.CANCELLED) return s == Operators.cancelledSubscription();
if (key == Attr.PARENT) return s;
if (key == Attr.ACTUAL) return parent;
if (key == Attr.PREFETCH) return Integer.MAX_VALUE;
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return null;
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.setOnce(S, this, s)) {
s.request(Long.MAX_VALUE);
}
}
@Override
public void onNext(Object t) {
//ignored
Operators.onDiscard(t, parent.actual.currentContext());
}
@Override
public void onError(Throwable t) {
parent.innerError(t, this);
}
@Override
public void onComplete() {
parent.innerComplete();
}
void cancel() {
Operators.terminate(S, this);
}
}
}
| ThenInner |
java | apache__camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultAutowiredLifecycleStrategy.java | {
"start": 1141,
"end": 2972
} | class ____ extends LifecycleStrategySupport implements AutowiredLifecycleStrategy, Ordered {
private final CamelContext camelContext;
public DefaultAutowiredLifecycleStrategy(CamelContext camelContext) {
this.camelContext = camelContext;
}
@Override
public int getOrder() {
// we should be last
return Ordered.LOWEST;
}
@Override
public void onComponentAdd(String name, Component component) {
autowireComponent(name, component);
}
@Override
public void onDataFormatCreated(String name, DataFormat dataFormat) {
autowireDataFormat(name, dataFormat);
}
@Override
public void onLanguageCreated(String name, Language language) {
autowireLanguage(name, language);
}
private void autowireComponent(String name, Component component) {
// autowiring can be turned off on context level and per component
boolean enabled = camelContext.isAutowiredEnabled() && component.isAutowiredEnabled();
if (enabled) {
autowire(name, "component", component);
}
}
private void autowireDataFormat(String name, DataFormat dataFormat) {
// autowiring can be turned off on context level
boolean enabled = camelContext.isAutowiredEnabled();
if (enabled) {
autowire(name, "dataformat", dataFormat);
}
}
private void autowireLanguage(String name, Language language) {
// autowiring can be turned off on context level
boolean enabled = camelContext.isAutowiredEnabled();
if (enabled) {
autowire(name, "language", language);
}
}
private void autowire(String name, String kind, Object target) {
doAutoWire(name, kind, target, camelContext);
}
}
| DefaultAutowiredLifecycleStrategy |
java | alibaba__fastjson | src/main/java/com/alibaba/fastjson/support/config/FastJsonConfig.java | {
"start": 1307,
"end": 5686
} | class ____ serializeFilter
*/
private Map<Class<?>, SerializeFilter> classSerializeFilters;
/**
* format date type
*/
private String dateFormat;
/**
* The Write content length.
*/
private boolean writeContentLength;
/**
* init param.
*/
public FastJsonConfig() {
this.charset = IOUtils.UTF8;
this.serializeConfig = SerializeConfig.getGlobalInstance();
this.parserConfig = ParserConfig.getGlobalInstance();
this.serializerFeatures = new SerializerFeature[] {
SerializerFeature.BrowserSecure
};
this.serializeFilters = new SerializeFilter[0];
this.features = new Feature[0];
this.writeContentLength = true;
}
/**
* @return the serializeConfig
*/
public SerializeConfig getSerializeConfig() {
return serializeConfig;
}
/**
* @param serializeConfig the serializeConfig to set
*/
public void setSerializeConfig(SerializeConfig serializeConfig) {
this.serializeConfig = serializeConfig;
}
/**
* @return the parserConfig
*/
public ParserConfig getParserConfig() {
return parserConfig;
}
/**
* @param parserConfig the parserConfig to set
*/
public void setParserConfig(ParserConfig parserConfig) {
this.parserConfig = parserConfig;
}
/**
* @return the serializerFeatures
*/
public SerializerFeature[] getSerializerFeatures() {
return serializerFeatures;
}
/**
* @param serializerFeatures the serializerFeatures to set
*/
public void setSerializerFeatures(SerializerFeature... serializerFeatures) {
this.serializerFeatures = serializerFeatures;
}
/**
* @return the serializeFilters
*/
public SerializeFilter[] getSerializeFilters() {
return serializeFilters;
}
/**
* @param serializeFilters the serializeFilters to set
*/
public void setSerializeFilters(SerializeFilter... serializeFilters) {
this.serializeFilters = serializeFilters;
}
/**
* @return the features
*/
public Feature[] getFeatures() {
return features;
}
/**
* @param features the features to set
*/
public void setFeatures(Feature... features) {
this.features = features;
}
/**
* @return the classSerializeFilters
*/
public Map<Class<?>, SerializeFilter> getClassSerializeFilters() {
return classSerializeFilters;
}
/**
* @param classSerializeFilters the classSerializeFilters to set
*/
public void setClassSerializeFilters(
Map<Class<?>, SerializeFilter> classSerializeFilters) {
if (classSerializeFilters == null)
return;
for (Entry<Class<?>, SerializeFilter> entry : classSerializeFilters.entrySet())
this.serializeConfig.addFilter(entry.getKey(), entry.getValue());
this.classSerializeFilters = classSerializeFilters;
}
/**
* @return the dateFormat
*/
public String getDateFormat() {
return dateFormat;
}
/**
* @param dateFormat the dateFormat to set
*/
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
/**
* @return the charset
*/
public Charset getCharset() {
return charset;
}
/**
* @param charset the charset to set
*/
public void setCharset(Charset charset) {
this.charset = charset;
}
/**
* Is write content length boolean.
*
* @return the boolean
*/
public boolean isWriteContentLength() {
return writeContentLength;
}
/**
* Sets write content length.
*
* @param writeContentLength the write content length
*/
public void setWriteContentLength(boolean writeContentLength) {
this.writeContentLength = writeContentLength;
}
/**
* Gets parse process.
*
* @return the parse process
*/
public ParseProcess getParseProcess() {
return parseProcess;
}
/**
* Sets parse process.
*
* @param parseProcess the parse process
*/
public void setParseProcess(ParseProcess parseProcess) {
this.parseProcess = parseProcess;
}
}
| level |
java | apache__camel | components/camel-ignite/src/main/java/org/apache/camel/component/ignite/AbstractIgniteComponent.java | {
"start": 2104,
"end": 4927
} | enum ____ {
USER_MANAGED,
COMPONENT_MANAGED
}
private IgniteLifecycleMode lifecycleMode = IgniteLifecycleMode.COMPONENT_MANAGED;
@Metadata
private IgniteConfiguration igniteConfiguration;
@Metadata
private Object configurationResource;
@Metadata
private Ignite ignite;
@Override
protected void doStart() throws Exception {
super.doStart();
if (lifecycleMode == IgniteLifecycleMode.USER_MANAGED) {
return;
}
// Try to load the configuration from the resource.
if (configurationResource != null) {
if (configurationResource instanceof URL) {
ignite = Ignition.start((URL) configurationResource);
} else if (configurationResource instanceof InputStream) {
ignite = Ignition.start((InputStream) configurationResource);
} else if (configurationResource instanceof String) {
ignite = Ignition.start((String) configurationResource);
} else {
throw new IllegalStateException(
"An unsupported configuration resource was provided to the Ignite component. "
+ "Supported types are: URL, InputStream, String.");
}
} else if (igniteConfiguration != null) {
ignite = Ignition.start(igniteConfiguration);
} else {
throw new IllegalStateException(
"No configuration resource or IgniteConfiguration was provided to the Ignite component.");
}
}
@Override
protected void doStop() throws Exception {
super.doStop();
if (lifecycleMode == IgniteLifecycleMode.USER_MANAGED) {
return;
}
if (ignite != null) {
ignite.close();
}
}
public Ignite getIgnite() {
return ignite;
}
/**
* To use an existing Ignite instance.
*/
public void setIgnite(Ignite ignite) {
this.ignite = ignite;
lifecycleMode = IgniteLifecycleMode.USER_MANAGED;
}
public Object getConfigurationResource() {
return configurationResource;
}
/**
* The resource from where to load the configuration. It can be a: URL, String or InputStream type.
*/
public void setConfigurationResource(Object configurationResource) {
this.configurationResource = configurationResource;
}
public IgniteConfiguration getIgniteConfiguration() {
return igniteConfiguration;
}
/**
* Allows the user to set a programmatic ignite configuration.
*/
public void setIgniteConfiguration(IgniteConfiguration igniteConfiguration) {
this.igniteConfiguration = igniteConfiguration;
}
}
| IgniteLifecycleMode |
java | quarkusio__quarkus | extensions/security/runtime/src/test/java/io/quarkus/security/runtime/QuarkusSecurityIdentityTest.java | {
"start": 849,
"end": 7437
} | class ____ {
@Test
public void testAddPermissionAsString() throws Exception {
SecurityIdentity identity = QuarkusSecurityIdentity.builder()
.setPrincipal(new QuarkusPrincipal("alice"))
.addPermissionAsString("read")
.build();
assertTrue(identity.checkPermissionBlocking(new StringPermission("read")));
assertFalse(identity.checkPermissionBlocking(new StringPermission("write")));
}
@Test
public void testAddPermissionWithActionAsString() throws Exception {
SecurityIdentity identity = QuarkusSecurityIdentity.builder()
.setPrincipal(new QuarkusPrincipal("alice"))
.addPermissionAsString("read:singledoc")
.build();
assertTrue(identity.checkPermissionBlocking(new StringPermission("read", "singledoc")));
assertFalse(identity.checkPermissionBlocking(new StringPermission("read", "all")));
assertFalse(identity.checkPermissionBlocking(new StringPermission("write")));
}
@Test
public void testAddPermissionsAsString() throws Exception {
SecurityIdentity identity = QuarkusSecurityIdentity.builder()
.setPrincipal(new QuarkusPrincipal("alice"))
.addPermissionsAsString(Set.of("read", "write"))
.build();
assertTrue(identity.checkPermissionBlocking(new StringPermission("read")));
assertTrue(identity.checkPermissionBlocking(new StringPermission("write")));
assertFalse(identity.checkPermissionBlocking(new StringPermission("comment")));
}
@Test
public void testAddPermissionsWithActionAsString() throws Exception {
SecurityIdentity identity = QuarkusSecurityIdentity.builder()
.setPrincipal(new QuarkusPrincipal("alice"))
.addPermissionsAsString(Set.of("read:singledoc", "write:singledoc"))
.build();
assertTrue(identity.checkPermissionBlocking(new StringPermission("read", "singledoc")));
assertTrue(identity.checkPermissionBlocking(new StringPermission("write", "singledoc")));
assertFalse(identity.checkPermissionBlocking(new StringPermission("read:all")));
assertFalse(identity.checkPermissionBlocking(new StringPermission("write:all")));
assertFalse(identity.checkPermissionBlocking(new StringPermission("comment")));
}
@Test
public void testAddPermission() throws Exception {
SecurityIdentity identity = QuarkusSecurityIdentity.builder()
.setPrincipal(new QuarkusPrincipal("alice"))
.addPermission(new StringPermission("read"))
.build();
assertTrue(identity.checkPermissionBlocking(new StringPermission("read")));
assertFalse(identity.checkPermissionBlocking(new StringPermission("write")));
}
@Test
public void testAddPermissions() throws Exception {
SecurityIdentity identity = QuarkusSecurityIdentity.builder()
.setPrincipal(new QuarkusPrincipal("alice"))
.addPermissions(Set.of(new StringPermission("read"), new StringPermission("write")))
.build();
assertTrue(identity.checkPermissionBlocking(new StringPermission("read")));
assertTrue(identity.checkPermissionBlocking(new StringPermission("write")));
assertFalse(identity.checkPermissionBlocking(new StringPermission("comment")));
}
@Test
public void testConvertStringToPermission() throws Exception {
assertEquals(toPermission("read"), new StringPermission("read"));
assertEquals(toPermission("read:d"), new StringPermission("read", "d"));
assertEquals(toPermission("read:"), new StringPermission("read:"));
assertEquals(toPermission(":read"), new StringPermission(":read"));
}
@Test
public void testCopyIdentity() throws Exception {
SecurityIdentity identity1 = QuarkusSecurityIdentity.builder()
.setPrincipal(new QuarkusPrincipal("alice"))
.addRole("admin")
.addCredential(new PasswordCredential("password".toCharArray()))
.addAttribute("key", "value")
.build();
assertFalse(identity1.isAnonymous());
SecurityIdentity identity2 = QuarkusSecurityIdentity.builder(identity1).build();
assertFalse(identity1.isAnonymous());
assertEquals(identity1.getAttributes(), identity2.getAttributes());
assertEquals(identity1.getPrincipal(), identity2.getPrincipal());
assertEquals(identity1.getCredentials(), identity2.getCredentials());
assertEquals(identity1.getRoles(), identity2.getRoles());
}
@Test
public void testAnonymousPrincipalWithCustomIdentity() throws Exception {
SecurityIdentity identity1 = new TestSecurityIdentityAnonymousPrincipal();
assertTrue(identity1.isAnonymous());
assertEquals("anonymous-principal", identity1.getPrincipal().getName());
SecurityIdentity identity2 = QuarkusSecurityIdentity.builder(identity1).build();
assertTrue(identity2.isAnonymous());
assertEquals("anonymous-principal", identity2.getPrincipal().getName());
}
@Test
public void testPrincipalNullAnonymousFalseWithBuilder() throws Exception {
QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder()
.addRole("admin")
.addCredential(new PasswordCredential("password".toCharArray()))
.addAttribute("key", "value");
;
assertThrows(IllegalStateException.class, () -> builder.build());
}
@Test
public void testPrincipalNullAnonymousFalseWithCustomIdentity() throws Exception {
SecurityIdentity identity1 = new TestSecurityIdentityPrincipalNullAnonymousFalse();
assertFalse(identity1.isAnonymous());
assertNull(identity1.getPrincipal());
assertThrows(IllegalStateException.class, () -> QuarkusSecurityIdentity.builder(identity1).build());
}
@Test
public void testPrincipalNullAnonymousFalseWithCustomIdentityFixed() throws Exception {
SecurityIdentity identity1 = new TestSecurityIdentityPrincipalNullAnonymousFalse();
assertFalse(identity1.isAnonymous());
assertNull(identity1.getPrincipal());
SecurityIdentity identity2 = QuarkusSecurityIdentity.builder(identity1).setAnonymous(true).build();
assertTrue(identity2.isAnonymous());
assertNull(identity2.getPrincipal());
}
static | QuarkusSecurityIdentityTest |
java | alibaba__nacos | client/src/main/java/com/alibaba/nacos/client/naming/remote/gprc/redo/data/InstanceRedoData.java | {
"start": 816,
"end": 1550
} | class ____ extends NamingRedoData<Instance> {
protected InstanceRedoData(String serviceName, String groupName) {
super(serviceName, groupName);
}
/**
* Build a new {@code RedoData} for register service instance.
*
* @param serviceName service name for redo data
* @param groupName group name for redo data
* @param instance instance for redo data
* @return new {@code RedoData} for register service instance
*/
public static InstanceRedoData build(String serviceName, String groupName, Instance instance) {
InstanceRedoData result = new InstanceRedoData(serviceName, groupName);
result.set(instance);
return result;
}
}
| InstanceRedoData |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SagaEndpointBuilderFactory.java | {
"start": 4354,
"end": 6479
} | interface ____ {
/**
* Saga (camel-saga)
* Execute custom actions within a route using the Saga EIP.
*
* Category: clustering
* Since: 2.21
* Maven coordinates: org.apache.camel:camel-saga
*
* @return the dsl builder for the headers' name.
*/
default SagaHeaderNameBuilder saga() {
return SagaHeaderNameBuilder.INSTANCE;
}
/**
* Saga (camel-saga)
* Execute custom actions within a route using the Saga EIP.
*
* Category: clustering
* Since: 2.21
* Maven coordinates: org.apache.camel:camel-saga
*
* Syntax: <code>saga:action</code>
*
* Path parameter: action (required)
* Action to execute (complete or compensate)
* There are 2 enums and the value can be one of: COMPLETE, COMPENSATE
*
* @param path action
* @return the dsl builder
*/
default SagaEndpointBuilder saga(String path) {
return SagaEndpointBuilderFactory.endpointBuilder("saga", path);
}
/**
* Saga (camel-saga)
* Execute custom actions within a route using the Saga EIP.
*
* Category: clustering
* Since: 2.21
* Maven coordinates: org.apache.camel:camel-saga
*
* Syntax: <code>saga:action</code>
*
* Path parameter: action (required)
* Action to execute (complete or compensate)
* There are 2 enums and the value can be one of: COMPLETE, COMPENSATE
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path action
* @return the dsl builder
*/
default SagaEndpointBuilder saga(String componentName, String path) {
return SagaEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the Saga component.
*/
public static | SagaBuilders |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/error/ElementsShouldHaveAtMost_create_Test.java | {
"start": 1224,
"end": 1843
} | class ____ {
@Test
void should_create_error_message() {
// GIVEN
ErrorMessageFactory factory = elementsShouldHaveAtMost(list("Yoda", "Luke", "Obiwan"), 2, new TestCondition<>("Jedi power"));
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting elements:%n" +
" [\"Yoda\", \"Luke\", \"Obiwan\"]%n" +
"to have at most 2 times Jedi power"));
}
}
| ElementsShouldHaveAtMost_create_Test |
java | apache__flink | flink-python/src/main/java/org/apache/flink/table/runtime/typeutils/PythonTypeUtils.java | {
"start": 9434,
"end": 20684
} | class ____
extends LogicalTypeDefaultVisitor<FlinkFnApi.Schema.FieldType> {
@Override
public FlinkFnApi.Schema.FieldType visit(BooleanType booleanType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.BOOLEAN)
.setNullable(booleanType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(TinyIntType tinyIntType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.TINYINT)
.setNullable(tinyIntType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(SmallIntType smallIntType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.SMALLINT)
.setNullable(smallIntType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(IntType intType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.INT)
.setNullable(intType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(BigIntType bigIntType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.BIGINT)
.setNullable(bigIntType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(FloatType floatType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.FLOAT)
.setNullable(floatType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(DoubleType doubleType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.DOUBLE)
.setNullable(doubleType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(BinaryType binaryType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.BINARY)
.setBinaryInfo(
FlinkFnApi.Schema.BinaryInfo.newBuilder()
.setLength(binaryType.getLength()))
.setNullable(binaryType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(VarBinaryType varBinaryType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.VARBINARY)
.setVarBinaryInfo(
FlinkFnApi.Schema.VarBinaryInfo.newBuilder()
.setLength(varBinaryType.getLength()))
.setNullable(varBinaryType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(CharType charType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.CHAR)
.setCharInfo(
FlinkFnApi.Schema.CharInfo.newBuilder().setLength(charType.getLength()))
.setNullable(charType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(VarCharType varCharType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.VARCHAR)
.setVarCharInfo(
FlinkFnApi.Schema.VarCharInfo.newBuilder()
.setLength(varCharType.getLength()))
.setNullable(varCharType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(DateType dateType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.DATE)
.setNullable(dateType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(TimeType timeType) {
return FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.TIME)
.setTimeInfo(
FlinkFnApi.Schema.TimeInfo.newBuilder()
.setPrecision(timeType.getPrecision()))
.setNullable(timeType.isNullable())
.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(TimestampType timestampType) {
FlinkFnApi.Schema.FieldType.Builder builder =
FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.TIMESTAMP)
.setNullable(timestampType.isNullable());
FlinkFnApi.Schema.TimestampInfo.Builder timestampInfoBuilder =
FlinkFnApi.Schema.TimestampInfo.newBuilder()
.setPrecision(timestampType.getPrecision());
builder.setTimestampInfo(timestampInfoBuilder);
return builder.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(LocalZonedTimestampType localZonedTimestampType) {
FlinkFnApi.Schema.FieldType.Builder builder =
FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.LOCAL_ZONED_TIMESTAMP)
.setNullable(localZonedTimestampType.isNullable());
FlinkFnApi.Schema.LocalZonedTimestampInfo.Builder dateTimeBuilder =
FlinkFnApi.Schema.LocalZonedTimestampInfo.newBuilder()
.setPrecision(localZonedTimestampType.getPrecision());
builder.setLocalZonedTimestampInfo(dateTimeBuilder.build());
return builder.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(DecimalType decimalType) {
FlinkFnApi.Schema.FieldType.Builder builder =
FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.DECIMAL)
.setNullable(decimalType.isNullable());
FlinkFnApi.Schema.DecimalInfo.Builder decimalInfoBuilder =
FlinkFnApi.Schema.DecimalInfo.newBuilder()
.setPrecision(decimalType.getPrecision())
.setScale(decimalType.getScale());
builder.setDecimalInfo(decimalInfoBuilder);
return builder.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(ArrayType arrayType) {
FlinkFnApi.Schema.FieldType.Builder builder =
FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.BASIC_ARRAY)
.setNullable(arrayType.isNullable());
FlinkFnApi.Schema.FieldType elementFieldType = arrayType.getElementType().accept(this);
builder.setCollectionElementType(elementFieldType);
return builder.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(MapType mapType) {
FlinkFnApi.Schema.FieldType.Builder builder =
FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.MAP)
.setNullable(mapType.isNullable());
FlinkFnApi.Schema.MapInfo.Builder mapBuilder =
FlinkFnApi.Schema.MapInfo.newBuilder()
.setKeyType(mapType.getKeyType().accept(this))
.setValueType(mapType.getValueType().accept(this));
builder.setMapInfo(mapBuilder.build());
return builder.build();
}
@Override
public FlinkFnApi.Schema.FieldType visit(RowType rowType) {
FlinkFnApi.Schema.FieldType.Builder builder =
FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.ROW)
.setNullable(rowType.isNullable());
FlinkFnApi.Schema.Builder schemaBuilder = FlinkFnApi.Schema.newBuilder();
for (RowType.RowField field : rowType.getFields()) {
schemaBuilder.addFields(
FlinkFnApi.Schema.Field.newBuilder()
.setName(field.getName())
.setDescription(field.getDescription().orElse(EMPTY_STRING))
.setType(field.getType().accept(this))
.build());
}
builder.setRowSchema(schemaBuilder.build());
return builder.build();
}
@Override
protected FlinkFnApi.Schema.FieldType defaultMethod(LogicalType logicalType) {
if (logicalType instanceof LegacyTypeInformationType) {
Class<?> typeClass =
((LegacyTypeInformationType) logicalType)
.getTypeInformation()
.getTypeClass();
if (typeClass == BigDecimal.class) {
FlinkFnApi.Schema.FieldType.Builder builder =
FlinkFnApi.Schema.FieldType.newBuilder()
.setTypeName(FlinkFnApi.Schema.TypeName.DECIMAL)
.setNullable(logicalType.isNullable());
// Because we can't get precision and scale from legacy BIG_DEC_TYPE_INFO,
// we set the precision and scale to default value compatible with python.
FlinkFnApi.Schema.DecimalInfo.Builder decimalTypeBuilder =
FlinkFnApi.Schema.DecimalInfo.newBuilder()
.setPrecision(38)
.setScale(18);
builder.setDecimalInfo(decimalTypeBuilder);
return builder.build();
}
}
throw new UnsupportedOperationException(
String.format(
"Python UDF doesn't support logical type %s currently.",
logicalType.asSummaryString()));
}
}
/** Data Converter that converts the data to the java format data which can be used in PemJa. */
public abstract static | LogicalTypeToProtoTypeConverter |
java | netty__netty | common/src/test/java/io/netty/util/concurrent/FastThreadLocalTest.java | {
"start": 6861,
"end": 11700
} | class ____ implements Runnable {
final Semaphore semaphore = new Semaphore(0);
final FutureTask<?> task = new FutureTask<>(this, null);
@Override
public void run() {
assertFalse(FastThreadLocalThread.currentThreadWillCleanupFastThreadLocals());
assertFalse(FastThreadLocalThread.currentThreadHasFastThreadLocal());
semaphore.acquireUninterruptibly();
FastThreadLocalThread.runWithFastThreadLocal(() -> {
assertTrue(FastThreadLocalThread.currentThreadWillCleanupFastThreadLocals());
assertTrue(FastThreadLocalThread.currentThreadHasFastThreadLocal());
semaphore.acquireUninterruptibly();
assertTrue(FastThreadLocalThread.currentThreadWillCleanupFastThreadLocals());
assertTrue(FastThreadLocalThread.currentThreadHasFastThreadLocal());
});
assertFalse(FastThreadLocalThread.currentThreadWillCleanupFastThreadLocals());
assertFalse(FastThreadLocalThread.currentThreadHasFastThreadLocal());
}
}
int n = 100;
List<Worker> workers = new ArrayList<>();
for (int i = 0; i < n; i++) {
Worker worker = new Worker();
workers.add(worker);
}
Collections.shuffle(workers);
for (int i = 0; i < workers.size(); i++) {
new Thread(workers.get(i).task, "worker-" + i).start();
}
for (int i = 0; i < 2; i++) {
Collections.shuffle(workers);
for (Worker worker : workers) {
worker.semaphore.release();
}
}
for (Worker worker : workers) {
worker.task.get();
}
}
@Test
@Timeout(value = 4000, unit = TimeUnit.MILLISECONDS)
public void testOnRemoveCalledForFastThreadLocalGet() throws Exception {
testOnRemoveCalled(true, false, true);
}
@Disabled("onRemoval(...) not called with non FastThreadLocal")
@Test
@Timeout(value = 4000, unit = TimeUnit.MILLISECONDS)
public void testOnRemoveCalledForNonFastThreadLocalGet() throws Exception {
testOnRemoveCalled(false, false, true);
}
@Test
@Timeout(value = 4000, unit = TimeUnit.MILLISECONDS)
public void testOnRemoveCalledForFastThreadLocalSet() throws Exception {
testOnRemoveCalled(true, false, false);
}
@Disabled("onRemoval(...) not called with non FastThreadLocal")
@Test
@Timeout(value = 4000, unit = TimeUnit.MILLISECONDS)
public void testOnRemoveCalledForNonFastThreadLocalSet() throws Exception {
testOnRemoveCalled(false, false, false);
}
@Test
@Timeout(value = 4000, unit = TimeUnit.MILLISECONDS)
public void testOnRemoveCalledForWrappedGet() throws Exception {
testOnRemoveCalled(false, true, true);
}
@Test
@Timeout(value = 4000, unit = TimeUnit.MILLISECONDS)
public void testOnRemoveCalledForWrappedSet() throws Exception {
testOnRemoveCalled(false, true, false);
}
private static void testOnRemoveCalled(boolean fastThreadLocal, boolean wrap, final boolean callGet)
throws Exception {
final TestFastThreadLocal threadLocal = new TestFastThreadLocal();
final TestFastThreadLocal threadLocal2 = new TestFastThreadLocal();
Runnable runnable = new Runnable() {
@Override
public void run() {
if (callGet) {
assertEquals(Thread.currentThread().getName(), threadLocal.get());
assertEquals(Thread.currentThread().getName(), threadLocal2.get());
} else {
threadLocal.set(Thread.currentThread().getName());
threadLocal2.set(Thread.currentThread().getName());
}
}
};
if (wrap) {
Runnable r = runnable;
runnable = () -> FastThreadLocalThread.runWithFastThreadLocal(r);
}
Thread thread = fastThreadLocal ? new FastThreadLocalThread(runnable) : new Thread(runnable);
thread.start();
thread.join();
String threadName = thread.getName();
// Null this out so it can be collected
thread = null;
// Loop until onRemoval(...) was called. This will fail the test if this not works due a timeout.
while (threadLocal.onRemovalCalled.get() == null || threadLocal2.onRemovalCalled.get() == null) {
System.gc();
System.runFinalization();
Thread.sleep(50);
}
assertEquals(threadName, threadLocal.onRemovalCalled.get());
assertEquals(threadName, threadLocal2.onRemovalCalled.get());
}
private static final | Worker |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/util/Timer.java | {
"start": 1462,
"end": 8556
} | enum ____ {
Started,
Stopped,
Paused
}
private Status status; // The timer's status
private long elapsedTime; // The elapsed time
private final int iterations;
private static long NANO_PER_SECOND = 1000000000L;
private static long NANO_PER_MINUTE = NANO_PER_SECOND * 60;
private static long NANO_PER_HOUR = NANO_PER_MINUTE * 60;
private ThreadLocal<Long> startTime = new ThreadLocal<Long>() {
@Override
protected Long initialValue() {
return 0L;
}
};
/**
* Constructor.
* @param name the timer name.
*/
public Timer(final String name) {
this(name, 0);
}
/**
* Constructor.
*
* @param name the timer name.
*/
public Timer(final String name, final int iterations) {
this.name = name;
status = Status.Stopped;
this.iterations = (iterations > 0) ? iterations : 0;
}
/**
* Start the timer.
*/
public synchronized void start() {
startTime.set(System.nanoTime());
elapsedTime = 0;
status = Status.Started;
}
public synchronized void startOrResume() {
if (status == Status.Stopped) {
start();
} else {
resume();
}
}
/**
* Stop the timer.
*/
public synchronized String stop() {
elapsedTime += System.nanoTime() - startTime.get();
startTime.set(0L);
status = Status.Stopped;
return toString();
}
/**
* Pause the timer.
*/
public synchronized void pause() {
elapsedTime += System.nanoTime() - startTime.get();
startTime.set(0L);
status = Status.Paused;
}
/**
* Resume the timer.
*/
public synchronized void resume() {
startTime.set(System.nanoTime());
status = Status.Started;
}
/**
* Accessor for the name.
* @return the timer's name.
*/
public String getName() {
return name;
}
/**
* Access the elapsed time.
*
* @return the elapsed time.
*/
public long getElapsedTime() {
return elapsedTime / 1000000;
}
/**
* Access the elapsed time.
*
* @return the elapsed time.
*/
public long getElapsedNanoTime() {
return elapsedTime;
}
/**
* Returns the name of the last operation performed on this timer (Start, Stop, Pause or
* Resume).
* @return the string representing the last operation performed.
*/
public Status getStatus() {
return status;
}
/**
* Returns the String representation of the timer based upon its current state
*/
@Override
public String toString() {
final StringBuilder result = new StringBuilder();
formatTo(result);
return result.toString();
}
@Override
public void formatTo(final StringBuilder buffer) {
buffer.append("Timer ").append(name);
switch (status) {
case Started:
buffer.append(" started");
break;
case Paused:
buffer.append(" paused");
break;
case Stopped:
long nanoseconds = elapsedTime;
// Get elapsed hours
long hours = nanoseconds / NANO_PER_HOUR;
// Get remaining nanoseconds
nanoseconds = nanoseconds % NANO_PER_HOUR;
// Get minutes
long minutes = nanoseconds / NANO_PER_MINUTE;
// Get remaining nanoseconds
nanoseconds = nanoseconds % NANO_PER_MINUTE;
// Get seconds
long seconds = nanoseconds / NANO_PER_SECOND;
// Get remaining nanoseconds
nanoseconds = nanoseconds % NANO_PER_SECOND;
String elapsed = Strings.EMPTY;
if (hours > 0) {
elapsed += hours + " hours ";
}
if (minutes > 0 || hours > 0) {
elapsed += minutes + " minutes ";
}
DecimalFormat numFormat;
numFormat = new DecimalFormat("#0");
elapsed += numFormat.format(seconds) + '.';
numFormat = new DecimalFormat("000000000");
elapsed += numFormat.format(nanoseconds) + " seconds";
buffer.append(" stopped. Elapsed time: ").append(elapsed);
if (iterations > 0) {
nanoseconds = elapsedTime / iterations;
// Get elapsed hours
hours = nanoseconds / NANO_PER_HOUR;
// Get remaining nanoseconds
nanoseconds = nanoseconds % NANO_PER_HOUR;
// Get minutes
minutes = nanoseconds / NANO_PER_MINUTE;
// Get remaining nanoseconds
nanoseconds = nanoseconds % NANO_PER_MINUTE;
// Get seconds
seconds = nanoseconds / NANO_PER_SECOND;
// Get remaining nanoseconds
nanoseconds = nanoseconds % NANO_PER_SECOND;
elapsed = Strings.EMPTY;
if (hours > 0) {
elapsed += hours + " hours ";
}
if (minutes > 0 || hours > 0) {
elapsed += minutes + " minutes ";
}
numFormat = new DecimalFormat("#0");
elapsed += numFormat.format(seconds) + '.';
numFormat = new DecimalFormat("000000000");
elapsed += numFormat.format(nanoseconds) + " seconds";
buffer.append(" Average per iteration: ").append(elapsed);
}
break;
default:
buffer.append(' ').append(status);
break;
}
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Timer)) {
return false;
}
final Timer timer = (Timer) o;
if (elapsedTime != timer.elapsedTime) {
return false;
}
if (startTime != timer.startTime) {
return false;
}
if (name != null ? !name.equals(timer.name) : timer.name != null) {
return false;
}
if (status != null ? !status.equals(timer.status) : timer.status != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result;
result = (name != null ? name.hashCode() : 0);
result = 29 * result + (status != null ? status.hashCode() : 0);
final long time = startTime.get();
result = 29 * result + (int) (time ^ (time >>> 32));
result = 29 * result + (int) (elapsedTime ^ (elapsedTime >>> 32));
return result;
}
}
| Status |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/struct/UnwrappedDoubleWithAnySetter3277Test.java | {
"start": 600,
"end": 871
} | class ____ {
Object value1;
@JsonUnwrapped
Holder2 holder2;
public Object getValue1() {
return value1;
}
public void setValue1(Object value1) {
this.value1 = value1;
}
}
static | Holder |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/filter/wall/sqlserver/SQLServerWallPermitObjectTest.java | {
"start": 853,
"end": 1951
} | class ____ extends TestCase {
/**
* @param name
*/
public SQLServerWallPermitObjectTest(String name) {
super(name);
}
/*
* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
}
/*
* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
super.tearDown();
}
public void test_user() throws Exception {
assertTrue(WallUtils.isValidateSqlServer("SELECT user;"));
}
public void test_user2() throws Exception {
assertFalse(WallUtils.isValidateSqlServer("SELECT id from T where 1=1 and 1!=1 union select user;"));
}
public void test_system_user() throws Exception {
assertTrue(WallUtils.isValidateSqlServer("SELECT system_user;"));
}
public void test_system_user2() throws Exception {
assertFalse(WallUtils.isValidateSqlServer("SELECT id from T where 1=1 and 1!=1 union select system_user;"));
}
}
| SQLServerWallPermitObjectTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/javatime/JavaTimeJdbcTypeBaselineTests.java | {
"start": 1508,
"end": 2483
} | class ____ {
@Test
void testMappings(DomainModelScope scope) {
final PersistentClass entityBinding = scope.getEntityBinding( EntityWithJavaTimeValues.class );
checkAttribute( entityBinding, "theLocalDate", DateJdbcType.class );
checkAttribute( entityBinding, "theLocalDateTime", TimestampJdbcType.class );
checkAttribute( entityBinding, "theLocalTime", TimeJdbcType.class );
}
private void checkAttribute(
PersistentClass entityBinding,
String attributeName,
Class<?> expectedJdbcTypeDescriptorType) {
final Property property = entityBinding.getProperty( attributeName );
final BasicValue value = (BasicValue) property.getValue();
final BasicValue.Resolution<?> resolution = value.resolve();
final JdbcType jdbcType = resolution.getJdbcType();
assertThat( jdbcType ).isInstanceOf( expectedJdbcTypeDescriptorType );
}
@Entity(name="EntityWithJavaTimeValues")
@Table(name="EntityWithJavaTimeValues")
public static | JavaTimeJdbcTypeBaselineTests |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/ReencryptionHandler.java | {
"start": 30696,
"end": 30944
} | class ____ extends TraverseInfo {
private String ezKeyVerName;
ZoneTraverseInfo(String ezKeyVerName) {
this.ezKeyVerName = ezKeyVerName;
}
public String getEzKeyVerName() {
return ezKeyVerName;
}
}
}
| ZoneTraverseInfo |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/TestingJobMasterPartitionTracker.java | {
"start": 1546,
"end": 6738
} | class ____ implements JobMasterPartitionTracker {
private Function<ResourceID, Boolean> isTrackingPartitionsForFunction = ignored -> false;
private Function<ResultPartitionID, Boolean> isPartitionTrackedFunction = ignored -> false;
private Consumer<ResourceID> stopTrackingAllPartitionsConsumer = ignored -> {};
private BiConsumer<ResourceID, ResultPartitionDeploymentDescriptor>
startTrackingPartitionsConsumer = (ignoredA, ignoredB) -> {};
private Consumer<Collection<ResultPartitionID>> stopTrackingAndReleasePartitionsConsumer =
ignored -> {};
private Consumer<Collection<ResultPartitionID>> stopTrackingAndPromotePartitionsConsumer =
ignored -> {};
private Consumer<Collection<ResultPartitionID>> stopTrackingPartitionsConsumer = ignored -> {};
private Supplier<Collection<ResultPartitionDeploymentDescriptor>>
getAllTrackedPartitionsSupplier = () -> Collections.emptyList();
public void setStartTrackingPartitionsConsumer(
BiConsumer<ResourceID, ResultPartitionDeploymentDescriptor>
startTrackingPartitionsConsumer) {
this.startTrackingPartitionsConsumer = startTrackingPartitionsConsumer;
}
public void setIsTrackingPartitionsForFunction(
Function<ResourceID, Boolean> isTrackingPartitionsForFunction) {
this.isTrackingPartitionsForFunction = isTrackingPartitionsForFunction;
}
public void setIsPartitionTrackedFunction(
Function<ResultPartitionID, Boolean> isPartitionTrackedFunction) {
this.isPartitionTrackedFunction = isPartitionTrackedFunction;
}
public void setStopTrackingAllPartitionsConsumer(
Consumer<ResourceID> stopTrackingAllPartitionsConsumer) {
this.stopTrackingAllPartitionsConsumer = stopTrackingAllPartitionsConsumer;
}
public void setStopTrackingAndReleasePartitionsConsumer(
Consumer<Collection<ResultPartitionID>> stopTrackingAndReleasePartitionsConsumer) {
this.stopTrackingAndReleasePartitionsConsumer = stopTrackingAndReleasePartitionsConsumer;
}
public void setStopTrackingPartitionsConsumer(
Consumer<Collection<ResultPartitionID>> stopTrackingPartitionsConsumer) {
this.stopTrackingPartitionsConsumer = stopTrackingPartitionsConsumer;
}
public void setGetAllTrackedPartitionsSupplier(
Supplier<Collection<ResultPartitionDeploymentDescriptor>>
getAllTrackedPartitionsSupplier) {
this.getAllTrackedPartitionsSupplier = getAllTrackedPartitionsSupplier;
}
public void setStopTrackingAndPromotePartitionsConsumer(
Consumer<Collection<ResultPartitionID>> stopTrackingAndPromotePartitionsConsumer) {
this.stopTrackingAndPromotePartitionsConsumer = stopTrackingAndPromotePartitionsConsumer;
}
@Override
public void startTrackingPartition(
ResourceID producingTaskExecutorId,
ResultPartitionDeploymentDescriptor resultPartitionDeploymentDescriptor) {
this.startTrackingPartitionsConsumer.accept(
producingTaskExecutorId, resultPartitionDeploymentDescriptor);
}
@Override
public Collection<PartitionTrackerEntry<ResourceID, ResultPartitionDeploymentDescriptor>>
stopTrackingPartitionsFor(ResourceID producingTaskExecutorId) {
stopTrackingAllPartitionsConsumer.accept(producingTaskExecutorId);
return Collections.emptyList();
}
@Override
public void stopTrackingAndReleasePartitions(
Collection<ResultPartitionID> resultPartitionIds, boolean releaseOnShuffleMaster) {
stopTrackingAndReleasePartitionsConsumer.accept(resultPartitionIds);
}
@Override
public CompletableFuture<Void> stopTrackingAndPromotePartitions(
Collection<ResultPartitionID> resultPartitionIds) {
stopTrackingAndPromotePartitionsConsumer.accept(resultPartitionIds);
return CompletableFuture.completedFuture(null);
}
@Override
public Collection<PartitionTrackerEntry<ResourceID, ResultPartitionDeploymentDescriptor>>
stopTrackingPartitions(Collection<ResultPartitionID> resultPartitionIds) {
stopTrackingPartitionsConsumer.accept(resultPartitionIds);
return Collections.emptyList();
}
@Override
public Collection<ResultPartitionDeploymentDescriptor> getAllTrackedPartitions() {
return getAllTrackedPartitionsSupplier.get();
}
@Override
public void connectToResourceManager(ResourceManagerGateway resourceManagerGateway) {}
@Override
public List<ShuffleDescriptor> getClusterPartitionShuffleDescriptors(
IntermediateDataSetID intermediateDataSetID) {
return Collections.emptyList();
}
@Override
public boolean isTrackingPartitionsFor(ResourceID producingTaskExecutorId) {
return isTrackingPartitionsForFunction.apply(producingTaskExecutorId);
}
@Override
public boolean isPartitionTracked(final ResultPartitionID resultPartitionID) {
return isPartitionTrackedFunction.apply(resultPartitionID);
}
}
| TestingJobMasterPartitionTracker |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/json/SQLServerJsonValueFunction.java | {
"start": 636,
"end": 2475
} | class ____ extends JsonValueFunction {
public SQLServerJsonValueFunction(TypeConfiguration typeConfiguration) {
super( typeConfiguration, true, false );
}
@Override
protected void render(
SqlAppender sqlAppender,
JsonValueArguments arguments,
ReturnableType<?> returnType,
SqlAstTranslator<?> walker) {
// openjson errors by default
if ( arguments.errorBehavior() != null && arguments.errorBehavior() != JsonValueErrorBehavior.ERROR ) {
throw new QueryException( "Can't emulate on error clause on SQL server" );
}
sqlAppender.appendSql( "(select v from openjson(" );
arguments.jsonDocument().accept( walker );
sqlAppender.appendSql( ") with (v " );
if ( arguments.returningType() != null ) {
arguments.returningType().accept( walker );
}
else {
sqlAppender.appendSql( "nvarchar(max)" );
}
sqlAppender.appendSql( ' ' );
final JsonPathPassingClause passingClause = arguments.passingClause();
if ( arguments.emptyBehavior() != null && arguments.emptyBehavior() != JsonValueEmptyBehavior.NULL ) {
// The strict modifier will cause an error to be thrown if a field doesn't exist
if ( passingClause != null ) {
JsonPathHelper.appendInlinedJsonPathIncludingPassingClause(
sqlAppender,
"strict ",
arguments.jsonPath(),
passingClause,
walker
);
}
else {
walker.getSessionFactory().getJdbcServices().getDialect().appendLiteral(
sqlAppender,
"strict " + walker.getLiteralValue( arguments.jsonPath() )
);
}
}
else if ( passingClause != null ) {
JsonPathHelper.appendInlinedJsonPathIncludingPassingClause(
sqlAppender,
"",
arguments.jsonPath(),
passingClause,
walker
);
}
else {
arguments.jsonPath().accept( walker );
}
sqlAppender.appendSql( "))" );
}
}
| SQLServerJsonValueFunction |
java | spring-projects__spring-data-jpa | spring-data-envers/src/main/java/org/springframework/data/envers/repository/config/EnableEnversRepositories.java | {
"start": 5086,
"end": 5387
} | class ____ be used for each repository instance. Defaults to
* {@link JpaRepositoryFactoryBean}.
*
* @return
*/
@AliasFor(annotation = EnableJpaRepositories.class)
Class<?> repositoryFactoryBeanClass() default EnversRevisionRepositoryFactoryBean.class;
/**
* Configure the repository base | to |
java | spring-projects__spring-security | oauth2/oauth2-jose/src/test/java/org/springframework/security/oauth2/jwt/NimbusJwtEncoderTests.java | {
"start": 21908,
"end": 22864
} | class ____ implements JWKSource<SecurityContext> {
private int keyId = 1000;
private JWKSet jwkSet;
private TestJWKSource() {
init();
}
@Override
public List<JWK> get(JWKSelector jwkSelector, SecurityContext context) {
return jwkSelector.select(this.jwkSet);
}
private void init() {
// @formatter:off
RSAKey rsaJwk = TestJwks.jwk(TestKeys.DEFAULT_PUBLIC_KEY, TestKeys.DEFAULT_PRIVATE_KEY)
.keyID("rsa-jwk-" + this.keyId++)
.build();
ECKey ecJwk = TestJwks.jwk((ECPublicKey) TestKeys.DEFAULT_EC_KEY_PAIR.getPublic(), (ECPrivateKey) TestKeys.DEFAULT_EC_KEY_PAIR.getPrivate())
.keyID("ec-jwk-" + this.keyId++)
.build();
OctetSequenceKey secretJwk = TestJwks.jwk(TestKeys.DEFAULT_SECRET_KEY)
.keyID("secret-jwk-" + this.keyId++)
.build();
// @formatter:on
this.jwkSet = new JWKSet(Arrays.asList(rsaJwk, ecJwk, secretJwk));
}
private void rotate() {
init();
}
}
}
| TestJWKSource |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/proxy/filter/MergeStatFilterTest3.java | {
"start": 876,
"end": 1959
} | class ____ extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xx");
dataSource.setFilters("mergeStat");
dataSource.setDbType("postgresql");
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void test_merge() throws Exception {
String sqllist = Utils.read(new InputStreamReader(this.getClass().getResourceAsStream("/bvt/parser/postgresql/16.txt")));
String[] ss = sqllist.split("--------------------");
for (String sql : ss) {
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
stmt.execute(sql);
stmt.close();
conn.close();
}
assertEquals(1, dataSource.getDataSourceStat().getSqlStatMap()
.size());
System.out.println(dataSource.getDataSourceStat().getSqlStatMap().keySet().iterator().next());
}
}
| MergeStatFilterTest3 |
java | quarkusio__quarkus | extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/security/AuthorizationPolicyStorage.java | {
"start": 1039,
"end": 1646
} | class ____ {
private final Map<MethodDescription, String> methodToPolicyName = new HashMap<>();
public MethodsToPolicyBuilder() {
}
public MethodsToPolicyBuilder addMethodToPolicyName(String policyName, String className, String methodName,
String[] parameterTypes) {
methodToPolicyName.put(new MethodDescription(className, methodName, parameterTypes), policyName);
return this;
}
public Map<MethodDescription, String> build() {
return Map.copyOf(methodToPolicyName);
}
}
}
| MethodsToPolicyBuilder |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java | {
"start": 43698,
"end": 44194
} | class ____ implements
ArgumentMatcher<LocalizationEvent> {
Container c;
LocalizationCleanupMatcher(Container c){
this.c = c;
}
@Override
public boolean matches(LocalizationEvent e) {
if (!(e instanceof ContainerLocalizationCleanupEvent)) {
return false;
}
ContainerLocalizationCleanupEvent evt =
(ContainerLocalizationCleanupEvent) e;
return (evt.getContainer() == c);
}
}
private static | LocalizationCleanupMatcher |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/engine/internal/EntityEntryImpl.java | {
"start": 22022,
"end": 22182
} | enum ____ from the number value storing it.
*/
private int getUnsetMask() {
return unsetMask;
}
/**
* Returns the constants of the represented | value |
java | mapstruct__mapstruct | core/src/main/java/org/mapstruct/Mapper.java | {
"start": 6979,
"end": 12441
} | class ____ should be used as configuration template.
*/
Class<?> config() default void.class;
/**
* The strategy to be applied when propagating the value of collection-typed properties. By default, only JavaBeans
* accessor methods (setters or getters) will be used, but it is also possible to invoke a corresponding adder
* method for each element of the source collection (e.g. {@code orderDto.addOrderLine()}).
* <p>
* Any setting given for this attribute will take precedence over {@link MapperConfig#collectionMappingStrategy()},
* if present.
*
* @return The strategy applied when propagating the value of collection-typed properties.
*/
CollectionMappingStrategy collectionMappingStrategy() default CollectionMappingStrategy.ACCESSOR_ONLY;
/**
* The strategy to be applied when {@code null} is passed as source argument value to the methods of this mapper.
* If no strategy is configured, the strategy given via {@link MapperConfig#nullValueMappingStrategy()} will be
* applied, using {@link NullValueMappingStrategy#RETURN_NULL} by default.
*
* @return The strategy to be applied when {@code null} is passed as source value to the methods of this mapper.
*/
NullValueMappingStrategy nullValueMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
/**
* The strategy to be applied when {@code null} is passed as source argument value to an {@link IterableMapping} of
* this mapper. If unset, the strategy set with {@link #nullValueMappingStrategy()} will be applied. If neither
* strategy is configured, the strategy given via {@link MapperConfig#nullValueIterableMappingStrategy()} will be
* applied, using {@link NullValueMappingStrategy#RETURN_NULL} by default.
*
* @since 1.5
*
* @return The strategy to be applied when {@code null} is passed as source value to an {@link IterableMapping} of
* this mapper.
*/
NullValueMappingStrategy nullValueIterableMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
/**
* The strategy to be applied when {@code null} is passed as source argument value to a {@link MapMapping} of this
* mapper. If unset, the strategy set with {@link #nullValueMappingStrategy()} will be applied. If neither strategy
* is configured, the strategy given via {@link MapperConfig#nullValueMapMappingStrategy()} will be applied, using
* {@link NullValueMappingStrategy#RETURN_NULL} by default.
*
* @since 1.5
*
* @return The strategy to be applied when {@code null} is passed as source value to a {@link MapMapping} of this
* mapper.
*/
NullValueMappingStrategy nullValueMapMappingStrategy() default NullValueMappingStrategy.RETURN_NULL;
/**
* The strategy to be applied when a source bean property is {@code null} or not present. If no strategy is
* configured, the strategy given via {@link MapperConfig#nullValuePropertyMappingStrategy()} will be applied,
* {@link NullValuePropertyMappingStrategy#SET_TO_NULL} will be used by default.
*
* @since 1.3
*
* @return The strategy to be applied when {@code null} is passed as source property value or the source property
* is not present.
*/
NullValuePropertyMappingStrategy nullValuePropertyMappingStrategy() default
NullValuePropertyMappingStrategy.SET_TO_NULL;
/**
* The strategy to use for applying method-level configuration annotations of prototype methods in the interface
* specified with {@link #config()}. Annotations that can be inherited are for example {@link Mapping},
* {@link IterableMapping}, {@link MapMapping}, or {@link BeanMapping}.
* <p>
* If no strategy is configured, the strategy given via {@link MapperConfig#mappingInheritanceStrategy()} will be
* applied, using {@link MappingInheritanceStrategy#EXPLICIT} as default.
*
* @return The strategy to use for applying {@code @Mapping} configurations of prototype methods in the interface
* specified with {@link #config()}.
*/
MappingInheritanceStrategy mappingInheritanceStrategy() default MappingInheritanceStrategy.EXPLICIT;
/**
* Determines when to include a null check on the source property value of a bean mapping.
*
* Can be overridden by the one on {@link MapperConfig}, {@link BeanMapping} or {@link Mapping}.
*
* @return strategy how to do null checking
*/
NullValueCheckStrategy nullValueCheckStrategy() default ON_IMPLICIT_CONVERSION;
/**
* Determines how to handle missing implementation for super classes when using the {@link SubclassMapping}.
*
* Can be overridden by the one on {@link BeanMapping}, but overrides {@link MapperConfig}.
*
* @return strategy to handle missing implementation combined with {@link SubclassMappings}.
*
* @since 1.5
*/
SubclassExhaustiveStrategy subclassExhaustiveStrategy() default COMPILE_ERROR;
/**
* Specifies the exception type to be thrown when a missing subclass implementation is detected
* in combination with {@link SubclassMappings}, based on the {@link #subclassExhaustiveStrategy()}.
* <p>
* This exception will only be thrown when the {@code subclassExhaustiveStrategy} is set to
* {@link SubclassExhaustiveStrategy#RUNTIME_EXCEPTION}.
*
* @return the exception | which |
java | dropwizard__dropwizard | dropwizard-hibernate/src/test/java/io/dropwizard/hibernate/LazyLoadingTest.java | {
"start": 1503,
"end": 3075
} | class ____ {
private final DropwizardAppExtension<TestConfiguration> appExtension = new DropwizardAppExtension<>(
TestApplication.class, "hibernate-integration-test.yaml", new ResourceConfigurationSourceProvider(),
config("dataSource.url", "jdbc:h2:mem:DbTest" + System.nanoTime())
);
@Test
void serialisesLazyObjectWhenEnabled() {
final Dog raf = appExtension.client().target("http://localhost:" + appExtension.getLocalPort()).path("/dogs/Raf").request(MediaType.APPLICATION_JSON).get(Dog.class);
assertThat(raf.getName()).isEqualTo("Raf");
assertThat(raf.getOwner()).satisfies(person -> assertThat(person.getName()).isEqualTo("Coda"));
}
@Test
void returnsErrorsWhenEnabled() {
final Dog raf = new Dog();
raf.setName("Raf");
// Raf already exists so this should cause a primary key constraint violation
final Response response = appExtension.client().target("http://localhost:" + appExtension.getLocalPort()).path("/dogs/Raf").request().put(Entity.entity(raf, MediaType.APPLICATION_JSON));
assertThat(response.getStatusInfo().toEnum()).isEqualTo(Response.Status.BAD_REQUEST);
assertThat(response.getHeaderString(HttpHeaders.CONTENT_TYPE)).isEqualTo(MediaType.APPLICATION_JSON);
assertThat(response.readEntity(ErrorMessage.class).getMessage()).contains("Unique index or primary key violation", "PUBLIC.DOGS(NAME)");
}
@Nested
@SuppressWarnings("ClassCanBeStatic")
@ExtendWith(DropwizardExtensionsSupport.class)
| LazyLoadingTest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/ReadOption.java | {
"start": 1086,
"end": 1283
} | enum ____ {
/**
* Skip checksums when reading. This option may be useful when reading a file
* format that has built-in checksums, or for testing purposes.
*/
SKIP_CHECKSUMS,
}
| ReadOption |
java | google__guice | extensions/assistedinject/src/com/google/inject/assistedinject/FactoryModuleBuilder.java | {
"start": 6656,
"end": 7001
} | interface ____ {
* Apple getApple(Color color);
* }
* ...
* protected void configure() {
* install(new FactoryModuleBuilder().build(FruitFactory.class));
* }</pre>
*
* Note that any type returned by the factory in this manner needs to be an implementation class.
*
* <p>To return two different implementations for the same | FruitFactory |
java | junit-team__junit5 | junit-platform-engine/src/testFixtures/java/org/junit/platform/fakes/TestEngineStub.java | {
"start": 625,
"end": 1135
} | class ____ implements TestEngine {
private final String id;
public TestEngineStub() {
this(TestEngineStub.class.getSimpleName());
}
public TestEngineStub(String id) {
this.id = id;
}
@Override
public String getId() {
return this.id;
}
@Override
public TestDescriptor discover(EngineDiscoveryRequest discoveryRequest, UniqueId uniqueId) {
return new TestDescriptorStub(UniqueId.forEngine(getId()), getId());
}
@Override
public void execute(ExecutionRequest request) {
}
}
| TestEngineStub |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/processor/PredicateValidationException.java | {
"start": 1047,
"end": 1807
} | class ____ extends ValidationException {
private static final @Serial long serialVersionUID = 5767438583860347105L;
private final Predicate predicate;
public PredicateValidationException(Exchange exchange, Predicate predicate) {
super(exchange, buildMessage(predicate, exchange));
this.predicate = predicate;
}
protected static String buildMessage(Predicate predicate, Exchange exchange) {
StringBuilder builder = new StringBuilder(256);
builder.append("Validation failed for Predicate[");
builder.append(predicate.toString());
builder.append("]");
return builder.toString();
}
public Predicate getPredicate() {
return predicate;
}
}
| PredicateValidationException |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/jdbc/MergedSqlConfigTests.java | {
"start": 16501,
"end": 16591
} | class ____ {
@Sql
public void globalConfigMethod() {
}
| GlobalConfigWithDefaultsClass |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/http/converter/json/AbstractJackson2HttpMessageConverter.java | {
"start": 2965,
"end": 3461
} | class ____ Jackson based and content type independent
* {@link HttpMessageConverter} implementations.
*
* @author Arjen Poutsma
* @author Keith Donald
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @author Sebastien Deleuze
* @author Sam Brannen
* @since 4.1
* @see MappingJackson2HttpMessageConverter
* @deprecated since 7.0 in favor of {@link AbstractJacksonHttpMessageConverter}
*/
@Deprecated(since = "7.0", forRemoval = true)
@SuppressWarnings("removal")
public abstract | for |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/internal/util/SessionBuilderFlushModeTest.java | {
"start": 729,
"end": 1109
} | class ____ {
@ParameterizedTest
@EnumSource( FlushMode.class )
public void testFlushModeSettingTakingEffect(FlushMode flushMode, SessionFactoryScope scope) {
try ( final Session session = scope.getSessionFactory().withOptions().flushMode( flushMode ).openSession() ) {
assertThat( session.getHibernateFlushMode() ).isEqualTo( flushMode );
}
}
}
| SessionBuilderFlushModeTest |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/context/support/ServletContextResourceLoader.java | {
"start": 1455,
"end": 2071
} | class ____ extends DefaultResourceLoader {
private final ServletContext servletContext;
/**
* Create a new ServletContextResourceLoader.
* @param servletContext the ServletContext to load resources with
*/
public ServletContextResourceLoader(ServletContext servletContext) {
this.servletContext = servletContext;
}
/**
* This implementation supports file paths beneath the root of the web application.
* @see ServletContextResource
*/
@Override
protected Resource getResourceByPath(String path) {
return new ServletContextResource(this.servletContext, path);
}
}
| ServletContextResourceLoader |
java | apache__camel | core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ManagedThrowExceptionMBean.java | {
"start": 916,
"end": 1198
} | interface ____ extends ManagedProcessorMBean {
@ManagedAttribute(description = "To create a new exception instance and use the given message as caused message (supports simple language)")
String getMessage();
@ManagedAttribute(description = "The | ManagedThrowExceptionMBean |
java | micronaut-projects__micronaut-core | http-server-netty/src/test/groovy/io/micronaut/docs/respondingnotfound/BooksController.java | {
"start": 954,
"end": 1211
} | class ____ {
@Get("/stock/{isbn}")
public Map stock(String isbn) {
return null; //<1>
}
@Get("/maybestock/{isbn}")
public Mono<Map> maybestock(String isbn) {
return Mono.empty(); //<2>
}
}
//end::clazz[]
| BooksController |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/status/SnapshotStatus.java | {
"start": 1366,
"end": 8105
} | class ____ implements ChunkedToXContentObject, Writeable {
private final Snapshot snapshot;
private final State state;
private final List<SnapshotIndexShardStatus> shards;
private Map<String, SnapshotIndexStatus> indicesStatus;
private SnapshotShardsStats shardsStats;
private SnapshotStats stats;
@Nullable
private final Boolean includeGlobalState;
SnapshotStatus(StreamInput in) throws IOException {
snapshot = new Snapshot(in);
state = State.fromValue(in.readByte());
shards = in.readCollectionAsImmutableList(SnapshotIndexShardStatus::new);
includeGlobalState = in.readOptionalBoolean();
final long startTime = in.readLong();
final long time = in.readLong();
updateShardStats(startTime, time);
}
SnapshotStatus(
Snapshot snapshot,
State state,
List<SnapshotIndexShardStatus> shards,
Boolean includeGlobalState,
long startTime,
long time
) {
this.snapshot = Objects.requireNonNull(snapshot);
this.state = Objects.requireNonNull(state);
this.shards = Objects.requireNonNull(shards);
this.includeGlobalState = includeGlobalState;
shardsStats = new SnapshotShardsStats(shards);
assert time >= 0 : "time must be >= 0 but received [" + time + "]";
updateShardStats(startTime, time);
}
SnapshotStatus(
Snapshot snapshot,
State state,
List<SnapshotIndexShardStatus> shards,
Map<String, SnapshotIndexStatus> indicesStatus,
SnapshotShardsStats shardsStats,
SnapshotStats stats,
Boolean includeGlobalState
) {
this.snapshot = snapshot;
this.state = state;
this.shards = shards;
this.indicesStatus = indicesStatus;
this.shardsStats = shardsStats;
this.stats = stats;
this.includeGlobalState = includeGlobalState;
}
/**
* Returns snapshot
*/
public Snapshot getSnapshot() {
return snapshot;
}
/**
* Returns snapshot state
*/
public State getState() {
return state;
}
/**
* Returns true if global state is included in the snapshot, false otherwise.
* Can be null if this information is unknown.
*/
public Boolean includeGlobalState() {
return includeGlobalState;
}
/**
* Returns list of snapshot shards
*/
public List<SnapshotIndexShardStatus> getShards() {
return shards;
}
public SnapshotShardsStats getShardsStats() {
return shardsStats;
}
/**
* Returns list of snapshot indices
*/
public Map<String, SnapshotIndexStatus> getIndices() {
var res = this.indicesStatus;
if (res != null) {
return res;
}
Map<String, List<SnapshotIndexShardStatus>> indices = new HashMap<>();
for (SnapshotIndexShardStatus shard : shards) {
indices.computeIfAbsent(shard.getIndex(), k -> new ArrayList<>()).add(shard);
}
Map<String, SnapshotIndexStatus> indicesStatus = Maps.newMapWithExpectedSize(indices.size());
for (Map.Entry<String, List<SnapshotIndexShardStatus>> entry : indices.entrySet()) {
indicesStatus.put(entry.getKey(), new SnapshotIndexStatus(entry.getKey(), entry.getValue()));
}
res = unmodifiableMap(indicesStatus);
this.indicesStatus = res;
return res;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
snapshot.writeTo(out);
out.writeByte(state.value());
out.writeCollection(shards);
out.writeOptionalBoolean(includeGlobalState);
out.writeLong(stats.getStartTime());
out.writeLong(stats.getTime());
}
@Override
public String toString() {
return Strings.toString(this, true, false);
}
/**
* Returns number of files in the snapshot
*/
public SnapshotStats getStats() {
return stats;
}
static final String SNAPSHOT = "snapshot";
static final String REPOSITORY = "repository";
static final String UUID = "uuid";
static final String STATE = "state";
static final String INDICES = "indices";
static final String INCLUDE_GLOBAL_STATE = "include_global_state";
@Override
public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params params) {
return Iterators.concat(Iterators.single((ToXContent) (b, p) -> {
b.startObject()
.field(SNAPSHOT, snapshot.getSnapshotId().getName())
.field(REPOSITORY, snapshot.getRepository())
.field(UUID, snapshot.getSnapshotId().getUUID())
.field(STATE, state.name());
if (includeGlobalState != null) {
b.field(INCLUDE_GLOBAL_STATE, includeGlobalState);
}
return b.field(SnapshotShardsStats.Fields.SHARDS_STATS, shardsStats, p)
.field(SnapshotStats.Fields.STATS, stats, p)
.startObject(INDICES);
}), getIndices().values().iterator(), Iterators.single((b, p) -> b.endObject().endObject()));
}
private void updateShardStats(long startTime, long time) {
stats = new SnapshotStats(startTime, time, 0, 0, 0, 0, 0, 0);
shardsStats = new SnapshotShardsStats(shards);
for (SnapshotIndexShardStatus shard : shards) {
// BWC: only update timestamps when we did not get a start time from an old node
stats.add(shard.getStats(), startTime == 0L);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SnapshotStatus that = (SnapshotStatus) o;
return Objects.equals(snapshot, that.snapshot)
&& state == that.state
&& Objects.equals(indicesStatus, that.indicesStatus)
&& Objects.equals(shardsStats, that.shardsStats)
&& Objects.equals(stats, that.stats)
&& Objects.equals(includeGlobalState, that.includeGlobalState);
}
@Override
public int hashCode() {
int result = snapshot != null ? snapshot.hashCode() : 0;
result = 31 * result + (state != null ? state.hashCode() : 0);
result = 31 * result + (indicesStatus != null ? indicesStatus.hashCode() : 0);
result = 31 * result + (shardsStats != null ? shardsStats.hashCode() : 0);
result = 31 * result + (stats != null ? stats.hashCode() : 0);
result = 31 * result + (includeGlobalState != null ? includeGlobalState.hashCode() : 0);
return result;
}
}
| SnapshotStatus |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/SpringCoreBlockHoundIntegrationTests.java | {
"start": 4054,
"end": 4120
} | interface ____ {
void run() throws Exception;
}
}
| NonBlockingTask |
java | resilience4j__resilience4j | resilience4j-bulkhead/src/main/java/io/github/resilience4j/bulkhead/internal/SemaphoreBulkhead.java | {
"start": 8642,
"end": 9001
} | class ____ implements Metrics {
private BulkheadMetrics() {
}
@Override
public int getAvailableConcurrentCalls() {
return semaphore.availablePermits();
}
@Override
public int getMaxAllowedConcurrentCalls() {
return config.getMaxConcurrentCalls();
}
}
}
| BulkheadMetrics |
java | quarkusio__quarkus | extensions/spring-cache/deployment/src/test/java/io/quarkus/cache/test/runtime/BasicTest.java | {
"start": 685,
"end": 4287
} | class ____ {
private static final Object KEY = new Object();
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class).addClass(CachedService.class));
@Inject
CachedService cachedService;
@Test
public void testAllCacheAnnotations() {
// STEP 1
// Action: no-arg @Cacheable-annotated method call.
// Expected effect: method invoked and result cached.
// Verified by: STEP 2.
String value1 = cachedService.cachedMethod();
// STEP 2
// Action: same call as STEP 1.
// Expected effect: method not invoked and result coming from the cache.
// Verified by: same object reference between STEPS 1 and 2 results.
String value2 = cachedService.cachedMethod();
assertSame(value1, value2);
// STEP 3
// Action: @Cacheable-annotated method call with a key argument.
// Expected effect: method invoked and result cached.
// Verified by: different objects references between STEPS 2 and 3 results.
String value3 = cachedService.cachedMethodWithKey(KEY);
assertNotSame(value2, value3);
// STEP 4
// Action: default key cache entry invalidation.
// Expected effect: STEP 2 cache entry removed.
// Verified by: STEP 5.
cachedService.invalidate();
// STEP 5
// Action: same call as STEP 2.
// Expected effect: method invoked because of STEP 4 and result cached.
// Verified by: different objects references between STEPS 2 and 5 results.
String value5 = cachedService.cachedMethod();
assertNotSame(value2, value5);
// STEP 6
// Action: same call as STEP 3.
// Expected effect: method not invoked and result coming from the cache.
// Verified by: same object reference between STEPS 3 and 6 results.
String value6 = cachedService.cachedMethodWithKey(KEY);
assertSame(value3, value6);
// STEP 7
// Action: full cache invalidation.
// Expected effect: empty cache.
// Verified by: STEPS 8 and 9.
cachedService.invalidateAll();
// STEP 8
// Action: same call as STEP 5.
// Expected effect: method invoked because of STEP 7 and result cached.
// Verified by: different objects references between STEPS 5 and 8 results.
String value8 = cachedService.cachedMethod();
assertNotSame(value5, value8);
// STEP 9
// Action: same call as STEP 6.
// Expected effect: method invoked because of STEP 7 and result cached.
// Verified by: different objects references between STEPS 6 and 9 results.
String value9 = cachedService.cachedMethodWithKey(KEY);
assertNotSame(value6, value9);
// STEP 10
// Action: @CachePut-annotated method call.
// Expected effect: previous cache entry invalidated and new result added to the cache
// Verified by: different objects references between STEPS 9 and 10 results. The addition to the cache is validated by STEP 11
String value10 = cachedService.cachePutMethod(KEY);
assertNotSame(value10, value9);
// STEP 11
// Action: @Cacheable-annotated method call.
// Expected effect: read cached data from previous call (since the same cache is used)
String value11 = cachedService.cachedMethodWithKey(KEY);
assertSame(value11, value10);
}
@Singleton
static | BasicTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/tool/schema/spi/SchemaValidator.java | {
"start": 283,
"end": 702
} | interface ____ {
/**
* Perform the validation of the schema described by Metadata
*
* @param metadata Represents the schema to be validated
* @param options Options for executing the validation
* @param contributableInclusionFilter Filter for Contributable instances to use
*/
void doValidation(Metadata metadata, ExecutionOptions options, ContributableMatcher contributableInclusionFilter);
}
| SchemaValidator |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/ASTHelpersTest.java | {
"start": 39846,
"end": 39939
} | interface ____ {
int value();
}
@Target({METHOD, FIELD, LOCAL_VARIABLE, PARAMETER})
@ | A |
java | spring-projects__spring-framework | spring-messaging/src/main/java/org/springframework/messaging/rsocket/service/RSocketServiceProxyFactory.java | {
"start": 7885,
"end": 9273
} | class ____ implements MethodInterceptor {
private final Map<Method, RSocketServiceMethod> serviceMethods;
private ServiceMethodInterceptor(List<RSocketServiceMethod> methods) {
this.serviceMethods = methods.stream()
.collect(Collectors.toMap(RSocketServiceMethod::getMethod, Function.identity()));
}
@Override
public @Nullable Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
RSocketServiceMethod serviceMethod = this.serviceMethods.get(method);
if (serviceMethod != null) {
@Nullable Object[] arguments = KotlinDetector.isSuspendingFunction(method) ?
resolveCoroutinesArguments(invocation.getArguments()) : invocation.getArguments();
return serviceMethod.invoke(arguments);
}
if (method.isDefault()) {
if (invocation instanceof ReflectiveMethodInvocation reflectiveMethodInvocation) {
Object proxy = reflectiveMethodInvocation.getProxy();
return InvocationHandler.invokeDefault(proxy, method, invocation.getArguments());
}
}
throw new IllegalStateException("Unexpected method invocation: " + method);
}
private static Object[] resolveCoroutinesArguments(@Nullable Object[] args) {
Object[] functionArgs = new Object[args.length - 1];
System.arraycopy(args, 0, functionArgs, 0, args.length - 1);
return functionArgs;
}
}
}
| ServiceMethodInterceptor |
java | quarkusio__quarkus | extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/InstrumentationTest.java | {
"start": 760,
"end": 1974
} | class ____ extends AbstractGraphQLTest {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(FooApi.class, Foo.class)
.addAsResource(new StringAsset(getPropertyAsString(configuration())), "application.properties")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"));
@Test
public void testQueryDepth() {
String query = getPayload("{ foo { nestedFoo { nestedFoo { message}}}}");
RestAssured.given()
.body(query)
.contentType(MEDIATYPE_JSON)
.post("/graphql/")
.then()
.log().all()
.assertThat()
.body("errors[0].message", equalTo("maximum query depth exceeded 4 > 1"))
.body("data", nullValue());
}
private static Map<String, String> configuration() {
Map<String, String> m = new HashMap<>();
m.put("quarkus.smallrye-graphql.events.enabled", "true");
m.put("quarkus.smallrye-graphql.instrumentation-query-depth", "1");
return m;
}
public static | InstrumentationTest |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/aot/hint/BindingReflectionHintsRegistrarTests.java | {
"start": 15703,
"end": 15787
} | class ____ {
public SampleClassC getC() {
return null;
}
}
static | SampleClassB |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/JsonAggregationFunctionsITCase.java | {
"start": 1679,
"end": 14717
} | class ____ extends BuiltInAggregateFunctionTestBase {
@Override
public Stream<TestSpec> getTestCaseSpecs() {
return Stream.of(
// JSON_OBJECTAGG
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_OBJECTAGG_NULL_ON_NULL)
.withDescription("Basic Aggregation")
.withSource(
ROW(STRING(), INT()),
Arrays.asList(
Row.ofKind(INSERT, "A", 1),
Row.ofKind(INSERT, "B", null),
Row.ofKind(INSERT, "C", 3)))
.testResult(
source -> "SELECT JSON_OBJECTAGG(f0 VALUE f1) FROM " + source,
TableApiAggSpec.select(
jsonObjectAgg(JsonOnNull.NULL, $("f0"), $("f1"))),
ROW(VARCHAR(2000).notNull()),
ROW(STRING().notNull()),
Collections.singletonList(Row.of("{\"A\":1,\"B\":null,\"C\":3}"))),
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_OBJECTAGG_ABSENT_ON_NULL)
.withDescription("Omits NULLs")
.withSource(
ROW(STRING(), INT()),
Arrays.asList(
Row.ofKind(INSERT, "A", 1),
Row.ofKind(INSERT, "B", null),
Row.ofKind(INSERT, "C", 3)))
.testResult(
source ->
"SELECT JSON_OBJECTAGG(f0 VALUE f1 ABSENT ON NULL) FROM "
+ source,
TableApiAggSpec.select(
jsonObjectAgg(JsonOnNull.ABSENT, $("f0"), $("f1"))),
ROW(VARCHAR(2000).notNull()),
ROW(STRING().notNull()),
Collections.singletonList(Row.of("{\"A\":1,\"C\":3}"))),
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_OBJECTAGG_NULL_ON_NULL)
.withDescription("Retractions")
.withSource(
ROW(STRING(), INT()),
Arrays.asList(
Row.ofKind(INSERT, "A", 1),
Row.ofKind(INSERT, "B", 2),
Row.ofKind(INSERT, "C", 3),
Row.ofKind(DELETE, "B", 2)))
.testResult(
source -> "SELECT JSON_OBJECTAGG(f0 VALUE f1) FROM " + source,
TableApiAggSpec.select(
jsonObjectAgg(JsonOnNull.NULL, $("f0"), $("f1"))),
ROW(VARCHAR(2000).notNull()),
ROW(STRING().notNull()),
Collections.singletonList(Row.of("{\"A\":1,\"C\":3}"))),
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_OBJECTAGG_NULL_ON_NULL)
.withDescription("Group Aggregation")
.withSource(
ROW(INT(), STRING(), INT()),
Arrays.asList(
Row.ofKind(INSERT, 1, "A", 0),
Row.ofKind(INSERT, 1, "B", 0),
Row.ofKind(INSERT, 2, "A", 0),
Row.ofKind(INSERT, 2, "C", 0)))
.testResult(
source ->
"SELECT f0, JSON_OBJECTAGG(f1 VALUE f2) FROM "
+ source
+ " GROUP BY f0",
TableApiAggSpec.groupBySelect(
Collections.singletonList($("f0")),
$("f0"),
jsonObjectAgg(JsonOnNull.NULL, $("f1"), $("f2"))),
ROW(INT(), VARCHAR(2000).notNull()),
ROW(INT(), STRING().notNull()),
Arrays.asList(
Row.of(1, "{\"A\":0,\"B\":0}"),
Row.of(2, "{\"A\":0,\"C\":0}"))),
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_OBJECTAGG_NULL_ON_NULL)
.withDescription("Basic Json Aggregation With Other Aggs")
.withSource(
ROW(STRING(), INT()),
Arrays.asList(
Row.ofKind(INSERT, "A", 1),
Row.ofKind(INSERT, "B", null),
Row.ofKind(INSERT, "C", 3)))
.testResult(
source ->
"SELECT max(f1), JSON_OBJECTAGG(f0 VALUE f1) FROM "
+ source,
TableApiAggSpec.select(
$("f1").max(),
jsonObjectAgg(JsonOnNull.NULL, $("f0"), $("f1"))),
ROW(INT(), VARCHAR(2000).notNull()),
ROW(INT(), STRING().notNull()),
Collections.singletonList(
Row.of(3, "{\"A\":1,\"B\":null,\"C\":3}"))),
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_OBJECTAGG_NULL_ON_NULL)
.withDescription("Group Json Aggregation With Other Aggs")
.withSource(
ROW(INT(), STRING(), INT()),
Arrays.asList(
Row.ofKind(INSERT, 1, "A", 1),
Row.ofKind(INSERT, 1, "B", 3),
Row.ofKind(INSERT, 2, "A", 2),
Row.ofKind(INSERT, 2, "C", 5)))
.testResult(
source ->
"SELECT f0, JSON_OBJECTAGG(f1 VALUE f2), max(f2) FROM "
+ source
+ " GROUP BY f0",
TableApiAggSpec.groupBySelect(
Collections.singletonList($("f0")),
$("f0"),
jsonObjectAgg(JsonOnNull.NULL, $("f1"), $("f2")),
$("f2").max()),
ROW(INT(), VARCHAR(2000).notNull(), INT()),
ROW(INT(), STRING().notNull(), INT()),
Arrays.asList(
Row.of(1, "{\"A\":1,\"B\":3}", 3),
Row.of(2, "{\"A\":2,\"C\":5}", 5))),
// JSON_ARRAYAGG
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_ARRAYAGG_ABSENT_ON_NULL)
.withDescription("Basic Aggregation")
.withSource(
ROW(STRING()),
Arrays.asList(
Row.ofKind(INSERT, "A"),
Row.ofKind(INSERT, (String) null),
Row.ofKind(INSERT, "C")))
.testResult(
source -> "SELECT JSON_ARRAYAGG(f0) FROM " + source,
TableApiAggSpec.select(jsonArrayAgg(JsonOnNull.ABSENT, $("f0"))),
ROW(VARCHAR(2000).notNull()),
ROW(STRING().notNull()),
Collections.singletonList(Row.of("[\"A\",\"C\"]"))),
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_ARRAYAGG_NULL_ON_NULL)
.withDescription("Keeps NULLs")
.withSource(
ROW(STRING()),
Arrays.asList(
Row.ofKind(INSERT, "A"),
Row.ofKind(INSERT, (String) null),
Row.ofKind(INSERT, "C")))
.testResult(
source -> "SELECT JSON_ARRAYAGG(f0 NULL ON NULL) FROM " + source,
TableApiAggSpec.select(jsonArrayAgg(JsonOnNull.NULL, $("f0"))),
ROW(VARCHAR(2000).notNull()),
ROW(STRING().notNull()),
Collections.singletonList(Row.of("[\"A\",null,\"C\"]"))),
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_ARRAYAGG_ABSENT_ON_NULL)
.withDescription("Retractions")
.withSource(
ROW(INT()),
Arrays.asList(
Row.ofKind(INSERT, 1),
Row.ofKind(INSERT, 2),
Row.ofKind(INSERT, 3),
Row.ofKind(DELETE, 2)))
.testResult(
source -> "SELECT JSON_ARRAYAGG(f0) FROM " + source,
TableApiAggSpec.select(jsonArrayAgg(JsonOnNull.ABSENT, $("f0"))),
ROW(VARCHAR(2000).notNull()),
ROW(STRING().notNull()),
Collections.singletonList(Row.of("[1,3]"))),
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_ARRAYAGG_ABSENT_ON_NULL)
.withDescription("Basic Array Aggregation With Other Aggs")
.withSource(
ROW(STRING()),
Arrays.asList(
Row.ofKind(INSERT, "A"),
Row.ofKind(INSERT, (String) null),
Row.ofKind(INSERT, "C")))
.testResult(
source -> "SELECT max(f0), JSON_ARRAYAGG(f0) FROM " + source,
TableApiAggSpec.select(
$("f0").max(), jsonArrayAgg(JsonOnNull.ABSENT, $("f0"))),
ROW(STRING(), VARCHAR(2000).notNull()),
ROW(STRING(), STRING().notNull()),
Collections.singletonList(Row.of("C", "[\"A\",\"C\"]"))),
TestSpec.forFunction(BuiltInFunctionDefinitions.JSON_ARRAYAGG_ABSENT_ON_NULL)
.withDescription("Group Array Aggregation With Other Aggs")
.withSource(
ROW(INT(), STRING()),
Arrays.asList(
Row.ofKind(INSERT, 1, "A"),
Row.ofKind(INSERT, 1, null),
Row.ofKind(INSERT, 2, "C"),
Row.ofKind(INSERT, 2, "D")))
.testResult(
source ->
"SELECT f0, max(f1), JSON_ARRAYAGG(f1)FROM "
+ source
+ " GROUP BY f0",
TableApiAggSpec.groupBySelect(
Collections.singletonList($("f0")),
$("f0"),
$("f1").max(),
jsonArrayAgg(JsonOnNull.ABSENT, $("f1"))),
ROW(INT(), STRING(), VARCHAR(2000).notNull()),
ROW(INT(), STRING(), STRING().notNull()),
Arrays.asList(
Row.of(1, "A", "[\"A\"]"),
Row.of(2, "D", "[\"C\",\"D\"]"))));
}
}
| JsonAggregationFunctionsITCase |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/persistent/PersistentTasksNodeService.java | {
"start": 12438,
"end": 19331
} | class ____<Params extends PersistentTaskParams> extends PersistentTasksExecutor<Params> {
PersistentTaskStartupFailureExecutor(String taskName, Executor executor) {
super(taskName, executor);
}
@Override
protected void nodeOperation(AllocatedPersistentTask task, Params params, PersistentTaskState state) {}
}
private <Params extends PersistentTaskParams> void doStartTask(
PersistentTask<Params> taskInProgress,
PersistentTasksExecutor<Params> executor,
TaskAwareRequest request
) {
final AllocatedPersistentTask task;
try {
task = (AllocatedPersistentTask) taskManager.register("persistent", taskInProgress.getTaskName() + "[c]", request);
} catch (Exception e) {
logger.error(
"Fatal error registering persistent task ["
+ taskInProgress.getTaskName()
+ "] with id ["
+ taskInProgress.getId()
+ "] and allocation id ["
+ taskInProgress.getAllocationId()
+ "], removing from persistent tasks",
e
);
// create a no-op placeholder task so that we don't keep trying to start this task while we wait for the cluster state update
// which handles the failure
final var placeholderTask = (AllocatedPersistentTask) taskManager.register(
"persistent",
taskInProgress.getTaskName() + "[c]",
new PersistentTaskAwareRequest<>(
taskInProgress,
new PersistentTaskStartupFailureExecutor<>(executor.getTaskName(), EsExecutors.DIRECT_EXECUTOR_SERVICE)
)
);
placeholderTask.init(persistentTasksService, taskManager, taskInProgress.getId(), taskInProgress.getAllocationId());
taskManager.unregister(placeholderTask);
runningTasks.put(taskInProgress.getAllocationId(), placeholderTask);
placeholderTask.markAsFailed(e);
return;
}
boolean processed = false;
Exception initializationException = null;
try {
task.init(persistentTasksService, taskManager, taskInProgress.getId(), taskInProgress.getAllocationId());
logger.trace(
"Persistent task [{}] with id [{}] and allocation id [{}] was created",
task.getAction(),
task.getPersistentTaskId(),
task.getAllocationId()
);
try {
runningTasks.put(taskInProgress.getAllocationId(), task);
nodePersistentTasksExecutor.executeTask(taskInProgress.getParams(), taskInProgress.getState(), task, executor);
} catch (Exception e) {
// Submit task failure
task.markAsFailed(e);
}
processed = true;
} catch (Exception e) {
initializationException = e;
} finally {
if (processed == false) {
// something went wrong - unregistering task
logger.warn(
"Persistent task [{}] with id [{}] and allocation id [{}] failed to create",
task.getAction(),
task.getPersistentTaskId(),
task.getAllocationId()
);
taskManager.unregister(task);
if (initializationException != null) {
notifyMasterOfFailedTask(taskInProgress, initializationException);
}
}
}
}
private <Params extends PersistentTaskParams> void notifyMasterOfFailedTask(
PersistentTask<Params> taskInProgress,
Exception originalException
) {
persistentTasksService.sendCompletionRequest(
taskInProgress.getId(),
taskInProgress.getAllocationId(),
originalException,
null,
TimeValue.THIRTY_SECONDS /* TODO should this be longer? infinite? */,
new ActionListener<>() {
@Override
public void onResponse(PersistentTask<?> persistentTask) {
logger.trace(
"completion notification for failed task [{}] with id [{}] was successful",
taskInProgress.getTaskName(),
taskInProgress.getAllocationId()
);
}
@Override
public void onFailure(Exception notificationException) {
notificationException.addSuppressed(originalException);
logger.warn(
() -> format(
"notification for task [%s] with id [%s] failed",
taskInProgress.getTaskName(),
taskInProgress.getAllocationId()
),
notificationException
);
}
}
);
}
/**
* Unregisters and then cancels the locally running task using the task manager. No notification to master will be sent upon
* cancellation.
*/
private void cancelTask(Long allocationId) {
AllocatedPersistentTask task = runningTasks.remove(allocationId);
if (task.markAsCancelled()) {
// Cancel the local task using the task manager
String reason = "task has been removed, cancelling locally";
persistentTasksService.sendCancelRequest(task.getId(), reason, new ActionListener<>() {
@Override
public void onResponse(ListTasksResponse cancelTasksResponse) {
logger.trace(
"Persistent {} task [{}] with id [{}] and allocation id [{}] was cancelled",
taskTypeString(task.getProjectId()),
task.getAction(),
task.getPersistentTaskId(),
task.getAllocationId()
);
}
@Override
public void onFailure(Exception e) {
// There is really nothing we can do in case of failure here
logger.warn(
() -> format(
"failed to cancel {} task [%s] with id [%s] and allocation id [%s]",
taskTypeString(task.getProjectId()),
task.getAction(),
task.getPersistentTaskId(),
task.getAllocationId()
),
e
);
}
});
}
}
public static | PersistentTaskStartupFailureExecutor |
java | quarkusio__quarkus | extensions/mongodb-client/deployment/src/main/java/io/quarkus/mongodb/deployment/MongoClientBuildItem.java | {
"start": 295,
"end": 972
} | class ____ extends MultiBuildItem {
private final RuntimeValue<MongoClient> client;
private final RuntimeValue<ReactiveMongoClient> reactive;
private final String name;
public MongoClientBuildItem(RuntimeValue<MongoClient> client, RuntimeValue<ReactiveMongoClient> reactiveClient,
String name) {
this.client = client;
this.reactive = reactiveClient;
this.name = name;
}
public RuntimeValue<MongoClient> getClient() {
return client;
}
public RuntimeValue<ReactiveMongoClient> getReactive() {
return reactive;
}
public String getName() {
return name;
}
}
| MongoClientBuildItem |
java | apache__hadoop | hadoop-tools/hadoop-resourceestimator/src/main/java/org/apache/hadoop/resourceestimator/solver/exceptions/InvalidInputException.java | {
"start": 1028,
"end": 1315
} | class ____ extends SolverException {
private static final long serialVersionUID = -684069387367879218L;
public InvalidInputException(final String entity, final String reason) {
super(entity + " is " + reason + ", please try again with valid " + entity);
}
}
| InvalidInputException |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/net/TcpSocketManager.java | {
"start": 12977,
"end": 17497
} | class ____ extends Log4jThread {
private final CountDownLatch latch = new CountDownLatch(1);
private boolean shutdown = false;
private final Object owner;
public Reconnector(final OutputStreamManager owner) {
super("TcpSocketManager-Reconnector");
this.owner = owner;
}
public void latch() {
try {
latch.await();
} catch (final InterruptedException ex) {
// Ignore the exception.
}
}
public void shutdown() {
shutdown = true;
}
@Override
public void run() {
while (!shutdown) {
try {
sleep(reconnectionDelayMillis);
reconnect();
} catch (final InterruptedException ie) {
LOGGER.debug("Reconnection interrupted.");
} catch (final ConnectException ex) {
LOGGER.debug("{}:{} refused connection", host, port);
} catch (final IOException ioe) {
LOGGER.debug("Unable to reconnect to {}:{}", host, port);
} finally {
latch.countDown();
}
}
}
void reconnect() throws IOException {
final List<InetSocketAddress> socketAddresses = TcpSocketManagerFactory.RESOLVER.resolveHost(host, port);
if (socketAddresses.size() == 1) {
LOGGER.debug("Reconnecting " + socketAddresses.get(0));
connect(socketAddresses.get(0));
} else {
IOException ioe = null;
for (InetSocketAddress socketAddress : socketAddresses) {
try {
LOGGER.debug("Reconnecting " + socketAddress);
connect(socketAddress);
return;
} catch (IOException ex) {
ioe = ex;
}
}
throw ioe;
}
}
private void connect(final InetSocketAddress socketAddress) throws IOException {
final Socket sock = createSocket(socketAddress);
@SuppressWarnings("resource") // newOS is managed by the enclosing Manager.
final OutputStream newOS = sock.getOutputStream();
final InetAddress prev = socket != null ? socket.getInetAddress() : null;
synchronized (owner) {
Closer.closeSilently(getOutputStream());
setOutputStream(newOS);
socket = sock;
reconnector = null;
shutdown = true;
}
final String type = prev != null
&& prev.getHostAddress()
.equals(socketAddress.getAddress().getHostAddress())
? "reestablished"
: "established";
LOGGER.debug("Connection to {}:{} {}: {}", host, port, type, socket);
}
@Override
public String toString() {
return "Reconnector [latch=" + latch + ", shutdown=" + shutdown + "]";
}
}
private Reconnector createReconnector() {
final Reconnector recon = new Reconnector(this);
recon.setDaemon(true);
recon.setPriority(Thread.MIN_PRIORITY);
return recon;
}
protected Socket createSocket(final InetSocketAddress socketAddress) throws IOException {
return createSocket(socketAddress, socketOptions, connectTimeoutMillis);
}
@SuppressFBWarnings(value = "UNENCRYPTED_SOCKET")
protected static Socket createSocket(
final InetSocketAddress socketAddress, final SocketOptions socketOptions, final int connectTimeoutMillis)
throws IOException {
LOGGER.debug("Creating socket {}", socketAddress.toString());
final Socket newSocket = new Socket();
if (socketOptions != null) {
// Not sure which options must be applied before or after the connect() call.
socketOptions.apply(newSocket);
}
newSocket.connect(socketAddress, connectTimeoutMillis);
if (socketOptions != null) {
// Not sure which options must be applied before or after the connect() call.
socketOptions.apply(newSocket);
}
return newSocket;
}
/**
* Data for the factory.
*/
static | Reconnector |
java | google__guava | android/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java | {
"start": 10976,
"end": 11026
} | class ____ {}
@Require(IMPLIES_BAR)
| BaseTester |
java | apache__kafka | tools/src/test/java/org/apache/kafka/tools/StreamsResetterTest.java | {
"start": 13752,
"end": 14384
} | class ____<K, V> extends MockConsumer<K, V> {
public EmptyPartitionConsumer(final String offsetResetStrategy) {
super(offsetResetStrategy);
}
@Override
public synchronized Map<TopicPartition, OffsetAndTimestamp> offsetsForTimes(final Map<TopicPartition, Long> timestampsToSearch) {
final Map<TopicPartition, OffsetAndTimestamp> topicPartitionToOffsetAndTimestamp = new HashMap<>();
timestampsToSearch.keySet().forEach(k -> topicPartitionToOffsetAndTimestamp.put(k, null));
return topicPartitionToOffsetAndTimestamp;
}
}
} | EmptyPartitionConsumer |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/NoAllocationCheckerTest.java | {
"start": 17276,
"end": 17507
} | class ____ extends NoAllocationAbstractClass {
@Override
// BUG: Diagnostic contains: @NoAllocation
void method() {}
}
public static | NoAllocationConcreteClass |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/internal/temptable/TableBasedUpdateHandler.java | {
"start": 4227,
"end": 28540
} | class ____
extends AbstractMutationHandler
implements UpdateHandler {
private static final Logger LOG = Logger.getLogger( TableBasedUpdateHandler.class );
private final TemporaryTable idTable;
private final TemporaryTableStrategy temporaryTableStrategy;
private final boolean forceDropAfterUse;
private final Function<SharedSessionContractImplementor,String> sessionUidAccess;
private final DomainParameterXref domainParameterXref;
private final Map<QueryParameterImplementor<?>, Map<SqmParameter<?>, List<JdbcParametersList>>> jdbcParamsXref;
private final Map<SqmParameter<?>, MappingModelExpressible<?>> resolvedParameterMappingModelTypes;
private final @Nullable JdbcParameter sessionUidParameter;
private final CacheableSqmInterpretation<InsertSelectStatement, JdbcOperationQueryMutation> matchingIdsIntoIdTableInsert;
private final List<TableUpdater> tableUpdaters;
public TableBasedUpdateHandler(
SqmUpdateStatement<?> sqmUpdate,
DomainParameterXref domainParameterXref,
TemporaryTable idTable,
TemporaryTableStrategy temporaryTableStrategy,
boolean forceDropAfterUse,
Function<SharedSessionContractImplementor, String> sessionUidAccess,
DomainQueryExecutionContext context,
MutableObject<JdbcParameterBindings> firstJdbcParameterBindingsConsumer) {
super( sqmUpdate, context.getSession().getSessionFactory() );
this.idTable = idTable;
this.temporaryTableStrategy = temporaryTableStrategy;
this.forceDropAfterUse = forceDropAfterUse;
this.sessionUidAccess = sessionUidAccess;
final TemporaryTableSessionUidColumn sessionUidColumn = idTable.getSessionUidColumn();
if ( sessionUidColumn == null ) {
this.sessionUidParameter = null;
}
else {
this.sessionUidParameter = new SqlTypedMappingJdbcParameter( sessionUidColumn );
}
final SessionFactoryImplementor sessionFactory = getSessionFactory();
final MappingMetamodel domainModel = sessionFactory.getMappingMetamodel();
final EntityPersister entityDescriptor =
domainModel.getEntityDescriptor( sqmUpdate.getTarget().getEntityName() );
final String rootEntityName = entityDescriptor.getRootEntityName();
final EntityPersister rootEntityDescriptor = domainModel.getEntityDescriptor( rootEntityName );
final String hierarchyRootTableName = rootEntityDescriptor.getTableName();
final MultiTableSqmMutationConverter converterDelegate = new MultiTableSqmMutationConverter(
entityDescriptor,
sqmUpdate,
sqmUpdate.getTarget(),
domainParameterXref,
context.getQueryOptions(),
context.getSession().getLoadQueryInfluencers(),
context.getQueryParameterBindings(),
sessionFactory.getSqlTranslationEngine()
);
final TableGroup updatingTableGroup = converterDelegate.getMutatingTableGroup();
final TableReference hierarchyRootTableReference = updatingTableGroup.resolveTableReference(
updatingTableGroup.getNavigablePath(),
hierarchyRootTableName
);
assert hierarchyRootTableReference != null;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// visit the set-clause using our special converter, collecting
// information about the assignments
final List<Assignment> assignments = converterDelegate.visitSetClause( sqmUpdate.getSetClause() );
converterDelegate.addVersionedAssignment( assignments::add, sqmUpdate );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// visit the where-clause using our special converter, collecting information
// about the restrictions
final PredicateCollector predicateCollector = new PredicateCollector(
converterDelegate.visitWhereClause( sqmUpdate.getWhereClause() )
);
entityDescriptor.applyBaseRestrictions(
predicateCollector::applyPredicate,
updatingTableGroup,
true,
context.getSession().getLoadQueryInfluencers().getEnabledFilters(),
false,
null,
converterDelegate
);
converterDelegate.pruneTableGroupJoins();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// cross-reference the TableReference by alias. The TableGroup already
// cross-references it by name, bu the ColumnReference only has the alias
final Map<String, TableReference> tableReferenceByAlias = CollectionHelper.mapOfSize( updatingTableGroup.getTableReferenceJoins().size() + 1 );
collectTableReference( updatingTableGroup.getPrimaryTableReference(), tableReferenceByAlias::put );
for ( int i = 0; i < updatingTableGroup.getTableReferenceJoins().size(); i++ ) {
collectTableReference( updatingTableGroup.getTableReferenceJoins().get( i ), tableReferenceByAlias::put );
}
final SoftDeleteMapping softDeleteMapping = entityDescriptor.getSoftDeleteMapping();
final Predicate suppliedPredicate;
if ( softDeleteMapping != null ) {
final NamedTableReference rootTableReference = (NamedTableReference) updatingTableGroup.resolveTableReference(
updatingTableGroup.getNavigablePath(),
entityDescriptor.getIdentifierTableDetails().getTableName()
);
suppliedPredicate = Predicate.combinePredicates(
predicateCollector.getPredicate(),
softDeleteMapping.createNonDeletedRestriction( rootTableReference )
);
}
else {
suppliedPredicate = predicateCollector.getPredicate();
}
Map<TableReference, List<Assignment>> assignmentsByTable = mapOfSize( updatingTableGroup.getTableReferenceJoins().size() + 1 );
this.domainParameterXref = domainParameterXref;
this.jdbcParamsXref = SqmUtil.generateJdbcParamsXref( domainParameterXref, converterDelegate );
this.resolvedParameterMappingModelTypes = converterDelegate.getSqmParameterMappingModelExpressibleResolutions();
final JdbcParameterBindings jdbcParameterBindings = SqmUtil.createJdbcParameterBindings(
context.getQueryParameterBindings(),
domainParameterXref,
jdbcParamsXref,
new SqmParameterMappingModelResolutionAccess() {
@Override @SuppressWarnings("unchecked")
public <T> MappingModelExpressible<T> getResolvedMappingModelType(SqmParameter<T> parameter) {
return (MappingModelExpressible<T>) resolvedParameterMappingModelTypes.get( parameter );
}
},
context.getSession()
);
if ( sessionUidParameter != null ) {
jdbcParameterBindings.addBinding(
sessionUidParameter,
new JdbcParameterBindingImpl(
idTable.getSessionUidColumn().getJdbcMapping(),
UUID.fromString( sessionUidAccess.apply( context.getSession() ) )
)
);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// segment the assignments by table-reference
for ( int i = 0; i < assignments.size(); i++ ) {
final Assignment assignment = assignments.get( i );
final List<ColumnReference> assignmentColumnRefs = assignment.getAssignable().getColumnReferences();
TableReference assignmentTableReference = null;
for ( int c = 0; c < assignmentColumnRefs.size(); c++ ) {
final ColumnReference columnReference = assignmentColumnRefs.get( c );
final TableReference tableReference = resolveTableReference(
columnReference,
tableReferenceByAlias
);
if ( assignmentTableReference != null && assignmentTableReference != tableReference ) {
throw new SemanticException( "Assignment referred to columns from multiple tables: " + assignment.getAssignable() );
}
assignmentTableReference = tableReference;
}
List<Assignment> assignmentsForTable = assignmentsByTable.get( assignmentTableReference );
if ( assignmentsForTable == null ) {
assignmentsForTable = new ArrayList<>();
assignmentsByTable.put( assignmentTableReference, assignmentsForTable );
}
assignmentsForTable.add( assignment );
}
final SqmJdbcExecutionContextAdapter executionContext = SqmJdbcExecutionContextAdapter.omittingLockingAndPaging( context );
this.matchingIdsIntoIdTableInsert = ExecuteWithTemporaryTableHelper.createMatchingIdsIntoIdTableInsert(
converterDelegate,
suppliedPredicate,
idTable,
sessionUidParameter,
jdbcParameterBindings,
executionContext
);
final QuerySpec idTableSubQuery = ExecuteWithTemporaryTableHelper.createIdTableSelectQuerySpec(
idTable,
sessionUidParameter,
entityDescriptor,
executionContext
);
final ArrayList<TableUpdater> tableUpdaters = new ArrayList<>();
entityDescriptor.visitConstraintOrderedTables(
(tableExpression, tableKeyColumnVisitationSupplier) -> tableUpdaters.add(
createTableUpdater(
updatingTableGroup,
tableExpression,
tableKeyColumnVisitationSupplier,
assignmentsByTable,
idTableSubQuery,
jdbcParameterBindings,
executionContext
)
)
);
this.tableUpdaters = tableUpdaters;
firstJdbcParameterBindingsConsumer.set( jdbcParameterBindings );
}
@Override
public JdbcParameterBindings createJdbcParameterBindings(DomainQueryExecutionContext context) {
final JdbcParameterBindings jdbcParameterBindings = SqmUtil.createJdbcParameterBindings(
context.getQueryParameterBindings(),
domainParameterXref,
jdbcParamsXref,
new SqmParameterMappingModelResolutionAccess() {
@Override
@SuppressWarnings("unchecked")
public <T> MappingModelExpressible<T> getResolvedMappingModelType(SqmParameter<T> parameter) {
return (MappingModelExpressible<T>) resolvedParameterMappingModelTypes.get( parameter );
}
},
context.getSession()
);
if ( sessionUidParameter != null ) {
jdbcParameterBindings.addBinding(
sessionUidParameter,
new JdbcParameterBindingImpl(
idTable.getSessionUidColumn().getJdbcMapping(),
UUID.fromString( sessionUidAccess.apply( context.getSession() ) )
)
);
}
return jdbcParameterBindings;
}
@Override
public boolean dependsOnParameterBindings() {
if ( matchingIdsIntoIdTableInsert.jdbcOperation().dependsOnParameterBindings() ) {
return true;
}
for ( TableUpdater updater : tableUpdaters ) {
if ( updater.jdbcUpdate.dependsOnParameterBindings() ) {
return true;
}
if ( updater.jdbcInsert != null && updater.jdbcInsert.dependsOnParameterBindings() ) {
return true;
}
}
return false;
}
@Override
public boolean isCompatibleWith(JdbcParameterBindings jdbcParameterBindings, QueryOptions queryOptions) {
if ( !matchingIdsIntoIdTableInsert.jdbcOperation().isCompatibleWith( jdbcParameterBindings, queryOptions ) ) {
return false;
}
for ( TableUpdater updater : tableUpdaters ) {
if ( !updater.jdbcUpdate.isCompatibleWith( jdbcParameterBindings, queryOptions ) ) {
return false;
}
if ( updater.jdbcInsert != null
&& !updater.jdbcInsert.isCompatibleWith( jdbcParameterBindings, queryOptions ) ) {
return false;
}
}
return true;
}
protected TableReference resolveTableReference(
ColumnReference columnReference,
Map<String, TableReference> tableReferenceByAlias) {
final TableReference tableReferenceByQualifier = tableReferenceByAlias.get( columnReference.getQualifier() );
if ( tableReferenceByQualifier != null ) {
return tableReferenceByQualifier;
}
throw new SemanticException( "Assignment referred to column of a joined association: " + columnReference );
}
protected NamedTableReference resolveUnionTableReference(
TableReference tableReference,
String tableExpression) {
if ( tableReference instanceof UnionTableReference ) {
return new NamedTableReference(
tableExpression,
tableReference.getIdentificationVariable(),
tableReference.isOptional()
);
}
return (NamedTableReference) tableReference;
}
private TableUpdater createTableUpdater(
TableGroup updatingTableGroup,
String tableExpression,
Supplier<Consumer<SelectableConsumer>> tableKeyColumnVisitationSupplier,
Map<TableReference, List<Assignment>> assignmentsByTable,
QuerySpec idTableSubQuery,
JdbcParameterBindings firstJdbcParameterBindings,
ExecutionContext executionContext) {
// update `updatingTableReference`
// set ...
// where `keyExpression` in ( `idTableSubQuery` )
final TableReference updatingTableReference = updatingTableGroup.getTableReference(
updatingTableGroup.getNavigablePath(),
tableExpression,
true
);
final List<Assignment> assignments = assignmentsByTable.get( updatingTableReference );
if ( assignments == null || assignments.isEmpty() ) {
// no assignments for this table - skip it
return null;
}
final NamedTableReference dmlTableReference = resolveUnionTableReference( updatingTableReference, tableExpression );
final JdbcServices jdbcServices = executionContext.getSession().getFactory().getJdbcServices();
final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcServices.getJdbcEnvironment().getSqlAstTranslatorFactory();
final Expression keyExpression =
resolveMutatingTableKeyExpression( tableExpression, tableKeyColumnVisitationSupplier );
return new TableUpdater(
createTableUpdate(
idTableSubQuery,
executionContext,
assignments,
dmlTableReference,
sqlAstTranslatorFactory,
firstJdbcParameterBindings,
keyExpression
),
isTableOptional( tableExpression ) ? createTableInsert(
tableExpression,
dmlTableReference,
keyExpression,
tableKeyColumnVisitationSupplier,
idTableSubQuery,
assignments,
sqlAstTranslatorFactory,
firstJdbcParameterBindings,
executionContext
) : null
);
}
protected boolean isTableOptional(String tableExpression) {
final EntityPersister entityPersister = getEntityDescriptor().getEntityPersister();
for ( int i = 0; i < entityPersister.getTableSpan(); i++ ) {
if ( tableExpression.equals( entityPersister.getTableName( i ) )
&& entityPersister.isNullableTable( i ) ) {
return true;
}
}
return false;
}
private JdbcOperationQueryMutation createTableInsert(
String targetTableExpression,
NamedTableReference targetTableReference,
Expression targetTableKeyExpression,
Supplier<Consumer<SelectableConsumer>> tableKeyColumnVisitationSupplier,
QuerySpec idTableSubQuery,
List<Assignment> assignments,
SqlAstTranslatorFactory sqlAstTranslatorFactory,
JdbcParameterBindings firstJdbcParameterBindings,
ExecutionContext executionContext) {
final SessionFactoryImplementor sessionFactory = executionContext.getSession().getFactory();
// Execute a query in the form -
//
// insert into <target> (...)
// select ...
// from <id-table> temptable_
// where not exists (
// select 1
// from <target> dml_
// where dml_.<key> = temptable_.<key>
// )
// Create a new QuerySpec for the "insert source" select query. This
// is mostly a copy of the incoming `idTableSubQuery` along with the
// NOT-EXISTS predicate
final QuerySpec insertSourceSelectQuerySpec = makeInsertSourceSelectQuerySpec( idTableSubQuery );
// create the `select 1 ...` sub-query and apply the not-exists predicate
final QuerySpec existsSubQuerySpec = createExistsSubQuerySpec( targetTableExpression, tableKeyColumnVisitationSupplier, idTableSubQuery, sessionFactory );
insertSourceSelectQuerySpec.applyPredicate(
new ExistsPredicate(
existsSubQuerySpec,
true,
sessionFactory.getTypeConfiguration().getBasicTypeForJavaType( Boolean.class )
)
);
// Collect the target column references from the key expressions
final List<ColumnReference> targetColumnReferences = new ArrayList<>();
if ( targetTableKeyExpression instanceof SqlTuple ) {
//noinspection unchecked
targetColumnReferences.addAll( (Collection<? extends ColumnReference>) ( (SqlTuple) targetTableKeyExpression ).getExpressions() );
}
else {
targetColumnReferences.add( (ColumnReference) targetTableKeyExpression );
}
// And transform assignments to target column references and selections
for ( Assignment assignment : assignments ) {
targetColumnReferences.addAll( assignment.getAssignable().getColumnReferences() );
insertSourceSelectQuerySpec.getSelectClause().addSqlSelection(
new SqlSelectionImpl( assignment.getAssignedValue() )
);
}
final InsertSelectStatement insertSqlAst = new InsertSelectStatement( targetTableReference );
insertSqlAst.addTargetColumnReferences( targetColumnReferences.toArray( new ColumnReference[0] ) );
insertSqlAst.setSourceSelectStatement( insertSourceSelectQuerySpec );
return sqlAstTranslatorFactory
.buildMutationTranslator( sessionFactory, insertSqlAst )
.translate( firstJdbcParameterBindings, executionContext.getQueryOptions() );
}
protected QuerySpec createExistsSubQuerySpec(
String targetTableExpression,
Supplier<Consumer<SelectableConsumer>> tableKeyColumnVisitationSupplier,
QuerySpec idTableSubQuery,
SessionFactoryImplementor sessionFactory) {
final NamedTableReference existsTableReference = new NamedTableReference(
targetTableExpression,
"dml_"
);
// Prepare a not exists sub-query to avoid violating constraints
final QuerySpec existsSubQuerySpec = new QuerySpec( false );
existsSubQuerySpec.getSelectClause().addSqlSelection(
new SqlSelectionImpl(
new QueryLiteral<>(
1,
sessionFactory.getTypeConfiguration().getBasicTypeForJavaType( Integer.class )
)
)
);
existsSubQuerySpec.getFromClause().addRoot( new TableGroupImpl(
null,
null,
existsTableReference,
getEntityDescriptor()
) );
final TableKeyExpressionCollector existsKeyColumnCollector = new TableKeyExpressionCollector( getEntityDescriptor() );
tableKeyColumnVisitationSupplier.get().accept( (columnIndex, selection) -> {
assert selection.getContainingTableExpression().equals( targetTableExpression );
existsKeyColumnCollector.apply( new ColumnReference( existsTableReference, selection ) );
} );
existsSubQuerySpec.applyPredicate(
new ComparisonPredicate(
existsKeyColumnCollector.buildKeyExpression(),
ComparisonOperator.EQUAL,
asExpression( idTableSubQuery.getSelectClause())
)
);
return existsSubQuerySpec;
}
protected static QuerySpec makeInsertSourceSelectQuerySpec(QuerySpec idTableSubQuery) {
final QuerySpec idTableQuerySpec = new QuerySpec( true );
for ( TableGroup root : idTableSubQuery.getFromClause().getRoots() ) {
idTableQuerySpec.getFromClause().addRoot( root );
}
for ( SqlSelection sqlSelection : idTableSubQuery.getSelectClause().getSqlSelections() ) {
idTableQuerySpec.getSelectClause().addSqlSelection( sqlSelection );
}
idTableQuerySpec.applyPredicate( idTableSubQuery.getWhereClauseRestrictions() );
return idTableQuerySpec;
}
private JdbcOperationQueryMutation createTableUpdate(
QuerySpec idTableSubQuery,
ExecutionContext executionContext,
List<Assignment> assignments,
NamedTableReference dmlTableReference,
SqlAstTranslatorFactory sqlAstTranslatorFactory,
JdbcParameterBindings firstJdbcParameterBindings,
Expression keyExpression) {
final UpdateStatement sqlAst = new UpdateStatement(
dmlTableReference,
assignments,
new InSubQueryPredicate( keyExpression, idTableSubQuery, false )
);
return sqlAstTranslatorFactory
.buildMutationTranslator( executionContext.getSession().getFactory(), sqlAst )
.translate( firstJdbcParameterBindings, executionContext.getQueryOptions() );
}
protected Expression resolveMutatingTableKeyExpression(String tableExpression, Supplier<Consumer<SelectableConsumer>> tableKeyColumnVisitationSupplier) {
final TableKeyExpressionCollector keyColumnCollector = new TableKeyExpressionCollector( getEntityDescriptor() );
tableKeyColumnVisitationSupplier.get().accept(
(columnIndex, selection) -> {
assert selection.getContainingTableExpression().equals( tableExpression );
keyColumnCollector.apply( new ColumnReference( (String) null, selection ) );
}
);
return keyColumnCollector.buildKeyExpression();
}
protected Expression asExpression(SelectClause selectClause) {
final List<SqlSelection> sqlSelections = selectClause.getSqlSelections();
if ( sqlSelections.size() == 1 ) {
return sqlSelections.get( 0 ).getExpression();
}
final List<Expression> expressions = new ArrayList<>( sqlSelections.size() );
for ( SqlSelection sqlSelection : sqlSelections ) {
expressions.add( sqlSelection.getExpression() );
}
return new SqlTuple( expressions, null );
}
protected void collectTableReference(
TableReference tableReference,
BiConsumer<String, TableReference> consumer) {
consumer.accept( tableReference.getIdentificationVariable(), tableReference );
}
protected void collectTableReference(
TableReferenceJoin tableReferenceJoin,
BiConsumer<String, TableReference> consumer) {
collectTableReference( tableReferenceJoin.getJoinedTableReference(), consumer );
}
@Override
public int execute(JdbcParameterBindings jdbcParameterBindings, DomainQueryExecutionContext context) {
if ( LOG.isTraceEnabled() ) {
LOG.tracef(
"Starting multi-table update execution - %s",
getSqmStatement().getTarget().getModel().getName()
);
}
final SqmJdbcExecutionContextAdapter executionContext = SqmJdbcExecutionContextAdapter.omittingLockingAndPaging( context );
ExecuteWithTemporaryTableHelper.performBeforeTemporaryTableUseActions(
idTable,
temporaryTableStrategy,
executionContext
);
try {
final int rows = ExecuteWithTemporaryTableHelper.saveIntoTemporaryTable(
matchingIdsIntoIdTableInsert.jdbcOperation(),
jdbcParameterBindings,
executionContext
);
for ( TableUpdater tableUpdater : tableUpdaters ) {
updateTable(
tableUpdater,
rows,
jdbcParameterBindings,
executionContext
);
}
return rows;
}
finally {
ExecuteWithTemporaryTableHelper.performAfterTemporaryTableUseActions(
idTable,
sessionUidAccess,
getAfterUseAction(),
executionContext
);
}
}
private void updateTable(
TableUpdater tableUpdater,
int expectedUpdateCount,
JdbcParameterBindings jdbcParameterBindings,
ExecutionContext executionContext) {
if ( tableUpdater == null ) {
// no assignments for this table - skip it
return;
}
final int updateCount = executeMutation( tableUpdater.jdbcUpdate, jdbcParameterBindings, executionContext );
// We are done when the update count matches
if ( updateCount == expectedUpdateCount ) {
return;
}
// If the table is optional, execute an insert
if ( tableUpdater.jdbcInsert != null ) {
final int insertCount = executeMutation( tableUpdater.jdbcInsert, jdbcParameterBindings, executionContext );
assert insertCount + updateCount == expectedUpdateCount;
}
}
private int executeMutation(JdbcOperationQueryMutation jdbcUpdate, JdbcParameterBindings jdbcParameterBindings, ExecutionContext executionContext) {
return executionContext.getSession().getFactory().getJdbcServices().getJdbcMutationExecutor().execute(
jdbcUpdate,
jdbcParameterBindings,
sql -> executionContext.getSession()
.getJdbcCoordinator()
.getStatementPreparer()
.prepareStatement( sql ),
(integer, preparedStatement) -> {
},
executionContext
);
}
protected record TableUpdater(
JdbcOperationQueryMutation jdbcUpdate,
@Nullable JdbcOperationQueryMutation jdbcInsert) {
}
// For Hibernate reactive
protected List<TableUpdater> getTableUpdaters() {
return tableUpdaters;
}
// For Hibernate reactive
protected AfterUseAction getAfterUseAction() {
return forceDropAfterUse ? AfterUseAction.DROP : temporaryTableStrategy.getTemporaryTableAfterUseAction();
}
// For Hibernate reactive
protected TemporaryTable getIdTable() {
return idTable;
}
// For Hibernate reactive
protected TemporaryTableStrategy getTemporaryTableStrategy() {
return temporaryTableStrategy;
}
// For Hibernate reactive
protected CacheableSqmInterpretation<InsertSelectStatement, JdbcOperationQueryMutation> getMatchingIdsIntoIdTableInsert() {
return matchingIdsIntoIdTableInsert;
}
// For Hibernate reactive
protected Function<SharedSessionContractImplementor, String> getSessionUidAccess() {
return sessionUidAccess;
}
// For Hibernate reactive
protected @Nullable JdbcParameter getSessionUidParameter() {
return sessionUidParameter;
}
}
| TableBasedUpdateHandler |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/id/uuid/sqlrep/sqlchar/UuidAsCharAnnotationTest.java | {
"start": 2770,
"end": 3052
} | class ____ {
@Id
@GeneratedValue
@JdbcTypeCode( Types.VARCHAR )
UUID id;
String name;
@ManyToOne
Node parent;
Node() {
}
Node(String name) {
this.name = name;
}
Node(String name, Node parent) {
this.name = name;
this.parent = parent;
}
}
}
| Node |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/internal/InFlightMetadataCollectorImpl.java | {
"start": 34715,
"end": 35051
} | class ____ known: " + entityName );
}
return persistentClass.getIdentifier().getType();
}
@Override
public String getIdentifierPropertyName(String entityName) throws MappingException {
final var persistentClass = entityBindingMap.get( entityName );
if ( persistentClass == null ) {
throw new MappingException( "persistent | not |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/ProcessOperatorTest.java | {
"start": 7179,
"end": 8405
} | class ____ extends ProcessFunction<Integer, String> {
private static final long serialVersionUID = 1L;
private final TimeDomain timeDomain;
public QueryingProcessFunction(TimeDomain timeDomain) {
this.timeDomain = timeDomain;
}
@Override
public void processElement(Integer value, Context ctx, Collector<String> out)
throws Exception {
if (timeDomain.equals(TimeDomain.EVENT_TIME)) {
out.collect(
value
+ "TIME:"
+ ctx.timerService().currentWatermark()
+ " TS:"
+ ctx.timestamp());
} else {
out.collect(
value
+ "TIME:"
+ ctx.timerService().currentProcessingTime()
+ " TS:"
+ ctx.timestamp());
}
}
@Override
public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out)
throws Exception {}
}
}
| QueryingProcessFunction |
java | grpc__grpc-java | android-interop-testing/src/generated/debug/grpc/io/grpc/testing/integration/TestServiceGrpc.java | {
"start": 37821,
"end": 40726
} | class ____
extends io.grpc.stub.AbstractFutureStub<TestServiceFutureStub> {
private TestServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected TestServiceFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new TestServiceFutureStub(channel, callOptions);
}
/**
* <pre>
* One empty request followed by one empty response.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> emptyCall(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getEmptyCallMethod(), getCallOptions()), request);
}
/**
* <pre>
* One request followed by one response.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.SimpleResponse> unaryCall(
io.grpc.testing.integration.Messages.SimpleRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUnaryCallMethod(), getCallOptions()), request);
}
/**
* <pre>
* One request followed by one response. Response has cache control
* headers set such that a caching HTTP proxy (such as GFE) can
* satisfy subsequent requests.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.Messages.SimpleResponse> cacheableUnaryCall(
io.grpc.testing.integration.Messages.SimpleRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCacheableUnaryCallMethod(), getCallOptions()), request);
}
/**
* <pre>
* The test server will not implement this method. It will be used
* to test the behavior when clients call unimplemented methods.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<io.grpc.testing.integration.EmptyProtos.Empty> unimplementedCall(
io.grpc.testing.integration.EmptyProtos.Empty request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUnimplementedCallMethod(), getCallOptions()), request);
}
}
private static final int METHODID_EMPTY_CALL = 0;
private static final int METHODID_UNARY_CALL = 1;
private static final int METHODID_CACHEABLE_UNARY_CALL = 2;
private static final int METHODID_STREAMING_OUTPUT_CALL = 3;
private static final int METHODID_UNIMPLEMENTED_CALL = 4;
private static final int METHODID_STREAMING_INPUT_CALL = 5;
private static final int METHODID_FULL_DUPLEX_CALL = 6;
private static final int METHODID_HALF_DUPLEX_CALL = 7;
private static final | TestServiceFutureStub |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/factory/BeanRegistrar.java | {
"start": 1060,
"end": 1440
} | class ____ {
* }</pre>
* Can also be applied to an application context via
* {@link org.springframework.context.support.GenericApplicationContext#register(BeanRegistrar...)}.
*
*
* <p>Bean registrar implementations use {@link BeanRegistry} and {@link Environment}
* APIs to register beans programmatically in a concise and flexible way.
* <pre class="code">
* | MyConfiguration |
java | quarkusio__quarkus | extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/proxies/PreGeneratedProxies.java | {
"start": 812,
"end": 1237
} | class ____ {
private String className;
public ProxyClassDetailsHolder() {
}
public ProxyClassDetailsHolder(String className) {
this.className = className;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
}
| ProxyClassDetailsHolder |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/aot/hint/BindingReflectionHintsRegistrarTests.java | {
"start": 16053,
"end": 16331
} | class ____ {
@JsonProperty
@JsonDeserialize(using = CustomDeserializer1.class)
private String privateField = "";
@JsonProperty
@JsonDeserialize(using = CustomDeserializer2.class)
String packagePrivateMethod() {
return "";
}
}
static | SampleClassWithJsonProperty |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/dialect/redshift/stmt/RedshiftObjectImpl.java | {
"start": 193,
"end": 332
} | class ____ extends SQLObjectImpl implements RedshiftObject {
public abstract void accept0(RedshiftASTVisitor visitor);
}
| RedshiftObjectImpl |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/mapper/SyntheticIdField.java | {
"start": 809,
"end": 2537
} | class ____ extends Field {
public static final String NAME = IdFieldMapper.NAME;
private static final String ENABLED_ATTRIBUTE_KEY = SyntheticIdField.class.getSimpleName() + ".enabled";
private static final String ENABLED_ATTRIBUTE_VALUE = Boolean.TRUE.toString();
private static final FieldType TYPE;
static {
TYPE = new FieldType();
TYPE.putAttribute(ENABLED_ATTRIBUTE_KEY, ENABLED_ATTRIBUTE_VALUE);
// Make sure the field is not indexed, but this option is changed at runtime
// in FieldInfos so that the field can use terms and postings.
TYPE.setIndexOptions(IndexOptions.NONE);
TYPE.setTokenized(false);
TYPE.setOmitNorms(true);
// The field is marked as stored, but storage on disk might be skipped
TYPE.setStored(true);
TYPE.freeze();
}
public SyntheticIdField(BytesRef bytes) {
super(NAME, bytes, TYPE);
}
@Override
public TokenStream tokenStream(Analyzer analyzer, TokenStream reuse) {
assert false : "this should never be called";
throw new UnsupportedOperationException();
}
@Override
public void setTokenStream(TokenStream tokenStream) {
assert false : "this should never be called";
throw new UnsupportedOperationException();
}
public static boolean hasSyntheticIdAttributes(Map<String, String> attributes) {
if (attributes != null) {
var attributeValue = attributes.get(SyntheticIdField.ENABLED_ATTRIBUTE_KEY);
if (attributeValue != null) {
return SyntheticIdField.ENABLED_ATTRIBUTE_VALUE.equals(attributeValue);
}
}
return false;
}
}
| SyntheticIdField |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/test/SecurityAssertions.java | {
"start": 696,
"end": 1149
} | class ____ {
public static void assertContainsWWWAuthenticateHeader(ElasticsearchSecurityException e) {
assertThat(e.status(), is(RestStatus.UNAUTHORIZED));
assertThat(e.getBodyHeaderKeys(), hasSize(1));
assertThat(e.getBodyHeader("WWW-Authenticate"), notNullValue());
assertThat(e.getBodyHeader("WWW-Authenticate"), contains("Basic realm=\"" + XPackField.SECURITY + "\", charset=\"UTF-8\""));
}
}
| SecurityAssertions |
java | google__dagger | javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java | {
"start": 2431,
"end": 2563
} | interface ____ {",
" A getA();",
" }",
"",
" @Module",
" static | Parent |
java | elastic__elasticsearch | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/pytorch/PriorityProcessWorkerExecutorServiceTests.java | {
"start": 9304,
"end": 10262
} | class ____ extends AbstractInitializableRunnable {
private boolean hasBeenRun = false;
private boolean hasBeenRejected = false;
private final int expectedOrder;
private final AtomicInteger counter;
private boolean initialized = false;
RunOrderValidator(int expectedOrder, AtomicInteger counter) {
this.expectedOrder = expectedOrder;
this.counter = counter;
}
@Override
public void init() {
initialized = true;
}
@Override
public void onRejection(Exception e) {
hasBeenRejected = true;
}
@Override
public void onFailure(Exception e) {
fail(e.getMessage());
}
@Override
protected void doRun() {
hasBeenRun = true;
assertThat(expectedOrder, equalTo(counter.incrementAndGet()));
}
}
private static | RunOrderValidator |
java | elastic__elasticsearch | test/framework/src/test/java/org/elasticsearch/test/compiler/InMemoryJavaCompilerTests.java | {
"start": 1268,
"end": 1403
} | class ____ { }"), notNullValue());
}
public void testCompilePackage() {
assertThat(compile("p.Foo", "package p; public | Foo |
java | apache__maven | impl/maven-impl/src/test/java/org/apache/maven/impl/DefaultPluginXmlFactoryTest.java | {
"start": 2100,
"end": 16064
} | class ____ {
private static final String NAME = "sample-plugin-" + randomUUID();
private static final String SAMPLE_PLUGIN_XML = """
<?xml version="1.0" encoding="UTF-8"?>
<plugin>
<name>%s</name>
<groupId>org.example</groupId>
<artifactId>sample-plugin</artifactId>
<version>1.0.0</version>
</plugin>
""".formatted(NAME);
private final DefaultPluginXmlFactory defaultPluginXmlFactory = new DefaultPluginXmlFactory();
@TempDir
Path tempDir;
@Test
void readFromInputStreamParsesPluginDescriptorCorrectly() {
PluginDescriptor descriptor = defaultPluginXmlFactory.read(XmlReaderRequest.builder()
.inputStream(new ByteArrayInputStream(SAMPLE_PLUGIN_XML.getBytes()))
.build());
assertEquals(NAME, descriptor.getName());
assertEquals("org.example", descriptor.getGroupId());
assertEquals("sample-plugin", descriptor.getArtifactId());
assertEquals("1.0.0", descriptor.getVersion());
}
@Test
void parsePlugin() {
String actualName = defaultPluginXmlFactory
.read(XmlReaderRequest.builder()
.reader(new StringReader(SAMPLE_PLUGIN_XML))
.build())
.getName();
assertEquals(NAME, actualName, "Expected plugin name to be " + NAME + " but was " + actualName);
}
@Test
void readFromPathParsesPluginDescriptorCorrectly() throws Exception {
Path xmlFile = tempDir.resolve("plugin.xml");
Files.write(xmlFile, SAMPLE_PLUGIN_XML.getBytes());
String actualName = defaultPluginXmlFactory
.read(XmlReaderRequest.builder().path(xmlFile).build())
.getName();
assertEquals(NAME, actualName, "Expected plugin name to be " + NAME + " but was " + actualName);
}
@Test
void readWithNoInputThrowsIllegalArgumentException() {
assertThrows(
IllegalArgumentException.class,
() -> defaultPluginXmlFactory.read(XmlReaderRequest.builder().build()));
}
@Test
void writeToWriterGeneratesValidXml() {
StringWriter writer = new StringWriter();
defaultPluginXmlFactory.write(XmlWriterRequest.<PluginDescriptor>builder()
.writer(writer)
.content(PluginDescriptor.newBuilder()
.name(NAME)
.groupId("org.example")
.artifactId("sample-plugin")
.version("1.0.0")
.build())
.build());
String output = writer.toString();
assertTrue(
output.contains("<name>" + NAME + "</name>"),
"Expected " + output + " to contain " + "<name>" + NAME + "</name>");
assertTrue(
output.contains("<groupId>org.example</groupId>"),
"Expected " + output + " to contain " + "<groupId>org.example</groupId>");
}
@Test
void writeToOutputStreamGeneratesValidXml() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
defaultPluginXmlFactory.write(XmlWriterRequest.<PluginDescriptor>builder()
.outputStream(outputStream)
.content(PluginDescriptor.newBuilder().name(NAME).build())
.build());
String output = outputStream.toString();
assertTrue(
output.contains("<name>" + NAME + "</name>"),
"Expected output to contain <name>" + NAME + "</name> but was: " + output);
}
@Test
void writeToPathGeneratesValidXmlFile() throws Exception {
Path xmlFile = tempDir.resolve("output-plugin.xml");
defaultPluginXmlFactory.write(XmlWriterRequest.<PluginDescriptor>builder()
.path(xmlFile)
.content(PluginDescriptor.newBuilder().name(NAME).build())
.build());
String fileContent = Files.readString(xmlFile);
assertTrue(
fileContent.contains("<name>" + NAME + "</name>"),
"Expected file content to contain <name>" + NAME + "</name> but was: " + fileContent);
}
@Test
void fromXmlStringParsesValidXml() {
PluginDescriptor descriptor = defaultPluginXmlFactory.fromXmlString(SAMPLE_PLUGIN_XML);
assertEquals(
NAME,
descriptor.getName(),
"Expected descriptor name to be " + NAME + " but was " + descriptor.getName());
assertEquals(
"org.example",
descriptor.getGroupId(),
"Expected descriptor groupId to be org.example but was " + descriptor.getGroupId());
assertEquals(
"sample-plugin",
descriptor.getArtifactId(),
"Expected descriptor artifactId to be sample-plugin but was " + descriptor.getArtifactId());
assertEquals(
"1.0.0",
descriptor.getVersion(),
"Expected descriptor version to be 1.0.0 but was " + descriptor.getVersion());
}
@Test
void toXmlStringGeneratesValidXml() {
String xml = defaultPluginXmlFactory.toXmlString(PluginDescriptor.newBuilder()
.name(NAME)
.groupId("org.example")
.artifactId("sample-plugin")
.version("1.0.0")
.build());
assertTrue(
xml.contains("<name>" + NAME + "</name>"),
"Expected " + xml + " to contain " + "<name>" + NAME + "</name>");
assertTrue(
xml.contains("<groupId>org.example</groupId>"),
"Expected " + xml + " to contain " + "<groupId>org.example</groupId>");
assertTrue(
xml.contains("<artifactId>sample-plugin</artifactId>"),
"Expected " + xml + " to contain " + "<artifactId>sample-plugin</artifactId>");
assertTrue(
xml.contains("<version>1.0.0</version>"),
"Expected " + xml + " to contain " + "<version>1.0.0</version>");
}
@Test
void staticFromXmlParsesValidXml() {
PluginDescriptor descriptor = DefaultPluginXmlFactory.fromXml(SAMPLE_PLUGIN_XML);
assertEquals(
NAME,
descriptor.getName(),
"Expected descriptor name to be " + NAME + " but was " + descriptor.getName());
assertEquals(
"org.example",
descriptor.getGroupId(),
"Expected descriptor groupId to be org.example but was " + descriptor.getGroupId());
assertEquals(
"sample-plugin",
descriptor.getArtifactId(),
"Expected descriptor artifactId to be sample-plugin but was " + descriptor.getArtifactId());
assertEquals(
"1.0.0",
descriptor.getVersion(),
"Expected descriptor version to be 1.0.0 but was " + descriptor.getVersion());
}
@Test
void staticToXmlGeneratesValidXml() {
String xml = DefaultPluginXmlFactory.toXml(PluginDescriptor.newBuilder()
.name(NAME)
.groupId("org.example")
.artifactId("sample-plugin")
.version("1.0.0")
.build());
assertTrue(
xml.contains("<name>" + NAME + "</name>"),
"Expected " + xml + " to contain " + "<name>" + NAME + "</name>");
assertTrue(
xml.contains("<name>" + NAME + "</name>"),
"Expected " + xml + " to contain " + "<name>" + NAME + "</name>");
assertTrue(
xml.contains("<groupId>org.example</groupId>"),
"Expected " + xml + " to contain " + "<groupId>org.example</groupId>");
assertTrue(
xml.contains("<artifactId>sample-plugin</artifactId>"),
"Expected " + xml + " to contain " + "<artifactId>sample-plugin</artifactId>");
assertTrue(
xml.contains("<version>1.0.0</version>"),
"Expected " + xml + " to contain " + "<version>1.0.0</version>");
}
@Test
void writeWithFailingWriterThrowsXmlWriterException() {
String unableToWritePlugin = "Unable to write plugin" + randomUUID();
String ioEx = "ioEx" + randomUUID();
XmlWriterException exception = assertThrows(
XmlWriterException.class,
() -> defaultPluginXmlFactory.write(XmlWriterRequest.<PluginDescriptor>builder()
.writer(new Writer() {
@Override
public void write(char[] cbuf, int off, int len) {
throw new XmlWriterException(unableToWritePlugin, null, new IOException(ioEx));
}
@Override
public void flush() {}
@Override
public void close() {}
})
.content(PluginDescriptor.newBuilder()
.name("Failing Plugin")
.build())
.build()));
assertTrue(exception.getMessage().contains(unableToWritePlugin));
assertInstanceOf(XmlWriterException.class, exception.getCause());
assertEquals(ioEx, exception.getCause().getCause().getMessage());
assertEquals(unableToWritePlugin, exception.getCause().getMessage());
}
@Test
void writeWithNoTargetThrowsIllegalArgumentException() {
IllegalArgumentException exception = assertThrows(
IllegalArgumentException.class,
() -> defaultPluginXmlFactory.write(XmlWriterRequest.<PluginDescriptor>builder()
.content(PluginDescriptor.newBuilder()
.name("No Output Plugin")
.build())
.build()));
assertEquals(
"writer, outputStream or path must be non null",
exception.getMessage(),
"Expected specific error message but was: " + exception.getMessage());
}
@Test
void readMalformedXmlThrowsXmlReaderException() {
XmlReaderException exception = assertThrows(
XmlReaderException.class,
() -> defaultPluginXmlFactory.read(XmlReaderRequest.builder()
.inputStream(new ByteArrayInputStream("<plugin><name>Broken Plugin".getBytes()))
.build()));
assertTrue(exception.getMessage().contains("Unable to read plugin"));
assertInstanceOf(WstxEOFException.class, exception.getCause());
}
@Test
void locateExistingPomWithFilePathShouldReturnSameFileIfRegularFile() throws IOException {
Path pomFile = Files.createTempFile(tempDir, "pom", ".xml");
DefaultModelProcessor processor = new DefaultModelProcessor(mock(ModelXmlFactory.class), List.of());
assertEquals(
pomFile, processor.locateExistingPom(pomFile), "Expected locateExistingPom to return the same file");
}
@Test
void readFromUrlParsesPluginDescriptorCorrectly() throws Exception {
Path xmlFile = tempDir.resolve("plugin.xml");
Files.write(xmlFile, SAMPLE_PLUGIN_XML.getBytes());
PluginDescriptor descriptor;
try (InputStream inputStream = xmlFile.toUri().toURL().openStream()) {
descriptor = defaultPluginXmlFactory.read(
XmlReaderRequest.builder().inputStream(inputStream).build());
}
assertEquals(
NAME,
descriptor.getName(),
"Expected descriptor name to be " + NAME + " but was " + descriptor.getName());
assertEquals(
"org.example",
descriptor.getGroupId(),
"Expected descriptor groupId to be org.example but was " + descriptor.getGroupId());
assertEquals(
"sample-plugin",
descriptor.getArtifactId(),
"Expected descriptor artifactId to be sample-plugin but was " + descriptor.getArtifactId());
assertEquals(
"1.0.0",
descriptor.getVersion(),
"Expected descriptor version to be 1.0.0 but was " + descriptor.getVersion());
}
@Test
void testReadWithPath() throws Exception {
Path tempPath = Files.createTempFile("plugin", ".xml");
Files.writeString(tempPath, "<plugin/>");
XmlReaderRequest request = mock(XmlReaderRequest.class);
when(request.getPath()).thenReturn(tempPath);
when(request.getInputStream()).thenReturn(null);
when(request.getReader()).thenReturn(null);
when(request.getURL()).thenReturn(null);
when(request.isAddDefaultEntities()).thenReturn(false);
when(request.isStrict()).thenReturn(false);
assertNotNull(new DefaultPluginXmlFactory().read(request));
Files.deleteIfExists(tempPath);
}
@Test
void testReadWithPathUrlDefault() throws Exception {
Path tempPath = Files.createTempFile("plugin", ".xml");
Files.writeString(tempPath, "<plugin/>");
XmlReaderRequest request = mock(XmlReaderRequest.class);
when(request.getPath()).thenReturn(null);
when(request.getInputStream()).thenReturn(null);
when(request.getReader()).thenReturn(null);
when(request.getURL()).thenReturn(tempPath.toUri().toURL());
when(request.isAddDefaultEntities()).thenReturn(false);
when(request.isStrict()).thenReturn(false);
assertNotNull(new DefaultPluginXmlFactory().read(request));
Files.deleteIfExists(tempPath);
}
}
| DefaultPluginXmlFactoryTest |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/taskexecutor/TaskManagerServices.java | {
"start": 13838,
"end": 26060
} | class ____ OOMs
* @param workingDirectory the working directory of the process
* @return task manager components
* @throws Exception
*/
public static TaskManagerServices fromConfiguration(
TaskManagerServicesConfiguration taskManagerServicesConfiguration,
PermanentBlobService permanentBlobService,
MetricGroup taskManagerMetricGroup,
ExecutorService ioExecutor,
ScheduledExecutor scheduledExecutor,
FatalErrorHandler fatalErrorHandler,
WorkingDirectory workingDirectory)
throws Exception {
// pre-start checks
checkTempDirs(taskManagerServicesConfiguration.getTmpDirPaths());
final TaskEventDispatcher taskEventDispatcher = new TaskEventDispatcher();
// start the I/O manager, it will create some temp directories.
final IOManager ioManager =
new IOManagerAsync(taskManagerServicesConfiguration.getTmpDirPaths(), ioExecutor);
final ShuffleEnvironment<?, ?> shuffleEnvironment =
createShuffleEnvironment(
taskManagerServicesConfiguration,
taskEventDispatcher,
taskManagerMetricGroup,
ioExecutor,
scheduledExecutor);
final int listeningDataPort = shuffleEnvironment.start();
LOG.info(
"TaskManager data connection initialized successfully; listening internally on port: {}",
listeningDataPort);
final KvStateService kvStateService =
KvStateService.fromConfiguration(taskManagerServicesConfiguration);
kvStateService.start();
final UnresolvedTaskManagerLocation unresolvedTaskManagerLocation =
new UnresolvedTaskManagerLocation(
taskManagerServicesConfiguration.getResourceID(),
taskManagerServicesConfiguration.getExternalAddress(),
// we expose the task manager location with the listening port
// iff the external data port is not explicitly defined
taskManagerServicesConfiguration.getExternalDataPort() > 0
? taskManagerServicesConfiguration.getExternalDataPort()
: listeningDataPort,
taskManagerServicesConfiguration.getNodeId());
final BroadcastVariableManager broadcastVariableManager = new BroadcastVariableManager();
final TaskSlotTable<Task> taskSlotTable =
createTaskSlotTable(
taskManagerServicesConfiguration.getNumberOfSlots(),
taskManagerServicesConfiguration.getTaskExecutorResourceSpec(),
taskManagerServicesConfiguration.getTimerServiceShutdownTimeout(),
taskManagerServicesConfiguration.getPageSize(),
ioExecutor);
final JobTable jobTable = DefaultJobTable.create();
final JobLeaderService jobLeaderService =
new DefaultJobLeaderService(
unresolvedTaskManagerLocation,
taskManagerServicesConfiguration.getRetryingRegistrationConfiguration());
final TaskExecutorLocalStateStoresManager taskStateManager =
new TaskExecutorLocalStateStoresManager(
taskManagerServicesConfiguration.isLocalRecoveryEnabled(),
taskManagerServicesConfiguration.isLocalBackupEnabled(),
taskManagerServicesConfiguration.getLocalRecoveryStateDirectories(),
ioExecutor);
final TaskExecutorStateChangelogStoragesManager changelogStoragesManager =
new TaskExecutorStateChangelogStoragesManager();
final TaskExecutorChannelStateExecutorFactoryManager channelStateExecutorFactoryManager =
new TaskExecutorChannelStateExecutorFactoryManager();
final TaskExecutorFileMergingManager fileMergingManager =
new TaskExecutorFileMergingManager();
final boolean failOnJvmMetaspaceOomError =
taskManagerServicesConfiguration
.getConfiguration()
.get(CoreOptions.FAIL_ON_USER_CLASS_LOADING_METASPACE_OOM);
final boolean checkClassLoaderLeak =
taskManagerServicesConfiguration
.getConfiguration()
.get(CoreOptions.CHECK_LEAKED_CLASSLOADER);
final LibraryCacheManager libraryCacheManager =
new BlobLibraryCacheManager(
permanentBlobService,
BlobLibraryCacheManager.defaultClassLoaderFactory(
taskManagerServicesConfiguration.getClassLoaderResolveOrder(),
taskManagerServicesConfiguration
.getAlwaysParentFirstLoaderPatterns(),
failOnJvmMetaspaceOomError ? fatalErrorHandler : null,
checkClassLoaderLeak),
false);
final SlotAllocationSnapshotPersistenceService slotAllocationSnapshotPersistenceService;
if (taskManagerServicesConfiguration.isLocalRecoveryEnabled()) {
slotAllocationSnapshotPersistenceService =
new FileSlotAllocationSnapshotPersistenceService(
workingDirectory.getSlotAllocationSnapshotDirectory());
} else {
slotAllocationSnapshotPersistenceService =
NoOpSlotAllocationSnapshotPersistenceService.INSTANCE;
}
final GroupCache<JobID, PermanentBlobKey, JobInformation> jobInformationCache =
new DefaultGroupCache.Factory<JobID, PermanentBlobKey, JobInformation>().create();
final GroupCache<JobID, PermanentBlobKey, TaskInformation> taskInformationCache =
new DefaultGroupCache.Factory<JobID, PermanentBlobKey, TaskInformation>().create();
final GroupCache<JobID, PermanentBlobKey, ShuffleDescriptorGroup> shuffleDescriptorsCache =
new DefaultGroupCache.Factory<JobID, PermanentBlobKey, ShuffleDescriptorGroup>()
.create();
return new TaskManagerServices(
unresolvedTaskManagerLocation,
taskManagerServicesConfiguration.getManagedMemorySize().getBytes(),
ioManager,
shuffleEnvironment,
kvStateService,
broadcastVariableManager,
taskSlotTable,
jobTable,
jobLeaderService,
taskStateManager,
fileMergingManager,
changelogStoragesManager,
channelStateExecutorFactoryManager,
taskEventDispatcher,
ioExecutor,
libraryCacheManager,
slotAllocationSnapshotPersistenceService,
new SharedResources(),
jobInformationCache,
taskInformationCache,
shuffleDescriptorsCache);
}
private static TaskSlotTable<Task> createTaskSlotTable(
final int numberOfSlots,
final TaskExecutorResourceSpec taskExecutorResourceSpec,
final long timerServiceShutdownTimeout,
final int pageSize,
final Executor memoryVerificationExecutor) {
final TimerService<AllocationID> timerService =
new DefaultTimerService<>(
new ScheduledThreadPoolExecutor(1), timerServiceShutdownTimeout);
return new TaskSlotTableImpl<>(
numberOfSlots,
TaskExecutorResourceUtils.generateTotalAvailableResourceProfile(
taskExecutorResourceSpec),
TaskExecutorResourceUtils.generateDefaultSlotResourceProfile(
taskExecutorResourceSpec, numberOfSlots),
pageSize,
timerService,
memoryVerificationExecutor);
}
private static ShuffleEnvironment<?, ?> createShuffleEnvironment(
TaskManagerServicesConfiguration taskManagerServicesConfiguration,
TaskEventDispatcher taskEventDispatcher,
MetricGroup taskManagerMetricGroup,
Executor ioExecutor,
ScheduledExecutor scheduledExecutor)
throws FlinkException {
final ShuffleEnvironmentContext shuffleEnvironmentContext =
new ShuffleEnvironmentContext(
taskManagerServicesConfiguration.getConfiguration(),
taskManagerServicesConfiguration.getResourceID(),
taskManagerServicesConfiguration.getNetworkMemorySize(),
taskManagerServicesConfiguration.isLocalCommunicationOnly(),
taskManagerServicesConfiguration.getBindAddress(),
taskManagerServicesConfiguration.getNumberOfSlots(),
taskManagerServicesConfiguration.getTmpDirPaths(),
taskEventDispatcher,
taskManagerMetricGroup,
ioExecutor,
scheduledExecutor);
return ShuffleServiceLoader.loadShuffleServiceFactory(
taskManagerServicesConfiguration.getConfiguration())
.createShuffleEnvironment(shuffleEnvironmentContext);
}
/**
* Validates that all the directories denoted by the strings do actually exist or can be
* created, are proper directories (not files), and are writable.
*
* @param tmpDirs The array of directory paths to check.
* @throws IOException Thrown if any of the directories does not exist and cannot be created or
* is not writable or is a file, rather than a directory.
*/
private static void checkTempDirs(String[] tmpDirs) throws IOException {
for (String dir : tmpDirs) {
if (dir != null && !dir.equals("")) {
File file = new File(dir);
if (!file.exists()) {
if (!file.mkdirs()) {
throw new IOException(
"Temporary file directory "
+ file.getAbsolutePath()
+ " does not exist and could not be created.");
}
}
if (!file.isDirectory()) {
throw new IOException(
"Temporary file directory "
+ file.getAbsolutePath()
+ " is not a directory.");
}
if (!file.canWrite()) {
throw new IOException(
"Temporary file directory "
+ file.getAbsolutePath()
+ " is not writable.");
}
if (LOG.isInfoEnabled()) {
long totalSpaceGb = file.getTotalSpace() >> 30;
long usableSpaceGb = file.getUsableSpace() >> 30;
double usablePercentage = (double) usableSpaceGb / totalSpaceGb * 100;
String path = file.getAbsolutePath();
LOG.info(
String.format(
"Temporary file directory '%s': total %d GB, "
+ "usable %d GB (%.2f%% usable)",
path, totalSpaceGb, usableSpaceGb, usablePercentage));
}
} else {
throw new IllegalArgumentException("Temporary file directory #$id is null.");
}
}
}
public SlotAllocationSnapshotPersistenceService getSlotAllocationSnapshotPersistenceService() {
return slotAllocationSnapshotPersistenceService;
}
}
| loading |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java | {
"start": 20817,
"end": 21121
} | class ____ maintaining a group of Lifecycle beans that should be started
* and stopped together based on their 'phase' value (or the default value of 0).
* The group is expected to be created in an ad-hoc fashion and group members are
* expected to always have the same 'phase' value.
*/
private | for |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/user/HasPrivilegesRequestBuilderFactory.java | {
"start": 371,
"end": 478
} | interface ____ {
HasPrivilegesRequestBuilder create(Client client);
| HasPrivilegesRequestBuilderFactory |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/api/JsonOnNull.java | {
"start": 1197,
"end": 1353
} | enum ____ implements TableSymbol {
/** Use a JSON {@code null} value. */
NULL,
/** Omit this key from the resulting JSON. */
ABSENT
}
| JsonOnNull |
java | quarkusio__quarkus | extensions/scheduler/deployment/src/test/java/io/quarkus/scheduler/test/NonStaticScheduledInterfaceTest.java | {
"start": 271,
"end": 640
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest test = new QuarkusUnitTest()
.setExpectedException(IllegalStateException.class)
.withApplicationRoot(root -> root
.addClasses(InterfaceWitchScheduledMethod.class));
@Test
public void test() {
fail();
}
| NonStaticScheduledInterfaceTest |
java | apache__kafka | group-coordinator/src/test/java/org/apache/kafka/coordinator/group/GroupCoordinatorServiceTest.java | {
"start": 280420,
"end": 283802
} | class ____ {
private final LogContext logContext = new LogContext();
private final GroupConfigManager configManager = createConfigManager();
private GroupCoordinatorConfig config;
private CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime;
private GroupCoordinatorMetrics metrics = new GroupCoordinatorMetrics();
private Persister persister = new NoOpStatePersister();
private CoordinatorMetadataImage metadataImage = null;
private PartitionMetadataClient partitionMetadataClient = null;
GroupCoordinatorService build() {
return build(false);
}
GroupCoordinatorService build(boolean serviceStartup) {
if (metadataImage == null) {
metadataImage = mock(CoordinatorMetadataImage.class);
}
GroupCoordinatorService service = new GroupCoordinatorService(
logContext,
config,
runtime,
metrics,
configManager,
persister,
new MockTimer(),
partitionMetadataClient
);
if (serviceStartup) {
service.startup(() -> 1);
service.onNewMetadataImage(metadataImage, null);
}
when(metadataImage.topicNames()).thenReturn(Set.of(TOPIC_NAME));
var topicMetadata = mock(CoordinatorMetadataImage.TopicMetadata.class);
when(topicMetadata.name()).thenReturn(TOPIC_NAME);
when(topicMetadata.id()).thenReturn(TOPIC_ID);
when(metadataImage.topicMetadata(TOPIC_ID)).thenReturn(Optional.of(topicMetadata));
when(metadataImage.topicMetadata(TOPIC_NAME)).thenReturn(Optional.of(topicMetadata));
return service;
}
public GroupCoordinatorServiceBuilder setConfig(GroupCoordinatorConfig config) {
this.config = config;
return this;
}
public GroupCoordinatorServiceBuilder setRuntime(CoordinatorRuntime<GroupCoordinatorShard, CoordinatorRecord> runtime) {
this.runtime = runtime;
return this;
}
public GroupCoordinatorServiceBuilder setPersister(Persister persister) {
this.persister = persister;
return this;
}
public GroupCoordinatorServiceBuilder setMetrics(GroupCoordinatorMetrics metrics) {
this.metrics = metrics;
return this;
}
public GroupCoordinatorServiceBuilder setPartitionMetadataClient(PartitionMetadataClient partitionMetadataClient) {
this.partitionMetadataClient = partitionMetadataClient;
return this;
}
}
private static DeleteShareGroupStateParameters createDeleteShareRequest(String groupId, Uuid topic, List<Integer> partitions) {
TopicData<PartitionIdData> topicData = new TopicData<>(topic,
partitions.stream().map(PartitionFactory::newPartitionIdData).toList()
);
return new DeleteShareGroupStateParameters.Builder()
.setGroupTopicPartitionData(new GroupTopicPartitionData.Builder<PartitionIdData>()
.setGroupId(groupId)
.setTopicsData(List.of(topicData))
.build())
.build();
}
}
| GroupCoordinatorServiceBuilder |
java | apache__camel | components/camel-huawei/camel-huaweicloud-imagerecognition/src/test/java/org/apache/camel/component/huaweicloud/image/ImageClientMock.java | {
"start": 1240,
"end": 1713
} | class ____ extends ImageClient {
public ImageClientMock(HcClient hcClient) {
super(null);
}
@Override
public RunCelebrityRecognitionResponse runCelebrityRecognition(RunCelebrityRecognitionRequest request) {
return MockResult.getCelebrityRecognitionResponse();
}
@Override
public RunImageTaggingResponse runImageTagging(RunImageTaggingRequest request) {
return MockResult.getTagRecognitionResponse();
}
}
| ImageClientMock |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherFactoryTests.java | {
"start": 17109,
"end": 17236
} | class ____ {
@Test
void dummyTest() {
// Just a placeholder to trigger the extension
}
}
static | SessionStoringTestCase |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/XsltSaxonEndpointBuilderFactory.java | {
"start": 14346,
"end": 29619
} | interface ____
extends
EndpointProducerBuilder {
default XsltSaxonEndpointBuilder basic() {
return (XsltSaxonEndpointBuilder) this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* To use a custom org.xml.sax.EntityResolver with
* javax.xml.transform.sax.SAXSource.
*
* The option is a: <code>org.xml.sax.EntityResolver</code> type.
*
* Group: advanced
*
* @param entityResolver the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder entityResolver(org.xml.sax.EntityResolver entityResolver) {
doSetProperty("entityResolver", entityResolver);
return this;
}
/**
* To use a custom org.xml.sax.EntityResolver with
* javax.xml.transform.sax.SAXSource.
*
* The option will be converted to a
* <code>org.xml.sax.EntityResolver</code> type.
*
* Group: advanced
*
* @param entityResolver the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder entityResolver(String entityResolver) {
doSetProperty("entityResolver", entityResolver);
return this;
}
/**
* Allows to configure to use a custom
* javax.xml.transform.ErrorListener. Beware when doing this then the
* default error listener which captures any errors or fatal errors and
* store information on the Exchange as properties is not in use. So
* only use this option for special use-cases.
*
* The option is a: <code>javax.xml.transform.ErrorListener</code> type.
*
* Group: advanced
*
* @param errorListener the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder errorListener(javax.xml.transform.ErrorListener errorListener) {
doSetProperty("errorListener", errorListener);
return this;
}
/**
* Allows to configure to use a custom
* javax.xml.transform.ErrorListener. Beware when doing this then the
* default error listener which captures any errors or fatal errors and
* store information on the Exchange as properties is not in use. So
* only use this option for special use-cases.
*
* The option will be converted to a
* <code>javax.xml.transform.ErrorListener</code> type.
*
* Group: advanced
*
* @param errorListener the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder errorListener(String errorListener) {
doSetProperty("errorListener", errorListener);
return this;
}
/**
* Allows you to use a custom
* org.apache.camel.builder.xml.ResultHandlerFactory which is capable of
* using custom org.apache.camel.builder.xml.ResultHandler types.
*
* The option is a:
* <code>org.apache.camel.component.xslt.ResultHandlerFactory</code>
* type.
*
* Group: advanced
*
* @param resultHandlerFactory the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder resultHandlerFactory(org.apache.camel.component.xslt.ResultHandlerFactory resultHandlerFactory) {
doSetProperty("resultHandlerFactory", resultHandlerFactory);
return this;
}
/**
* Allows you to use a custom
* org.apache.camel.builder.xml.ResultHandlerFactory which is capable of
* using custom org.apache.camel.builder.xml.ResultHandler types.
*
* The option will be converted to a
* <code>org.apache.camel.component.xslt.ResultHandlerFactory</code>
* type.
*
* Group: advanced
*
* @param resultHandlerFactory the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder resultHandlerFactory(String resultHandlerFactory) {
doSetProperty("resultHandlerFactory", resultHandlerFactory);
return this;
}
/**
* To use a custom Saxon configuration.
*
* The option is a: <code>net.sf.saxon.Configuration</code> type.
*
* Group: advanced
*
* @param saxonConfiguration the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder saxonConfiguration(net.sf.saxon.Configuration saxonConfiguration) {
doSetProperty("saxonConfiguration", saxonConfiguration);
return this;
}
/**
* To use a custom Saxon configuration.
*
* The option will be converted to a
* <code>net.sf.saxon.Configuration</code> type.
*
* Group: advanced
*
* @param saxonConfiguration the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder saxonConfiguration(String saxonConfiguration) {
doSetProperty("saxonConfiguration", saxonConfiguration);
return this;
}
/**
* Allows you to use a custom
* net.sf.saxon.lib.ExtensionFunctionDefinition. You would need to add
* camel-saxon to the classpath. The function is looked up in the
* registry, where you can comma to separate multiple values to lookup.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param saxonExtensionFunctions the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder saxonExtensionFunctions(String saxonExtensionFunctions) {
doSetProperty("saxonExtensionFunctions", saxonExtensionFunctions);
return this;
}
/**
* Feature for XML secure processing (see javax.xml.XMLConstants). This
* is enabled by default. However, when using Saxon Professional you may
* need to turn this off to allow Saxon to be able to use Java extension
* functions.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param secureProcessing the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder secureProcessing(boolean secureProcessing) {
doSetProperty("secureProcessing", secureProcessing);
return this;
}
/**
* Feature for XML secure processing (see javax.xml.XMLConstants). This
* is enabled by default. However, when using Saxon Professional you may
* need to turn this off to allow Saxon to be able to use Java extension
* functions.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param secureProcessing the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder secureProcessing(String secureProcessing) {
doSetProperty("secureProcessing", secureProcessing);
return this;
}
/**
* To use a custom XSLT transformer factory.
*
* The option is a: <code>javax.xml.transform.TransformerFactory</code>
* type.
*
* Group: advanced
*
* @param transformerFactory the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder transformerFactory(javax.xml.transform.TransformerFactory transformerFactory) {
doSetProperty("transformerFactory", transformerFactory);
return this;
}
/**
* To use a custom XSLT transformer factory.
*
* The option will be converted to a
* <code>javax.xml.transform.TransformerFactory</code> type.
*
* Group: advanced
*
* @param transformerFactory the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder transformerFactory(String transformerFactory) {
doSetProperty("transformerFactory", transformerFactory);
return this;
}
/**
* To use a custom XSLT transformer factory, specified as a FQN class
* name.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param transformerFactoryClass the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder transformerFactoryClass(String transformerFactoryClass) {
doSetProperty("transformerFactoryClass", transformerFactoryClass);
return this;
}
/**
* A configuration strategy to apply on freshly created instances of
* TransformerFactory.
*
* The option is a:
* <code>org.apache.camel.component.xslt.TransformerFactoryConfigurationStrategy</code> type.
*
* Group: advanced
*
* @param transformerFactoryConfigurationStrategy the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder transformerFactoryConfigurationStrategy(org.apache.camel.component.xslt.TransformerFactoryConfigurationStrategy transformerFactoryConfigurationStrategy) {
doSetProperty("transformerFactoryConfigurationStrategy", transformerFactoryConfigurationStrategy);
return this;
}
/**
* A configuration strategy to apply on freshly created instances of
* TransformerFactory.
*
* The option will be converted to a
* <code>org.apache.camel.component.xslt.TransformerFactoryConfigurationStrategy</code> type.
*
* Group: advanced
*
* @param transformerFactoryConfigurationStrategy the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder transformerFactoryConfigurationStrategy(String transformerFactoryConfigurationStrategy) {
doSetProperty("transformerFactoryConfigurationStrategy", transformerFactoryConfigurationStrategy);
return this;
}
/**
* To use a custom javax.xml.transform.URIResolver.
*
* The option is a: <code>javax.xml.transform.URIResolver</code> type.
*
* Group: advanced
*
* @param uriResolver the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder uriResolver(javax.xml.transform.URIResolver uriResolver) {
doSetProperty("uriResolver", uriResolver);
return this;
}
/**
* To use a custom javax.xml.transform.URIResolver.
*
* The option will be converted to a
* <code>javax.xml.transform.URIResolver</code> type.
*
* Group: advanced
*
* @param uriResolver the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder uriResolver(String uriResolver) {
doSetProperty("uriResolver", uriResolver);
return this;
}
/**
* A consumer to messages generated during XSLT transformations.
*
* The option is a:
* <code>org.apache.camel.component.xslt.XsltMessageLogger</code> type.
*
* Group: advanced
*
* @param xsltMessageLogger the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder xsltMessageLogger(org.apache.camel.component.xslt.XsltMessageLogger xsltMessageLogger) {
doSetProperty("xsltMessageLogger", xsltMessageLogger);
return this;
}
/**
* A consumer to messages generated during XSLT transformations.
*
* The option will be converted to a
* <code>org.apache.camel.component.xslt.XsltMessageLogger</code> type.
*
* Group: advanced
*
* @param xsltMessageLogger the value to set
* @return the dsl builder
*/
default AdvancedXsltSaxonEndpointBuilder xsltMessageLogger(String xsltMessageLogger) {
doSetProperty("xsltMessageLogger", xsltMessageLogger);
return this;
}
}
public | AdvancedXsltSaxonEndpointBuilder |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/idempotent/SpringCacheIdempotentTest.java | {
"start": 1152,
"end": 1846
} | class ____ extends ContextTestSupport {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this, "org/apache/camel/spring/processor/idempotent/SpringCacheIdempotentTest.xml");
}
@Test
public void testIdempotent() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
String messageId = UUID.randomUUID().toString();
for (int i = 0; i < 5; i++) {
template.sendBodyAndHeader("direct:start", UUID.randomUUID().toString(), "MessageId", messageId);
}
mock.assertIsSatisfied();
}
}
| SpringCacheIdempotentTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.