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
|
micronaut-projects__micronaut-core
|
inject/src/main/java/io/micronaut/context/event/BeanInitializingEvent.java
|
{
"start": 1114,
"end": 1478
}
|
class ____<T> extends BeanEvent<T> {
/**
* @param beanContext The bean context
* @param beanDefinition The bean definition
* @param bean The bean
*/
public BeanInitializingEvent(BeanContext beanContext, BeanDefinition<T> beanDefinition, T bean) {
super(beanContext, beanDefinition, bean);
}
}
|
BeanInitializingEvent
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/error/ShouldOnlyHaveElementsOfTypes_create_Test.java
|
{
"start": 1122,
"end": 2126
}
|
class ____ {
@Test
void should_create_error_message() {
// GIVEN
ErrorMessageFactory factory = shouldOnlyHaveElementsOfTypes(list("Yoda", 42, "Luke"),
array(Number.class, Long.class),
list("Yoda", "Luke"));
// WHEN
String message = factory.create(new TestDescription("Test"), new StandardRepresentation());
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting actual:%n" +
" [\"Yoda\", 42, \"Luke\"]%n" +
"to only have instances of:%n" +
" [java.lang.Number, java.lang.Long]%n" +
"but these elements are not:%n" +
" [\"Yoda\" (java.lang.String), \"Luke\" (java.lang.String)]"));
}
}
|
ShouldOnlyHaveElementsOfTypes_create_Test
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/errors/UnsupportedForMessageFormatException.java
|
{
"start": 1065,
"end": 1422
}
|
class ____ extends InvalidConfigurationException {
private static final long serialVersionUID = 1L;
public UnsupportedForMessageFormatException(String message) {
super(message);
}
public UnsupportedForMessageFormatException(String message, Throwable cause) {
super(message, cause);
}
}
|
UnsupportedForMessageFormatException
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/embeddables/DollarValueUserType.java
|
{
"start": 469,
"end": 1880
}
|
class ____ implements UserType<DollarValue> {
@Override
public int getSqlType() {
return Types.BIGINT;
}
@Override
public Class<DollarValue> returnedClass() {
return DollarValue.class;
}
@Override
public boolean equals(DollarValue x, DollarValue y) throws HibernateException {
return x.getAmount().equals(y.getAmount());
}
@Override
public int hashCode(DollarValue x) throws HibernateException {
return x.getAmount().hashCode();
}
@Override
public DollarValue nullSafeGet(ResultSet rs, int position, WrapperOptions options)
throws SQLException {
return new DollarValue( rs.getBigDecimal( position ) );
}
@Override
public void nullSafeSet(
PreparedStatement st,
DollarValue value,
int index,
WrapperOptions options) throws SQLException {
st.setBigDecimal(index, value.getAmount());
}
@Override
public DollarValue deepCopy(DollarValue value) throws HibernateException {
return new DollarValue();
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(DollarValue value) throws HibernateException {
return null;
}
@Override
public DollarValue assemble(Serializable cached, Object owner)
throws HibernateException {
return null;
}
@Override
public DollarValue replace(DollarValue original, DollarValue target, Object owner)
throws HibernateException {
return null;
}
}
|
DollarValueUserType
|
java
|
alibaba__nacos
|
persistence/src/main/java/com/alibaba/nacos/persistence/constants/PersistenceConstant.java
|
{
"start": 731,
"end": 1700
}
|
class ____ {
public static final String DEFAULT_ENCODE = "UTF-8";
/**
* May be removed with the upgrade of springboot version.
*/
public static final String DATASOURCE_PLATFORM_PROPERTY_OLD = "spring.datasource.platform";
public static final String DATASOURCE_PLATFORM_PROPERTY = "spring.sql.init.platform";
public static final String MYSQL = "mysql";
public static final String DERBY = "derby";
public static final String EMPTY_DATASOURCE_PLATFORM = "";
public static final String EMBEDDED_STORAGE = "embeddedStorage";
/**
* The derby base dir.
*/
public static final String DERBY_BASE_DIR = "derby-data";
/**
* Specifies that reads wait without timeout.
*/
public static final String EXTEND_NEED_READ_UNTIL_HAVE_DATA = "00--0-read-join-0--00";
public static final String CONFIG_MODEL_RAFT_GROUP = "nacos_config";
}
|
PersistenceConstant
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/Storage.java
|
{
"start": 5025,
"end": 5254
}
|
interface ____ {
public StorageDirType getStorageDirType();
public boolean isOfType(StorageDirType type);
}
private final List<StorageDirectory> storageDirs =
new CopyOnWriteArrayList<>();
private
|
StorageDirType
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/tenantid/Client.java
|
{
"start": 391,
"end": 629
}
|
class ____ {
@Id
@GeneratedValue
Long id;
String name;
@TenantId
String tenantId;
@OneToMany(mappedBy = "client")
Set<Account> accounts = new HashSet<>();
public Client(String name) {
this.name = name;
}
Client() {}
}
|
Client
|
java
|
netty__netty
|
transport/src/main/java/io/netty/channel/SelectStrategy.java
|
{
"start": 936,
"end": 1933
}
|
interface ____ {
/**
* Indicates a blocking select should follow.
*/
int SELECT = -1;
/**
* Indicates the IO loop should be retried, no blocking select to follow directly.
*/
int CONTINUE = -2;
/**
* Indicates the IO loop to poll for new events without blocking.
*/
int BUSY_WAIT = -3;
/**
* The {@link SelectStrategy} can be used to steer the outcome of a potential select
* call.
*
* @param selectSupplier The supplier with the result of a select result.
* @param hasTasks true if tasks are waiting to be processed.
* @return {@link #SELECT} if the next step should be blocking select {@link #CONTINUE} if
* the next step should be to not select but rather jump back to the IO loop and try
* again. Any value >= 0 is treated as an indicator that work needs to be done.
*/
int calculateStrategy(IntSupplier selectSupplier, boolean hasTasks) throws Exception;
}
|
SelectStrategy
|
java
|
apache__camel
|
components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/tx/TransactionMinimalConfigurationIT.java
|
{
"start": 1350,
"end": 2450
}
|
class ____ extends AbstractSpringJMSITSupport {
@Override
protected ClassPathXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext(
"/org/apache/camel/component/jms/integration/spring/tx/TransactionMinimalConfigurationIT.xml");
}
@Test
public void testTransactionSuccess() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.expectedBodiesReceived("Bye World");
// success at 3rd attempt
mock.message(0).header("count").isEqualTo(3);
// since its JMS that does the redeliver we should test for that
mock.message(0).header("JMSRedelivered").isEqualTo(true);
// and not Camel doing the redelivery
mock.message(0).header(Exchange.REDELIVERED).isNull();
mock.message(0).header(Exchange.REDELIVERY_COUNTER).isNull();
template.sendBody("activemq:queue:TransactionMinimalConfigurationTest", "Hello World");
mock.assertIsSatisfied();
}
}
|
TransactionMinimalConfigurationIT
|
java
|
google__guice
|
core/src/com/google/inject/internal/Messages.java
|
{
"start": 4852,
"end": 5208
}
|
enum ____ for the error
* @param messageFormat Format string
* @param arguments format string arguments
*/
public static Message create(ErrorId errorId, String messageFormat, Object... arguments) {
return create(errorId, null, messageFormat, arguments);
}
/**
* Creates a new Message with the given cause.
*
* @param errorId The
|
id
|
java
|
quarkusio__quarkus
|
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/EchoJson.java
|
{
"start": 366,
"end": 655
}
|
class ____ {
@Inject
EchoService echoService;
@OnTextMessage
Uni<JsonObject> echo(JsonObject msg) {
assertTrue(Context.isOnEventLoopThread());
return Uni.createFrom().item(new JsonObject().put("msg", echoService.echo(msg.getString("msg"))));
}
}
|
EchoJson
|
java
|
elastic__elasticsearch
|
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryGroupsResolver.java
|
{
"start": 1899,
"end": 5036
}
|
class ____ implements GroupsResolver {
private final String baseDn;
private final LdapSearchScope scope;
private final boolean ignoreReferralErrors;
ActiveDirectoryGroupsResolver(RealmConfig config) {
this.baseDn = config.getSetting(
SearchGroupsResolverSettings.BASE_DN,
() -> buildDnFromDomain(config.getSetting(ActiveDirectorySessionFactorySettings.AD_DOMAIN_NAME_SETTING))
);
this.scope = config.getSetting(SearchGroupsResolverSettings.SCOPE);
this.ignoreReferralErrors = config.getSetting(IGNORE_REFERRAL_ERRORS_SETTING);
}
@Override
public void resolve(
LDAPInterface connection,
String userDn,
TimeValue timeout,
Logger logger,
Collection<Attribute> attributes,
ActionListener<List<String>> listener
) {
buildGroupQuery(connection, userDn, timeout, ignoreReferralErrors, ActionListener.wrap((filter) -> {
if (filter == null) {
listener.onResponse(List.of());
} else {
logger.debug("group SID to DN [{}] search filter: [{}]", userDn, filter);
search(
connection,
baseDn,
scope.scope(),
filter,
Math.toIntExact(timeout.seconds()),
ignoreReferralErrors,
ActionListener.wrap((results) -> {
List<String> groups = results.stream().map(SearchResultEntry::getDN).toList();
listener.onResponse(groups);
}, listener::onFailure),
SearchRequest.NO_ATTRIBUTES
);
}
}, listener::onFailure));
}
@Override
public String[] attributes() {
// we have to return null since the tokenGroups attribute is computed and can only be retrieved using a BASE level search
return null;
}
static void buildGroupQuery(
LDAPInterface connection,
String userDn,
TimeValue timeout,
boolean ignoreReferralErrors,
ActionListener<Filter> listener
) {
searchForEntry(
connection,
userDn,
SearchScope.BASE,
OBJECT_CLASS_PRESENCE_FILTER,
Math.toIntExact(timeout.seconds()),
ignoreReferralErrors,
ActionListener.wrap((entry) -> {
if (entry == null || entry.hasAttribute(TOKEN_GROUPS) == false) {
listener.onResponse(null);
} else {
final byte[][] tokenGroupSIDBytes = entry.getAttributeValueByteArrays(TOKEN_GROUPS);
List<Filter> orFilters = Arrays.stream(tokenGroupSIDBytes)
.map((sidBytes) -> Filter.createEqualityFilter("objectSid", convertToString(sidBytes)))
.toList();
listener.onResponse(Filter.createORFilter(orFilters));
}
}, listener::onFailure),
TOKEN_GROUPS
);
}
}
|
ActiveDirectoryGroupsResolver
|
java
|
apache__camel
|
components/camel-platform-http/src/main/java/org/apache/camel/component/platform/http/cookie/CookieConfiguration.java
|
{
"start": 4005,
"end": 5999
}
|
class ____ {
private String path = DEFAULT_PATH;
private String domain;
private Long maxAge;
private boolean secure = DEFAULT_SECURE_FLAG;
private boolean httpOnly = DEFAULT_HTTP_ONLY_FLAG;
private CookieSameSite sameSite = DEFAULT_SAME_SITE;
public Builder() {
}
/**
* Sets the URL path that must exist in the requested URL in order to send the Cookie.
*/
public Builder setPath(String path) {
this.path = path;
return this;
}
/**
* Sets which server can receive cookies.
*/
public Builder setDomain(String domain) {
this.domain = domain;
return this;
}
/**
* Sets the maximum cookie age in seconds.
*/
public Builder setMaxAge(Long maxAge) {
this.maxAge = maxAge;
return this;
}
/**
* Sets whether the cookie is only sent to the server with an encrypted request over HTTPS.
*/
public Builder setSecure(boolean secure) {
this.secure = secure;
return this;
}
/**
* Sets whether to prevent client side scripts from accessing created cookies.
*/
public Builder setHttpOnly(boolean httpOnly) {
this.httpOnly = httpOnly;
return this;
}
/**
* Sets whether to prevent the browser from sending cookies along with cross-site requests.
*/
public Builder setSameSite(CookieSameSite sameSite) {
this.sameSite = sameSite;
return this;
}
public CookieConfiguration build() {
return new CookieConfiguration(path, domain, maxAge, secure, httpOnly, sameSite);
}
}
/**
* The Cookie {@code SameSite} policy that declares whether a Cookie should be sent with cross-site requests.
*/
public
|
Builder
|
java
|
junit-team__junit5
|
junit-jupiter-api/src/main/java/org/junit/jupiter/api/DisplayNameGenerator.java
|
{
"start": 18571,
"end": 19393
}
|
class ____ which to find the annotation; never {@code null}
* @param enclosingInstanceTypes the runtime types of the enclosing
* instances; never {@code null}
* @return an {@code Optional} containing the annotation, potentially empty if not found
*/
@API(status = INTERNAL, since = "5.12")
private static Optional<DisplayNameGeneration> findDisplayNameGeneration(Class<?> testClass,
List<Class<?>> enclosingInstanceTypes) {
return findAnnotation(testClass, DisplayNameGeneration.class, enclosingInstanceTypes);
}
/**
* Find the first {@code IndicativeSentencesGeneration} annotation that is either
* <em>directly present</em>, <em>meta-present</em>, or <em>indirectly present</em>
* on the supplied {@code testClass} or on an enclosing instance type.
*
* @param testClass the test
|
on
|
java
|
apache__dubbo
|
dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/netty4/NettyHttpHeaders.java
|
{
"start": 1308,
"end": 6767
}
|
class ____<T extends Headers<CharSequence, CharSequence, ?>> implements HttpHeaders {
private final T headers;
public NettyHttpHeaders(T headers) {
this.headers = headers;
}
@Override
public final int size() {
return headers.size();
}
@Override
public final boolean isEmpty() {
return headers.isEmpty();
}
@Override
public final boolean containsKey(CharSequence key) {
return headers.contains(key);
}
@Override
public final String getFirst(CharSequence name) {
CharSequence value = headers.get(name);
return value == null ? null : value.toString();
}
@Override
public final List<String> get(CharSequence key) {
List<CharSequence> all = headers.getAll(key);
if (all.isEmpty()) {
return Collections.emptyList();
}
ListIterator<CharSequence> it = all.listIterator();
while (it.hasNext()) {
CharSequence next = it.next();
if (next != null && next.getClass() != String.class) {
it.set(next.toString());
}
}
return (List) all;
}
@Override
public final HttpHeaders add(CharSequence name, String value) {
headers.add(name, value);
return this;
}
public final HttpHeaders add(CharSequence name, Iterable<String> values) {
headers.add(name, values);
return this;
}
@Override
public final HttpHeaders add(CharSequence name, String... values) {
if (values != null && values.length != 0) {
headers.add(name, Arrays.asList(values));
}
return this;
}
@Override
public final HttpHeaders add(Map<? extends CharSequence, ? extends Iterable<String>> map) {
for (Entry<? extends CharSequence, ? extends Iterable<String>> entry : map.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public final HttpHeaders add(HttpHeaders headers) {
for (Entry<CharSequence, String> entry : headers) {
this.headers.add(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public final HttpHeaders set(CharSequence name, String value) {
headers.set(name, value);
return this;
}
public final HttpHeaders set(CharSequence name, Iterable<String> values) {
headers.set(name, values);
return this;
}
@Override
public final HttpHeaders set(CharSequence name, String... values) {
if (values != null && values.length != 0) {
headers.set(name, Arrays.asList(values));
}
return this;
}
@Override
public final HttpHeaders set(Map<? extends CharSequence, ? extends Iterable<String>> map) {
for (Entry<? extends CharSequence, ? extends Iterable<String>> entry : map.entrySet()) {
headers.set(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public final HttpHeaders set(HttpHeaders headers) {
for (Entry<CharSequence, String> entry : headers) {
this.headers.set(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public final List<String> remove(CharSequence key) {
return (List) headers.getAllAndRemove(key);
}
@Override
public final void clear() {
headers.clear();
}
@Override
public final Set<String> names() {
Set<CharSequence> names = headers.names();
return new AbstractSet<String>() {
@Override
public Iterator<String> iterator() {
Iterator<CharSequence> it = names.iterator();
return new Iterator<String>() {
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public String next() {
CharSequence next = it.next();
return next == null ? null : next.toString();
}
@Override
public void remove() {
it.remove();
}
};
}
@Override
public int size() {
return names.size();
}
@Override
public boolean contains(Object o) {
return names.contains(o);
}
};
}
@Override
public Set<CharSequence> nameSet() {
return headers.names();
}
@Override
public final Map<String, List<String>> asMap() {
return headers.isEmpty() ? Collections.emptyMap() : new HttpHeadersMapAdapter(this);
}
@Override
public final Iterator<Entry<CharSequence, String>> iterator() {
return new StringValueIterator(headers.iterator());
}
public final T getHeaders() {
return headers;
}
@Override
public boolean equals(Object obj) {
return obj instanceof NettyHttpHeaders && headers.equals(((NettyHttpHeaders<?>) obj).headers);
}
@Override
public int hashCode() {
return headers.hashCode();
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" + "headers=" + headers + '}';
}
}
|
NettyHttpHeaders
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/jwt/JwtRealmSettings.java
|
{
"start": 3444,
"end": 28227
}
|
enum ____ {
ID_TOKEN("id_token"),
ACCESS_TOKEN("access_token");
private final String value;
TokenType(String value) {
this.value = value;
}
public String value() {
return value;
}
public static TokenType parse(String value, String settingKey) {
return EnumSet.allOf(TokenType.class)
.stream()
.filter(type -> type.value.equalsIgnoreCase(value))
.findFirst()
.orElseThrow(
() -> new IllegalArgumentException(
Strings.format(
"Invalid value [%s] for [%s], allowed values are [%s]",
value,
settingKey,
Stream.of(values()).map(TokenType::value).collect(Collectors.joining(","))
)
)
);
}
}
// Default values and min/max constraints
private static final TimeValue DEFAULT_ALLOWED_CLOCK_SKEW = TimeValue.timeValueSeconds(60);
private static final List<String> DEFAULT_ALLOWED_SIGNATURE_ALGORITHMS = Collections.singletonList("RS256");
private static final boolean DEFAULT_POPULATE_USER_METADATA = true;
private static final TimeValue DEFAULT_JWT_CACHE_TTL = TimeValue.timeValueMinutes(20);
private static final TimeValue DEFAULT_JWT_CLIENT_AUTH_GRACE_PERIOD = TimeValue.timeValueMinutes(1);
private static final int DEFAULT_JWT_CACHE_SIZE = 100_000;
private static final int MIN_JWT_CACHE_SIZE = 0;
private static final TimeValue DEFAULT_HTTP_CONNECT_TIMEOUT = TimeValue.timeValueSeconds(5);
private static final TimeValue DEFAULT_HTTP_CONNECTION_READ_TIMEOUT = TimeValue.timeValueSeconds(5);
private static final TimeValue DEFAULT_HTTP_SOCKET_TIMEOUT = TimeValue.timeValueSeconds(5);
private static final int DEFAULT_HTTP_MAX_CONNECTIONS = 200;
private static final int MIN_HTTP_MAX_CONNECTIONS = 0;
private static final int DEFAULT_HTTP_MAX_ENDPOINT_CONNECTIONS = 200;
private static final int MIN_HTTP_MAX_ENDPOINT_CONNECTIONS = 0;
// All settings
/**
* Get all secure and non-secure settings.
* @return All secure and non-secure settings.
*/
public static Set<Setting.AffixSetting<?>> getSettings() {
final Set<Setting.AffixSetting<?>> set = new HashSet<>();
set.addAll(JwtRealmSettings.getNonSecureSettings());
set.addAll(JwtRealmSettings.getSecureSettings());
return set;
}
/**
* Get all non-secure settings.
* @return All non-secure settings.
*/
private static Set<Setting.AffixSetting<?>> getNonSecureSettings() {
// Standard realm settings: order, enabled
final Set<Setting.AffixSetting<?>> set = new HashSet<>(RealmSettings.getStandardSettings(TYPE));
set.add(TOKEN_TYPE);
// JWT Issuer settings
set.addAll(
List.of(
ALLOWED_ISSUER,
ALLOWED_SIGNATURE_ALGORITHMS,
ALLOWED_CLOCK_SKEW,
PKC_JWKSET_PATH,
PKC_JWKSET_RELOAD_ENABLED,
PKC_JWKSET_RELOAD_FILE_INTERVAL,
PKC_JWKSET_RELOAD_URL_INTERVAL_MIN,
PKC_JWKSET_RELOAD_URL_INTERVAL_MAX
)
);
// JWT Audience settings
set.addAll(List.of(ALLOWED_AUDIENCES));
// JWT End-user settings
set.addAll(
List.of(
ALLOWED_SUBJECTS,
ALLOWED_SUBJECT_PATTERNS,
FALLBACK_SUB_CLAIM,
FALLBACK_AUD_CLAIM,
REQUIRED_CLAIMS,
CLAIMS_PRINCIPAL.getClaim(),
CLAIMS_PRINCIPAL.getPattern(),
CLAIMS_GROUPS.getClaim(),
CLAIMS_GROUPS.getPattern(),
CLAIMS_DN.getClaim(),
CLAIMS_DN.getPattern(),
CLAIMS_MAIL.getClaim(),
CLAIMS_MAIL.getPattern(),
CLAIMS_NAME.getClaim(),
CLAIMS_NAME.getPattern(),
POPULATE_USER_METADATA,
CLIENT_AUTH_SHARED_SECRET_ROTATION_GRACE_PERIOD
)
);
// JWT Client settings
set.addAll(List.of(CLIENT_AUTHENTICATION_TYPE));
// JWT Cache settings
set.addAll(List.of(JWT_CACHE_TTL, JWT_CACHE_SIZE));
// Standard HTTP settings for outgoing connections to get JWT issuer jwkset_path
set.addAll(
List.of(
HTTP_CONNECT_TIMEOUT,
HTTP_CONNECTION_READ_TIMEOUT,
HTTP_SOCKET_TIMEOUT,
HTTP_MAX_CONNECTIONS,
HTTP_MAX_ENDPOINT_CONNECTIONS,
HTTP_PROXY_SCHEME,
HTTP_PROXY_HOST,
HTTP_PROXY_PORT
)
);
// Standard TLS connection settings for outgoing connections to get JWT issuer jwkset_path
set.addAll(SSL_CONFIGURATION_SETTINGS);
// JWT End-user delegated authorization settings: authorization_realms
set.addAll(DELEGATED_AUTHORIZATION_REALMS_SETTINGS);
return set;
}
/**
* Get all secure settings.
* @return All secure settings.
*/
private static Set<Setting.AffixSetting<SecureString>> getSecureSettings() {
return new HashSet<>(List.of(HMAC_JWKSET, HMAC_KEY, CLIENT_AUTHENTICATION_SHARED_SECRET));
}
public static final Setting.AffixSetting<TokenType> TOKEN_TYPE = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"token_type",
key -> new Setting<>(key, TokenType.ID_TOKEN.value(), value -> TokenType.parse(value, key), Setting.Property.NodeScope)
);
// JWT issuer settings
public static final Setting.AffixSetting<String> ALLOWED_ISSUER = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"allowed_issuer",
key -> Setting.simpleString(key, value -> verifyNonNullNotEmpty(key, value, null), Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<TimeValue> ALLOWED_CLOCK_SKEW = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"allowed_clock_skew",
key -> Setting.timeSetting(key, DEFAULT_ALLOWED_CLOCK_SKEW, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<List<String>> ALLOWED_SIGNATURE_ALGORITHMS = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"allowed_signature_algorithms",
key -> Setting.stringListSetting(
key,
DEFAULT_ALLOWED_SIGNATURE_ALGORITHMS,
values -> verifyNonNullNotEmpty(key, values, SUPPORTED_SIGNATURE_ALGORITHMS),
Setting.Property.NodeScope
)
);
public static final Setting.AffixSetting<String> PKC_JWKSET_PATH = RealmSettings.simpleString(
TYPE,
"pkc_jwkset_path",
Setting.Property.NodeScope
);
public static final Setting.AffixSetting<Boolean> PKC_JWKSET_RELOAD_ENABLED = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"pkc_jwkset_reload.enabled",
key -> Setting.boolSetting(key, false, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<TimeValue> PKC_JWKSET_RELOAD_FILE_INTERVAL = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"pkc_jwkset_reload.file_interval",
key -> Setting.timeSetting(key, TimeValue.timeValueMinutes(5), TimeValue.timeValueMinutes(5), Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<TimeValue> PKC_JWKSET_RELOAD_URL_INTERVAL_MIN = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"pkc_jwkset_reload.url_interval_min",
key -> Setting.timeSetting(key, TimeValue.timeValueHours(1), TimeValue.timeValueMinutes(5), Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<TimeValue> PKC_JWKSET_RELOAD_URL_INTERVAL_MAX = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"pkc_jwkset_reload.url_interval_max",
key -> Setting.timeSetting(key, TimeValue.timeValueDays(5), TimeValue.timeValueMinutes(5), Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<SecureString> HMAC_JWKSET = RealmSettings.secureString(TYPE, "hmac_jwkset");
public static final Setting.AffixSetting<SecureString> HMAC_KEY = RealmSettings.secureString(TYPE, "hmac_key");
// JWT audience settings
public static final Setting.AffixSetting<List<String>> ALLOWED_AUDIENCES = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"allowed_audiences",
key -> Setting.stringListSetting(key, values -> verifyNonNullNotEmpty(key, values, null), Setting.Property.NodeScope)
);
// JWT end-user settings
public static final Setting.AffixSetting<List<String>> ALLOWED_SUBJECTS = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"allowed_subjects",
key -> Setting.stringListSetting(key, new Setting.Validator<>() {
@Override
public void validate(List<String> allowedSubjects) {
// validate values themselves are not null or empty
allowedSubjects.forEach(allowedSubject -> verifyNonNullNotEmpty(key, allowedSubject, null));
}
@Override
@SuppressWarnings("unchecked")
public void validate(List<String> allowedSubjects, Map<Setting<?>, Object> settings) {
// validate both allowed_subjects and allowed_subject_patterns are not simultaneously empty (which is the default value)
final String namespace = ALLOWED_SUBJECTS.getNamespace(ALLOWED_SUBJECTS.getConcreteSetting(key));
final List<String> allowedSubjectPatterns = (List<String>) settings.get(
ALLOWED_SUBJECT_PATTERNS.getConcreteSettingForNamespace(namespace)
);
if (allowedSubjects.isEmpty() && allowedSubjectPatterns.isEmpty()) {
throw new SettingsException(
"One of either ["
+ ALLOWED_SUBJECTS.getConcreteSettingForNamespace(namespace).getKey()
+ "] or ["
+ ALLOWED_SUBJECT_PATTERNS.getConcreteSettingForNamespace(namespace).getKey()
+ "] must be specified and not be empty."
);
}
}
@Override
public Iterator<Setting<?>> settings() {
final String namespace = ALLOWED_SUBJECTS.getNamespace(ALLOWED_SUBJECTS.getConcreteSetting(key));
final List<Setting<?>> settings = List.of(ALLOWED_SUBJECT_PATTERNS.getConcreteSettingForNamespace(namespace));
return settings.iterator();
}
}, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<List<String>> ALLOWED_SUBJECT_PATTERNS = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"allowed_subject_patterns",
key -> Setting.stringListSetting(key, new Setting.Validator<>() {
@Override
public void validate(List<String> allowedSubjectPatterns) {
// validate values themselves are not null or empty
allowedSubjectPatterns.forEach(allowedSubjectPattern -> verifyNonNullNotEmpty(key, allowedSubjectPattern, null));
}
@Override
@SuppressWarnings("unchecked")
public void validate(List<String> allowedSubjectPatterns, Map<Setting<?>, Object> settings) {
// validate both allowed_subjects and allowed_subject_patterns are not simultaneously empty (which is the default value)
final String namespace = ALLOWED_SUBJECT_PATTERNS.getNamespace(ALLOWED_SUBJECT_PATTERNS.getConcreteSetting(key));
final List<String> allowedSubjects = (List<String>) settings.get(
ALLOWED_SUBJECTS.getConcreteSettingForNamespace(namespace)
);
if (allowedSubjects.isEmpty() && allowedSubjectPatterns.isEmpty()) {
throw new SettingsException(
"One of either ["
+ ALLOWED_SUBJECTS.getConcreteSettingForNamespace(namespace).getKey()
+ "] or ["
+ ALLOWED_SUBJECT_PATTERNS.getConcreteSettingForNamespace(namespace).getKey()
+ "] must be specified and not be empty."
);
}
}
@Override
public Iterator<Setting<?>> settings() {
final String namespace = ALLOWED_SUBJECT_PATTERNS.getNamespace(ALLOWED_SUBJECT_PATTERNS.getConcreteSetting(key));
final List<Setting<?>> settings = List.of(ALLOWED_SUBJECTS.getConcreteSettingForNamespace(namespace));
return settings.iterator();
}
}, Setting.Property.NodeScope)
);
// Registered claim names from the JWT spec https://www.rfc-editor.org/rfc/rfc7519#section-4.1.
// Being registered means they have prescribed meanings when they present in a JWT.
public static final List<String> REGISTERED_CLAIM_NAMES = List.of("iss", "sub", "aud", "exp", "nbf", "iat", "jti");
public static final Setting.AffixSetting<String> FALLBACK_SUB_CLAIM = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"fallback_claims.sub",
key -> Setting.simpleString(key, "sub", new Setting.Validator<>() {
@Override
public void validate(String value) {}
@Override
public void validate(String value, Map<Setting<?>, Object> settings, boolean isPresent) {
validateFallbackClaimSetting(FALLBACK_SUB_CLAIM, key, value, settings, isPresent);
}
@Override
public Iterator<Setting<?>> settings() {
final String namespace = FALLBACK_SUB_CLAIM.getNamespace(FALLBACK_SUB_CLAIM.getConcreteSetting(key));
final List<Setting<?>> settings = List.of(TOKEN_TYPE.getConcreteSettingForNamespace(namespace));
return settings.iterator();
}
}, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<String> FALLBACK_AUD_CLAIM = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"fallback_claims.aud",
key -> Setting.simpleString(key, "aud", new Setting.Validator<>() {
@Override
public void validate(String value) {}
@Override
public void validate(String value, Map<Setting<?>, Object> settings, boolean isPresent) {
validateFallbackClaimSetting(FALLBACK_AUD_CLAIM, key, value, settings, isPresent);
}
@Override
public Iterator<Setting<?>> settings() {
final String namespace = FALLBACK_AUD_CLAIM.getNamespace(FALLBACK_AUD_CLAIM.getConcreteSetting(key));
final List<Setting<?>> settings = List.of(TOKEN_TYPE.getConcreteSettingForNamespace(namespace));
return settings.iterator();
}
}, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<Settings> REQUIRED_CLAIMS = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"required_claims",
key -> Setting.groupSetting(key + ".", settings -> {
final List<String> invalidRequiredClaims = List.of("iss", "sub", "aud", "exp", "nbf", "iat");
for (String name : settings.names()) {
final String fullName = key + "." + name;
if (invalidRequiredClaims.contains(name)) {
throw new IllegalArgumentException(
Strings.format("required claim [%s] cannot be one of [%s]", fullName, String.join(",", invalidRequiredClaims))
);
}
final List<String> values = settings.getAsList(name);
if (values.isEmpty()) {
throw new IllegalArgumentException(Strings.format("required claim [%s] cannot be empty", fullName));
}
}
}, Setting.Property.NodeScope)
);
// Note: ClaimSetting is a wrapper for two individual settings: getClaim(), getPattern()
public static final ClaimSetting CLAIMS_PRINCIPAL = new ClaimSetting(TYPE, "principal");
public static final ClaimSetting CLAIMS_GROUPS = new ClaimSetting(TYPE, "groups");
public static final ClaimSetting CLAIMS_DN = new ClaimSetting(TYPE, "dn");
public static final ClaimSetting CLAIMS_MAIL = new ClaimSetting(TYPE, "mail");
public static final ClaimSetting CLAIMS_NAME = new ClaimSetting(TYPE, "name");
public static final Setting.AffixSetting<Boolean> POPULATE_USER_METADATA = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"populate_user_metadata",
key -> Setting.boolSetting(key, DEFAULT_POPULATE_USER_METADATA, Setting.Property.NodeScope)
);
// Client authentication settings for incoming connections
public static final Setting.AffixSetting<ClientAuthenticationType> CLIENT_AUTHENTICATION_TYPE = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"client_authentication.type",
key -> new Setting<>(
key,
ClientAuthenticationType.SHARED_SECRET.value,
value -> ClientAuthenticationType.parse(value, key),
Setting.Property.NodeScope
)
);
public static final Setting.AffixSetting<SecureString> CLIENT_AUTHENTICATION_SHARED_SECRET = RealmSettings.secureString(
TYPE,
"client_authentication.shared_secret"
);
public static final Setting.AffixSetting<TimeValue> CLIENT_AUTH_SHARED_SECRET_ROTATION_GRACE_PERIOD = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"client_authentication.rotation_grace_period",
key -> Setting.timeSetting(key, DEFAULT_JWT_CLIENT_AUTH_GRACE_PERIOD, Setting.Property.NodeScope)
);
// Individual Cache settings
public static final Setting.AffixSetting<TimeValue> JWT_CACHE_TTL = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"jwt.cache.ttl",
key -> Setting.timeSetting(key, DEFAULT_JWT_CACHE_TTL, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<Integer> JWT_CACHE_SIZE = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"jwt.cache.size",
key -> Setting.intSetting(key, DEFAULT_JWT_CACHE_SIZE, MIN_JWT_CACHE_SIZE, Setting.Property.NodeScope)
);
// Individual outgoing HTTP settings
public static final Setting.AffixSetting<TimeValue> HTTP_CONNECT_TIMEOUT = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"http.connect_timeout",
key -> Setting.timeSetting(key, DEFAULT_HTTP_CONNECT_TIMEOUT, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<TimeValue> HTTP_CONNECTION_READ_TIMEOUT = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"http.connection_read_timeout",
key -> Setting.timeSetting(key, DEFAULT_HTTP_CONNECTION_READ_TIMEOUT, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<TimeValue> HTTP_SOCKET_TIMEOUT = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"http.socket_timeout",
key -> Setting.timeSetting(key, DEFAULT_HTTP_SOCKET_TIMEOUT, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<Integer> HTTP_MAX_CONNECTIONS = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"http.max_connections",
key -> Setting.intSetting(key, DEFAULT_HTTP_MAX_CONNECTIONS, MIN_HTTP_MAX_CONNECTIONS, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<Integer> HTTP_MAX_ENDPOINT_CONNECTIONS = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"http.max_endpoint_connections",
key -> Setting.intSetting(key, DEFAULT_HTTP_MAX_ENDPOINT_CONNECTIONS, MIN_HTTP_MAX_ENDPOINT_CONNECTIONS, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<String> HTTP_PROXY_HOST = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"http.proxy.host",
key -> Setting.simpleString(key, new Setting.Validator<>() {
@Override
public void validate(String value) {
// There is no point in validating the hostname in itself without the scheme and port
}
@Override
public void validate(String value, Map<Setting<?>, Object> settings) {
verifyProxySettings(key, value, settings, HTTP_PROXY_HOST, HTTP_PROXY_SCHEME, HTTP_PROXY_PORT);
}
@Override
public Iterator<Setting<?>> settings() {
final String namespace = HTTP_PROXY_HOST.getNamespace(HTTP_PROXY_HOST.getConcreteSetting(key));
final List<Setting<?>> settings = List.of(
HTTP_PROXY_PORT.getConcreteSettingForNamespace(namespace),
HTTP_PROXY_SCHEME.getConcreteSettingForNamespace(namespace)
);
return settings.iterator();
}
}, Setting.Property.NodeScope)
);
public static final Setting.AffixSetting<Integer> HTTP_PROXY_PORT = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"http.proxy.port",
key -> Setting.intSetting(key, 80, 1, 65535, Setting.Property.NodeScope),
() -> HTTP_PROXY_HOST
);
public static final Setting.AffixSetting<String> HTTP_PROXY_SCHEME = Setting.affixKeySetting(
RealmSettings.realmSettingPrefix(TYPE),
"http.proxy.scheme",
key -> Setting.simpleString(
key,
"http",
// TODO allow HTTPS once https://github.com/elastic/elasticsearch/issues/100264 is fixed
value -> verifyNonNullNotEmpty(key, value, List.of("http")),
Setting.Property.NodeScope
)
);
// SSL Configuration settings
public static final Collection<Setting.AffixSetting<?>> SSL_CONFIGURATION_SETTINGS = SSLConfigurationSettings.getRealmSettings(TYPE);
public static final SSLConfigurationSettings ssl = SSLConfigurationSettings.withoutPrefix(true);
// Delegated Authorization Realms settings
public static final Collection<Setting.AffixSetting<?>> DELEGATED_AUTHORIZATION_REALMS_SETTINGS = DelegatedAuthorizationSettings
.getSettings(TYPE);
private static void validateFallbackClaimSetting(
Setting.AffixSetting<String> setting,
String key,
String value,
Map<Setting<?>, Object> settings,
boolean isPresent
) {
if (false == isPresent) {
return;
}
final String namespace = setting.getNamespace(setting.getConcreteSetting(key));
final TokenType tokenType = (TokenType) settings.get(TOKEN_TYPE.getConcreteSettingForNamespace(namespace));
if (tokenType == TokenType.ID_TOKEN) {
throw new IllegalArgumentException(
Strings.format(
"fallback claim setting [%s] is not allowed when JWT realm [%s] is [%s] type",
key,
namespace,
JwtRealmSettings.TokenType.ID_TOKEN.value()
)
);
}
verifyFallbackClaimName(key, value);
}
private static void verifyFallbackClaimName(String key, String fallbackClaimName) {
final String claimName = key.substring(key.lastIndexOf('.') + 1);
verifyNonNullNotEmpty(key, fallbackClaimName, null);
if (claimName.equals(fallbackClaimName)) {
return;
}
// Registered claims have prescribed meanings and should not be used for something else.
if (REGISTERED_CLAIM_NAMES.contains(fallbackClaimName)) {
throw new IllegalArgumentException(
Strings.format(
"Invalid fallback claims setting [%s]. Claim [%s] cannot fallback to a registered claim [%s]",
key,
claimName,
fallbackClaimName
)
);
}
}
}
|
TokenType
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/immutable/ImmutableBlogMapper.java
|
{
"start": 835,
"end": 1169
}
|
interface ____ {
ImmutableBlog retrieveFullImmutableBlog(int i);
List<ImmutableBlog> retrieveAllBlogsWithoutPosts();
List<ImmutableBlog> retrieveAllBlogsWithPostsButNoCommentsOrTags();
List<ImmutableBlog> retrieveAllBlogsWithMissingConstructor();
List<ImmutableBlog> retrieveAllBlogsAndPostsJoined();
}
|
ImmutableBlogMapper
|
java
|
apache__dubbo
|
dubbo-remoting/dubbo-remoting-api/src/test/java/org/apache/dubbo/remoting/codec/ExchangeCodecTest.java
|
{
"start": 2481,
"end": 23339
}
|
class ____ extends TelnetCodecTest {
// magic header.
private static final short MAGIC = (short) 0xdabb;
private static final byte MAGIC_HIGH = (byte) Bytes.short2bytes(MAGIC)[0];
private static final byte MAGIC_LOW = (byte) Bytes.short2bytes(MAGIC)[1];
Serialization serialization = getSerialization(DefaultSerializationSelector.getDefaultRemotingSerialization());
private static final byte SERIALIZATION_BYTE = FrameworkModel.defaultModel()
.getExtension(Serialization.class, DefaultSerializationSelector.getDefaultRemotingSerialization())
.getContentTypeId();
private static Serialization getSerialization(String name) {
Serialization serialization =
ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(name);
return serialization;
}
private Object decode(byte[] request) throws IOException {
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request);
AbstractMockChannel channel = getServerSideChannel(url);
// decode
Object obj = codec.decode(channel, buffer);
return obj;
}
private byte[] getRequestBytes(Object obj, byte[] header) throws IOException {
// encode request data.
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
ObjectOutput out = serialization.serialize(url, bos);
out.writeObject(obj);
out.flushBuffer();
bos.flush();
bos.close();
byte[] data = bos.toByteArray();
byte[] len = Bytes.int2bytes(data.length);
System.arraycopy(len, 0, header, 12, 4);
byte[] request = join(header, data);
return request;
}
private byte[] getReadonlyEventRequestBytes(Object obj, byte[] header) throws IOException {
// encode request data.
UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024);
ObjectOutput out = serialization.serialize(url, bos);
out.writeObject(obj);
out.flushBuffer();
bos.flush();
bos.close();
byte[] data = bos.toByteArray();
// byte[] len = Bytes.int2bytes(data.length);
System.arraycopy(data, 0, header, 12, data.length);
byte[] request = join(header, data);
return request;
}
private byte[] assemblyDataProtocol(byte[] header) {
Person request = new Person();
byte[] newbuf = join(header, objectToByte(request));
return newbuf;
}
// ===================================================================================
@BeforeEach
public void setUp() throws Exception {
codec = new ExchangeCodec();
}
@Test
void test_Decode_Error_MagicNum() throws IOException {
HashMap<byte[], Object> inputBytes = new HashMap<byte[], Object>();
inputBytes.put(new byte[] {0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT);
inputBytes.put(new byte[] {MAGIC_HIGH, 0}, TelnetCodec.DecodeResult.NEED_MORE_INPUT);
inputBytes.put(new byte[] {0, MAGIC_LOW}, TelnetCodec.DecodeResult.NEED_MORE_INPUT);
for (Map.Entry<byte[], Object> entry : inputBytes.entrySet()) {
testDecode_assertEquals(assemblyDataProtocol(entry.getKey()), entry.getValue());
}
}
@Test
void test_Decode_Error_Length() throws IOException {
DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null);
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
Channel channel = getServerSideChannel(url);
byte[] baddata = new byte[] {1, 2};
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(join(request, baddata));
Response obj = (Response) codec.decode(channel, buffer);
Assertions.assertEquals(person, obj.getResult());
// only decode necessary bytes
Assertions.assertEquals(request.length, buffer.readerIndex());
future.cancel();
}
@Test
void test_Decode_Error_Response_Object() throws IOException {
// 00000010-response/oneway/heartbeat=true |20-stats=ok|id=0|length=0
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
// bad object
byte[] badbytes = new byte[] {-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4};
System.arraycopy(badbytes, 0, request, 21, badbytes.length);
Response obj = (Response) decode(request);
Assertions.assertEquals(90, obj.getStatus());
}
@Test
void testInvalidSerializaitonId() throws Exception {
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, (byte) 0x8F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Object obj = decode(header);
Assertions.assertTrue(obj instanceof Request);
Request request = (Request) obj;
Assertions.assertTrue(request.isBroken());
Assertions.assertTrue(request.getData() instanceof IOException);
header = new byte[] {MAGIC_HIGH, MAGIC_LOW, (byte) 0x1F, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
obj = decode(header);
Assertions.assertTrue(obj instanceof Response);
Response response = (Response) obj;
Assertions.assertEquals(response.getStatus(), Response.CLIENT_ERROR);
Assertions.assertTrue(response.getErrorMessage().contains("IOException"));
}
@Test
void test_Decode_Check_Payload() throws IOException {
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
byte[] request = assemblyDataProtocol(header);
try {
Channel channel = getServerSideChannel(url);
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request);
Object obj = codec.decode(channel, buffer);
Assertions.assertTrue(obj instanceof Response);
Assertions.assertTrue(((Response) obj)
.getErrorMessage()
.startsWith("Data length too large: " + Bytes.bytes2int(new byte[] {1, 1, 1, 1})));
} catch (IOException expected) {
Assertions.assertTrue(expected.getMessage()
.startsWith("Data length too large: " + Bytes.bytes2int(new byte[] {1, 1, 1, 1})));
}
}
@Test
void test_Decode_Header_Need_Readmore() throws IOException {
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0};
testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT);
}
@Test
void test_Decode_Body_Need_Readmore() throws IOException {
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 'a', 'a'};
testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT);
}
@Test
void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException {
byte[] header = new byte[] {0, 0, MAGIC_HIGH, MAGIC_LOW, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Channel channel = getServerSideChannel(url);
ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(header);
Object obj = codec.decode(channel, buffer);
Assertions.assertEquals(TelnetCodec.DecodeResult.NEED_MORE_INPUT, obj);
// If the telnet data and request data are in the same data packet, we should guarantee that the receipt of
// request data won't be affected by the factor that telnet does not have an end characters.
Assertions.assertEquals(2, buffer.readerIndex());
}
@Test
void test_Decode_Return_Response_Person() throws IOException {
DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null);
// 00000010-response/oneway/heartbeat=false/hessian |20-stats=ok|id=0|length=0
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
Response obj = (Response) decode(request);
Assertions.assertEquals(20, obj.getStatus());
Assertions.assertEquals(person, obj.getResult());
future.cancel();
}
@Test // The status input has a problem, and the read information is wrong when the serialization is serialized.
public void test_Decode_Return_Response_Error() throws IOException {
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
String errorString = "encode request data error ";
byte[] request = getRequestBytes(errorString, header);
Response obj = (Response) decode(request);
Assertions.assertEquals(90, obj.getStatus());
Assertions.assertEquals(errorString, obj.getErrorMessage());
}
@Test
@Disabled("Event should not be object.")
void test_Decode_Return_Request_Event_Object() throws IOException {
// |10011111|20-stats=ok|id=0|length=0
byte[] header = new byte[] {
MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
System.setProperty("deserialization.event.size", "100");
Request obj = (Request) decode(request);
Assertions.assertEquals(person, obj.getData());
Assertions.assertTrue(obj.isTwoWay());
Assertions.assertTrue(obj.isEvent());
Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion());
System.clearProperty("deserialization.event.size");
}
@Test
void test_Decode_Return_Request_Event_String() throws IOException {
// |10011111|20-stats=ok|id=0|length=0
byte[] header = new byte[] {
MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
String event = READONLY_EVENT;
byte[] request = getRequestBytes(event, header);
Request obj = (Request) decode(request);
Assertions.assertEquals(event, obj.getData());
Assertions.assertTrue(obj.isTwoWay());
Assertions.assertTrue(obj.isEvent());
Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion());
}
@Test
void test_Decode_Return_Request_Heartbeat_Object() throws IOException {
// |10011111|20-stats=ok|id=0|length=0
byte[] header = new byte[] {
MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
byte[] request = getRequestBytes(null, header);
Request obj = (Request) decode(request);
Assertions.assertNull(obj.getData());
Assertions.assertTrue(obj.isTwoWay());
Assertions.assertTrue(obj.isHeartbeat());
Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion());
}
@Test
@Disabled("Event should not be object.")
void test_Decode_Return_Request_Object() throws IOException {
// |10011111|20-stats=ok|id=0|length=0
byte[] header = new byte[] {
MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
System.setProperty("deserialization.event.size", "100");
Request obj = (Request) decode(request);
Assertions.assertEquals(person, obj.getData());
Assertions.assertTrue(obj.isTwoWay());
Assertions.assertFalse(obj.isHeartbeat());
Assertions.assertEquals(Version.getProtocolVersion(), obj.getVersion());
System.clearProperty("deserialization.event.size");
}
@Test
void test_Decode_Error_Request_Object() throws IOException {
// 00000010-response/oneway/heartbeat=true |20-stats=ok|id=0|length=0
byte[] header = new byte[] {
MAGIC_HIGH, MAGIC_LOW, (byte) (SERIALIZATION_BYTE | (byte) 0xe0), 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
// bad object
byte[] badbytes = new byte[] {-1, -2, -3, -4, -3, -4, -3, -4, -3, -4, -3, -4};
System.arraycopy(badbytes, 0, request, 21, badbytes.length);
Request obj = (Request) decode(request);
Assertions.assertTrue(obj.isBroken());
Assertions.assertTrue(obj.getData() instanceof Throwable);
}
@Test
void test_Header_Response_NoSerializationFlag() throws IOException {
DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null);
// 00000010-response/oneway/heartbeat=false/noset |20-stats=ok|id=0|length=0
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
Response obj = (Response) decode(request);
Assertions.assertEquals(20, obj.getStatus());
Assertions.assertEquals(person, obj.getResult());
future.cancel();
}
@Test
void test_Header_Response_Heartbeat() throws IOException {
DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(0), 100000, null);
// 00000010-response/oneway/heartbeat=true |20-stats=ok|id=0|length=0
byte[] header = new byte[] {MAGIC_HIGH, MAGIC_LOW, SERIALIZATION_BYTE, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Person person = new Person();
byte[] request = getRequestBytes(person, header);
Response obj = (Response) decode(request);
Assertions.assertEquals(20, obj.getStatus());
Assertions.assertEquals(person, obj.getResult());
future.cancel();
}
@Test
void test_Encode_Request() throws IOException {
ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(2014);
Channel channel = getClientSideChannel(url);
Request request = new Request();
Person person = new Person();
request.setData(person);
codec.encode(channel, encodeBuffer, request);
// encode resault check need decode
byte[] data = new byte[encodeBuffer.writerIndex()];
encodeBuffer.readBytes(data);
ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data);
Request obj = (Request) codec.decode(channel, decodeBuffer);
Assertions.assertEquals(request.isBroken(), obj.isBroken());
Assertions.assertEquals(request.isHeartbeat(), obj.isHeartbeat());
Assertions.assertEquals(request.isTwoWay(), obj.isTwoWay());
Assertions.assertEquals(person, obj.getData());
}
@Test
@Disabled("Event should not be object.")
void test_Encode_Response() throws IOException {
DefaultFuture future = DefaultFuture.newFuture(Mockito.mock(Channel.class), new Request(1001), 100000, null);
ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024);
Channel channel = getClientSideChannel(url);
Response response = new Response();
response.setHeartbeat(true);
response.setId(1001L);
response.setStatus((byte) 20);
response.setVersion("11");
Person person = new Person();
response.setResult(person);
codec.encode(channel, encodeBuffer, response);
byte[] data = new byte[encodeBuffer.writerIndex()];
encodeBuffer.readBytes(data);
// encode resault check need decode
ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data);
Response obj = (Response) codec.decode(channel, decodeBuffer);
Assertions.assertEquals(response.getId(), obj.getId());
Assertions.assertEquals(response.getStatus(), obj.getStatus());
Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat());
Assertions.assertEquals(person, obj.getResult());
// encode response version ??
// Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion());
future.cancel();
}
@Test
void test_Encode_Error_Response() throws IOException {
ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024);
Channel channel = getClientSideChannel(url);
Response response = new Response();
response.setHeartbeat(true);
response.setId(1001L);
response.setStatus((byte) 10);
response.setVersion("11");
String badString = "bad";
response.setErrorMessage(badString);
Person person = new Person();
response.setResult(person);
codec.encode(channel, encodeBuffer, response);
byte[] data = new byte[encodeBuffer.writerIndex()];
encodeBuffer.readBytes(data);
// encode resault check need decode
ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data);
Response obj = (Response) codec.decode(channel, decodeBuffer);
Assertions.assertEquals(response.getId(), obj.getId());
Assertions.assertEquals(response.getStatus(), obj.getStatus());
Assertions.assertEquals(response.isHeartbeat(), obj.isHeartbeat());
Assertions.assertEquals(badString, obj.getErrorMessage());
Assertions.assertNull(obj.getResult());
// Assertions.assertEquals(response.getProtocolVersion(), obj.getVersion());
}
@Test
void testMessageLengthGreaterThanMessageActualLength() throws Exception {
Channel channel = getClientSideChannel(url);
Request request = new Request(1L);
request.setVersion(Version.getProtocolVersion());
Date date = new Date();
request.setData(date);
ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024);
codec.encode(channel, encodeBuffer, request);
byte[] bytes = new byte[encodeBuffer.writerIndex()];
encodeBuffer.readBytes(bytes);
int len = Bytes.bytes2int(bytes, 12);
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
out.write(bytes, 0, 12);
/*
* The fill length can not be less than 256, because by default, hessian reads 256 bytes from the stream each time.
* Refer Hessian2Input.readBuffer for more details
*/
int padding = 512;
out.write(Bytes.int2bytes(len + padding));
out.write(bytes, 16, bytes.length - 16);
for (int i = 0; i < padding; i++) {
out.write(1);
}
out.write(bytes);
/* request|1111...|request */
ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(out.toByteArray());
Request decodedRequest = (Request) codec.decode(channel, decodeBuffer);
Assertions.assertEquals(date, decodedRequest.getData());
Assertions.assertEquals(bytes.length + padding, decodeBuffer.readerIndex());
decodedRequest = (Request) codec.decode(channel, decodeBuffer);
Assertions.assertEquals(date, decodedRequest.getData());
}
@Test
void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception {
Request request = new Request(1L);
request.setData("hello");
ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(512);
AbstractMockChannel channel = getClientSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4));
try {
codec.encode(channel, encodeBuffer, request);
Assertions.fail();
} catch (IOException e) {
Assertions.assertTrue(e.getMessage().startsWith("Data length too large: "));
Assertions.assertTrue(e.getMessage()
.contains("max payload: 4, channel: org.apache.dubbo.remoting.codec.AbstractMockChannel"));
}
Response response = new Response(1L);
response.setResult("hello");
encodeBuffer = ChannelBuffers.dynamicBuffer(512);
channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4));
codec.encode(channel, encodeBuffer, response);
Assertions.assertTrue(channel.getReceivedMessage() instanceof Response);
Response receiveMessage = (Response) channel.getReceivedMessage();
Assertions.assertEquals(Response.SERIALIZATION_ERROR, receiveMessage.getStatus());
Assertions.assertTrue(receiveMessage.getErrorMessage().contains("Data length too large: "));
}
}
|
ExchangeCodecTest
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/ser/jdk/IndexedListSerializer.java
|
{
"start": 673,
"end": 6809
}
|
class ____
extends AsArraySerializerBase<Object>
{
public IndexedListSerializer(JavaType elemType, boolean staticTyping, TypeSerializer vts,
ValueSerializer<Object> valueSerializer)
{
super(List.class, elemType, staticTyping, vts, valueSerializer);
}
public IndexedListSerializer(IndexedListSerializer src,
TypeSerializer vts, ValueSerializer<?> valueSerializer,
Boolean unwrapSingle, BeanProperty property) {
super(src, vts, valueSerializer, unwrapSingle, property);
}
@Override
protected StdContainerSerializer<?> _withValueTypeSerializer(TypeSerializer vts) {
return new IndexedListSerializer(this,
vts, _elementSerializer, _unwrapSingle, _property);
}
@Override
public IndexedListSerializer withResolved(BeanProperty property,
TypeSerializer vts, ValueSerializer<?> elementSerializer,
Boolean unwrapSingle) {
return new IndexedListSerializer(this, vts, elementSerializer, unwrapSingle, property);
}
/*
/**********************************************************************
/* Accessors
/**********************************************************************
*/
@Override
public boolean isEmpty(SerializationContext prov, Object value) {
return ((List<?>)value).isEmpty();
}
@Override
public boolean hasSingleElement(Object value) {
return (((List<?>)value).size() == 1);
}
@Override
public final void serialize(Object value0, JsonGenerator gen, SerializationContext provider)
throws JacksonException
{
final List<?> value = (List<?>) value0;
final int len = value.size();
if (len == 1) {
if (((_unwrapSingle == null) &&
provider.isEnabled(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED))
|| (_unwrapSingle == Boolean.TRUE)) {
serializeContents(value, gen, provider);
return;
}
}
gen.writeStartArray(value, len);
serializeContents(value, gen, provider);
gen.writeEndArray();
}
@Override
public void serializeContents(Object value0, JsonGenerator g, SerializationContext ctxt)
throws JacksonException
{
final List<?> value = (List<?>) value0;
if (_elementSerializer != null) {
serializeContentsUsing(value, g, ctxt, _elementSerializer);
return;
}
if (_valueTypeSerializer != null) {
serializeTypedContents(value, g, ctxt);
return;
}
final int len = value.size();
if (len == 0) {
return;
}
int i = 0;
try {
for (; i < len; ++i) {
Object elem = value.get(i);
if (elem == null) {
ctxt.defaultSerializeNullValue(g);
} else {
Class<?> cc = elem.getClass();
ValueSerializer<Object> serializer = _dynamicValueSerializers.serializerFor(cc);
if (serializer == null) {
// To fix [JACKSON-508]
if (_elementType.hasGenericTypes()) {
serializer = _findAndAddDynamic(ctxt,
ctxt.constructSpecializedType(_elementType, cc));
} else {
serializer = _findAndAddDynamic(ctxt, cc);
}
}
serializer.serialize(elem, g, ctxt);
}
}
} catch (Exception e) {
wrapAndThrow(ctxt, e, value, i);
}
}
public void serializeContentsUsing(List<?> value, JsonGenerator jgen, SerializationContext provider,
ValueSerializer<Object> ser)
throws JacksonException
{
final int len = value.size();
if (len == 0) {
return;
}
final TypeSerializer typeSer = _valueTypeSerializer;
for (int i = 0; i < len; ++i) {
Object elem = value.get(i);
try {
if (elem == null) {
provider.defaultSerializeNullValue(jgen);
} else if (typeSer == null) {
ser.serialize(elem, jgen, provider);
} else {
ser.serializeWithType(elem, jgen, provider, typeSer);
}
} catch (Exception e) {
// [JACKSON-55] Need to add reference information
wrapAndThrow(provider, e, value, i);
}
}
}
public void serializeTypedContents(List<?> value, JsonGenerator g, SerializationContext ctxt)
throws JacksonException
{
final int len = value.size();
if (len == 0) {
return;
}
int i = 0;
try {
final TypeSerializer typeSer = _valueTypeSerializer;
PropertySerializerMap serializers = _dynamicValueSerializers;
for (; i < len; ++i) {
Object elem = value.get(i);
if (elem == null) {
ctxt.defaultSerializeNullValue(g);
} else {
Class<?> cc = elem.getClass();
ValueSerializer<Object> serializer = serializers.serializerFor(cc);
if (serializer == null) {
if (_elementType.hasGenericTypes()) {
serializer = _findAndAddDynamic(ctxt,
ctxt.constructSpecializedType(_elementType, cc));
} else {
serializer = _findAndAddDynamic(ctxt, cc);
}
serializers = _dynamicValueSerializers;
}
serializer.serializeWithType(elem, g, ctxt, typeSer);
}
}
} catch (Exception e) {
wrapAndThrow(ctxt, e, value, i);
}
}
}
|
IndexedListSerializer
|
java
|
elastic__elasticsearch
|
server/src/internalClusterTest/java/org/elasticsearch/snapshots/AbortedSnapshotIT.java
|
{
"start": 2465,
"end": 5492
}
|
class ____ implements Runnable {
@Override
public void run() {
safeAwait(barrier);
safeAwait(barrier);
if (stopBlocking.get() == false) {
// enqueue another block to happen just after the currently-enqueued tasks
snapshotExecutor.execute(BlockingTask.this);
}
}
}
snapshotExecutor.execute(new BlockingTask());
safeAwait(barrier); // wait for snapshot thread to be blocked
clusterAdmin().prepareCreateSnapshot(TEST_REQUEST_TIMEOUT, repoName, "snapshot-1")
.setWaitForCompletion(false)
.setPartial(true)
.get();
// resulting cluster state has been applied on all nodes, which means the first task for the SNAPSHOT pool is queued up
final var snapshot = SnapshotsInProgress.get(clusterService.state()).forRepo(repoName).get(0).snapshot();
final var snapshotShardsService = internalCluster().getInstance(SnapshotShardsService.class, dataNode);
// Run up to 3 snapshot tasks, which are (in order):
// 1. run BlobStoreRepository#snapshotShard
// 2. run BlobStoreRepository#doSnapshotShard (moves the shard to state STARTED)
// 3. process one file (there will be at least two, but the per-file tasks are enqueued one at a time by the throttling executor)
final var steps = between(0, 3);
for (int i = 0; i < steps; i++) {
safeAwait(barrier); // release snapshot thread so it can run the enqueued task
safeAwait(barrier); // wait for snapshot thread to be blocked again
final var shardStatuses = snapshotShardsService.currentSnapshotShards(snapshot);
assertEquals(1, shardStatuses.size());
final var shardStatus = shardStatuses.get(new ShardId(index, 0));
logger.info("--> {}", shardStatus);
if (i == 0) {
assertEquals(IndexShardSnapshotStatus.Stage.INIT, shardStatus.getStage());
assertEquals(0, shardStatus.getProcessedFileCount());
assertEquals(0, shardStatus.getTotalFileCount());
} else {
assertEquals(IndexShardSnapshotStatus.Stage.STARTED, shardStatus.getStage());
assertThat(shardStatus.getProcessedFileCount(), greaterThan(0));
assertThat(shardStatus.getProcessedFileCount(), lessThan(shardStatus.getTotalFileCount()));
}
}
assertTrue(store.hasReferences());
assertAcked(indicesAdmin().prepareDelete(indexName).get());
// this is the key assertion: we must release the store without needing any SNAPSHOT threads to make further progress
assertBusy(() -> assertFalse(store.hasReferences()));
stopBlocking.set(true);
safeAwait(barrier); // release snapshot thread
assertBusy(() -> assertTrue(SnapshotsInProgress.get(clusterService.state()).isEmpty()));
}
}
|
BlockingTask
|
java
|
grpc__grpc-java
|
core/src/main/java/io/grpc/internal/StreamListener.java
|
{
"start": 1749,
"end": 2275
}
|
interface ____ {
/**
* Returns the next gRPC message, if the data has been received by the deframer and the
* application has requested another message.
*
* <p>The provided {@code message} {@link InputStream} must be closed by the listener.
*
* <p>This is intended to be used similar to an iterator, invoking {@code next()} to obtain
* messages until the producer returns null, at which point the producer may be discarded.
*/
@Nullable
InputStream next();
}
}
|
MessageProducer
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/DriverCompletionInfo.java
|
{
"start": 4540,
"end": 5269
}
|
class ____ {
private long documentsFound;
private long valuesLoaded;
private final List<DriverProfile> driverProfiles = new ArrayList<>();
private final List<PlanProfile> planProfiles = new ArrayList<>();
public void accumulate(DriverCompletionInfo info) {
this.documentsFound += info.documentsFound;
this.valuesLoaded += info.valuesLoaded;
this.driverProfiles.addAll(info.driverProfiles);
this.planProfiles.addAll(info.planProfiles);
}
public DriverCompletionInfo finish() {
return new DriverCompletionInfo(documentsFound, valuesLoaded, driverProfiles, planProfiles);
}
}
public static
|
Accumulator
|
java
|
apache__camel
|
components/camel-sql/src/main/java/org/apache/camel/processor/aggregate/jdbc/DefaultJdbcOptimisticLockingExceptionMapper.java
|
{
"start": 1931,
"end": 2028
}
|
class ____ is also matched. This allows to add vendor specific
* exception classes.
*/
public
|
names
|
java
|
quarkusio__quarkus
|
extensions/load-shedding/runtime/src/main/java/io/quarkus/load/shedding/RequestClassifier.java
|
{
"start": 774,
"end": 1382
}
|
interface ____<R> {
int MIN_COHORT = 1;
int MAX_COHORT = 128;
/**
* Returns whether this request classifier applies to given {@code request}.
*
* @param request the request, never {@code null}
* @return whether this request classifier applies to given {@code request}
*/
boolean appliesTo(Object request);
/**
* Returns the cohort to which the given {@code request} belongs.
*
* @param request the request, never {@code null}
* @return the cohort to which the given {@code request} belongs
*/
int cohort(R request);
}
|
RequestClassifier
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/function/json/JsonObjectTest.java
|
{
"start": 866,
"end": 1682
}
|
class ____ {
@Test
public void testSimple(SessionFactoryScope scope) {
scope.inSession( em -> {
//tag::hql-json-object-example[]
em.createQuery( "select json_object('key', 'value'), json_object(KEY 'key1' VALUE 'value1', 'key2' VALUE 'value2', 'key3': 'value3')" ).getResultList();
//end::hql-json-object-example[]
} );
}
@Test
public void testNullClause(SessionFactoryScope scope) {
scope.inSession( em -> {
em.createQuery("select json_object('key': null null on null)" ).getResultList();
} );
}
@Test
public void testAbsentOnNull(SessionFactoryScope scope) {
scope.inSession( em -> {
//tag::hql-json-object-on-null-example[]
em.createQuery("select json_object('key': null absent on null)" ).getResultList();
//end::hql-json-object-on-null-example[]
} );
}
}
|
JsonObjectTest
|
java
|
elastic__elasticsearch
|
distribution/tools/server-cli/src/test/java/org/elasticsearch/server/cli/ServerCliTests.java
|
{
"start": 19925,
"end": 20412
}
|
interface ____ {
void syncPlugins(Terminal terminal, OptionSet options, Environment env, ProcessInfo processInfo) throws UserException;
}
SyncPluginsMethod syncPluginsCallback;
private final MockSyncPluginsCli SYNC_PLUGINS_CLI = new MockSyncPluginsCli();
@Before
public void resetCommand() {
argsValidator = null;
autoConfigCallback = null;
syncPluginsCallback = null;
mockServerExitCode = 0;
}
private
|
SyncPluginsMethod
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/web/method/support/ModelAndViewContainer.java
|
{
"start": 1973,
"end": 9912
}
|
class ____ {
private @Nullable Object view;
private final ModelMap defaultModel = new BindingAwareModelMap();
private @Nullable ModelMap redirectModel;
private boolean redirectModelScenario = false;
private @Nullable HttpStatusCode status;
private final Set<String> noBinding = new HashSet<>(4);
private final Set<String> bindingDisabled = new HashSet<>(4);
private final SessionStatus sessionStatus = new SimpleSessionStatus();
private boolean requestHandled = false;
/**
* Set a view name to be resolved by the DispatcherServlet via a ViewResolver.
* Will override any pre-existing view name or View.
*/
public void setViewName(@Nullable String viewName) {
this.view = viewName;
}
/**
* Return the view name to be resolved by the DispatcherServlet via a
* ViewResolver, or {@code null} if a View object is set.
*/
public @Nullable String getViewName() {
return (this.view instanceof String viewName ? viewName : null);
}
/**
* Set a View object to be used by the DispatcherServlet.
* Will override any pre-existing view name or View.
*/
public void setView(@Nullable Object view) {
this.view = view;
}
/**
* Return the View object, or {@code null} if we are using a view name
* to be resolved by the DispatcherServlet via a ViewResolver.
*/
public @Nullable Object getView() {
return this.view;
}
/**
* Whether the view is a view reference specified via a name to be
* resolved by the DispatcherServlet via a ViewResolver.
*/
public boolean isViewReference() {
return (this.view instanceof String);
}
/**
* Return the model to use -- either the "default" or the "redirect" model.
* The default model is used if {@code redirectModelScenario=false} or
* there is no redirect model (i.e. RedirectAttributes was not declared as
* a method argument) and {@code ignoreDefaultModelOnRedirect=false}.
*/
public ModelMap getModel() {
if (!this.redirectModelScenario) {
return this.defaultModel;
}
if (this.redirectModel == null) {
this.redirectModel = new ModelMap();
}
return this.redirectModel;
}
/**
* Return the "default" model created at instantiation.
* <p>In general it is recommended to use {@link #getModel()} instead which
* returns either the "default" model (template rendering) or the "redirect"
* model (redirect URL preparation). Use of this method may be needed for
* advanced cases when access to the "default" model is needed regardless,
* for example, to save model attributes specified via {@code @SessionAttributes}.
* @return the default model (never {@code null})
* @since 4.1.4
*/
public ModelMap getDefaultModel() {
return this.defaultModel;
}
/**
* Provide a separate model instance to use in a redirect scenario.
* <p>The provided additional model however is not used unless
* {@link #setRedirectModelScenario} gets set to {@code true}
* to signal an actual redirect scenario.
*/
public void setRedirectModel(ModelMap redirectModel) {
this.redirectModel = redirectModel;
}
/**
* Whether the controller has returned a redirect instruction, for example, a
* "redirect:" prefixed view name, a RedirectView instance, etc.
*/
public void setRedirectModelScenario(boolean redirectModelScenario) {
this.redirectModelScenario = redirectModelScenario;
}
/**
* Provide an HTTP status that will be passed on to with the
* {@code ModelAndView} used for view rendering purposes.
* @since 4.3
*/
public void setStatus(@Nullable HttpStatusCode status) {
this.status = status;
}
/**
* Return the configured HTTP status, if any.
* @since 4.3
*/
public @Nullable HttpStatusCode getStatus() {
return this.status;
}
/**
* Programmatically register an attribute for which data binding should not occur,
* not even for a subsequent {@code @ModelAttribute} declaration.
* @param attributeName the name of the attribute
* @since 4.3
*/
public void setBindingDisabled(String attributeName) {
this.bindingDisabled.add(attributeName);
}
/**
* Whether binding is disabled for the given model attribute.
* @since 4.3
*/
public boolean isBindingDisabled(String name) {
return (this.bindingDisabled.contains(name) || this.noBinding.contains(name));
}
/**
* Register whether data binding should occur for a corresponding model attribute,
* corresponding to an {@code @ModelAttribute(binding=true/false)} declaration.
* <p>Note: While this flag will be taken into account by {@link #isBindingDisabled},
* a hard {@link #setBindingDisabled} declaration will always override it.
* @param attributeName the name of the attribute
* @since 4.3.13
*/
public void setBinding(String attributeName, boolean enabled) {
if (!enabled) {
this.noBinding.add(attributeName);
}
else {
this.noBinding.remove(attributeName);
}
}
/**
* Return the {@link SessionStatus} instance to use that can be used to
* signal that session processing is complete.
*/
public SessionStatus getSessionStatus() {
return this.sessionStatus;
}
/**
* Whether the request has been handled fully within the handler, for example,
* {@code @ResponseBody} method, and therefore view resolution is not
* necessary. This flag can also be set when controller methods declare an
* argument of type {@code ServletResponse} or {@code OutputStream}).
* <p>The default value is {@code false}.
*/
public void setRequestHandled(boolean requestHandled) {
this.requestHandled = requestHandled;
}
/**
* Whether the request has been handled fully within the handler.
*/
public boolean isRequestHandled() {
return this.requestHandled;
}
/**
* Add the supplied attribute to the underlying model.
* A shortcut for {@code getModel().addAttribute(String, Object)}.
*/
public ModelAndViewContainer addAttribute(String name, @Nullable Object value) {
getModel().addAttribute(name, value);
return this;
}
/**
* Add the supplied attribute to the underlying model.
* A shortcut for {@code getModel().addAttribute(Object)}.
*/
public ModelAndViewContainer addAttribute(Object value) {
getModel().addAttribute(value);
return this;
}
/**
* Copy all attributes to the underlying model.
* A shortcut for {@code getModel().addAllAttributes(Map)}.
*/
public ModelAndViewContainer addAllAttributes(@Nullable Map<String, ?> attributes) {
getModel().addAllAttributes(attributes);
return this;
}
/**
* Copy attributes in the supplied {@code Map} with existing objects of
* the same name taking precedence (i.e. not getting replaced).
* A shortcut for {@code getModel().mergeAttributes(Map<String, ?>)}.
*/
public ModelAndViewContainer mergeAttributes(@Nullable Map<String, ?> attributes) {
getModel().mergeAttributes(attributes);
return this;
}
/**
* Remove the given attributes from the model.
*/
public ModelAndViewContainer removeAttributes(@Nullable Map<String, ?> attributes) {
if (attributes != null) {
for (String key : attributes.keySet()) {
getModel().remove(key);
}
}
return this;
}
/**
* Whether the underlying model contains the given attribute name.
* A shortcut for {@code getModel().containsAttribute(String)}.
*/
public boolean containsAttribute(String name) {
return getModel().containsAttribute(name);
}
/**
* Return diagnostic information.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ModelAndViewContainer: ");
if (!isRequestHandled()) {
if (isViewReference()) {
sb.append("reference to view with name '").append(this.view).append('\'');
}
else {
sb.append("View is [").append(this.view).append(']');
}
if (!this.redirectModelScenario) {
sb.append("; default model ");
}
else {
sb.append("; redirect model ");
}
sb.append(getModel());
}
else {
sb.append("Request handled directly");
}
return sb.toString();
}
}
|
ModelAndViewContainer
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/createTable/MySqlCreateTableTest121_fulltext.java
|
{
"start": 556,
"end": 6647
}
|
class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "CREATE TABLE IF NOT EXISTS ddd ( pk int NOT NULL PRIMARY KEY AUTO_INCREMENT" +
", tint tinyint(10) UNSIGNED ZEROFILL, sint smallint DEFAULT 1000, mint mediumint UNIQUE, bint bigint(20) COMMENT 'bigint'" +
", rint real(10, 2) REFERENCES tt1 (rint) MATCH FULL ON DELETE RESTRICT, dble double(10, 2) REFERENCES tt1 (dble) MATCH PARTIAL ON DELETE CASCADE" +
", fl float(10, 2) REFERENCES tt1 (fl) MATCH SIMPLE ON DELETE SET NULL, dc decimal(10, 2) REFERENCES tt1 (dc) MATCH SIMPLE ON UPDATE NO ACTION" +
", num numeric(10, 2), dt date NULL, ti time, tis timestamp, dti datetime" +
", vc varchar(100) BINARY , vc2 varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, tb tinyblob, bl blob, mb mediumblob" +
", lb longblob, tt tinytext, mt mediumtext, lt longtext, en enum('1', '2'), st set('5', '6'), id1 int, id2 int, id3 varchar(100)" +
", vc1 varchar(100), vc3 varchar(100), INDEX idx1 USING hash(id1), KEY idx2 USING hash (id2), FULLTEXT key idx4(id3(20))" +
", CONSTRAINT c1 UNIQUE c1 USING btree (vc1(20)) ) ENGINE = InnoDB AUTO_INCREMENT = 2 AVG_ROW_LENGTH = 100 CHARACTER SET = utf8 COLLATE utf8_bin CHECKSUM = 0 COMMENT 'abcd'";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0);
assertEquals(1, statementList.size());
assertEquals(34, stmt.getTableElementList().size());
assertEquals("CREATE TABLE IF NOT EXISTS ddd (\n" +
"\tpk int NOT NULL PRIMARY KEY AUTO_INCREMENT,\n" +
"\ttint tinyint(10) UNSIGNED ZEROFILL,\n" +
"\tsint smallint DEFAULT 1000,\n" +
"\tmint mediumint UNIQUE,\n" +
"\tbint bigint(20) COMMENT 'bigint',\n" +
"\trint real(10, 2) REFERENCES tt1 (rint) MATCH FULL ON DELETE RESTRICT,\n" +
"\tdble double(10, 2) REFERENCES tt1 (dble) MATCH PARTIAL ON DELETE CASCADE,\n" +
"\tfl float(10, 2) REFERENCES tt1 (fl) MATCH SIMPLE ON DELETE SET NULL,\n" +
"\tdc decimal(10, 2) REFERENCES tt1 (dc) MATCH SIMPLE ON UPDATE NO ACTION,\n" +
"\tnum numeric(10, 2),\n" +
"\tdt date NULL,\n" +
"\tti time,\n" +
"\ttis timestamp,\n" +
"\tdti datetime,\n" +
"\tvc varchar(100) BINARY ,\n" +
"\tvc2 varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,\n" +
"\ttb tinyblob,\n" +
"\tbl blob,\n" +
"\tmb mediumblob,\n" +
"\tlb longblob,\n" +
"\ttt tinytext,\n" +
"\tmt mediumtext,\n" +
"\tlt longtext,\n" +
"\ten enum('1', '2'),\n" +
"\tst set('5', '6'),\n" +
"\tid1 int,\n" +
"\tid2 int,\n" +
"\tid3 varchar(100),\n" +
"\tvc1 varchar(100),\n" +
"\tvc3 varchar(100),\n" +
"\tINDEX idx1 USING hash(id1),\n" +
"\tKEY idx2 USING hash (id2),\n" +
"\tFULLTEXT KEY idx4 (id3(20)),\n" +
"\tUNIQUE c1 USING btree (vc1(20))\n" +
") ENGINE = InnoDB AUTO_INCREMENT = 2 AVG_ROW_LENGTH = 100 CHARACTER SET = utf8 COLLATE = utf8_bin CHECKSUM = 0 COMMENT 'abcd'", stmt.toString());
assertEquals("create table if not exists ddd (\n" +
"\tpk int not null primary key auto_increment,\n" +
"\ttint tinyint(10) unsigned zerofill,\n" +
"\tsint smallint default 1000,\n" +
"\tmint mediumint unique,\n" +
"\tbint bigint(20) comment 'bigint',\n" +
"\trint real(10, 2) references tt1 (rint) match full on delete restrict,\n" +
"\tdble double(10, 2) references tt1 (dble) match partial on delete cascade,\n" +
"\tfl float(10, 2) references tt1 (fl) match simple on delete set null,\n" +
"\tdc decimal(10, 2) references tt1 (dc) match simple on update no action,\n" +
"\tnum numeric(10, 2),\n" +
"\tdt date null,\n" +
"\tti time,\n" +
"\ttis timestamp,\n" +
"\tdti datetime,\n" +
"\tvc varchar(100) binary ,\n" +
"\tvc2 varchar(100) character set utf8 collate utf8_bin not null,\n" +
"\ttb tinyblob,\n" +
"\tbl blob,\n" +
"\tmb mediumblob,\n" +
"\tlb longblob,\n" +
"\ttt tinytext,\n" +
"\tmt mediumtext,\n" +
"\tlt longtext,\n" +
"\ten enum('1', '2'),\n" +
"\tst set('5', '6'),\n" +
"\tid1 int,\n" +
"\tid2 int,\n" +
"\tid3 varchar(100),\n" +
"\tvc1 varchar(100),\n" +
"\tvc3 varchar(100),\n" +
"\tindex idx1 using hash(id1),\n" +
"\tkey idx2 using hash (id2),\n" +
"\tfulltext key idx4 (id3(20)),\n" +
"\tunique c1 using btree (vc1(20))\n" +
") engine = InnoDB auto_increment = 2 avg_row_length = 100 character set = utf8 collate = utf8_bin checksum = 0 comment 'abcd'", stmt.toLowerCaseString());
SchemaStatVisitor v = SQLUtils.createSchemaStatVisitor(JdbcConstants.MYSQL);
stmt.accept(v);
assertEquals(30, v.getColumns().size());
SQLColumnDefinition column = stmt.findColumn("bint");
assertNotNull(column);
assertEquals(0, column.getConstraints().size());
assertFalse(column.isPrimaryKey());
assertEquals(Types.BIGINT, column.jdbcType());
}
}
|
MySqlCreateTableTest121_fulltext
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/SelfThrottlingIntercept.java
|
{
"start": 7408,
"end": 7603
}
|
class ____ extends StorageEvent<ResponseReceivedEvent> {
@Override
public void eventOccurred(ResponseReceivedEvent event) {
responseReceived(event);
}
}
}
|
ResponseReceivedListener
|
java
|
spring-projects__spring-framework
|
spring-expression/src/test/java/org/springframework/expression/spel/MapTests.java
|
{
"start": 6914,
"end": 7117
}
|
class ____ {
public Map foo = Map.of(
"NEW", "VALUE",
"new", "value",
"T", "TV",
"t", "tv",
"abc.def", "value",
"VALUE","37",
"value","38",
"TV","new"
);
}
}
|
MapHolder
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/common/utils/MockTimeTest.java
|
{
"start": 996,
"end": 1742
}
|
class ____ extends TimeTest {
@Test
public void testAdvanceClock() {
MockTime time = new MockTime(0, 100, 200);
assertEquals(100, time.milliseconds());
assertEquals(200, time.nanoseconds());
time.sleep(1);
assertEquals(101, time.milliseconds());
assertEquals(1000200, time.nanoseconds());
}
@Test
public void testAutoTickMs() {
MockTime time = new MockTime(1, 100, 200);
assertEquals(101, time.milliseconds());
assertEquals(2000200, time.nanoseconds());
assertEquals(103, time.milliseconds());
assertEquals(104, time.milliseconds());
}
@Override
protected Time createTime() {
return new MockTime();
}
}
|
MockTimeTest
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/wsrs/LongParam.java
|
{
"start": 948,
"end": 1251
}
|
class ____ extends Param<Long> {
public LongParam(String name, Long defaultValue) {
super(name, defaultValue);
}
@Override
protected Long parse(String str) throws Exception {
return Long.parseLong(str);
}
@Override
protected String getDomain() {
return "a long";
}
}
|
LongParam
|
java
|
elastic__elasticsearch
|
libs/simdvec/src/main/java/org/elasticsearch/simdvec/VectorScorerFactory.java
|
{
"start": 875,
"end": 2400
}
|
interface ____ {
static Optional<VectorScorerFactory> instance() {
return Optional.ofNullable(VectorScorerFactoryImpl.INSTANCE);
}
/**
* Returns an optional containing an int7 scalar quantized vector score supplier
* for the given parameters, or an empty optional if a scorer is not supported.
*
* @param similarityType the similarity type
* @param input the index input containing the vector data;
* offset of the first vector is 0,
* the length must be (maxOrd + Float#BYTES) * dims
* @param values the random access vector values
* @param scoreCorrectionConstant the score correction constant
* @return an optional containing the vector scorer supplier, or empty
*/
Optional<RandomVectorScorerSupplier> getInt7SQVectorScorerSupplier(
VectorSimilarityType similarityType,
IndexInput input,
QuantizedByteVectorValues values,
float scoreCorrectionConstant
);
/**
* Returns an optional containing an int7 scalar quantized vector scorer for
* the given parameters, or an empty optional if a scorer is not supported.
*
* @param sim the similarity type
* @param values the random access vector values
* @param queryVector the query vector
* @return an optional containing the vector scorer, or empty
*/
Optional<RandomVectorScorer> getInt7SQVectorScorer(VectorSimilarityFunction sim, QuantizedByteVectorValues values, float[] queryVector);
}
|
VectorScorerFactory
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/scheduling/concurrent/ConcurrentTaskScheduler.java
|
{
"start": 11991,
"end": 12067
}
|
class ____ order to avoid a hard dependency on the JSR-236 API.
*/
private
|
in
|
java
|
quarkusio__quarkus
|
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/generatedresolvers/HierarchyTest.java
|
{
"start": 2176,
"end": 2303
}
|
class ____ {
public String getName() {
return "foo";
}
}
@TemplateData
public static
|
Foo
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/util/DescriptiveJsonGeneratingVisitorSmokeTest.java
|
{
"start": 8234,
"end": 9021
}
|
class ____ implements Serializable {
@Id
private long id;
@Column(nullable = false)
private String name;
@Embedded
private Address address;
@OneToMany(mappedBy = "company")
private List<Employee> employees;
public Company() {
}
public Company(long id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
this.employees = new ArrayList<>();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
@Embeddable
static
|
Company
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AbfsTailLatencyTrackerFactory.java
|
{
"start": 1128,
"end": 1157
}
|
class ____ account.
*/
final
|
per
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/expressions/AggregateExpression.java
|
{
"start": 2030,
"end": 5757
}
|
class ____ implements ResolvedExpression {
private final FunctionDefinition functionDefinition;
private final List<FieldReferenceExpression> args;
private final @Nullable CallExpression filterExpression;
private final DataType resultType;
private final boolean distinct;
private final boolean approximate;
private final boolean ignoreNulls;
public AggregateExpression(
FunctionDefinition functionDefinition,
List<FieldReferenceExpression> args,
@Nullable CallExpression filterExpression,
DataType resultType,
boolean distinct,
boolean approximate,
boolean ignoreNulls) {
this.functionDefinition =
Preconditions.checkNotNull(
functionDefinition, "Function definition must not be null.");
this.args = args;
this.filterExpression = filterExpression;
this.resultType = resultType;
this.distinct = distinct;
this.approximate = approximate;
this.ignoreNulls = ignoreNulls;
}
public FunctionDefinition getFunctionDefinition() {
return functionDefinition;
}
public boolean isDistinct() {
return distinct;
}
public boolean isApproximate() {
return approximate;
}
public boolean isIgnoreNulls() {
return ignoreNulls;
}
public List<FieldReferenceExpression> getArgs() {
return args;
}
public Optional<CallExpression> getFilterExpression() {
return Optional.ofNullable(filterExpression);
}
@Override
public DataType getOutputDataType() {
return resultType;
}
@Override
public List<ResolvedExpression> getResolvedChildren() {
List<ResolvedExpression> resolvedChildren = new ArrayList<>(this.args);
resolvedChildren.add(this.filterExpression);
return Collections.unmodifiableList(resolvedChildren);
}
@Override
public String asSummaryString() {
final String argList =
args.stream()
.map(Expression::asSummaryString)
.collect(Collectors.joining(", ", "(", ")"));
return functionDefinition.toString() + argList;
}
@Override
public List<Expression> getChildren() {
List<Expression> children = new ArrayList<>(this.args);
children.add(this.filterExpression);
return Collections.unmodifiableList(children);
}
@Override
public <R> R accept(ExpressionVisitor<R> visitor) {
return visitor.visit(this);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AggregateExpression that = (AggregateExpression) o;
return Objects.equals(functionDefinition, that.functionDefinition)
&& Objects.equals(args, that.args)
&& Objects.equals(filterExpression, that.filterExpression)
&& Objects.equals(resultType, that.resultType)
&& Objects.equals(distinct, that.distinct)
&& Objects.equals(approximate, that.approximate)
&& Objects.equals(ignoreNulls, that.ignoreNulls);
}
@Override
public int hashCode() {
return Objects.hash(
functionDefinition,
args,
filterExpression,
resultType,
distinct,
approximate,
ignoreNulls);
}
@Override
public String toString() {
return asSummaryString();
}
}
|
AggregateExpression
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/BasicTypeSerializerUpgradeTestSpecifications.java
|
{
"start": 4329,
"end": 5430
}
|
class ____
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<BigInteger> {
@Override
public TypeSerializer<BigInteger> createUpgradedSerializer() {
return BigIntSerializer.INSTANCE;
}
@Override
public Condition<BigInteger> testDataCondition() {
return new Condition<>(
value -> value.equals(new BigInteger("123456789012345678901234567890123456")),
"value is 123456789012345678901234567890123456");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<BigInteger>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "BooleanSerializer"
// ----------------------------------------------------------------------------------------------
/** BooleanSerializerSetup. */
public static final
|
BigIntSerializerVerifier
|
java
|
alibaba__nacos
|
naming/src/test/java/com/alibaba/nacos/naming/web/ClientAttributesFilterTest.java
|
{
"start": 2023,
"end": 4110
}
|
class ____ {
@Mock
ClientManager clientManager;
@Mock
IpPortBasedClient client;
@Mock
HttpServletRequest request;
@Mock
HttpServletResponse response;
@Mock
Servlet servlet;
@InjectMocks
ClientAttributesFilter filter;
@BeforeEach
void setUp() {
RequestContextHolder.getContext().getBasicContext().setUserAgent("Nacos-Java-Client:v2.4.0");
RequestContextHolder.getContext().getBasicContext().setApp("testApp");
RequestContextHolder.getContext().getBasicContext().getAddressContext().setRemoteIp("1.1.1.1");
RequestContextHolder.getContext().getBasicContext().getAddressContext().setSourceIp("2.2.2.2");
}
@AfterEach
void tearDown() {
RequestContextHolder.removeContext();
}
@Test
void testDoFilterForRegisterUri() throws IOException {
when(request.getRequestURI()).thenReturn(
UtilsAndCommons.NACOS_SERVER_CONTEXT + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT);
when(request.getMethod()).thenReturn("POST");
filter.doFilter(request, response, new MockFilterChain(servlet, new MockRegisterFilter()));
}
@Test
void testDoFilterForBeatUri() throws IOException {
when(request.getParameter("ip")).thenReturn("127.0.0.1");
when(request.getParameter("port")).thenReturn("8848");
when(request.getParameter("encoding")).thenReturn("utf-8");
when(clientManager.getClient("127.0.0.1:8848#true")).thenReturn(client);
when(request.getRequestURI()).thenReturn(
UtilsAndCommons.NACOS_SERVER_CONTEXT + UtilsAndCommons.NACOS_NAMING_CONTEXT
+ UtilsAndCommons.NACOS_NAMING_INSTANCE_CONTEXT + "/beat");
when(request.getMethod()).thenReturn("PUT");
filter.doFilter(request, response, new MockFilterChain());
verify(client).setAttributes(any(ClientAttributes.class));
}
private static
|
ClientAttributesFilterTest
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/cfg/MutableCoercionConfig.java
|
{
"start": 312,
"end": 745
}
|
class ____
extends CoercionConfig
implements java.io.Serializable
{
private static final long serialVersionUID = 3L;
public MutableCoercionConfig() { }
protected MutableCoercionConfig(MutableCoercionConfig src) {
super(src);
}
public MutableCoercionConfig copy() {
return new MutableCoercionConfig(this);
}
/**
* Method to set coercions to target type or
|
MutableCoercionConfig
|
java
|
elastic__elasticsearch
|
build-tools-internal/src/main/java/org/elasticsearch/gradle/internal/toolchain/AbstractCustomJavaToolchainResolver.java
|
{
"start": 720,
"end": 1846
}
|
class ____ implements JavaToolchainResolver {
static String toOsString(OperatingSystem operatingSystem) {
return toOsString(operatingSystem, null);
}
static String toOsString(OperatingSystem operatingSystem, JvmVendorSpec v) {
return switch (operatingSystem) {
case MAC_OS -> (v == null || v.equals(JvmVendorSpec.ADOPTIUM) == false) ? "macos" : "mac";
case LINUX -> "linux";
case WINDOWS -> "windows";
default -> throw new UnsupportedOperationException("Operating system " + operatingSystem);
};
}
static String toArchString(Architecture architecture) {
return switch (architecture) {
case X86_64 -> "x64";
case AARCH64 -> "aarch64";
case X86 -> "x86";
default -> throw new UnsupportedOperationException("Architecture " + architecture);
};
}
protected static boolean anyVendorOr(JvmVendorSpec givenVendor, JvmVendorSpec expectedVendor) {
return givenVendor.matches("any") || givenVendor.equals(expectedVendor);
}
}
|
AbstractCustomJavaToolchainResolver
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/annotations/BackpressureKind.java
|
{
"start": 735,
"end": 1674
}
|
enum ____ {
/**
* The backpressure-related requests pass through this operator without change.
*/
PASS_THROUGH,
/**
* The operator fully supports backpressure and may coordinate downstream requests
* with upstream requests through batching, arbitration or by other means.
*/
FULL,
/**
* The operator performs special backpressure management; see the associated javadoc.
*/
SPECIAL,
/**
* The operator requests {@link Long#MAX_VALUE} from upstream but respects the backpressure
* of the downstream.
*/
UNBOUNDED_IN,
/**
* The operator will emit a {@link io.reactivex.rxjava3.exceptions.MissingBackpressureException MissingBackpressureException}
* if the downstream didn't request enough or in time.
*/
ERROR,
/**
* The operator ignores all kinds of backpressure and may overflow the downstream.
*/
NONE
}
|
BackpressureKind
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/TestOfflineImageViewerForStoragePolicy.java
|
{
"start": 1972,
"end": 6416
}
|
class ____ {
private static final Logger LOG =
LoggerFactory.getLogger(TestOfflineImageViewerForStoragePolicy.class);
private static File originalFsimage = null;
private static File tempDir;
/**
* Create a populated namespace for later testing. Save its contents to a
* data structure and store its fsimage location.
*/
@BeforeAll
public static void createOriginalFSImage() throws IOException {
MiniDFSCluster cluster = null;
try {
Configuration conf = new Configuration();
conf.setBoolean(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, true);
conf.setBoolean(DFSConfigKeys.DFS_STORAGE_POLICY_ENABLED_KEY, true);
File[] nnDirs = MiniDFSCluster.getNameNodeDirectory(
MiniDFSCluster.getBaseDirectory(), 0, 0);
tempDir = nnDirs[0];
cluster = new MiniDFSCluster.Builder(conf).build();
cluster.waitActive();
DistributedFileSystem hdfs = cluster.getFileSystem();
Path dir = new Path("/dir_wo_sp");
hdfs.mkdirs(dir);
dir = new Path("/dir_wo_sp/sub_dir_wo_sp");
hdfs.mkdirs(dir);
dir = new Path("/dir_wo_sp/sub_dir_w_sp_allssd");
hdfs.mkdirs(dir);
hdfs.setStoragePolicy(dir, ALLSSD_STORAGE_POLICY_NAME);
Path file = new Path("/dir_wo_sp/file_wo_sp");
try (FSDataOutputStream o = hdfs.create(file)) {
o.write(123);
o.close();
}
file = new Path("/dir_wo_sp/file_w_sp_allssd");
try (FSDataOutputStream o = hdfs.create(file)) {
o.write(123);
o.close();
hdfs.setStoragePolicy(file, HdfsConstants.ALLSSD_STORAGE_POLICY_NAME);
}
dir = new Path("/dir_w_sp_allssd");
hdfs.mkdirs(dir);
hdfs.setStoragePolicy(dir, HdfsConstants.ALLSSD_STORAGE_POLICY_NAME);
dir = new Path("/dir_w_sp_allssd/sub_dir_wo_sp");
hdfs.mkdirs(dir);
file = new Path("/dir_w_sp_allssd/file_wo_sp");
try (FSDataOutputStream o = hdfs.create(file)) {
o.write(123);
o.close();
}
dir = new Path("/dir_w_sp_allssd/sub_dir_w_sp_hot");
hdfs.mkdirs(dir);
hdfs.setStoragePolicy(dir, HdfsConstants.HOT_STORAGE_POLICY_NAME);
// Write results to the fsimage file
hdfs.setSafeMode(SafeModeAction.ENTER, false);
hdfs.saveNamespace();
// Determine the location of the fsimage file
originalFsimage = FSImageTestUtil.findLatestImageFile(FSImageTestUtil
.getFSImage(cluster.getNameNode()).getStorage().getStorageDir(0));
if (originalFsimage == null) {
throw new RuntimeException("Didn't generate or can't find fsimage");
}
LOG.debug("original FS image file is " + originalFsimage);
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
}
@AfterAll
public static void deleteOriginalFSImage() throws IOException {
if (originalFsimage != null && originalFsimage.exists()) {
originalFsimage.delete();
}
}
@Test
public void testPBDelimitedWriterForStoragePolicy() throws Exception {
String expected = DFSTestUtil.readResoucePlainFile(
"testStoragePolicy.csv");
String result = readStoragePolicyFromFsimageFile();
assertEquals(expected, result);
}
private String readStoragePolicyFromFsimageFile() throws Exception {
StringBuilder builder = new StringBuilder();
ByteArrayOutputStream output = new ByteArrayOutputStream();
String delemiter = "\t";
File delimitedOutput = new File(tempDir, "delimitedOutput");
if (OfflineImageViewerPB.run(new String[] {"-p", "Delimited",
"-i", originalFsimage.getAbsolutePath(),
"-o", delimitedOutput.getAbsolutePath(),
"-sp"}) != 0) {
throw new IOException("oiv returned failure creating " +
"delimited output with sp.");
}
try (InputStream input = new FileInputStream(delimitedOutput);
BufferedReader reader =
new BufferedReader(new InputStreamReader(input))) {
String line;
boolean header = true;
while ((line = reader.readLine()) != null) {
String[] fields = line.split(delemiter);
if (!header) {
String path = fields[0];
int storagePolicy = Integer.parseInt(fields[12]);
builder.append(path).append(",").append(storagePolicy).append("\n");
}
header = false;
}
}
return builder.toString();
}
}
|
TestOfflineImageViewerForStoragePolicy
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/resource/transaction/spi/IsolationDelegate.java
|
{
"start": 408,
"end": 1265
}
|
interface ____ {
/**
* Perform the given work in isolation from current transaction.
*
* @param work The work to be performed.
* @param transacted Should the work itself be done in a (isolated) transaction?
*
* @return The work result
*
* @throws HibernateException Indicates a problem performing the work.
*/
<T> T delegateWork(WorkExecutorVisitable<T> work, boolean transacted) throws HibernateException;
/**
* Invoke the given callable in isolation from current transaction.
*
* @param callable The callable to be invoked.
* @param transacted Should the work itself be done in a (isolated) transaction?
*
* @return The work result
*
* @throws HibernateException Indicates a problem performing the work.
*/
<T> T delegateCallable(Callable<T> callable, boolean transacted) throws HibernateException;
}
|
IsolationDelegate
|
java
|
elastic__elasticsearch
|
x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/AutoscalingIT.java
|
{
"start": 2901,
"end": 16233
}
|
class ____ extends MlNativeAutodetectIntegTestCase {
private static final long PER_JOB_OVERHEAD_MB = 10;
private static final long PER_MODEL_OVERHEAD_MB = 240;
private static final long PER_NODE_OVERHEAD_MB = 30;
@Before
public void putSettings() {
updateClusterSettings(
Settings.builder().put(MachineLearningField.MAX_LAZY_ML_NODES.getKey(), 100).put("logger.org.elasticsearch.xpack.ml", "DEBUG")
);
}
@After
public void removeSettings() {
updateClusterSettings(
Settings.builder().putNull(MachineLearningField.MAX_LAZY_ML_NODES.getKey()).putNull("logger.org.elasticsearch.xpack.ml")
);
cleanUp();
}
// This test assumes that xpack.ml.max_machine_memory_percent is 30
// and that xpack.ml.use_auto_machine_memory_percent is false.
// It also assumes that 30% of RAM on the test machine is sufficient
// to run a 200MB job but not a 50000MB job. (If we move to 256GB CI
// workers then it will need to be adjusted.)
public void testMLAutoscalingCapacity() throws Exception {
SortedMap<String, Settings> deciders = new TreeMap<>();
deciders.put(
MlAutoscalingDeciderService.NAME,
Settings.builder().put(MlAutoscalingDeciderService.DOWN_SCALE_DELAY.getKey(), TimeValue.ZERO).build()
);
final PutAutoscalingPolicyAction.Request request = new PutAutoscalingPolicyAction.Request(
TEST_REQUEST_TIMEOUT,
TEST_REQUEST_TIMEOUT,
"ml_test",
new TreeSet<>(List.of("master", "data", "ingest", "ml")),
deciders
);
assertAcked(client().execute(PutAutoscalingPolicyAction.INSTANCE, request).actionGet());
assertBusy(
() -> assertMlCapacity(
client().execute(GetAutoscalingCapacityAction.INSTANCE, new GetAutoscalingCapacityAction.Request(TEST_REQUEST_TIMEOUT))
.actionGet(),
"Requesting scale down as tier and/or node size could be smaller",
0L,
0L
)
);
putJob("job1", 100);
putJob("job2", 200);
openJob("job1");
openJob("job2");
long expectedTierBytes = (long) Math.ceil(
ByteSizeValue.ofMb(100 + PER_JOB_OVERHEAD_MB + 200 + PER_JOB_OVERHEAD_MB + PER_NODE_OVERHEAD_MB).getBytes() * 100 / 30.0
);
long expectedNodeBytes = (long) Math.ceil(
ByteSizeValue.ofMb(200 + PER_JOB_OVERHEAD_MB + PER_NODE_OVERHEAD_MB).getBytes() * 100 / 30.0
);
assertMlCapacity(
client().execute(GetAutoscalingCapacityAction.INSTANCE, new GetAutoscalingCapacityAction.Request(TEST_REQUEST_TIMEOUT))
.actionGet(),
"Requesting scale down as tier and/or node size could be smaller",
expectedTierBytes,
expectedNodeBytes
);
putJob("bigjob1", 60_000);
putJob("bigjob2", 50_000);
openJob("bigjob1");
openJob("bigjob2");
long lowestMlMemory = admin().cluster()
.prepareNodesInfo()
.all()
.get()
.getNodes()
.stream()
.map(NodeInfo::getNode)
.filter(MachineLearning::isMlNode)
.map(node -> Long.parseLong(node.getAttributes().get(MachineLearning.MACHINE_MEMORY_NODE_ATTR)) * 30 / 100)
.min(Long::compareTo)
.orElse(0L);
long lowestFreeMemory = lowestMlMemory - ByteSizeValue.ofMb(200 + PER_JOB_OVERHEAD_MB + PER_NODE_OVERHEAD_MB).getBytes();
assertThat(lowestFreeMemory, greaterThan(0L));
// We'll have some free memory on both ML nodes, but not enough to load the huge model.
// The amount of free memory on one of the ML nodes should be taken into account.
expectedTierBytes = (long) Math.ceil(
(ByteSizeValue.ofMb(
100 + PER_JOB_OVERHEAD_MB + 200 + PER_JOB_OVERHEAD_MB + 50_000 + PER_JOB_OVERHEAD_MB + 60_000 + PER_JOB_OVERHEAD_MB
+ PER_NODE_OVERHEAD_MB
).getBytes() + lowestFreeMemory) * 100 / 30.0
);
expectedNodeBytes = (long) Math.ceil(
ByteSizeValue.ofMb(60_000 + PER_JOB_OVERHEAD_MB + PER_NODE_OVERHEAD_MB).getBytes() * 100 / 30.0
);
assertMlCapacity(
client().execute(GetAutoscalingCapacityAction.INSTANCE, new GetAutoscalingCapacityAction.Request(TEST_REQUEST_TIMEOUT))
.actionGet(),
"requesting scale up as number of jobs in queues exceeded configured limit",
expectedTierBytes,
expectedNodeBytes
);
closeJob("bigjob1");
closeJob("bigjob2");
expectedTierBytes = (long) Math.ceil(
ByteSizeValue.ofMb(100 + PER_JOB_OVERHEAD_MB + 200 + PER_JOB_OVERHEAD_MB + PER_NODE_OVERHEAD_MB).getBytes() * 100 / 30.0
);
expectedNodeBytes = (long) Math.ceil(ByteSizeValue.ofMb(200 + PER_JOB_OVERHEAD_MB + PER_NODE_OVERHEAD_MB).getBytes() * 100 / 30.0);
assertMlCapacity(
client().execute(GetAutoscalingCapacityAction.INSTANCE, new GetAutoscalingCapacityAction.Request(TEST_REQUEST_TIMEOUT))
.actionGet(),
"Requesting scale down as tier and/or node size could be smaller",
expectedTierBytes,
expectedNodeBytes
);
closeJob("job1");
closeJob("job2");
assertMlCapacity(
client().execute(GetAutoscalingCapacityAction.INSTANCE, new GetAutoscalingCapacityAction.Request(TEST_REQUEST_TIMEOUT))
.actionGet(),
"Requesting scale down as tier and/or node size could be smaller",
0L,
0L
);
}
// This test assumes that xpack.ml.max_machine_memory_percent is 30
// and that xpack.ml.use_auto_machine_memory_percent is false.
// It also assumes that 30% of RAM on the test machine is sufficient
// to run a 200MB job but not a 50000MB model. (If we move to 512GB CI
// workers then it will need to be adjusted.)
@AwaitsFix(bugUrl = "Cannot be fixed until we move estimation to config and not rely on definition length only")
public void testMLAutoscalingForLargeModelAssignment() {
String modelId = "really_big_model";
String deploymentId = "really_big_model_deployment";
SortedMap<String, Settings> deciders = new TreeMap<>();
deciders.put(
MlAutoscalingDeciderService.NAME,
Settings.builder().put(MlAutoscalingDeciderService.DOWN_SCALE_DELAY.getKey(), TimeValue.ZERO).build()
);
final PutAutoscalingPolicyAction.Request request = new PutAutoscalingPolicyAction.Request(
TEST_REQUEST_TIMEOUT,
TEST_REQUEST_TIMEOUT,
"ml_test",
new TreeSet<>(List.of("master", "data", "ingest", "ml")),
deciders
);
assertAcked(client().execute(PutAutoscalingPolicyAction.INSTANCE, request).actionGet());
putAndStartModelDeployment("smaller1", "dep1", ByteSizeValue.ofMb(100).getBytes(), AllocationStatus.State.STARTED);
putAndStartModelDeployment("smaller2", "dep2", ByteSizeValue.ofMb(100).getBytes(), AllocationStatus.State.STARTED);
long expectedTierBytes = (long) Math.ceil(
ByteSizeValue.ofMb(100 + PER_JOB_OVERHEAD_MB + 200 + PER_JOB_OVERHEAD_MB + PER_NODE_OVERHEAD_MB).getBytes() * 100 / 30.0
);
long expectedNodeBytes = (long) Math.ceil(
ByteSizeValue.ofMb(200 + PER_JOB_OVERHEAD_MB + PER_NODE_OVERHEAD_MB).getBytes() * 100 / 30.0
);
assertMlCapacity(
client().execute(GetAutoscalingCapacityAction.INSTANCE, new GetAutoscalingCapacityAction.Request(TEST_REQUEST_TIMEOUT))
.actionGet(),
"Requesting scale down as tier and/or node size could be smaller",
expectedTierBytes,
expectedNodeBytes
);
long modelSize = ByteSizeValue.ofMb(50_000).getBytes();
putAndStartModelDeployment(modelId, deploymentId, modelSize, AllocationStatus.State.STARTING);
long lowestMlMemory = admin().cluster()
.prepareNodesInfo()
.all()
.get()
.getNodes()
.stream()
.map(NodeInfo::getNode)
.filter(MachineLearning::isMlNode)
.map(node -> Long.parseLong(node.getAttributes().get(MachineLearning.MACHINE_MEMORY_NODE_ATTR)) * 30 / 100)
.min(Long::compareTo)
.orElse(0L);
long lowestFreeMemory = lowestMlMemory - ByteSizeValue.ofMb(200 + PER_JOB_OVERHEAD_MB + PER_NODE_OVERHEAD_MB).getBytes();
assertThat(lowestFreeMemory, greaterThan(0L));
// We'll have some free memory on both ML nodes, but not enough to load the huge model.
// The amount of free memory on one of the ML nodes should be taken into account.
expectedTierBytes = (long) Math.ceil(
(ByteSizeValue.ofMb(
100 + PER_JOB_OVERHEAD_MB + 200 + PER_JOB_OVERHEAD_MB + 2 * 50_000 + PER_MODEL_OVERHEAD_MB + PER_NODE_OVERHEAD_MB
).getBytes() + lowestFreeMemory) * 100 / 30.0
);
expectedNodeBytes = (long) Math.ceil(
ByteSizeValue.ofMb(50_000 + PER_JOB_OVERHEAD_MB + PER_NODE_OVERHEAD_MB).getBytes() * 100 / 30.0
);
assertMlCapacity(
client().execute(GetAutoscalingCapacityAction.INSTANCE, new GetAutoscalingCapacityAction.Request(TEST_REQUEST_TIMEOUT))
.actionGet(),
"requesting scale up as number of jobs in queues exceeded configured limit "
+ "or there is at least one trained model waiting for assignment "
+ "and current capacity is not large enough for waiting jobs",
expectedTierBytes,
expectedNodeBytes
);
}
private void assertMlCapacity(GetAutoscalingCapacityAction.Response capacity, String reason, long tierBytes, long nodeBytes) {
assertThat(capacity.getResults(), hasKey("ml_test"));
AutoscalingDeciderResults autoscalingDeciderResults = capacity.getResults().get("ml_test");
assertThat(autoscalingDeciderResults.results(), hasKey("ml"));
AutoscalingDeciderResult autoscalingDeciderResult = autoscalingDeciderResults.results().get("ml");
assertThat(autoscalingDeciderResult.reason().summary(), containsString(reason));
assertThat(autoscalingDeciderResult.requiredCapacity().node().memory().getBytes(), equalTo(nodeBytes));
// For the tier we might ask for more than expected because this cluster has multiple small nodes in one availability zone.
// But the discrepancy should not be huge.
assertThat(autoscalingDeciderResult.requiredCapacity().total().memory().getBytes(), greaterThanOrEqualTo(tierBytes));
assertThat(autoscalingDeciderResult.requiredCapacity().total().memory().getBytes(), lessThan(tierBytes + PER_NODE_OVERHEAD_MB));
}
private void putJob(String jobId, long limitMb) {
Job.Builder job = new Job.Builder(jobId).setAllowLazyOpen(true)
.setAnalysisLimits(new AnalysisLimits(limitMb, null))
.setAnalysisConfig(
new AnalysisConfig.Builder((List<Detector>) null).setBucketSpan(TimeValue.timeValueHours(1))
.setDetectors(Collections.singletonList(new Detector.Builder("count", null).setPartitionFieldName("user").build()))
)
.setDataDescription(new DataDescription.Builder().setTimeFormat("epoch"));
putJob(job);
}
private void putAndStartModelDeployment(String modelId, String deploymentId, long memoryUse, AllocationStatus.State state) {
client().execute(
PutTrainedModelAction.INSTANCE,
new PutTrainedModelAction.Request(
TrainedModelConfig.builder()
.setModelType(TrainedModelType.PYTORCH)
.setInferenceConfig(
new PassThroughConfig(null, new BertTokenization(null, false, null, Tokenization.Truncate.NONE, -1), null)
)
.setModelId(modelId)
.build(),
false
)
).actionGet();
client().execute(
PutTrainedModelDefinitionPartAction.INSTANCE,
new PutTrainedModelDefinitionPartAction.Request(
modelId,
new BytesArray(Base64.getDecoder().decode(BASE_64_ENCODED_MODEL)),
0,
memoryUse,
1,
false
)
).actionGet();
client().execute(
PutTrainedModelVocabularyAction.INSTANCE,
new PutTrainedModelVocabularyAction.Request(
modelId,
List.of("these", "are", "my", "words", BertTokenizer.UNKNOWN_TOKEN, BertTokenizer.PAD_TOKEN),
List.of(),
List.of(),
false
)
).actionGet();
client().execute(
StartTrainedModelDeploymentAction.INSTANCE,
new StartTrainedModelDeploymentAction.Request(modelId, deploymentId).setWaitForState(state)
).actionGet();
}
}
|
AutoscalingIT
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/jsontype/ext/ExternalTypeIdWithCreatorTest.java
|
{
"start": 1347,
"end": 1819
}
|
class ____ {
public String name;
public Attacks preferredAttack;
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, defaultImpl=Kick.class,
include=JsonTypeInfo.As.EXTERNAL_PROPERTY, property="preferredAttack")
@JsonSubTypes({
@JsonSubTypes.Type(value=Kick.class, name="KICK"),
@JsonSubTypes.Type(value=Punch.class, name="PUNCH")
})
public Attack attack;
}
public static abstract
|
Character
|
java
|
apache__dubbo
|
dubbo-common/src/main/java/org/apache/dubbo/config/context/ConfigValidator.java
|
{
"start": 899,
"end": 972
}
|
interface ____ {
void validate(AbstractConfig config);
}
|
ConfigValidator
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/IndexRange.java
|
{
"start": 1033,
"end": 2160
}
|
class ____ implements Serializable {
protected final int startIndex;
protected final int endIndex;
public IndexRange(int startIndex, int endIndex) {
checkArgument(startIndex >= 0);
checkArgument(endIndex >= startIndex);
this.startIndex = startIndex;
this.endIndex = endIndex;
}
public int getStartIndex() {
return startIndex;
}
public int getEndIndex() {
return endIndex;
}
public int size() {
return endIndex - startIndex + 1;
}
@Override
public String toString() {
return String.format("[%d, %d]", startIndex, endIndex);
}
@Override
public int hashCode() {
return this.startIndex * 31 + this.endIndex;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj != null && obj.getClass() == getClass()) {
IndexRange that = (IndexRange) obj;
return that.startIndex == this.startIndex && that.endIndex == this.endIndex;
} else {
return false;
}
}
}
|
IndexRange
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/DiscriminatorTest.java
|
{
"start": 1459,
"end": 10343
}
|
class ____ {
@AfterEach
public void tearDown(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Test
public void testDiscriminatorSubclass(SessionFactoryScope scope) {
scope.inTransaction(
s -> {
Employee mark = new Employee();
mark.setName( "Mark" );
mark.setTitle( "internal sales" );
mark.setSex( 'M' );
mark.setAddress( "buckhead" );
mark.setZip( "30305" );
mark.setCountry( "USA" );
Customer joe = new Customer();
joe.setName( "Joe" );
joe.setAddress( "San Francisco" );
joe.setZip( "XXXXX" );
joe.setCountry( "USA" );
joe.setComments( "Very demanding" );
joe.setSex( 'M' );
joe.setSalesperson( mark );
Person yomomma = new Person();
yomomma.setName( "mum" );
yomomma.setSex( 'F' );
s.persist( yomomma );
s.persist( mark );
s.persist( joe );
try {
s.createQuery( "from java.io.Serializable" ).list();
fail( "Expected IllegalAccessException" );
}
catch (Exception e) {
assertThat( e, instanceOf( IllegalArgumentException.class ) );
}
assertThat( s.createQuery( "from Person" ).list().size(), is( 3 ) );
assertThat( s.createQuery( "from Person p where p.class = Person" ).list().size(), is( 1 ) );
assertThat( s.createQuery( "from Person p where p.class = Customer" ).list().size(), is( 1 ) );
s.clear();
List<Customer> customers = s.createQuery( "from Customer c left join fetch c.salesperson" ).list();
for ( Customer c : customers ) {
assertTrue( Hibernate.isInitialized( c.getSalesperson() ) );
assertThat( c.getSalesperson().getName(), is( "Mark" ) );
}
assertThat( customers.size(), is( 1 ) );
s.clear();
customers = s.createQuery( "from Customer" ).list();
for ( Customer c : customers ) {
assertFalse( Hibernate.isInitialized( c.getSalesperson() ) );
assertThat( c.getSalesperson().getName(), is( "Mark" ) );
}
assertThat( customers.size(), is( 1 ) );
s.clear();
mark = s.get( Employee.class, mark.getId() );
joe = s.get( Customer.class, joe.getId() );
mark.setZip( "30306" );
assertThat( s.createQuery( "from Person p where p.address.zip = '30306'" ).list().size(), is( 1 ) );
s.remove( mark );
s.remove( joe );
s.remove( yomomma );
assertTrue( s.createQuery( "from Person" ).list().isEmpty() );
}
);
}
@Test
public void testAccessAsIncorrectSubclass(SessionFactoryScope scope) {
Employee employee = new Employee();
scope.inTransaction(
s -> {
employee.setName( "Steve" );
employee.setSex( 'M' );
employee.setTitle( "grand poobah" );
s.persist( employee );
}
);
Customer c = null;
scope.fromTransaction(
s -> s.get( Customer.class, employee.getId() )
);
assertNull( c );
scope.inTransaction(
s -> {
Employee e = s.get( Employee.class, employee.getId() );
Customer customer = s.get( Customer.class, employee.getId() );
assertNotNull( e );
assertNull( customer );
}
);
scope.inTransaction(
session -> session.remove( employee )
);
}
@Test
public void testQuerySubclassAttribute(SessionFactoryScope scope) {
scope.inTransaction(
s -> {
Person p = new Person();
p.setName( "Emmanuel" );
p.setSex( 'M' );
s.persist( p );
Employee q = new Employee();
q.setName( "Steve" );
q.setSex( 'M' );
q.setTitle( "Mr" );
q.setSalary( new BigDecimal( 1000 ) );
s.persist( q );
List result = s.createQuery( "from Person where salary > 100" ).list();
assertEquals( result.size(), 1 );
assertSame( result.get( 0 ), q );
result = s.createQuery( "from Person where salary > 100 or name like 'E%'" ).list();
assertEquals( result.size(), 2 );
CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
CriteriaQuery<Person> criteria = criteriaBuilder.createQuery( Person.class );
Root<Person> root = criteria.from( Person.class );
criteria.where( criteriaBuilder.gt( criteriaBuilder.treat( root, Employee.class ).get( "salary" ), new BigDecimal( 100 ) ) );
result = s.createQuery( criteria ).list();
// result = s.createCriteria(Person.class)
// .add( Property.forName( "salary").gt( new BigDecimal( 100) ) )
// .list();
assertEquals( result.size(), 1 );
assertSame( result.get( 0 ), q );
//TODO: make this work:
/*result = s.createQuery("select salary from Person where salary > 100").list();
assertEquals( result.size(), 1 );
assertEquals( result.get(0), new BigDecimal(1000) );*/
s.remove( p );
s.remove( q );
}
);
}
@Test
public void testLoadSuperclassProxyPolymorphicAccess(SessionFactoryScope scope) {
Employee e = new Employee();
scope.inTransaction(
s -> {
e.setName( "Steve" );
e.setSex( 'M' );
e.setTitle( "grand poobah" );
s.persist( e );
}
);
scope.inTransaction(
s -> {
// load the superclass proxy.
Person pLoad = s.getReference( Person.class, e.getId() );
assertTrue( pLoad instanceof HibernateProxy );
Person pGet = s.get( Person.class, e.getId() );
Person pQuery = (Person) s.createQuery( "from Person where id = :id" )
.setParameter( "id", e.getId() )
.uniqueResult();
CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
CriteriaQuery<Person> criteria = criteriaBuilder.createQuery( Person.class );
Root<Person> root = criteria.from( Person.class );
criteria.where( criteriaBuilder.equal( root.get( "id" ), e.getId() ) );
Person pCriteria = s.createQuery( criteria ).uniqueResult();
// Person pCriteria = ( Person ) s.createCriteria( Person.class )
// .add( Restrictions.idEq( new Long( e.getId() ) ) )
// .uniqueResult();
// assert that executing the queries polymorphically returns the same proxy
assertSame( pLoad, pGet );
assertSame( pLoad, pQuery );
assertSame( pLoad, pCriteria );
// assert that the proxy is not an instance of Employee
assertFalse( pLoad instanceof Employee );
}
);
scope.inTransaction(
s -> {
// load the superclass proxy.
Person pLoad = s.getReference( Person.class, e.getId() );
assertTrue( pLoad instanceof HibernateProxy );
Person pGet = s.get( Person.class, e.getId() );
Person pQuery = (Person) s.createQuery( "from Person where id = :id" )
.setParameter( "id", e.getId() )
.uniqueResult();
CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
CriteriaQuery<Employee> criteria = criteriaBuilder.createQuery( Employee.class );
Root<Employee> root = criteria.from( Employee.class );
criteria.where( criteriaBuilder.equal( root.get( "id" ), e.getId() ) );
Employee pCriteria = s.createQuery( criteria ).uniqueResult();
// Person pCriteria = ( Person ) s.createCriteria( Person.class )
// .add( Restrictions.idEq( new Long( e.getId() ) ) )
// .uniqueResult();
// assert that executing the queries polymorphically returns the same proxy
assertSame( pLoad, pGet );
assertSame( pLoad, pQuery );
assertNotSame( pLoad, pCriteria );
// assert that the proxy is not an instance of Employee
assertFalse( pLoad instanceof Employee );
}
);
scope.inTransaction(
s -> s.remove( e )
);
}
@Test
public void testLoadSuperclassProxyEvictPolymorphicAccess(SessionFactoryScope scope) {
Employee e = new Employee();
scope.inTransaction(
s -> {
e.setName( "Steve" );
e.setSex( 'M' );
e.setTitle( "grand poobah" );
s.persist( e );
}
);
scope.inTransaction(
s -> {
// load the superclass proxy.
Person pLoad = s.getReference( Person.class, e.getId() );
assertTrue( pLoad instanceof HibernateProxy );
// evict the proxy
s.evict( pLoad );
Employee pGet = (Employee) s.get( Person.class, e.getId() );
Employee pQuery = (Employee) s.createQuery( "from Person where id = :id" )
.setParameter( "id", e.getId() )
.uniqueResult();
CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder();
CriteriaQuery<Person> criteria = criteriaBuilder.createQuery( Person.class );
Root<Person> root = criteria.from( Person.class );
criteria.where( criteriaBuilder.equal( root.get( "id" ), e.getId() ) );
Employee pCriteria = (Employee) s.createQuery( criteria ).uniqueResult();
// Employee pCriteria = ( Employee ) s.createCriteria( Person.class )
// .add( Restrictions.idEq( new Long( e.getId() ) ) )
// .uniqueResult();
// assert that executing the queries polymorphically returns the same Employee instance
assertSame( pGet, pQuery );
assertSame( pGet, pCriteria );
}
);
scope.inTransaction(
s -> s.remove( e )
);
}
}
|
DiscriminatorTest
|
java
|
google__dagger
|
javatests/dagger/functional/factory/FactoryRequiredModulesTest.java
|
{
"start": 1197,
"end": 1882
}
|
interface ____ {
UninstantiableConcreteModuleComponent create(UninstantiableConcreteModule module);
}
}
@Test
public void uninstantiableConcreteModule() {
UninstantiableConcreteModuleComponent component =
DaggerFactoryRequiredModulesTest_UninstantiableConcreteModuleComponent.factory()
.create(new UninstantiableConcreteModule(42L));
assertThat(component.getLong()).isEqualTo(42L);
}
@Test
public void uninstantiableConcreteModule_failsOnNull() {
try {
DaggerFactoryRequiredModulesTest_UninstantiableConcreteModuleComponent.factory().create(null);
fail();
} catch (NullPointerException expected) {
}
}
}
|
Factory
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/AbstractSslBuilder.java
|
{
"start": 654,
"end": 2144
}
|
class ____<T> {
public T build(SslConfiguration config, SSLContext sslContext) {
String[] ciphers = supportedCiphers(sslParameters(sslContext).getCipherSuites(), config.getCipherSuites(), false);
String[] supportedProtocols = config.supportedProtocols().toArray(Strings.EMPTY_ARRAY);
HostnameVerifier verifier;
if (config.verificationMode().isHostnameVerificationEnabled()) {
verifier = SSLIOSessionStrategy.getDefaultHostnameVerifier();
} else {
verifier = NoopHostnameVerifier.INSTANCE;
}
return build(sslContext, supportedProtocols, ciphers, verifier);
}
/**
* This method exists to simplify testing
*/
String[] supportedCiphers(String[] supportedCiphers, List<String> requestedCiphers, boolean log) {
return SSLService.supportedCiphers(supportedCiphers, requestedCiphers, log);
}
/**
* The {@link SSLParameters} that are associated with the {@code sslContext}.
* <p>
* This method exists to simplify testing since {@link SSLContext#getSupportedSSLParameters()} is {@code final}.
*
* @param sslContext The SSL context for the current SSL settings
* @return Never {@code null}.
*/
SSLParameters sslParameters(SSLContext sslContext) {
return sslContext.getSupportedSSLParameters();
}
abstract T build(SSLContext sslContext, String[] protocols, String[] ciphers, HostnameVerifier verifier);
}
|
AbstractSslBuilder
|
java
|
spring-projects__spring-framework
|
spring-web/src/test/java/org/springframework/http/codec/json/JacksonJsonDecoderTests.java
|
{
"start": 14276,
"end": 14629
}
|
class ____ extends StdDeserializer<TestObject> {
Deserializer() {
super(TestObject.class);
}
@Override
public TestObject deserialize(JsonParser p, DeserializationContext ctxt) {
JsonNode node = p.readValueAsTree();
TestObject result = new TestObject();
result.setTest(node.get("test").asInt());
return result;
}
}
}
|
Deserializer
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_2663/RequestDto.java
|
{
"start": 232,
"end": 753
}
|
class ____ {
private JsonNullable<String> name = JsonNullable.undefined();
private JsonNullable<ChildRequestDto> child = JsonNullable.undefined();
public JsonNullable<String> getName() {
return name;
}
public void setName(JsonNullable<String> name) {
this.name = name;
}
public JsonNullable<ChildRequestDto> getChild() {
return child;
}
public void setChild(JsonNullable<ChildRequestDto> child) {
this.child = child;
}
public static
|
RequestDto
|
java
|
apache__kafka
|
tools/src/main/java/org/apache/kafka/tools/ManifestWorkspace.java
|
{
"start": 8587,
"end": 10521
}
|
class ____ extends SourceWorkspace<Map<Path, Map<PluginType, Set<String>>>> {
private ClasspathWorkspace(PluginSource source) throws IOException {
super(source);
}
@Override
protected Map<Path, Map<PluginType, Set<String>>> load(PluginSource source) throws IOException {
Map<Path, Map<PluginType, Set<String>>> manifestsBySubLocation = new HashMap<>();
for (URL url : source.urls()) {
Path jarPath = Paths.get(url.getPath());
manifestsBySubLocation.put(jarPath, loadManifest(jarBaseUrl(url)));
}
return manifestsBySubLocation;
}
public boolean hasManifest(PluginType type, String className) {
return manifests.values()
.stream()
.map(m -> m.get(type))
.anyMatch(s -> s.contains(className));
}
public void forEach(BiConsumer<String, PluginType> consumer) {
manifests.values().forEach(m -> forEach(m, consumer));
}
@Override
public void addManifest(PluginType type, String pluginClass) {
throw new UnsupportedOperationException("Cannot change the contents of the classpath");
}
@Override
public void removeManifest(PluginType type, String pluginClass) {
throw new UnsupportedOperationException("Cannot change the contents of the classpath");
}
@Override
protected boolean commit(boolean dryRun) throws IOException, TerseException {
// There is never anything to commit for the classpath
return false;
}
}
/**
* A multi-jar workspace is similar to the classpath workspace because it has multiple jars.
* However, the multi-jar workspace is writable, and injects a managed jar where it writes added manifests.
*/
private
|
ClasspathWorkspace
|
java
|
apache__dubbo
|
dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/main/java/org/apache/dubbo/spring/boot/autoconfigure/observability/zipkin/customizer/ZipkinWebClientBuilderCustomizer.java
|
{
"start": 971,
"end": 1149
}
|
interface ____ can be implemented by beans wishing to customize the
* {@link WebClient.Builder} used to send spans to Zipkin.
*
* @since 3.2.0
*/
@FunctionalInterface
public
|
that
|
java
|
quarkusio__quarkus
|
extensions/hibernate-search-orm-outbox-polling/runtime/src/main/java/io/quarkus/hibernate/search/orm/outboxpolling/runtime/HibernateSearchOutboxPollingRuntimeConfigPersistenceUnit.java
|
{
"start": 9973,
"end": 13890
}
|
interface ____ {
// @formatter:off
/**
* How long to wait for another query to the agent table
* when actively waiting for event processors to suspend themselves.
*
* Low values will reduce the time it takes for the mass indexer agent to detect
* that event processors finally suspended themselves,
* but will increase the stress on the database while the mass indexer agent is actively waiting.
*
* High values will increase the time it takes for the mass indexer agent to detect
* that event processors finally suspended themselves,
* but will reduce the stress on the database while the mass indexer agent is actively waiting.
*
* See
* link:{hibernate-search-docs-url}#coordination-outbox-polling-mass-indexer[this section of the reference documentation]
* for more information.
*
* @asciidoclet
*/
// @formatter:on
@WithDefault("0.100S")
Duration pollingInterval();
// @formatter:off
/**
* How long the mass indexer can wait before it must perform a "pulse",
* updating and checking registrations in the agent table.
*
* The pulse interval must be set to a value between the polling interval
* and one third (1/3) of the expiration interval.
*
* Low values (closer to the polling interval) mean reduced risk of
* event processors starting to process events again during mass indexing
* because a mass indexer agent is incorrectly considered disconnected,
* but more stress on the database because of more frequent updates of the mass indexer agent's entry in the agent table.
*
* High values (closer to the expiration interval) mean increased risk of
* event processors starting to process events again during mass indexing
* because a mass indexer agent is incorrectly considered disconnected,
* but less stress on the database because of less frequent updates of the mass indexer agent's entry in the agent table.
*
* See
* link:{hibernate-search-docs-url}#coordination-outbox-polling-mass-indexer[this section of the reference documentation]
* for more information.
*
* @asciidoclet
*/
// @formatter:on
@WithDefault("2S")
Duration pulseInterval();
// @formatter:off
/**
* How long an event processor "pulse" remains valid before considering the processor disconnected
* and forcibly removing it from the cluster.
*
* The expiration interval must be set to a value at least 3 times larger than the pulse interval.
*
* Low values (closer to the pulse interval) mean less time wasted with event processors not processing events
* when a mass indexer agent terminates due to a crash,
* but increased risk of event processors starting to process events again during mass indexing
* because a mass indexer agent is incorrectly considered disconnected.
*
* High values (much larger than the pulse interval) mean more time wasted with event processors not processing events
* when a mass indexer agent terminates due to a crash,
* but reduced risk of event processors starting to process events again during mass indexing
* because a mass indexer agent is incorrectly considered disconnected.
*
* See
* link:{hibernate-search-docs-url}#coordination-outbox-polling-mass-indexer[this section of the reference documentation]
* for more information.
*
* @asciidoclet
*/
// @formatter:on
@WithDefault("30S")
Duration pulseExpiration();
}
}
|
MassIndexerConfig
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/AttributePath.java
|
{
"start": 478,
"end": 1274
}
|
class ____ extends AbstractAttributeKey {
public static final char DELIMITER = '.';
public AttributePath() {
super();
}
@Override
protected char getDelimiter() {
return DELIMITER;
}
@Override
public AttributePath append(String property) {
return new AttributePath( this, property );
}
@Override
public AttributePath getParent() {
return (AttributePath) super.getParent();
}
public AttributePath(AttributePath parent, String property) {
super( parent, property );
}
public static AttributePath parse(String path) {
if ( path != null ) {
AttributePath attributePath = new AttributePath();
for ( String part : split( ".", path ) ) {
attributePath = attributePath.append( part );
}
return attributePath;
}
else {
return null;
}
}
}
|
AttributePath
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/action/apikey/CreateApiKeyRequestBuilderTests.java
|
{
"start": 995,
"end": 4567
}
|
class ____ extends ESTestCase {
public void testParserAndCreateApiRequestBuilder() throws IOException {
boolean withExpiration = randomBoolean();
Object[] args = new Object[] { withExpiration ? """
"expiration": "1d",""" : "" };
final String json = Strings.format("""
{
"name": "my-api-key",
%s
"role_descriptors": {
"role-a": {
"cluster": [ "a-1", "a-2" ],
"index": [
{
"names": [ "indx-a" ],
"privileges": [ "read" ]
}
]
},
"role-b": {
"cluster": [ "b" ],
"index": [
{
"names": [ "indx-b" ],
"privileges": [ "read" ]
}
]
}
}
}""", args);
final BytesArray source = new BytesArray(json);
final NodeClient mockClient = mock(NodeClient.class);
final CreateApiKeyRequest request = new CreateApiKeyRequestBuilder(mockClient).source(source, XContentType.JSON).request();
final List<RoleDescriptor> actualRoleDescriptors = request.getRoleDescriptors();
assertThat(request.getName(), equalTo("my-api-key"));
assertThat(actualRoleDescriptors.size(), is(2));
for (RoleDescriptor rd : actualRoleDescriptors) {
String[] clusters = null;
IndicesPrivileges indicesPrivileges = null;
if (rd.getName().equals("role-a")) {
clusters = new String[] { "a-1", "a-2" };
indicesPrivileges = RoleDescriptor.IndicesPrivileges.builder().indices("indx-a").privileges("read").build();
} else if (rd.getName().equals("role-b")) {
clusters = new String[] { "b" };
indicesPrivileges = RoleDescriptor.IndicesPrivileges.builder().indices("indx-b").privileges("read").build();
} else {
fail("unexpected role name");
}
assertThat(rd.getClusterPrivileges(), arrayContainingInAnyOrder(clusters));
assertThat(rd.getIndicesPrivileges(), arrayContainingInAnyOrder(indicesPrivileges));
}
if (withExpiration) {
assertThat(request.getExpiration(), equalTo(TimeValue.parseTimeValue("1d", "expiration")));
}
}
public void testParserAndCreateApiRequestBuilderWithNullOrEmptyRoleDescriptors() throws IOException {
boolean withExpiration = randomBoolean();
boolean noRoleDescriptorsField = randomBoolean();
final String json = "{ \"name\" : \"my-api-key\""
+ ((withExpiration) ? ", \"expiration\": \"1d\"" : "")
+ ((noRoleDescriptorsField) ? "" : ", \"role_descriptors\": {}")
+ "}";
final BytesArray source = new BytesArray(json);
final NodeClient mockClient = mock(NodeClient.class);
final CreateApiKeyRequest request = new CreateApiKeyRequestBuilder(mockClient).source(source, XContentType.JSON).request();
final List<RoleDescriptor> actualRoleDescriptors = request.getRoleDescriptors();
assertThat(request.getName(), equalTo("my-api-key"));
assertThat(actualRoleDescriptors.size(), is(0));
if (withExpiration) {
assertThat(request.getExpiration(), equalTo(TimeValue.parseTimeValue("1d", "expiration")));
}
}
}
|
CreateApiKeyRequestBuilderTests
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeLocalTest.java
|
{
"start": 2120,
"end": 2476
}
|
class ____ {
private int unusedA;
int foo() {
unusedA = 1;
return unusedA;
}
}
""")
.doTest();
}
@Test
public void multipleAssignments() {
refactoringTestHelper
.addInputLines(
"Test.java",
"""
|
Test
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/security/support/CancellableRunnableTests.java
|
{
"start": 919,
"end": 4982
}
|
class ____ extends ESTestCase {
public void testTimingOutARunnable() {
AtomicReference<Exception> exceptionAtomicReference = new AtomicReference<>();
final CancellableRunnable<Object> runnable = new CancellableRunnable<>(ActionListener.wrap(user -> {
throw new AssertionError("onResponse should not be called");
}, exceptionAtomicReference::set), e -> null, () -> { throw new AssertionError("runnable should not be executed"); }, logger);
runnable.maybeTimeout();
runnable.run();
assertNotNull(exceptionAtomicReference.get());
assertThat(exceptionAtomicReference.get(), instanceOf(ElasticsearchTimeoutException.class));
assertThat(exceptionAtomicReference.get().getMessage(), containsString("timed out waiting for execution"));
}
public void testCallTimeOutAfterRunning() {
final AtomicBoolean ran = new AtomicBoolean(false);
final AtomicBoolean listenerCalled = new AtomicBoolean(false);
final CancellableRunnable<Object> runnable = new CancellableRunnable<>(ActionListener.wrap(user -> {
listenerCalled.set(true);
throw new AssertionError("onResponse should not be called");
}, e -> {
listenerCalled.set(true);
throw new AssertionError("onFailure should not be called");
}), e -> null, () -> ran.set(ran.get() == false), logger);
runnable.run();
assertTrue(ran.get());
runnable.maybeTimeout();
assertTrue(ran.get());
// the listener shouldn't have ever been called. If it was, then either something called
// onResponse or onFailure was called as part of the timeout
assertFalse(listenerCalled.get());
}
public void testRejectingExecution() {
AtomicReference<Exception> exceptionAtomicReference = new AtomicReference<>();
final CancellableRunnable<Object> runnable = new CancellableRunnable<>(ActionListener.wrap(user -> {
throw new AssertionError("onResponse should not be called");
}, exceptionAtomicReference::set), e -> null, () -> { throw new AssertionError("runnable should not be executed"); }, logger);
final Exception e = new RuntimeException("foo");
runnable.onRejection(e);
assertNotNull(exceptionAtomicReference.get());
assertThat(exceptionAtomicReference.get(), sameInstance(e));
}
public void testTimeoutDuringExecution() throws InterruptedException {
final CountDownLatch listenerCalledLatch = new CountDownLatch(1);
final CountDownLatch timeoutCalledLatch = new CountDownLatch(1);
final CountDownLatch runningLatch = new CountDownLatch(1);
final ActionListener<User> listener = ActionTestUtils.assertNoFailureListener(user -> listenerCalledLatch.countDown());
final CancellableRunnable<User> runnable = new CancellableRunnable<>(listener, e -> null, () -> {
runningLatch.countDown();
try {
timeoutCalledLatch.await();
listener.onResponse(null);
} catch (InterruptedException e) {
throw new AssertionError("don't interrupt me", e);
}
}, logger);
Thread t = new Thread(runnable);
t.start();
runningLatch.await();
runnable.maybeTimeout();
timeoutCalledLatch.countDown();
listenerCalledLatch.await();
t.join();
}
public void testExceptionInRunnable() {
AtomicReference<String> resultRef = new AtomicReference<>();
final ActionListener<String> listener = ActionTestUtils.assertNoFailureListener(resultRef::set);
String defaultValue = randomAlphaOfLengthBetween(2, 10);
final CancellableRunnable<String> runnable = new CancellableRunnable<>(listener, e -> defaultValue, () -> {
throw new RuntimeException("runnable intentionally failed");
}, logger);
runnable.run();
assertThat(resultRef.get(), equalTo(defaultValue));
}
}
|
CancellableRunnableTests
|
java
|
elastic__elasticsearch
|
x-pack/plugin/enrich/src/test/java/org/elasticsearch/xpack/enrich/action/PutEnrichPolicyActionRequestTests.java
|
{
"start": 687,
"end": 1436
}
|
class ____ extends AbstractWireSerializingTestCase<PutEnrichPolicyAction.Request> {
@Override
protected PutEnrichPolicyAction.Request createTestInstance() {
final EnrichPolicy policy = randomEnrichPolicy(XContentType.JSON);
return new PutEnrichPolicyAction.Request(TEST_REQUEST_TIMEOUT, randomAlphaOfLength(3), policy);
}
@Override
protected PutEnrichPolicyAction.Request mutateInstance(PutEnrichPolicyAction.Request instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
@Override
protected Writeable.Reader<PutEnrichPolicyAction.Request> instanceReader() {
return PutEnrichPolicyAction.Request::new;
}
}
|
PutEnrichPolicyActionRequestTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/ProxyInitializeAndUpdateInlineDirtyTrackingTest.java
|
{
"start": 1607,
"end": 8573
}
|
class ____ {
@Test
public void testInitializeWithGetter(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Animal animal = new Animal();
animal.name = "animal";
animal.age = 3;
animal.sex = "female";
animal.color = "green";
session.persist( animal );
}
);
scope.inTransaction(
session -> {
Animal animal = session.getReference( Animal.class, "animal" );
assertFalse( Hibernate.isInitialized( animal ) );
assertEquals( "female", animal.getSex() );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( 3, animal.getAge() );
animal.setSex( "other" );
}
);
scope.inSession(
session -> {
Animal animal = session.get( Animal.class, "animal" );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( "other", animal.getSex() );
assertEquals( 3, animal.getAge() );
assertEquals( "green", animal.getColor() );
}
);
}
@Test
public void testInitializeWithSetter(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Animal animal = new Animal();
animal.name = "animal";
animal.age = 3;
animal.sex = "female";
animal.color = "green";
session.persist( animal );
}
);
scope.inTransaction(
session -> {
Animal animal = session.getReference( Animal.class, "animal" );
assertFalse( Hibernate.isInitialized( animal ) );
animal.setSex( "other" );
// Setting the attribute value should have initialized animal.
assertTrue( Hibernate.isInitialized( animal ) );
}
);
scope.inSession(
session -> {
Animal animal = session.get( Animal.class, "animal" );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( "other", animal.getSex() );
assertEquals( "green", animal.getColor() );
assertEquals( 3, animal.getAge() );
}
);
}
@Test
public void testMergeUpdatedOntoUninitialized(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Animal animal = new Animal();
animal.name = "animal";
animal.age = 3;
animal.sex = "female";
session.persist( animal );
}
);
final Animal animalInitialized = scope.fromTransaction( session -> {
final Animal animal = session.get( Animal.class, "animal" );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( "female", animal.getSex() );
assertEquals( 3, animal.getAge() );
return animal;
}
);
animalInitialized.setAge( 4 );
animalInitialized.setSex( "other" );
scope.inTransaction(
session -> {
final Animal animal = session.getReference( Animal.class, "animal" );
assertFalse( Hibernate.isInitialized( animal ) );
session.merge( animalInitialized );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( 4, animal.getAge() );
assertEquals( "other", animal.getSex() );
}
);
scope.inTransaction(
session -> {
final Animal animal = session.get( Animal.class, "animal" );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( "other", animal.getSex() );
assertEquals( 4, animal.getAge() );
}
);
}
@Test
public void testMergeUpdatedOntoUpdated(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Animal animal = new Animal();
animal.name = "animal";
animal.age = 3;
animal.sex = "female";
session.persist( animal );
}
);
final Animal animalInitialized = scope.fromTransaction( session -> {
final Animal animal = session.get( Animal.class, "animal" );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( "female", animal.getSex() );
assertEquals( 3, animal.getAge() );
return animal;
}
);
animalInitialized.setAge( 4 );
animalInitialized.setSex( "other" );
scope.inTransaction(
session -> {
final Animal animal = session.get( Animal.class, "animal" );
assertTrue( Hibernate.isInitialized( animal ) );
animal.setAge( 5 );
animal.setSex( "male" );
session.merge( animalInitialized );
assertEquals( 4, animal.getAge() );
assertEquals( "other", animal.getSex() );
}
);
scope.inTransaction(
session -> {
final Animal animal = session.get( Animal.class, "animal" );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( "other", animal.getSex() );
assertEquals( 4, animal.getAge() );
}
);
}
@Test
public void testMergeUninitializedOntoUninitialized(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Animal animal = new Animal();
animal.name = "animal";
animal.age = 3;
animal.sex = "female";
session.persist( animal );
}
);
final Animal animalUninitialized = scope.fromTransaction( session -> {
final Animal animal = session.getReference( Animal.class, "animal" );
assertFalse( Hibernate.isInitialized( animal ) );
return animal;
}
);
scope.inTransaction(
session -> {
final Animal animal = session.getReference( Animal.class, "animal" );
assertFalse( Hibernate.isInitialized( animal ) );
session.merge( animalUninitialized );
assertFalse( Hibernate.isInitialized( animal ) );
}
);
scope.inTransaction(
session -> {
final Animal animal = session.get( Animal.class, "animal" );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( "female", animal.getSex() );
assertEquals( 3, animal.getAge() );
}
);
}
@Test
public void testMergeUninitializedOntoUpdated(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
Animal animal = new Animal();
animal.name = "animal";
animal.age = 3;
animal.sex = "female";
session.persist( animal );
}
);
final Animal animalUninitialized = scope.fromTransaction( session -> {
final Animal animal = session.getReference( Animal.class, "animal" );
assertFalse( Hibernate.isInitialized( animal ) );
return animal;
}
);
scope.inTransaction(
session -> {
final Animal animal = session.get( Animal.class, "animal" );
assertTrue( Hibernate.isInitialized( animal ) );
animal.setSex( "other" );
animal.setAge( 4 );
session.merge( animalUninitialized );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( "other", animal.getSex() );
assertEquals( 4, animal.getAge() );
}
);
scope.inTransaction(
session -> {
final Animal animal = session.get( Animal.class, "animal" );
assertTrue( Hibernate.isInitialized( animal ) );
assertEquals( "other", animal.getSex() );
assertEquals( 4, animal.getAge() );
}
);
}
@AfterEach
public void cleanUpTestData(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
@Entity(name = "Animal")
@Table(name = "Animal")
public static
|
ProxyInitializeAndUpdateInlineDirtyTrackingTest
|
java
|
quarkusio__quarkus
|
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/PlatformPreferenceIndex.java
|
{
"start": 228,
"end": 714
}
|
class ____ a registry index (typically representing a specific registry)
* to a list of {@link PlatformReleasePreferenceIndex} instances, each corresponding
* to a particular platform key. It provides efficient retrieval and creation of
* platform release preference indices for use in managing platform preferences
* across different registries.
* </p>
* <p>
* Intended for internal use within the registry client to support platform preference
* resolution logic.
* </p>
*/
|
maps
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestYarnClientProtocolProvider.java
|
{
"start": 2010,
"end": 5025
}
|
class ____ {
private static final RecordFactory recordFactory = RecordFactoryProvider.
getRecordFactory(null);
@Test
public void testClusterWithYarnClientProtocolProvider() throws Exception {
Configuration conf = new Configuration(false);
Cluster cluster = null;
try {
cluster = new Cluster(conf);
} catch (Exception e) {
throw new Exception(
"Failed to initialize a local runner w/o a cluster framework key", e);
}
try {
assertTrue(cluster.getClient() instanceof LocalJobRunner,
"client is not a LocalJobRunner");
} finally {
if (cluster != null) {
cluster.close();
}
}
try {
conf = new Configuration();
conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_FRAMEWORK_NAME);
cluster = new Cluster(conf);
ClientProtocol client = cluster.getClient();
assertTrue(client instanceof YARNRunner, "client is a YARNRunner");
} catch (IOException e) {
} finally {
if (cluster != null) {
cluster.close();
}
}
}
@Test
public void testClusterGetDelegationToken() throws Exception {
Configuration conf = new Configuration(false);
Cluster cluster = null;
try {
conf = new Configuration();
conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_FRAMEWORK_NAME);
cluster = new Cluster(conf);
YARNRunner yrunner = (YARNRunner) cluster.getClient();
GetDelegationTokenResponse getDTResponse =
recordFactory.newRecordInstance(GetDelegationTokenResponse.class);
org.apache.hadoop.yarn.api.records.Token rmDTToken = recordFactory.newRecordInstance(
org.apache.hadoop.yarn.api.records.Token.class);
rmDTToken.setIdentifier(ByteBuffer.wrap(new byte[2]));
rmDTToken.setKind("Testclusterkind");
rmDTToken.setPassword(ByteBuffer.wrap("testcluster".getBytes()));
rmDTToken.setService("0.0.0.0:8032");
getDTResponse.setRMDelegationToken(rmDTToken);
final ApplicationClientProtocol cRMProtocol =
MockitoUtil.mockProtocol(ApplicationClientProtocol.class);
when(cRMProtocol.getDelegationToken(any(
GetDelegationTokenRequest.class))).thenReturn(getDTResponse);
ResourceMgrDelegate rmgrDelegate = new ResourceMgrDelegate(
new YarnConfiguration(conf)) {
@Override
protected void serviceStart() throws Exception {
assertTrue(this.client instanceof YarnClientImpl);
this.client = spy(this.client);
doNothing().when(this.client).close();
((YarnClientImpl) this.client).setRMClient(cRMProtocol);
}
};
yrunner.setResourceMgrDelegate(rmgrDelegate);
Token t = cluster.getDelegationToken(new Text(" "));
assertTrue("Testclusterkind".equals(t.getKind().toString()),
"Token kind is instead " + t.getKind().toString());
} finally {
if (cluster != null) {
cluster.close();
}
}
}
}
|
TestYarnClientProtocolProvider
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/resource/beans/container/spi/BeanContainer.java
|
{
"start": 881,
"end": 1274
}
|
interface ____ {
boolean canUseCachedReferences();
boolean useJpaCompliantCreation();
}
<B> ContainedBean<B> getBean(
Class<B> beanType,
LifecycleOptions lifecycleOptions,
BeanInstanceProducer fallbackProducer);
<B> ContainedBean<B> getBean(
String name,
Class<B> beanType,
LifecycleOptions lifecycleOptions,
BeanInstanceProducer fallbackProducer);
}
|
LifecycleOptions
|
java
|
google__auto
|
value/src/test/java/com/google/auto/value/processor/ExtensionTest.java
|
{
"start": 50675,
"end": 51786
}
|
interface ____ {",
" Builder property(Integer property);",
" Builder listProperty(List<String> listProperty);",
" Builder listProperty(Integer listPropertyValues);",
" Test build();",
" }",
"}");
// We don't actually expect the extension to be invoked. Previously it was, and that led to a
// NullPointerException when calling .setters() in the checker.
ContextChecker checker =
context -> {
assertThat(context.builder()).isPresent();
assertThat(context.builder().get().setters()).isEmpty();
};
ContextCheckingExtension extension = new ContextCheckingExtension(checker);
Compilation compilation =
javac()
.withProcessors(new AutoValueProcessor(ImmutableList.of(extension)))
.compile(autoValueClass);
assertThat(compilation)
.hadErrorContaining("Parameter type java.lang.Integer of setter method")
.inFile(autoValueClass)
.onLineContaining("Builder listProperty(Integer listPropertyValues)");
}
private
|
Builder
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_2133/Issue2133Mapper.java
|
{
"start": 308,
"end": 501
}
|
interface ____ {
Issue2133Mapper INSTANCE = Mappers.getMapper( Issue2133Mapper.class );
@BeanMapping(resultType = Target.class)
AbstractTarget map(Source source);
|
Issue2133Mapper
|
java
|
apache__flink
|
flink-core-api/src/main/java/org/apache/flink/api/java/tuple/builder/Tuple17Builder.java
|
{
"start": 1268,
"end": 1926
}
|
class ____ {@link Tuple17}.
*
* @param <T0> The type of field 0
* @param <T1> The type of field 1
* @param <T2> The type of field 2
* @param <T3> The type of field 3
* @param <T4> The type of field 4
* @param <T5> The type of field 5
* @param <T6> The type of field 6
* @param <T7> The type of field 7
* @param <T8> The type of field 8
* @param <T9> The type of field 9
* @param <T10> The type of field 10
* @param <T11> The type of field 11
* @param <T12> The type of field 12
* @param <T13> The type of field 13
* @param <T14> The type of field 14
* @param <T15> The type of field 15
* @param <T16> The type of field 16
*/
@Public
public
|
for
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/web/service/registry/HttpServiceProxyRegistry.java
|
{
"start": 943,
"end": 2149
}
|
interface ____ {
/**
* Return an HTTP service client from any group as long as there is only one
* client of this type across all groups.
* @param httpServiceType the type of client
* @param <P> the type of HTTP service client
* @return the matched client
* @throws IllegalArgumentException if there is no client of the given type,
* or there is more than one client of the given type.
*/
<P> P getClient(Class<P> httpServiceType);
/**
* Return an HTTP service client from the named group.
* @param groupName the name of the group
* @param httpServiceType the type of client
* @param <P> the type of HTTP service client
* @return the matched client
* @throws IllegalArgumentException if there is no matching client.
*/
<P> P getClient(String groupName, Class<P> httpServiceType);
/**
* Return the names of all groups in the registry.
*/
Set<String> getGroupNames();
/**
* Return all HTTP service client types in the named group.
* @param groupName the name of the group
* @return the HTTP service types
* @throws IllegalArgumentException if there is no matching group.
*/
Set<Class<?>> getClientTypesInGroup(String groupName);
}
|
HttpServiceProxyRegistry
|
java
|
alibaba__nacos
|
api/src/main/java/com/alibaba/nacos/api/config/ConfigType.java
|
{
"start": 817,
"end": 2178
}
|
enum ____ {
/**
* config type is "properties".
*/
PROPERTIES("properties"),
/**
* config type is "xml".
*/
XML("xml"),
/**
* config type is "json".
*/
JSON("json"),
/**
* config type is "text".
*/
TEXT("text"),
/**
* config type is "html".
*/
HTML("html"),
/**
* config type is "yaml".
*/
YAML("yaml"),
/**
* config type is "toml".
*/
TOML("toml"),
/**
* not a real type.
*/
UNSET("unset");
private final String type;
private static final Map<String, ConfigType> LOCAL_MAP = new HashMap<>();
static {
for (ConfigType configType : values()) {
LOCAL_MAP.put(configType.getType(), configType);
}
}
ConfigType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public static ConfigType getDefaultType() {
return TEXT;
}
/**
* check input type is valid.
*
* @param type config type
* @return it the type valid
*/
public static Boolean isValidType(String type) {
if (StringUtils.isBlank(type)) {
return false;
}
return null != LOCAL_MAP.get(type);
}
}
|
ConfigType
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/refresh/RefreshAndCollections.java
|
{
"start": 3657,
"end": 4938
}
|
class ____ {
@Id
protected Long id;
@ManyToOne(optional = false, cascade = CascadeType.REFRESH)
@JoinColumn(name = "CATEGORY_ID")
protected Category category = new Category();
@ManyToOne(optional = false, cascade = CascadeType.REFRESH)
@JoinColumn(name = "PRODUCT_ID")
protected Product product = new Product();
protected Integer displayOrder;
public CategoryProduct() {
}
public CategoryProduct(Long id, Category category, Product product, Integer displayOrder) {
this.id = id;
this.category = category;
this.product = product;
this.displayOrder = displayOrder;
product.getCategoryProducts().add( this );
category.getProducts().add( this );
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Integer getDisplayOrder() {
return displayOrder;
}
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
}
}
@Entity(name = "Product")
public static
|
CategoryProduct
|
java
|
apache__camel
|
components/camel-platform-http-vertx/src/main/java/org/apache/camel/component/platform/http/vertx/DefaultHttpRequestBodyHandler.java
|
{
"start": 1412,
"end": 2030
}
|
class ____ extends HttpRequestBodyHandler {
DefaultHttpRequestBodyHandler(Handler<RoutingContext> delegate) {
super(delegate);
}
@Override
void configureRoute(Route route) {
route.handler(delegate);
}
@Override
Future<Void> handle(RoutingContext routingContext, Message message) {
if (!isMultiPartFormData(routingContext) && !isFormUrlEncoded(routingContext)) {
final RequestBody requestBody = routingContext.body();
message.setBody(requestBody.buffer());
}
return Future.succeededFuture();
}
}
|
DefaultHttpRequestBodyHandler
|
java
|
apache__commons-lang
|
src/test/java/org/apache/commons/lang3/concurrent/ConstantInitializerTest.java
|
{
"start": 1186,
"end": 4616
}
|
class ____ extends AbstractLangTest {
/** Constant for the object managed by the initializer. */
private static final Integer VALUE = 42;
/** The initializer to be tested. */
private ConstantInitializer<Integer> init;
/**
* Helper method for testing equals() and hashCode().
*
* @param obj the object to compare with the test instance
* @param expected the expected result
*/
private void checkEquals(final Object obj, final boolean expected) {
assertEquals(expected, init.equals(obj), "Wrong result of equals");
if (obj != null) {
assertEquals(expected, obj.equals(init), "Not symmetric");
if (expected) {
assertEquals(init.hashCode(), obj.hashCode(), "Different hash codes");
}
}
}
@BeforeEach
public void setUp() {
init = new ConstantInitializer<>(VALUE);
}
/**
* Tests equals() if the expected result is false.
*/
@Test
void testEqualsFalse() {
ConstantInitializer<Integer> init2 = new ConstantInitializer<>(
null);
checkEquals(init2, false);
init2 = new ConstantInitializer<>(VALUE + 1);
checkEquals(init2, false);
}
/**
* Tests equals() if the expected result is true.
*/
@Test
void testEqualsTrue() {
checkEquals(init, true);
ConstantInitializer<Integer> init2 = new ConstantInitializer<>(
Integer.valueOf(VALUE.intValue()));
checkEquals(init2, true);
init = new ConstantInitializer<>(null);
init2 = new ConstantInitializer<>(null);
checkEquals(init2, true);
}
/**
* Tests equals() with objects of other classes.
*/
@Test
void testEqualsWithOtherObjects() {
checkEquals(null, false);
checkEquals(this, false);
checkEquals(new ConstantInitializer<>("Test"), false);
}
/**
* Tests whether get() returns the correct object.
*
* @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it
*/
@Test
void testGet() throws ConcurrentException {
assertEquals(VALUE, init.get(), "Wrong object");
}
/**
* Tests whether the correct object is returned.
*/
@Test
void testGetObject() {
assertEquals(VALUE, init.getObject(), "Wrong object");
}
/**
* Tests a simple invocation of the isInitialized() method.
*/
@Test
void testisInitialized() {
assertTrue(init.isInitialized(), "was not initialized before get()");
assertEquals(VALUE, init.getObject(), "Wrong object");
assertTrue(init.isInitialized(), "was not initialized after get()");
}
/**
* Tests the string representation.
*/
@Test
void testToString() {
final String s = init.toString();
final Pattern pattern = Pattern
.compile("ConstantInitializer@-?\\d+ \\[ object = " + VALUE
+ " \\]");
assertTrue(pattern.matcher(s).matches(), "Wrong string: " + s);
}
/**
* Tests the string representation if the managed object is null.
*/
@Test
void testToStringNull() {
final String s = new ConstantInitializer<>(null).toString();
assertTrue(s.indexOf("object = null") > 0, "Object not found: " + s);
}
}
|
ConstantInitializerTest
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/search/suggest/Suggester.java
|
{
"start": 652,
"end": 1750
}
|
class ____<T extends SuggestionSearchContext.SuggestionContext> {
protected abstract Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> innerExecute(
String name,
T suggestion,
IndexSearcher searcher,
CharsRefBuilder spare
) throws IOException;
protected abstract Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> emptySuggestion(
String name,
T suggestion,
CharsRefBuilder spare
) throws IOException;
public Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> execute(
String name,
T suggestion,
IndexSearcher searcher,
CharsRefBuilder spare
) throws IOException {
// we only want to output an empty suggestion on empty shards
if (searcher.getIndexReader().numDocs() == 0) {
return emptySuggestion(name, suggestion, spare);
}
return innerExecute(name, suggestion, searcher, spare);
}
}
|
Suggester
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/named/parsed/entity/Publisher.java
|
{
"start": 433,
"end": 685
}
|
class ____ {
@Id
private Integer id;
private String registrationId;
@ManyToOne
@JoinColumn(name = "person_data_fk")
private Person personDetails;
@ManyToOne
@JoinColumn(name = "pub_house_fk")
private PublishingHouse publishingHouse;
}
|
Publisher
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/options/BaseMapOptions.java
|
{
"start": 786,
"end": 4685
}
|
class ____<T extends ExMapOptions<T, K, V>, K, V> extends BaseOptions<T, Codec>
implements ExMapOptions<T, K, V> {
private int writeRetryAttempts = 0;
private MapWriter<K, V> writer;
private MapWriterAsync<K, V> writerAsync;
private int writeBehindBatchSize;
private int writeBehindDelay;
private WriteMode writeMode;
private long writeRetryInterval;
private MapLoader<K, V> loader;
private MapLoaderAsync<K, V> loaderAsync;
public T writer(MapWriter<K, V> writer) {
if (writer != null) {
org.redisson.api.MapOptions<K, V> options = (org.redisson.api.MapOptions<K, V>) org.redisson.api.MapOptions.defaults()
.writerRetryInterval(Duration.ofMillis(getWriteRetryInterval()));
if (getWriteRetryAttempts() > 0) {
options.writerRetryAttempts(getWriteRetryAttempts());
}
this.writer = new RetryableMapWriter<>(options, writer);
}
return (T) this;
}
public MapWriter<K, V> getWriter() {
return writer;
}
public T writerAsync(MapWriterAsync<K, V> writer) {
if (writer != null) {
org.redisson.api.MapOptions<K, V> options = (org.redisson.api.MapOptions<K, V>) org.redisson.api.MapOptions.defaults()
.writerRetryInterval(Duration.ofMillis(getWriteRetryInterval()));
if (getWriteRetryAttempts() > 0) {
options.writerRetryAttempts(getWriteRetryAttempts());
}
this.writerAsync = new RetryableMapWriterAsync<>(options, writer);
}
return (T) this;
}
public MapWriterAsync<K, V> getWriterAsync() {
return writerAsync;
}
public T writeBehindBatchSize(int writeBehindBatchSize) {
this.writeBehindBatchSize = writeBehindBatchSize;
return (T) this;
}
public int getWriteBehindBatchSize() {
return writeBehindBatchSize;
}
public T writeBehindDelay(int writeBehindDelay) {
this.writeBehindDelay = writeBehindDelay;
return (T) this;
}
public int getWriteBehindDelay() {
return writeBehindDelay;
}
public T writeMode(WriteMode writeMode) {
this.writeMode = writeMode;
return (T) this;
}
public WriteMode getWriteMode() {
return writeMode;
}
public int getWriteRetryAttempts() {
return writeRetryAttempts;
}
/**
* Sets max retry attempts for {@link RetryableMapWriter} or {@link RetryableMapWriterAsync}
*
* @param writerRetryAttempts object
* @return MapOptions instance
*/
public T writeRetryAttempts(int writerRetryAttempts) {
if (writerRetryAttempts <= 0){
throw new IllegalArgumentException("writerRetryAttempts must be bigger than 0");
}
this.writeRetryAttempts = writerRetryAttempts;
return (T) this;
}
public long getWriteRetryInterval() {
return writeRetryInterval;
}
public T writeRetryInterval(Duration writerRetryInterval) {
if (writerRetryInterval.isNegative()) {
throw new IllegalArgumentException("writerRetryInterval must be positive");
}
this.writeRetryInterval = writerRetryInterval.toMillis();
return (T) this;
}
/**
* Sets {@link MapLoader} object.
*
* @param loader object
* @return MapOptions instance
*/
public T loader(MapLoader<K, V> loader) {
this.loader = loader;
return (T) this;
}
public MapLoader<K, V> getLoader() {
return loader;
}
public T loaderAsync(MapLoaderAsync<K, V> loaderAsync) {
this.loaderAsync = loaderAsync;
return (T) this;
}
public MapLoaderAsync<K, V> getLoaderAsync() {
return loaderAsync;
}
}
|
BaseMapOptions
|
java
|
lettuce-io__lettuce-core
|
src/main/java/io/lettuce/core/dynamic/ReactiveTypeAdapters.java
|
{
"start": 9056,
"end": 9447
}
|
enum ____ implements Function<Single<?>, Mono<?>> {
INSTANCE;
@Override
public Mono<?> apply(Single<?> source) {
return Mono.defer(() -> Mono.from((Publisher<?>) RxReactiveStreams.toPublisher(source)));
}
}
/**
* An adapter {@link Function} to adopt a {@link Single} to {@link Publisher}.
*/
public
|
RxJava1SingleToMonoAdapter
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/util/StateHandleStoreUtilsTest.java
|
{
"start": 3574,
"end": 4350
}
|
class ____ implements StateObject {
private static final long serialVersionUID = 6382458109061973983L;
private final RunnableWithException discardStateRunnable;
public FailingSerializationStateObject(RunnableWithException discardStateRunnable) {
this.discardStateRunnable = discardStateRunnable;
}
private void writeObject(ObjectOutputStream outputStream) throws IOException {
throw new IOException("Expected IOException to test serialization error.");
}
@Override
public void discardState() throws Exception {
discardStateRunnable.run();
}
@Override
public long getStateSize() {
return 0;
}
}
}
|
FailingSerializationStateObject
|
java
|
apache__flink
|
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/operations/ModifyOperationVisitor.java
|
{
"start": 1037,
"end": 1462
}
|
interface ____<T> {
T visit(SinkModifyOperation catalogSink);
T visit(OutputConversionModifyOperation outputConversion);
T visit(ExternalModifyOperation externalModifyOperation);
<U> T visit(UnregisteredSinkModifyOperation<U> unregisteredSink);
T visit(CollectModifyOperation selectOperation);
T visit(CreateTableASOperation ctas);
T visit(ReplaceTableAsOperation rtas);
}
|
ModifyOperationVisitor
|
java
|
apache__camel
|
core/camel-core-model/src/main/java/org/apache/camel/model/errorhandler/DeadLetterChannelConfiguration.java
|
{
"start": 1126,
"end": 1657
}
|
class ____ extends DefaultErrorHandlerConfiguration implements DeadLetterChannelProperties {
// has no additional configurations
@Override
public Predicate getRetryWhilePolicy(CamelContext context) {
Predicate answer = getRetryWhile();
if (getRetryWhileRef() != null) {
// its a bean expression
Language bean = context.resolveLanguage("bean");
answer = bean.createPredicate(getRetryWhileRef());
}
return answer;
}
}
|
DeadLetterChannelConfiguration
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvtVO/vip_com/QueryLoanOrderRsp.java
|
{
"start": 207,
"end": 2298
}
|
class ____ {
private String loan_card_no;
private String loan_prod_code;
private String last_row_type;//最后一条记录类型
private String last_row_key;//最后一条记录键值
private String nextpage_flag;//是否有下一页标志
private List<TxnListItsm> txn_list;
public QueryLoanOrderRsp() {
super();
}
public String getLoan_card_no() {
return loan_card_no;
}
public void setLoan_card_no(String loan_card_no) {
this.loan_card_no = loan_card_no;
}
public String getLoan_prod_code() {
return loan_prod_code;
}
public void setLoan_prod_code(String loan_prod_code) {
this.loan_prod_code = loan_prod_code;
}
public String getLast_row_type() {
return last_row_type;
}
public void setLast_row_type(String last_row_type) {
this.last_row_type = last_row_type;
}
public String getLast_row_key() {
return last_row_key;
}
public void setLast_row_key(String last_row_key) {
this.last_row_key = last_row_key;
}
public String getNextpage_flag() {
return nextpage_flag;
}
public void setNextpage_flag(String nextpage_flag) {
this.nextpage_flag = nextpage_flag;
}
public List<TxnListItsm> getTxn_list() {
return txn_list;
}
public void setTxn_list(List<TxnListItsm> txn_list) {
this.txn_list = txn_list;
}
public static void main(String[] args) {
QueryLoanOrderRsp rsp = new QueryLoanOrderRsp();
rsp.setLast_row_key("A");
List<TxnListItsm> txn_list = new ArrayList<TxnListItsm>();
TxnListItsm itsm = new TxnListItsm();
itsm.setAssets_no("B");
itsm.setCover_vol(new BigDecimal("300"));
txn_list.add(itsm);
rsp.setTxn_list(txn_list);
String txt = JSON.toJSONString(rsp);
System.out.println(txt);
String txt2 = JSON.toJSONString(txn_list);
System.out.println(txt2);
List<TxnListItsm> itsms = JSON.parseObject(txt2,
new TypeReference<List<TxnListItsm>>(){});
System.out.println(itsms);
rsp = JSON.parseObject(txt,
new TypeReference<QueryLoanOrderRsp>(){});
System.out.println(rsp);
}
}
|
QueryLoanOrderRsp
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/erroneous/interceptorBean/InterceptorBeanWrongTypeTest.java
|
{
"start": 855,
"end": 1327
}
|
class ____ {
@RegisterExtension
ArcTestContainer container = ArcTestContainer.builder().beanClasses(InterceptorBeanWrongTypeTest.class,
MyInterceptor.class, Binding.class).shouldFail().build();
@Test
public void testExceptionThrown() {
Throwable error = container.getFailure();
assertThat(error).isInstanceOf(DefinitionException.class);
}
@Interceptor
@Priority(1)
@Binding
static
|
InterceptorBeanWrongTypeTest
|
java
|
elastic__elasticsearch
|
x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/MonitoredSystemTests.java
|
{
"start": 526,
"end": 1345
}
|
class ____ extends ESTestCase {
public void testGetSystem() {
// everything is just lowercased...
for (final MonitoredSystem system : MonitoredSystem.values()) {
assertEquals(system.name().toLowerCase(Locale.ROOT), system.getSystem());
}
}
public void testFromSystem() {
for (final MonitoredSystem system : MonitoredSystem.values()) {
final String lowercased = system.name().toLowerCase(Locale.ROOT);
assertSame(system, MonitoredSystem.fromSystem(system.name()));
assertSame(system, MonitoredSystem.fromSystem(lowercased));
}
}
public void testFromUnknownSystem() {
assertThat(MonitoredSystem.fromSystem(randomAlphaOfLengthBetween(3, 4)), equalTo(MonitoredSystem.UNKNOWN));
}
}
|
MonitoredSystemTests
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
|
{
"start": 48961,
"end": 49290
}
|
interface ____");
});
}
@Test
public void requestUnusedBindingInDifferentComponent() {
Source parent =
CompilerTests.javaSource(
"test.Parent",
"package test;",
"",
"import dagger.Component;",
"",
"@Component",
"
|
Parent
|
java
|
grpc__grpc-java
|
xds/src/main/java/io/grpc/xds/GcpAuthenticationFilter.java
|
{
"start": 8373,
"end": 8832
}
|
class ____ implements FilterConfig {
private final int cacheSize;
public GcpAuthenticationConfig(int cacheSize) {
this.cacheSize = cacheSize;
}
public int getCacheSize() {
return cacheSize;
}
@Override
public String typeUrl() {
return GcpAuthenticationFilter.TYPE_URL;
}
}
/** An implementation of {@link ClientCall} that fails when started. */
@VisibleForTesting
static final
|
GcpAuthenticationConfig
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/AvoidObjectArraysTest.java
|
{
"start": 869,
"end": 1204
}
|
class ____ {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(AvoidObjectArrays.class, getClass());
@Test
public void methodParam_instanceMethods() {
compilationHelper
.addSourceLines(
"ArrayUsage.java",
"""
public
|
AvoidObjectArraysTest
|
java
|
netty__netty
|
microbench/src/main/java/io/netty/microbench/concurrent/FastThreadLocalFastPathBenchmark.java
|
{
"start": 999,
"end": 1144
}
|
class ____ the fast path of FastThreadLocal and the JDK ThreadLocal.
*/
@Threads(4)
@Measurement(iterations = 10, batchSize = 100)
public
|
benchmarks
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/DuplicateBindingsValidationTest.java
|
{
"start": 30487,
"end": 31610
}
|
class ____ {",
" @Provides static Object acConflict() {",
" return \"c\";",
" }",
" }",
"}");
CompilerTests.daggerCompiler(aComponent, bComponent, cComponent)
.withProcessingOptions(
ImmutableMap.<String, String>builder()
.putAll(fullBindingGraphValidationOption())
.buildOrThrow())
.compile(
subject -> {
String errorMessage =
message(
"Object is bound multiple times:",
" @Provides Object test.A.AModule.acConflict()",
" @Provides Object test.C.CModule.acConflict()");
if (fullBindingGraphValidation) {
subject.hasErrorCount(2);
subject.hasErrorContaining("test.A.AModule has errors")
.onSource(aComponent)
.onLineContaining("@Component(");
subject.hasErrorContaining(errorMessage)
.onSource(aComponent)
.onLineContaining("
|
CModule
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/CompileTimeConstantCheckerTest.java
|
{
"start": 25073,
"end": 25713
}
|
class ____ {
abstract String something();
// BUG: Diagnostic contains: Non-compile-time constant expression
@CompileTimeConstant final String x = something();
}
""")
.doTest();
}
@Test
public void constantField_immutableList() {
compilationHelper
.addSourceLines(
"test/CompileTimeConstantTestCase.java",
"""
package test;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CompileTimeConstant;
public abstract
|
CompileTimeConstantTestCase
|
java
|
mockito__mockito
|
mockito-core/src/test/java/org/mockitousage/bugs/creation/PackagePrivateWithContextClassLoaderTest.java
|
{
"start": 7720,
"end": 8200
}
|
class ____ from a given input stream.
*/
private byte[] loadClassData(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream(BUF_SIZE);
byte[] buffer = new byte[BUF_SIZE];
int readCount;
while ((readCount = input.read(buffer, 0, BUF_SIZE)) >= 0) {
output.write(buffer, 0, readCount);
}
return output.toByteArray();
}
}
}
|
data
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-cw/src/main/java/org/apache/camel/component/aws2/cw/client/impl/Cw2ClientSessionTokenImpl.java
|
{
"start": 1890,
"end": 5274
}
|
class ____ implements Cw2InternalClient {
private static final Logger LOG = LoggerFactory.getLogger(Cw2ClientStandardImpl.class);
private Cw2Configuration configuration;
/**
* Constructor that uses the config file.
*/
public Cw2ClientSessionTokenImpl(Cw2Configuration configuration) {
LOG.trace("Creating an AWS CloudWatch manager using static credentials.");
this.configuration = configuration;
}
/**
* Getting the Cloud Watch AWS client that is used.
*
* @return Amazon Cloud Watch Client.
*/
@Override
public CloudWatchClient getCloudWatchClient() {
CloudWatchClient client = null;
CloudWatchClientBuilder clientBuilder = CloudWatchClient.builder();
ProxyConfiguration.Builder proxyConfig = null;
ApacheHttpClient.Builder httpClientBuilder = null;
boolean isClientConfigFound = false;
if (ObjectHelper.isNotEmpty(configuration.getProxyHost()) && ObjectHelper.isNotEmpty(configuration.getProxyPort())) {
proxyConfig = ProxyConfiguration.builder();
URI proxyEndpoint = URI.create(configuration.getProxyProtocol() + "://" + configuration.getProxyHost() + ":"
+ configuration.getProxyPort());
proxyConfig.endpoint(proxyEndpoint);
httpClientBuilder = ApacheHttpClient.builder().proxyConfiguration(proxyConfig.build());
isClientConfigFound = true;
}
if (configuration.getAccessKey() != null && configuration.getSecretKey() != null
&& configuration.getSessionToken() != null) {
AwsSessionCredentials cred = AwsSessionCredentials.create(configuration.getAccessKey(),
configuration.getSecretKey(), configuration.getSessionToken());
if (isClientConfigFound) {
clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder)
.credentialsProvider(StaticCredentialsProvider.create(cred));
} else {
clientBuilder = clientBuilder.credentialsProvider(StaticCredentialsProvider.create(cred));
}
} else {
if (!isClientConfigFound) {
clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder);
}
}
if (ObjectHelper.isNotEmpty(configuration.getRegion())) {
clientBuilder = clientBuilder.region(Region.of(configuration.getRegion()));
}
if (configuration.isOverrideEndpoint()) {
clientBuilder.endpointOverride(URI.create(configuration.getUriEndpointOverride()));
}
if (configuration.isTrustAllCertificates()) {
if (httpClientBuilder == null) {
httpClientBuilder = ApacheHttpClient.builder();
}
SdkHttpClient ahc = httpClientBuilder.buildWithDefaults(AttributeMap
.builder()
.put(
SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES,
Boolean.TRUE)
.build());
// set created http client to use instead of builder
clientBuilder.httpClient(ahc);
clientBuilder.httpClientBuilder(null);
}
client = clientBuilder.build();
return client;
}
}
|
Cw2ClientSessionTokenImpl
|
java
|
apache__flink
|
flink-core/src/main/java/org/apache/flink/types/IntValue.java
|
{
"start": 1182,
"end": 4796
}
|
class ____
implements NormalizableKey<IntValue>, ResettableValue<IntValue>, CopyableValue<IntValue> {
private static final long serialVersionUID = 1L;
private int value;
/** Initializes the encapsulated int with 0. */
public IntValue() {
this.value = 0;
}
/**
* Initializes the encapsulated int with the provided value.
*
* @param value Initial value of the encapsulated int.
*/
public IntValue(int value) {
this.value = value;
}
/**
* Returns the value of the encapsulated int.
*
* @return the value of the encapsulated int.
*/
public int getValue() {
return this.value;
}
/**
* Sets the encapsulated int to the specified value.
*
* @param value the new value of the encapsulated int.
*/
public void setValue(int value) {
this.value = value;
}
@Override
public void setValue(IntValue value) {
this.value = value.value;
}
@Override
public String toString() {
return String.valueOf(this.value);
}
// --------------------------------------------------------------------------------------------
@Override
public void read(DataInputView in) throws IOException {
this.value = in.readInt();
}
@Override
public void write(DataOutputView out) throws IOException {
out.writeInt(this.value);
}
// --------------------------------------------------------------------------------------------
@Override
public int compareTo(IntValue o) {
final int other = o.value;
return this.value < other ? -1 : this.value > other ? 1 : 0;
}
@Override
public int hashCode() {
return this.value;
}
@Override
public boolean equals(final Object obj) {
if (obj instanceof IntValue) {
return ((IntValue) obj).value == this.value;
}
return false;
}
// --------------------------------------------------------------------------------------------
@Override
public int getMaxNormalizedKeyLen() {
return 4;
}
@Override
public void copyNormalizedKey(MemorySegment target, int offset, int len) {
// take out value and add the integer min value. This gets an offset
// representation when interpreted as an unsigned integer (as is the case
// with normalized keys). write this value as big endian to ensure the
// most significant byte comes first.
if (len == 4) {
target.putIntBigEndian(offset, value - Integer.MIN_VALUE);
} else if (len <= 0) {
} else if (len < 4) {
int value = this.value - Integer.MIN_VALUE;
for (int i = 0; len > 0; len--, i++) {
target.put(offset + i, (byte) ((value >>> ((3 - i) << 3)) & 0xff));
}
} else {
target.putIntBigEndian(offset, value - Integer.MIN_VALUE);
for (int i = 4; i < len; i++) {
target.put(offset + i, (byte) 0);
}
}
}
// --------------------------------------------------------------------------------------------
@Override
public int getBinaryLength() {
return 4;
}
@Override
public void copyTo(IntValue target) {
target.value = this.value;
}
@Override
public IntValue copy() {
return new IntValue(this.value);
}
@Override
public void copy(DataInputView source, DataOutputView target) throws IOException {
target.write(source, 4);
}
}
|
IntValue
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/health/TestNodeHealthCheckerService.java
|
{
"start": 2180,
"end": 2235
}
|
class ____ {@link NodeHealthCheckerService}.
*/
public
|
for
|
java
|
elastic__elasticsearch
|
qa/smoke-test-http/src/internalClusterTest/java/org/elasticsearch/http/ClusterInfoRestCancellationIT.java
|
{
"start": 2396,
"end": 4325
}
|
class ____ extends HttpSmokeTestCase {
public void testClusterInfoRequestCancellation() throws Exception {
// we create a barrier with one extra party, so we can lock in each node within this method.
final var cyclicBarrier = new CyclicBarrier(internalCluster().size() + 1);
var future = new PlainActionFuture<Response>();
internalCluster().getInstances(HttpServerTransport.class)
.forEach(transport -> ((FakeHttpTransport) transport).cyclicBarrier = cyclicBarrier);
logger.info("--> Sending request");
var cancellable = getRestClient().performRequestAsync(
new Request(HttpGet.METHOD_NAME, "/_info/_all"),
wrapAsRestResponseListener(future)
);
assertFalse(future.isDone());
awaitTaskWithPrefix(TransportNodesStatsAction.TYPE.name());
logger.info("--> Checking that all the HttpTransport are waiting...");
safeAwait(cyclicBarrier);
logger.info("--> Cancelling request");
cancellable.cancel();
assertTrue(future.isDone());
expectThrows(CancellationException.class, future::actionGet);
assertAllCancellableTasksAreCancelled(TransportNodesStatsAction.TYPE.name());
logger.info("--> Releasing all the node requests :)");
safeAwait(cyclicBarrier);
assertAllTasksHaveFinished(TransportNodesStatsAction.TYPE.name());
}
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return CollectionUtils.appendToCopy(super.nodePlugins(), FakeNetworkPlugin.class);
}
@Override
protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) {
return Settings.builder()
.put(super.nodeSettings(nodeOrdinal, otherSettings))
.put(NetworkModule.HTTP_TYPE_KEY, FakeHttpTransport.NAME)
.build();
}
public static
|
ClusterInfoRestCancellationIT
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-ec2/src/test/java/org/apache/camel/component/aws2/ec2/EC2ComponentConfigurationTest.java
|
{
"start": 1428,
"end": 7846
}
|
class ____ extends CamelTestSupport {
@Test
public void createEndpointWithMinimalConfiguration() throws Exception {
Ec2Client amazonEc2Client = new AmazonEC2ClientMock();
context.getRegistry().bind("amazonEc2Client", amazonEc2Client);
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
AWS2EC2Endpoint endpoint = (AWS2EC2Endpoint) component
.createEndpoint("aws2-ec2://TestDomain?amazonEc2Client=#amazonEc2Client&accessKey=xxx&secretKey=yyy");
assertEquals("xxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyy", endpoint.getConfiguration().getSecretKey());
assertNotNull(endpoint.getConfiguration().getAmazonEc2Client());
}
@Test
public void createEndpointWithOnlyAccessKeyAndSecretKey() throws Exception {
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
AWS2EC2Endpoint endpoint
= (AWS2EC2Endpoint) component.createEndpoint("aws2-ec2://TestDomain?accessKey=xxx&secretKey=yyy");
assertEquals("xxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyy", endpoint.getConfiguration().getSecretKey());
assertNull(endpoint.getConfiguration().getAmazonEc2Client());
}
@Test
public void createEndpointWithoutDomainName() {
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
assertThrows(IllegalArgumentException.class, () -> {
component.createEndpoint("aws2-ec2:// ");
});
}
@Test
public void createEndpointWithoutAmazonSDBClientConfiguration() {
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
assertThrows(IllegalArgumentException.class, () -> {
component.createEndpoint("aws2-ec2://TestDomain");
});
}
@Test
public void createEndpointWithoutAccessKeyConfiguration() {
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
assertThrows(IllegalArgumentException.class, () -> {
component.createEndpoint("aws2-ec2://TestDomain?secretKey=yyy");
});
}
@Test
public void createEndpointWithoutSecretKeyConfiguration() {
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
assertThrows(IllegalArgumentException.class, () -> {
component.createEndpoint("aws2-ec2://TestDomain?accessKey=xxx");
});
}
@Test
public void createEndpointWithoutSecretKeyAndAccessKeyConfiguration() throws Exception {
Ec2Client amazonEc2Client = new AmazonEC2ClientMock();
context.getRegistry().bind("amazonEc2Client", amazonEc2Client);
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
Endpoint ep = component.createEndpoint("aws2-ec2://TestDomain?amazonEc2Client=#amazonEc2Client");
assertNotNull(ep, "Could not create the endpoint");
}
@Test
public void createEndpointWithComponentElements() throws Exception {
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
component.getConfiguration().setAccessKey("XXX");
component.getConfiguration().setSecretKey("YYY");
AWS2EC2Endpoint endpoint = (AWS2EC2Endpoint) component.createEndpoint("aws2-ec2://testDomain");
assertEquals("XXX", endpoint.getConfiguration().getAccessKey());
assertEquals("YYY", endpoint.getConfiguration().getSecretKey());
}
@Test
public void createEndpointWithComponentAndEndpointElements() throws Exception {
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
component.getConfiguration().setAccessKey("XXX");
component.getConfiguration().setSecretKey("YYY");
component.getConfiguration().setRegion(Region.US_WEST_1.toString());
AWS2EC2Endpoint endpoint = (AWS2EC2Endpoint) component
.createEndpoint("aws2-ec2://testDomain?accessKey=xxxxxx&secretKey=yyyyy®ion=US_EAST_1");
assertEquals("xxxxxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyyyy", endpoint.getConfiguration().getSecretKey());
assertEquals("US_EAST_1", endpoint.getConfiguration().getRegion());
}
@Test
public void createEndpointWithComponentEndpointElementsAndProxy() throws Exception {
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
component.getConfiguration().setAccessKey("XXX");
component.getConfiguration().setSecretKey("YYY");
component.getConfiguration().setRegion(Region.US_WEST_1.toString());
AWS2EC2Endpoint endpoint = (AWS2EC2Endpoint) component
.createEndpoint(
"aws2-ec2://testDomain?accessKey=xxxxxx&secretKey=yyyyy®ion=US_EAST_1&proxyHost=localhost&proxyPort=9000&proxyProtocol=HTTP");
assertEquals("xxxxxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyyyy", endpoint.getConfiguration().getSecretKey());
assertEquals("US_EAST_1", endpoint.getConfiguration().getRegion());
assertEquals(Protocol.HTTP, endpoint.getConfiguration().getProxyProtocol());
assertEquals("localhost", endpoint.getConfiguration().getProxyHost());
assertEquals(Integer.valueOf(9000), endpoint.getConfiguration().getProxyPort());
}
@Test
public void createEndpointWithUriOverride() throws Exception {
AWS2EC2Component component = context.getComponent("aws2-ec2", AWS2EC2Component.class);
AWS2EC2Endpoint endpoint = (AWS2EC2Endpoint) component
.createEndpoint(
"aws2-ec2://testDomain?accessKey=xxxxxx&secretKey=yyyyy®ion=US_EAST_1&overrideEndpoint=true&uriEndpointOverride=http://localhost:9090");
assertEquals("xxxxxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyyyy", endpoint.getConfiguration().getSecretKey());
assertEquals("US_EAST_1", endpoint.getConfiguration().getRegion());
assertTrue(endpoint.getConfiguration().isOverrideEndpoint());
assertEquals("http://localhost:9090", endpoint.getConfiguration().getUriEndpointOverride());
}
}
|
EC2ComponentConfigurationTest
|
java
|
apache__camel
|
components/camel-bean/src/main/java/org/apache/camel/component/bean/ConstantStaticTypeBeanHolder.java
|
{
"start": 1009,
"end": 1138
}
|
class ____ the intention is to
* only invoke static methods, without the need for creating an instance of the type.
*/
public
|
where
|
java
|
grpc__grpc-java
|
core/src/test/java/io/grpc/internal/RetriableStreamTest.java
|
{
"start": 132043,
"end": 132208
}
|
interface ____ {
void postCommit();
ClientStream newSubstream(int previousAttempts);
Status prestart();
}
private static final
|
RetriableStreamRecorder
|
java
|
quarkusio__quarkus
|
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/AsyncObserverExceptionHandler.java
|
{
"start": 542,
"end": 793
}
|
interface ____ {
/**
*
* @param throwable
* @param observerMethod
* @param eventContext
*/
void handle(Throwable throwable, ObserverMethod<?> observerMethod, EventContext<?> eventContext);
}
|
AsyncObserverExceptionHandler
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java
|
{
"start": 47713,
"end": 48268
}
|
class ____ {
public static Set<Resource> findMatchingResources(
URL rootDirUrl, String locationPattern, PathMatcher pathMatcher) throws IOException {
Object root = VfsPatternUtils.findRoot(rootDirUrl);
PatternVirtualFileVisitor visitor =
new PatternVirtualFileVisitor(VfsPatternUtils.getPath(root), locationPattern, pathMatcher);
VfsPatternUtils.visit(root, visitor);
return visitor.getResources();
}
}
/**
* VFS visitor for path matching purposes.
*/
@SuppressWarnings("unused")
private static
|
VfsResourceMatchingDelegate
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.