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 | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/authentication/rememberme/TokenBasedRememberMeServices.java | {
"start": 7006,
"end": 13865
} | interface ____ violation");
// Check signature of token matches remaining details. Must do this after user
// lookup, as we need the DAO-derived password. If efficiency was a major issue,
// just add in a UserCache implementation, but recall that this method is usually
// only called once per HttpSession - if the token is valid, it will cause
// SecurityContextHolder population, whilst if invalid, will cause the cookie to
// be cancelled.
String actualTokenSignature = cookieTokens[2];
RememberMeTokenAlgorithm actualAlgorithm = this.matchingAlgorithm;
// If the cookie value contains the algorithm, we use that algorithm to check the
// signature
if (cookieTokens.length == 4) {
actualTokenSignature = cookieTokens[3];
actualAlgorithm = RememberMeTokenAlgorithm.valueOf(cookieTokens[2]);
}
String expectedTokenSignature = makeTokenSignature(tokenExpiryTime, userDetails.getUsername(),
userDetails.getPassword(), actualAlgorithm);
if (!equals(expectedTokenSignature, actualTokenSignature)) {
throw new InvalidCookieException("Cookie contained signature '" + actualTokenSignature + "' but expected '"
+ expectedTokenSignature + "'");
}
return userDetails;
}
private boolean isValidCookieTokensLength(String[] cookieTokens) {
return cookieTokens.length == 3 || cookieTokens.length == 4;
}
private long getTokenExpiryTime(String[] cookieTokens) {
try {
return Long.valueOf(cookieTokens[1]);
}
catch (NumberFormatException nfe) {
throw new InvalidCookieException(
"Cookie token[1] did not contain a valid number (contained '" + cookieTokens[1] + "')");
}
}
/**
* Calculates the digital signature to be put in the cookie. Default value is
* {@link #encodingAlgorithm} applied to ("username:tokenExpiryTime:password:key")
*/
protected String makeTokenSignature(long tokenExpiryTime, String username, String password) {
String data = username + ":" + tokenExpiryTime + ":" + password + ":" + getKey();
try {
MessageDigest digest = MessageDigest.getInstance(this.encodingAlgorithm.getDigestAlgorithm());
return new String(Hex.encode(digest.digest(data.getBytes())));
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("No " + this.encodingAlgorithm.name() + " algorithm available!");
}
}
/**
* Calculates the digital signature to be put in the cookie.
* @since 5.8
*/
protected String makeTokenSignature(long tokenExpiryTime, String username, @Nullable String password,
RememberMeTokenAlgorithm algorithm) {
String data = username + ":" + tokenExpiryTime + ":" + password + ":" + getKey();
try {
MessageDigest digest = MessageDigest.getInstance(algorithm.getDigestAlgorithm());
return new String(Hex.encode(digest.digest(data.getBytes())));
}
catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException("No " + algorithm.name() + " algorithm available!");
}
}
protected boolean isTokenExpired(long tokenExpiryTime) {
return tokenExpiryTime < System.currentTimeMillis();
}
@Override
public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication successfulAuthentication) {
String username = retrieveUserName(successfulAuthentication);
String password = retrievePassword(successfulAuthentication);
// If unable to find a username and password, just abort as
// TokenBasedRememberMeServices is
// unable to construct a valid token in this case.
if (!StringUtils.hasLength(username)) {
this.logger.debug("Unable to retrieve username");
return;
}
if (!StringUtils.hasLength(password)) {
UserDetails user = getUserDetailsService().loadUserByUsername(username);
password = user.getPassword();
if (!StringUtils.hasLength(password)) {
this.logger.debug("Unable to obtain password for user: " + username);
return;
}
}
int tokenLifetime = calculateLoginLifetime(request, successfulAuthentication);
long expiryTime = System.currentTimeMillis();
// SEC-949
expiryTime += 1000L * ((tokenLifetime < 0) ? TWO_WEEKS_S : tokenLifetime);
String signatureValue = makeTokenSignature(expiryTime, username, password, this.encodingAlgorithm);
setCookie(new String[] { username, Long.toString(expiryTime), this.encodingAlgorithm.name(), signatureValue },
tokenLifetime, request, response);
if (this.logger.isDebugEnabled()) {
this.logger
.debug("Added remember-me cookie for user '" + username + "', expiry: '" + new Date(expiryTime) + "'");
}
}
/**
* Sets the algorithm to be used to match the token signature
* @param matchingAlgorithm the matching algorithm
* @since 5.8
*/
public void setMatchingAlgorithm(RememberMeTokenAlgorithm matchingAlgorithm) {
Assert.notNull(matchingAlgorithm, "matchingAlgorithm cannot be null");
this.matchingAlgorithm = matchingAlgorithm;
}
/**
* Calculates the validity period in seconds for a newly generated remember-me login.
* After this period (from the current time) the remember-me login will be considered
* expired. This method allows customization based on request parameters supplied with
* the login or information in the <tt>Authentication</tt> object. The default value
* is just the token validity period property, <tt>tokenValiditySeconds</tt>.
* <p>
* The returned value will be used to work out the expiry time of the token and will
* also be used to set the <tt>maxAge</tt> property of the cookie.
* <p>
* See SEC-485.
* @param request the request passed to onLoginSuccess
* @param authentication the successful authentication object.
* @return the lifetime in seconds.
*/
protected int calculateLoginLifetime(HttpServletRequest request, Authentication authentication) {
return getTokenValiditySeconds();
}
protected String retrieveUserName(Authentication authentication) {
Object principal = authentication.getPrincipal();
Assert.notNull(principal, "Authentication.getPrincipal() cannot be null");
if (principal instanceof UserDetails userDetails) {
return userDetails.getUsername();
}
return principal.toString();
}
protected @Nullable String retrievePassword(Authentication authentication) {
Object principal = authentication.getPrincipal();
if (principal instanceof UserDetails userDetails) {
return userDetails.getPassword();
}
if (authentication.getCredentials() != null) {
return authentication.getCredentials().toString();
}
return null;
}
/**
* Constant time comparison to prevent against timing attacks.
*/
private static boolean equals(String expected, String actual) {
byte[] expectedBytes = bytesUtf8(expected);
byte[] actualBytes = bytesUtf8(actual);
return MessageDigest.isEqual(expectedBytes, actualBytes);
}
private static byte @Nullable [] bytesUtf8(String s) {
return (s != null) ? Utf8.encode(s) : null;
}
public | contract |
java | micronaut-projects__micronaut-core | inject-java/src/test/groovy/io/micronaut/aop/introduction/with_around/ObservableInterceptor.java | {
"start": 239,
"end": 453
} | class ____ implements MethodInterceptor<Object, Object> {
@Nullable
@Override
public Object intercept(MethodInvocationContext<Object, Object> context) {
return "World";
}
}
| ObservableInterceptor |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/type/TypeFactory.java | {
"start": 31767,
"end": 57519
} | class ____ which
* member declared but may be sub-type of that type (to bind actual bound
* type parameters). Not used if {@code type} is of type {@code Class<?>}.
*
* @return Fully resolved type
*/
public JavaType resolveMemberType(Type type, TypeBindings contextBindings) {
return _fromAny(null, type, contextBindings);
}
/*
/**********************************************************************
/* Direct factory methods
/**********************************************************************
*/
/**
* Method for constructing an {@link ArrayType}.
*<p>
* NOTE: type modifiers are NOT called on array type itself; but are called
* for element type (and other contained types)
*/
public ArrayType constructArrayType(Class<?> elementType) {
return ArrayType.construct(_fromAny(null, elementType, null), null);
}
/**
* Method for constructing an {@link ArrayType}.
*<p>
* NOTE: type modifiers are NOT called on array type itself; but are called
* for contained types.
*/
public ArrayType constructArrayType(JavaType elementType) {
return ArrayType.construct(elementType, null);
}
/**
* Method for constructing a {@link CollectionType}.
*<p>
* NOTE: type modifiers are NOT called on Collection type itself; but are called
* for contained types.
*/
@SuppressWarnings({"rawtypes" })
public CollectionType constructCollectionType(Class<? extends Collection> collectionClass,
Class<?> elementClass) {
return constructCollectionType(collectionClass,
_fromClass(null, elementClass, EMPTY_BINDINGS));
}
/**
* Method for constructing a {@link CollectionType}.
*<p>
* NOTE: type modifiers are NOT called on Collection type itself; but are called
* for contained types.
*/
@SuppressWarnings({"rawtypes" })
public CollectionType constructCollectionType(Class<? extends Collection> collectionClass,
JavaType elementType)
{
TypeBindings bindings = TypeBindings.createIfNeeded(collectionClass, elementType);
CollectionType result = (CollectionType) _fromClass(null, collectionClass, bindings);
// 17-May-2017, tatu: As per [databind#1415], we better verify bound values if (but only if)
// type being resolved was non-generic (i.e.element type was ignored)
if (bindings.isEmpty() && (elementType != null)) {
JavaType t = result.findSuperType(Collection.class);
JavaType realET = t.getContentType();
if (!realET.equals(elementType)) {
throw new IllegalArgumentException(String.format(
"Non-generic Collection class %s did not resolve to something with element type %s but %s ",
ClassUtil.nameOf(collectionClass), elementType, realET));
}
}
return result;
}
/**
* Method for constructing a {@link CollectionLikeType}.
*<p>
* NOTE: type modifiers are NOT called on constructed type itself; but are called
* for contained types.
*/
public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, Class<?> elementClass) {
return constructCollectionLikeType(collectionClass,
_fromClass(null, elementClass, EMPTY_BINDINGS));
}
/**
* Method for constructing a {@link CollectionLikeType}.
*<p>
* NOTE: type modifiers are NOT called on constructed type itself; but are called
* for contained types.
*/
public CollectionLikeType constructCollectionLikeType(Class<?> collectionClass, JavaType elementType) {
JavaType type = _fromClass(null, collectionClass,
TypeBindings.createIfNeeded(collectionClass, elementType));
if (type instanceof CollectionLikeType collectionLikeType) {
return collectionLikeType;
}
return CollectionLikeType.upgradeFrom(type, elementType);
}
/**
* Method for constructing a {@link MapType} instance
*<p>
* NOTE: type modifiers are NOT called on constructed type itself; but are called
* for contained types.
*/
@SuppressWarnings({"rawtypes" })
public MapType constructMapType(Class<? extends Map> mapClass,
Class<?> keyClass, Class<?> valueClass) {
JavaType kt, vt;
if (mapClass == Properties.class) {
kt = vt = CORE_TYPE_STRING;
} else {
kt = _fromClass(null, keyClass, EMPTY_BINDINGS);
vt = _fromClass(null, valueClass, EMPTY_BINDINGS);
}
return constructMapType(mapClass, kt, vt);
}
/**
* Method for constructing a {@link MapType} instance
*<p>
* NOTE: type modifiers are NOT called on constructed type itself.
*/
@SuppressWarnings({"rawtypes" })
public MapType constructMapType(Class<? extends Map> mapClass, JavaType keyType, JavaType valueType) {
TypeBindings bindings = TypeBindings.createIfNeeded(mapClass, new JavaType[] { keyType, valueType });
MapType result = (MapType) _fromClass(null, mapClass, bindings);
// 17-May-2017, tatu: As per [databind#1415], we better verify bound values if (but only if)
// type being resolved was non-generic (i.e.element type was ignored)
if (bindings.isEmpty()) {
JavaType t = result.findSuperType(Map.class);
JavaType realKT = t.getKeyType();
if (!realKT.equals(keyType)) {
throw new IllegalArgumentException(String.format(
"Non-generic Map class %s did not resolve to something with key type %s but %s ",
ClassUtil.nameOf(mapClass), keyType, realKT));
}
JavaType realVT = t.getContentType();
if (!realVT.equals(valueType)) {
throw new IllegalArgumentException(String.format(
"Non-generic Map class %s did not resolve to something with value type %s but %s ",
ClassUtil.nameOf(mapClass), valueType, realVT));
}
}
return result;
}
/**
* Method for constructing a {@link MapLikeType} instance.
* <p>
* Do not use this method to create a true Map type -- use {@link #constructMapType} instead.
* Map-like types are only meant for supporting things that do not implement Map interface
* and as such cannot use standard Map handlers.
* </p>
* <p>
* NOTE: type modifiers are NOT called on constructed type itself; but are called
* for contained types.
*/
public MapLikeType constructMapLikeType(Class<?> mapClass, Class<?> keyClass, Class<?> valueClass) {
return constructMapLikeType(mapClass,
_fromClass(null, keyClass, EMPTY_BINDINGS),
_fromClass(null, valueClass, EMPTY_BINDINGS));
}
/**
* Method for constructing a {@link MapLikeType} instance
* <p>
* Do not use this method to create a true Map type -- use {@link #constructMapType} instead.
* Map-like types are only meant for supporting things that do not implement Map interface
* and as such cannot use standard Map handlers.
* </p>
* <p>
* NOTE: type modifiers are NOT called on constructed type itself.
*/
public MapLikeType constructMapLikeType(Class<?> mapClass, JavaType keyType, JavaType valueType) {
// 19-Oct-2015, tatu: Allow case of no-type-variables, since it seems likely to be
// a valid use case here
JavaType type = _fromClass(null, mapClass,
TypeBindings.createIfNeeded(mapClass, new JavaType[] { keyType, valueType }));
if (type instanceof MapLikeType mapLikeType) {
return mapLikeType;
}
return MapLikeType.upgradeFrom(type, keyType, valueType);
}
/**
* Method for constructing a type instance with specified parameterization.
*<p>
* NOTE: type modifiers are NOT called on constructed type itself.
*/
public JavaType constructSimpleType(Class<?> rawType, JavaType[] parameterTypes) {
return _fromClass(null, rawType, TypeBindings.create(rawType, parameterTypes));
}
/**
* Method for constructing a {@link ReferenceType} instance with given type parameter
* (type MUST take one and only one type parameter)
*<p>
* NOTE: type modifiers are NOT called on constructed type itself.
*/
public JavaType constructReferenceType(Class<?> rawType, JavaType referredType)
{
return ReferenceType.construct(rawType,
TypeBindings.create(rawType, referredType), // [databind#2091]
null, null, // or super-class, interfaces?
referredType);
}
/**
* Factory method for constructing {@link JavaType} that
* represents a parameterized type. For example, to represent
* type {@code Foo<Bar, Baz>}, you could
* call
*<pre>
* return typeFactory.constructParametricType(Foo.class, Bar.class, Baz.class);
*</pre>
*
* @param parametrized Type-erased type to parameterize
* @param parameterClasses Type parameters to apply
*/
public JavaType constructParametricType(Class<?> parametrized, Class<?>... parameterClasses) {
int len = parameterClasses.length;
JavaType[] pt = new JavaType[len];
for (int i = 0; i < len; ++i) {
pt[i] = _fromClass(null, parameterClasses[i], EMPTY_BINDINGS);
}
return constructParametricType(parametrized, pt);
}
/**
* Factory method for constructing {@link JavaType} that
* represents a parameterized type. For example, to represent
* type {@code List<Set<Integer>>}, you could
*<pre>
* JavaType inner = typeFactory.constructParametricType(Set.class, Integer.class);
* return typeFactory.constructParametricType(List.class, inner);
*</pre>
*
* @param rawType Actual type-erased type
* @param parameterTypes Type parameters to apply
*
* @return Fully resolved type for given base type and type parameters
*/
public JavaType constructParametricType(Class<?> rawType, JavaType... parameterTypes)
{
return constructParametricType(rawType, TypeBindings.create(rawType, parameterTypes));
}
/**
* Factory method for constructing {@link JavaType} that
* represents a parameterized type. The type's parameters are
* specified as an instance of {@link TypeBindings}. This
* is useful if you already have the type's parameters such
* as those found on {@link JavaType}. For example, you could call
* <pre>
* return typeFactory.constructParametricType(ArrayList.class, javaType.getBindings());
* </pre>
* This effectively applies the parameterized types from one
* {@link JavaType} to another class.
*
* @param rawType Actual type-erased type
* @param parameterTypes Type bindings for the raw type
* @since 3.0
*/
public JavaType constructParametricType(Class<?> rawType, TypeBindings parameterTypes)
{
// 16-Jul-2020, tatu: Since we do not call `_fromAny()`, need to make
// sure `TypeModifier`s are applied:
JavaType resultType = _fromClass(null, rawType, parameterTypes);
return _applyModifiers(rawType, resultType);
}
/*
/**********************************************************************
/* Direct factory methods for "raw" variants, used when
/* parameterization is unknown
/**********************************************************************
*/
/**
* Method that can be used to construct "raw" Collection type; meaning that its
* parameterization is unknown.
* This is similar to using <code>Object.class</code> parameterization,
* and is equivalent to calling:
*<pre>
* typeFactory.constructCollectionType(collectionClass, typeFactory.unknownType());
*</pre>
*<p>
* This method should only be used if parameterization is completely unavailable.
*/
@SuppressWarnings({"rawtypes" })
public CollectionType constructRawCollectionType(Class<? extends Collection> collectionClass) {
return constructCollectionType(collectionClass, unknownType());
}
/**
* Method that can be used to construct "raw" Collection-like type; meaning that its
* parameterization is unknown.
* This is similar to using <code>Object.class</code> parameterization,
* and is equivalent to calling:
*<pre>
* typeFactory.constructCollectionLikeType(collectionClass, typeFactory.unknownType());
*</pre>
*<p>
* This method should only be used if parameterization is completely unavailable.
*/
public CollectionLikeType constructRawCollectionLikeType(Class<?> collectionClass) {
return constructCollectionLikeType(collectionClass, unknownType());
}
/**
* Method that can be used to construct "raw" Map type; meaning that its
* parameterization is unknown.
* This is similar to using <code>Object.class</code> parameterization,
* and is equivalent to calling:
*<pre>
* typeFactory.constructMapType(collectionClass, typeFactory.unknownType(), typeFactory.unknownType());
*</pre>
*<p>
* This method should only be used if parameterization is completely unavailable.
*/
@SuppressWarnings({"rawtypes" })
public MapType constructRawMapType(Class<? extends Map> mapClass) {
return constructMapType(mapClass, unknownType(), unknownType());
}
/**
* Method that can be used to construct "raw" Map-like type; meaning that its
* parameterization is unknown.
* This is similar to using <code>Object.class</code> parameterization,
* and is equivalent to calling:
*<pre>
* typeFactory.constructMapLikeType(collectionClass, typeFactory.unknownType(), typeFactory.unknownType());
*</pre>
*<p>
* This method should only be used if parameterization is completely unavailable.
*/
public MapLikeType constructRawMapLikeType(Class<?> mapClass) {
return constructMapLikeType(mapClass, unknownType(), unknownType());
}
/*
/**********************************************************************
/* Low-level factory methods
/**********************************************************************
*/
private JavaType _mapType(Class<?> rawClass, TypeBindings bindings,
JavaType superClass, JavaType[] superInterfaces)
{
JavaType kt, vt;
// 28-May-2015, tatu: Properties are special, as per [databind#810]; fake "correct" parameter sig
if (rawClass == Properties.class) {
kt = vt = CORE_TYPE_STRING;
} else {
List<JavaType> typeParams = bindings.getTypeParameters();
// ok to have no types ("raw")
final int pc = typeParams.size();
switch (pc) {
case 0: // acceptable?
kt = vt = _unknownType();
break;
case 2:
kt = typeParams.get(0);
vt = typeParams.get(1);
break;
default:
throw new IllegalArgumentException(String.format(
"Strange Map type %s with %d type parameter%s (%s), cannot resolve",
ClassUtil.nameOf(rawClass), pc, (pc == 1) ? "" : "s", bindings));
}
}
return MapType.construct(rawClass, bindings, superClass, superInterfaces, kt, vt);
}
private JavaType _collectionType(Class<?> rawClass, TypeBindings bindings,
JavaType superClass, JavaType[] superInterfaces)
{
List<JavaType> typeParams = bindings.getTypeParameters();
// ok to have no types ("raw")
JavaType ct;
if (typeParams.isEmpty()) {
ct = _unknownType();
} else if (typeParams.size() == 1) {
ct = typeParams.get(0);
} else {
throw new IllegalArgumentException("Strange Collection type "+rawClass.getName()+": cannot determine type parameters");
}
return CollectionType.construct(rawClass, bindings, superClass, superInterfaces, ct);
}
protected JavaType _referenceType(Class<?> rawClass, TypeBindings bindings,
JavaType superClass, JavaType[] superInterfaces)
{
List<JavaType> typeParams = bindings.getTypeParameters();
// ok to have no types ("raw")
JavaType ct;
if (typeParams.isEmpty()) {
ct = _unknownType();
} else if (typeParams.size() == 1) {
ct = typeParams.get(0);
} else {
throw new IllegalArgumentException("Strange Reference type "+rawClass.getName()+": cannot determine type parameters");
}
return ReferenceType.construct(rawClass, bindings, superClass, superInterfaces, ct);
}
private JavaType _iterationType(Class<?> rawClass, TypeBindings bindings,
JavaType superClass, JavaType[] superInterfaces)
{
List<JavaType> typeParams = bindings.getTypeParameters();
// ok to have no types ("raw")
JavaType ct;
if (typeParams.isEmpty()) {
ct = _unknownType();
} else if (typeParams.size() == 1) {
ct = typeParams.get(0);
} else {
throw new IllegalArgumentException("Strange Iteration type "+rawClass.getName()+": cannot determine type parameters");
}
return _iterationType(rawClass, bindings, superClass, superInterfaces, ct);
}
private JavaType _iterationType(Class<?> rawClass, TypeBindings bindings,
JavaType superClass, JavaType[] superInterfaces,
JavaType iteratedType)
{
return IterationType.construct(rawClass, bindings, superClass, superInterfaces,
iteratedType);
}
/**
* Factory method to call when no special {@link JavaType} is needed,
* no generic parameters are passed. Default implementation may check
* pre-constructed values for "well-known" types, but if none found
* will simply call {@link #_newSimpleType}
*/
protected JavaType _constructSimple(Class<?> raw, TypeBindings bindings,
JavaType superClass, JavaType[] superInterfaces)
{
if (bindings.isEmpty()) {
JavaType result = _findWellKnownSimple(raw);
if (result != null) {
return result;
}
}
return _newSimpleType(raw, bindings, superClass, superInterfaces);
}
/**
* Factory method that is to create a new {@link SimpleType} with no
* checks whatsoever. Default implementation calls the single argument
* constructor of {@link SimpleType}.
*/
protected JavaType _newSimpleType(Class<?> raw, TypeBindings bindings,
JavaType superClass, JavaType[] superInterfaces)
{
return new SimpleType(raw, bindings, superClass, superInterfaces);
}
protected JavaType _unknownType() {
return CORE_TYPE_OBJECT;
}
/**
* Helper method called to see if requested, non-generic-parameterized
* type is one of common, "well-known" types, instances of which are
* pre-constructed and do not need dynamic caching.
*/
protected static JavaType _findWellKnownSimple(Class<?> clz) {
if (clz.isPrimitive()) {
if (clz == CLS_BOOL) return CORE_TYPE_BOOL;
if (clz == CLS_INT) return CORE_TYPE_INT;
if (clz == CLS_LONG) return CORE_TYPE_LONG;
if (clz == CLS_DOUBLE) return CORE_TYPE_DOUBLE;
} else {
if (clz == CLS_STRING) return CORE_TYPE_STRING;
if (clz == CLS_OBJECT) return CORE_TYPE_OBJECT;
if (clz == CLS_JSON_NODE) return CORE_TYPE_JSON_NODE;
}
return null;
}
/*
/**********************************************************************
/* Actual type resolution, traversal
/**********************************************************************
*/
/**
* Factory method that can be used if type information is passed
* as Java typing returned from <code>getGenericXxx</code> methods
* (usually for a return or argument type).
*/
protected JavaType _fromAny(ClassStack context, Type srcType, TypeBindings bindings)
{
JavaType resultType;
// simple class?
if (srcType instanceof Class<?> class1) {
// Important: remove possible bindings since this is type-erased thingy
resultType = _fromClass(context, class1, EMPTY_BINDINGS);
}
// But if not, need to start resolving.
else if (srcType instanceof ParameterizedType pt) {
resultType = _fromParamType(context, pt, bindings);
}
else if (srcType instanceof JavaType jt) { // [databind#116]
// no need to modify further if we already had JavaType
return jt;
}
else if (srcType instanceof GenericArrayType genericArrayType) {
resultType = _fromArrayType(context, genericArrayType, bindings);
}
else if (srcType instanceof TypeVariable<?> typeVariable) {
resultType = _fromVariable(context, typeVariable, bindings);
}
else if (srcType instanceof WildcardType wildcardType) {
resultType = _fromWildcard(context, wildcardType, bindings);
} else {
// sanity check
throw new IllegalArgumentException("Unrecognized Type: "+((srcType == null) ? "[null]" : srcType.toString()));
}
// 21-Feb-2016, nateB/tatu: as per [databind#1129] (applied for 2.7.2),
// we do need to let all kinds of types to be refined, esp. for Scala module.
return _applyModifiers(srcType, resultType);
}
protected JavaType _applyModifiers(Type srcType, JavaType resolvedType)
{
if (_modifiers == null) {
return resolvedType;
}
JavaType resultType = resolvedType;
TypeBindings b = resultType.getBindings();
if (b == null) {
b = EMPTY_BINDINGS;
}
for (TypeModifier mod : _modifiers) {
JavaType t = mod.modifyType(resultType, srcType, b, this);
if (t == null) {
throw new IllegalStateException(String.format(
"TypeModifier %s (of type %s) return null for type %s",
mod, mod.getClass().getName(), resultType));
}
resultType = t;
}
return resultType;
}
/**
* @param bindings Mapping of formal parameter declarations (for generic
* types) into actual types
*/
protected JavaType _fromClass(ClassStack context, Class<?> rawType, TypeBindings bindings)
{
// Very first thing: small set of core types we know well:
JavaType result = _findWellKnownSimple(rawType);
if (result != null) {
return result;
}
// Barring that, we may have recently constructed an instance
final Object key;
if ((bindings == null) || bindings.isEmpty()) {
key = rawType;
} else {
key = bindings.asKey(rawType);
}
result = key == null ? null : _typeCache.get(key); // ok, cache object is synced
if (result != null) {
return result;
}
// 15-Oct-2015, tatu: recursive reference?
if (context == null) {
context = new ClassStack(rawType);
} else {
ClassStack prev = context.find(rawType);
if (prev != null) {
// Self-reference: needs special handling, then...
ResolvedRecursiveType selfRef = new ResolvedRecursiveType(rawType, EMPTY_BINDINGS);
prev.addSelfReference(selfRef);
return selfRef;
}
// no, but need to update context to allow for proper cycle resolution
context = context.child(rawType);
}
// First: do we have an array type?
if (rawType.isArray()) {
result = ArrayType.construct(_fromAny(context, rawType.getComponentType(), bindings),
bindings);
} else {
// If not, need to proceed by first resolving parent type hierarchy
JavaType superClass;
JavaType[] superInterfaces;
if (rawType.isInterface()) {
superClass = null;
superInterfaces = _resolveSuperInterfaces(context, rawType, bindings);
} else {
// Note: even Enums can implement interfaces, so cannot drop those
superClass = _resolveSuperClass(context, rawType, bindings);
superInterfaces = _resolveSuperInterfaces(context, rawType, bindings);
}
// 19-Oct-2015, tatu: Bit messy, but we need to 'fix' java.util.Properties here...
if (rawType == Properties.class) {
result = MapType.construct(rawType, bindings, superClass, superInterfaces,
CORE_TYPE_STRING, CORE_TYPE_STRING);
}
// And then check what flavor of type we got. Start by asking resolved
// super-type if refinement is all that is needed?
else if (superClass != null) {
result = superClass.refine(rawType, bindings, superClass, superInterfaces);
}
// if not, perhaps we are now resolving a well-known | in |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/DatanodeID.java | {
"start": 1135,
"end": 1694
} | class ____ the primary identifier for a Datanode.
* Datanodes are identified by how they can be contacted (hostname
* and ports) and their storage ID, a unique number that associates
* the Datanodes blocks with a particular Datanode.
*
* {@link DatanodeInfo#getName()} should be used to get the network
* location (for topology) of a datanode, instead of using
* {@link DatanodeID#getXferAddr()} here. Helpers are defined below
* for each context in which a DatanodeID is used.
*/
@InterfaceAudience.Private
@InterfaceStability.Evolving
public | represents |
java | grpc__grpc-java | stub/src/main/java/io/grpc/stub/ClientCallStreamObserver.java | {
"start": 1730,
"end": 5021
} | class ____ be called after this method has been called.
*
* <p>It is recommended that at least one of the arguments to be non-{@code null}, to provide
* useful debug information. Both argument being null may log warnings and result in suboptimal
* performance. Also note that the provided information will not be sent to the server.
*
* @param message if not {@code null}, will appear as the description of the CANCELLED status
* @param cause if not {@code null}, will appear as the cause of the CANCELLED status
*/
public abstract void cancel(@Nullable String message, @Nullable Throwable cause);
/**
* Swaps to manual flow control where no message will be delivered to {@link
* StreamObserver#onNext(Object)} unless it is {@link #request request()}ed. Since {@code
* request()} may not be called before the call is started, a number of initial requests may be
* specified.
*
* <p>This method may only be called during {@link ClientResponseObserver#beforeStart
* ClientResponseObserver.beforeStart()}.
*/
public void disableAutoRequestWithInitial(int request) {
throw new UnsupportedOperationException();
}
/**
* If {@code true}, indicates that the observer is capable of sending additional messages
* without requiring excessive buffering internally. This value is just a suggestion and the
* application is free to ignore it, however doing so may result in excessive buffering within the
* observer.
*
* <p>If {@code false}, the runnable passed to {@link #setOnReadyHandler} will be called after
* {@code isReady()} transitions to {@code true}.
*/
@Override
public abstract boolean isReady();
/**
* Set a {@link Runnable} that will be executed every time the stream {@link #isReady()} state
* changes from {@code false} to {@code true}. While it is not guaranteed that the same
* thread will always be used to execute the {@link Runnable}, it is guaranteed that executions
* are serialized with calls to the 'inbound' {@link StreamObserver}.
*
* <p>May only be called during {@link ClientResponseObserver#beforeStart}.
*
* <p>Because there is a processing delay to deliver this notification, it is possible for
* concurrent writes to cause {@code isReady() == false} within this callback. Handle "spurious"
* notifications by checking {@code isReady()}'s current value instead of assuming it is now
* {@code true}. If {@code isReady() == false} the normal expectations apply, so there would be
* <em>another</em> {@code onReadyHandler} callback.
*
* @param onReadyHandler to call when peer is ready to receive more messages.
*/
@Override
public abstract void setOnReadyHandler(Runnable onReadyHandler);
/**
* Requests the peer to produce {@code count} more messages to be delivered to the 'inbound'
* {@link StreamObserver}.
*
* <p>This method is safe to call from multiple threads without external synchronization.
*
* @param count more messages
*/
@Override
public abstract void request(int count);
/**
* Sets message compression for subsequent calls to {@link #onNext}.
*
* @param enable whether to enable compression.
*/
@Override
public abstract void setMessageCompression(boolean enable);
}
| can |
java | apache__flink | flink-core/src/main/java/org/apache/flink/configuration/PipelineOptionsInternal.java | {
"start": 1043,
"end": 1513
} | class ____ {
public static final ConfigOption<String> PIPELINE_FIXED_JOB_ID =
key("$internal.pipeline.job-id")
.stringType()
.noDefaultValue()
.withDescription(
"**DO NOT USE** The static JobId to be used for the specific pipeline. "
+ "For fault-tolerance, this value needs to stay the same across runs.");
}
| PipelineOptionsInternal |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/scroll/RestSearchScrollActionTests.java | {
"start": 1224,
"end": 3143
} | class ____ extends ESTestCase {
public void testParseSearchScrollRequestWithInvalidJsonThrowsException() throws Exception {
RestSearchScrollAction action = new RestSearchScrollAction();
RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent(
new BytesArray("{invalid_json}"),
XContentType.JSON
).build();
Exception e = expectThrows(IllegalArgumentException.class, () -> action.prepareRequest(request, null));
assertThat(e.getMessage(), equalTo("Failed to parse request body"));
}
public void testBodyParamsOverrideQueryStringParams() throws Exception {
SetOnce<Boolean> scrollCalled = new SetOnce<>();
try (var threadPool = createThreadPool()) {
final var nodeClient = new NoOpNodeClient(threadPool) {
@Override
public void searchScroll(SearchScrollRequest request, ActionListener<SearchResponse> listener) {
scrollCalled.set(true);
assertThat(request.scrollId(), equalTo("BODY"));
assertThat(request.scroll().getStringRep(), equalTo("1m"));
}
};
RestSearchScrollAction action = new RestSearchScrollAction();
Map<String, String> params = new HashMap<>();
params.put("scroll_id", "QUERY_STRING");
params.put("scroll", "1000m");
RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withParams(params)
.withContent(new BytesArray("{\"scroll_id\":\"BODY\", \"scroll\":\"1m\"}"), XContentType.JSON)
.build();
FakeRestChannel channel = new FakeRestChannel(request, randomBoolean(), 0);
action.handleRequest(request, channel, nodeClient);
assertThat(scrollCalled.get(), equalTo(true));
}
}
}
| RestSearchScrollActionTests |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/submitted/cache/PersonMapper.java | {
"start": 1039,
"end": 1843
} | interface ____ {
@Insert("insert into person (id, firstname, lastname) values (#{id}, #{firstname}, #{lastname})")
void create(Person person);
@Insert("insert into person (id, firstname, lastname) values (#{id}, #{firstname}, #{lastname})")
@Options
void createWithOptions(Person person);
@Insert("insert into person (id, firstname, lastname) values (#{id}, #{firstname}, #{lastname})")
@Options(flushCache = FlushCachePolicy.FALSE)
void createWithoutFlushCache(Person person);
@Delete("delete from person where id = #{id}")
void delete(int id);
@Select("select id, firstname, lastname from person")
List<Person> findAll();
@Select("select id, firstname, lastname from person")
@Options(flushCache = FlushCachePolicy.TRUE)
List<Person> findWithFlushCache();
}
| PersonMapper |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/socket/adapter/AbstractWebSocketSession.java | {
"start": 1399,
"end": 1671
} | class ____ {@link WebSocketSession} implementations that
* holds common fields and exposes accessors. Also implements the
* {@code WebSocketMessage} factory methods.
*
* @author Rossen Stoyanchev
* @since 5.0
* @param <T> the native delegate type
*/
public abstract | for |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/error/ShouldBeInSameSecondWindow.java | {
"start": 925,
"end": 1401
} | class ____ extends BasicErrorMessageFactory {
public static ErrorMessageFactory shouldBeInSameSecondWindow(Date actual, Date other) {
return new ShouldBeInSameSecondWindow(actual, other);
}
private ShouldBeInSameSecondWindow(Date actual, Date other) {
super("%nExpecting actual:%n %s%nto be close to:%n %s%nby less than one second (strictly) but difference was: "
+ formatTimeDifference(actual, other), actual, other);
}
}
| ShouldBeInSameSecondWindow |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/naturalid/immutable/Parent.java | {
"start": 356,
"end": 790
} | class ____ {
@Id
private Integer id;
private String name;
@OneToMany( mappedBy = "parent" )
private List<Child> children = new ArrayList<>();
Parent() {}
public Parent(Integer id, String name) {
this.id = id;
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public List getChildren() {
return children;
}
public void setChildren(List children) {
this.children = children;
}
}
| Parent |
java | apache__avro | lang/java/ipc/src/main/java/org/apache/avro/ipc/Responder.java | {
"start": 1917,
"end": 9308
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(Responder.class);
private static final Schema META = Schema.createMap(Schema.create(Schema.Type.BYTES));
private static final GenericDatumReader<Map<String, ByteBuffer>> META_READER = new GenericDatumReader<>(META);
private static final GenericDatumWriter<Map<String, ByteBuffer>> META_WRITER = new GenericDatumWriter<>(META);
private static final ThreadLocal<Protocol> REMOTE = new ThreadLocal<>();
private final Map<MD5, Protocol> protocols = new ConcurrentHashMap<>();
private final Protocol local;
private final MD5 localHash;
protected final List<RPCPlugin> rpcMetaPlugins;
protected Responder(Protocol local) {
this.local = local;
this.localHash = new MD5();
localHash.bytes(local.getMD5());
protocols.put(localHash, local);
this.rpcMetaPlugins = new CopyOnWriteArrayList<>();
}
/**
* Return the remote protocol. Accesses a {@link ThreadLocal} that's set around
* calls to {@link #respond(Protocol.Message, Object)}.
*/
public static Protocol getRemote() {
return REMOTE.get();
}
/** Return the local protocol. */
public Protocol getLocal() {
return local;
}
/**
* Adds a new plugin to manipulate per-call metadata. Plugins are executed in
* the order that they are added.
*
* @param plugin a plugin that will manipulate RPC metadata
*/
public void addRPCPlugin(RPCPlugin plugin) {
rpcMetaPlugins.add(plugin);
}
/**
* Called by a server to deserialize a request, compute and serialize a response
* or error.
*/
public List<ByteBuffer> respond(List<ByteBuffer> buffers) throws IOException {
return respond(buffers, null);
}
/**
* Called by a server to deserialize a request, compute and serialize a response
* or error. Transceiver is used by connection-based servers to track handshake
* status of connection.
*/
public List<ByteBuffer> respond(List<ByteBuffer> buffers, Transceiver connection) throws IOException {
Decoder in = DecoderFactory.get().binaryDecoder(new ByteBufferInputStream(buffers), null);
ByteBufferOutputStream bbo = new ByteBufferOutputStream();
BinaryEncoder out = EncoderFactory.get().binaryEncoder(bbo, null);
Exception error = null;
RPCContext context = new RPCContext();
List<ByteBuffer> payload = null;
List<ByteBuffer> handshake = null;
boolean wasConnected = connection != null && connection.isConnected();
try {
Protocol remote = handshake(in, out, connection);
out.flush();
if (remote == null) // handshake failed
return bbo.getBufferList();
handshake = bbo.getBufferList();
// read request using remote protocol specification
context.setRequestCallMeta(META_READER.read(null, in));
String messageName = in.readString(null).toString();
if (messageName.equals("")) // a handshake ping
return handshake;
Message rm = remote.getMessages().get(messageName);
if (rm == null)
throw new AvroRuntimeException("No such remote message: " + messageName);
Message m = getLocal().getMessages().get(messageName);
if (m == null)
throw new AvroRuntimeException("No message named " + messageName + " in " + getLocal());
Object request = readRequest(rm.getRequest(), m.getRequest(), in);
context.setMessage(rm);
for (RPCPlugin plugin : rpcMetaPlugins) {
plugin.serverReceiveRequest(context);
}
// create response using local protocol specification
if ((m.isOneWay() != rm.isOneWay()) && wasConnected)
throw new AvroRuntimeException("Not both one-way: " + messageName);
Object response = null;
try {
REMOTE.set(remote);
response = respond(m, request);
context.setResponse(response);
} catch (Exception e) {
error = e;
context.setError(error);
LOG.warn("user error", e);
} finally {
REMOTE.set(null);
}
if (m.isOneWay() && wasConnected) // no response data
return null;
out.writeBoolean(error != null);
if (error == null)
writeResponse(m.getResponse(), response, out);
else
try {
writeError(m.getErrors(), error, out);
} catch (UnresolvedUnionException e) { // unexpected error
throw error;
}
} catch (Exception e) { // system error
LOG.warn("system error", e);
context.setError(e);
bbo = new ByteBufferOutputStream();
out = EncoderFactory.get().binaryEncoder(bbo, null);
out.writeBoolean(true);
writeError(Protocol.SYSTEM_ERRORS, new Utf8(e.toString()), out);
if (null == handshake) {
handshake = new ByteBufferOutputStream().getBufferList();
}
}
out.flush();
payload = bbo.getBufferList();
// Grab meta-data from plugins
context.setResponsePayload(payload);
for (RPCPlugin plugin : rpcMetaPlugins) {
plugin.serverSendResponse(context);
}
META_WRITER.write(context.responseCallMeta(), out);
out.flush();
// Prepend handshake and append payload
bbo.prepend(handshake);
bbo.append(payload);
return bbo.getBufferList();
}
private SpecificDatumWriter<HandshakeResponse> handshakeWriter = new SpecificDatumWriter<>(HandshakeResponse.class);
private SpecificDatumReader<HandshakeRequest> handshakeReader = new SpecificDatumReader<>(HandshakeRequest.class);
private Protocol handshake(Decoder in, Encoder out, Transceiver connection) throws IOException {
if (connection != null && connection.isConnected())
return connection.getRemote();
HandshakeRequest request = handshakeReader.read(null, in);
Protocol remote = protocols.get(request.getClientHash());
if (remote == null && request.getClientProtocol() != null) {
remote = Protocol.parse(request.getClientProtocol().toString());
protocols.put(request.getClientHash(), remote);
}
HandshakeResponse response = new HandshakeResponse();
if (localHash.equals(request.getServerHash())) {
response.setMatch(remote == null ? HandshakeMatch.NONE : HandshakeMatch.BOTH);
} else {
response.setMatch(remote == null ? HandshakeMatch.NONE : HandshakeMatch.CLIENT);
}
if (response.getMatch() != HandshakeMatch.BOTH) {
response.setServerProtocol(local.toString());
response.setServerHash(localHash);
}
RPCContext context = new RPCContext();
context.setHandshakeRequest(request);
context.setHandshakeResponse(response);
for (RPCPlugin plugin : rpcMetaPlugins) {
plugin.serverConnecting(context);
}
handshakeWriter.write(response, out);
if (connection != null && response.getMatch() != HandshakeMatch.NONE)
connection.setRemote(remote);
return remote;
}
/** Computes the response for a message. */
public abstract Object respond(Message message, Object request) throws Exception;
/** Reads a request message. */
public abstract Object readRequest(Schema actual, Schema expected, Decoder in) throws IOException;
/** Writes a response message. */
public abstract void writeResponse(Schema schema, Object response, Encoder out) throws IOException;
/** Writes an error message. */
public abstract void writeError(Schema schema, Object error, Encoder out) throws IOException;
}
| Responder |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/context/expression/MapAccessor.java | {
"start": 1087,
"end": 1590
} | class ____ extends org.springframework.expression.spel.support.MapAccessor {
/**
* Create a new {@code MapAccessor} for reading as well as writing.
* @see #MapAccessor(boolean)
*/
public MapAccessor() {
this(true);
}
/**
* Create a new {@code MapAccessor} for reading and possibly also writing.
* @param allowWrite whether to allow write operations on a target instance
* @since 6.2
* @see #canWrite
*/
public MapAccessor(boolean allowWrite) {
super(allowWrite);
}
}
| MapAccessor |
java | apache__flink | flink-test-utils-parent/flink-table-filesystem-test-utils/src/main/java/org/apache/flink/table/file/testutils/catalog/TestFileSystemCatalog.java | {
"start": 4487,
"end": 28536
} | class ____ extends AbstractCatalog {
public static final String SCHEMA_PATH = "schema";
public static final String DATA_PATH = "data";
private static final String SCHEMA_FILE_EXTENSION = ".json";
private final String catalogPathStr;
private Path catalogPath;
private FileSystem fs;
public TestFileSystemCatalog(String pathStr, String name, String defaultDatabase) {
super(name, defaultDatabase);
this.catalogPathStr = pathStr;
}
@VisibleForTesting
public String getCatalogPathStr() {
return catalogPathStr;
}
@Override
public Optional<Factory> getFactory() {
return Optional.of(new TestFileSystemTableFactory());
}
@Override
public void open() throws CatalogException {
try {
catalogPath = new Path(catalogPathStr);
fs = catalogPath.getFileSystem();
if (!fs.exists(catalogPath)) {
throw new CatalogException(
String.format(
"Catalog %s path %s does not exist.", getName(), catalogPath));
}
if (!fs.getFileStatus(catalogPath).isDir()) {
throw new CatalogException(
String.format(
"Failed to open catalog path. The given path %s is not a directory.",
catalogPath));
}
} catch (IOException e) {
throw new CatalogException(
String.format("Checking catalog path %s exists occur exception.", catalogPath),
e);
}
}
@Override
public void close() throws CatalogException {}
@Override
public List<String> listDatabases() throws CatalogException {
try {
FileStatus[] fileStatuses = fs.listStatus(catalogPath);
return Arrays.stream(fileStatuses)
.filter(FileStatus::isDir)
.map(fileStatus -> fileStatus.getPath().getName())
.collect(Collectors.toList());
} catch (IOException e) {
throw new CatalogException("Listing database occur exception.", e);
}
}
@Override
public CatalogDatabase getDatabase(String databaseName)
throws DatabaseNotExistException, CatalogException {
if (databaseExists(databaseName)) {
return new CatalogDatabaseImpl(Collections.emptyMap(), null);
} else {
throw new DatabaseNotExistException(getName(), databaseName);
}
}
@Override
public boolean databaseExists(String databaseName) throws CatalogException {
checkArgument(
!StringUtils.isNullOrWhitespaceOnly(databaseName),
"The database name cannot be null or empty.");
return listDatabases().contains(databaseName);
}
@Override
public void createDatabase(String name, CatalogDatabase database, boolean ignoreIfExists)
throws DatabaseAlreadyExistException, CatalogException {
if (databaseExists(name)) {
if (ignoreIfExists) {
return;
} else {
throw new DatabaseAlreadyExistException(getName(), name);
}
}
if (!CollectionUtil.isNullOrEmpty(database.getProperties())) {
throw new CatalogException(
"TestFilesystem catalog doesn't support to create database with options.");
}
Path dbPath = new Path(catalogPath, name);
try {
fs.mkdirs(dbPath);
} catch (IOException e) {
throw new CatalogException(
String.format("Creating database %s occur exception.", name), e);
}
}
@Override
public void dropDatabase(String databaseName, boolean ignoreIfNotExists, boolean cascade)
throws DatabaseNotExistException, DatabaseNotEmptyException, CatalogException {
if (!databaseExists(databaseName)) {
if (ignoreIfNotExists) {
return;
} else {
throw new DatabaseNotExistException(getName(), databaseName);
}
}
List<String> tables = listTables(databaseName);
if (!tables.isEmpty() && !cascade) {
throw new DatabaseNotEmptyException(getName(), databaseName);
}
if (databaseName.equals(getDefaultDatabase())) {
throw new IllegalArgumentException(
"TestFilesystem catalog doesn't support to drop the default database.");
}
Path dbPath = new Path(catalogPath, databaseName);
try {
fs.delete(dbPath, true);
} catch (IOException e) {
throw new CatalogException(
String.format("Dropping database %s occur exception.", databaseName), e);
}
}
@Override
public void alterDatabase(String name, CatalogDatabase newDatabase, boolean ignoreIfNotExists)
throws DatabaseNotExistException, CatalogException {
throw new UnsupportedOperationException("alterDatabase is not implemented.");
}
@Override
public List<String> listTables(String databaseName)
throws DatabaseNotExistException, CatalogException {
if (!databaseExists(databaseName)) {
throw new DatabaseNotExistException(getName(), databaseName);
}
Path dbPath = new Path(catalogPath, databaseName);
try {
return Arrays.stream(fs.listStatus(dbPath))
.filter(FileStatus::isDir)
.map(fileStatus -> fileStatus.getPath().getName())
.filter(name -> tableExists(new ObjectPath(databaseName, name)))
.collect(Collectors.toList());
} catch (IOException e) {
throw new CatalogException(
String.format("Listing table in database %s occur exception.", dbPath), e);
}
}
@Override
public List<String> listViews(String databaseName)
throws DatabaseNotExistException, CatalogException {
return Collections.emptyList();
}
@Override
public CatalogBaseTable getTable(ObjectPath tablePath)
throws TableNotExistException, CatalogException {
if (!tableExists(tablePath)) {
throw new TableNotExistException(getName(), tablePath);
}
final Path tableSchemaPath =
tableSchemaFilePath(
inferTableSchemaPath(catalogPathStr, tablePath), tablePath.getObjectName());
final Path tableDataPath = inferTableDataPath(catalogPathStr, tablePath);
try {
FileSystemTableInfo tableInfo =
JsonSerdeUtil.fromJson(
readFileUtf8(tableSchemaPath), FileSystemTableInfo.class);
return deserializeTable(
tableInfo.getTableKind(),
tableInfo.getCatalogTableInfo(),
tableDataPath.toString());
} catch (IOException e) {
throw new CatalogException(
String.format("Getting table %s occur exception.", tablePath), e);
}
}
@Internal
public static boolean isFileSystemTable(Map<String, String> properties) {
String connector = properties.get(CONNECTOR.key());
return StringUtils.isNullOrWhitespaceOnly(connector)
|| IDENTIFIER.equalsIgnoreCase(connector);
}
@Override
public boolean tableExists(ObjectPath tablePath) throws CatalogException {
Path path = inferTablePath(catalogPathStr, tablePath);
Path tableSchemaFilePath =
tableSchemaFilePath(
inferTableSchemaPath(catalogPathStr, tablePath), tablePath.getObjectName());
try {
return fs.exists(path) && fs.exists(tableSchemaFilePath);
} catch (IOException e) {
throw new CatalogException(
String.format("Checking table %s exists occur exception.", tablePath), e);
}
}
@Override
public void dropTable(ObjectPath tablePath, boolean ignoreIfNotExists)
throws TableNotExistException, CatalogException {
if (!tableExists(tablePath)) {
if (ignoreIfNotExists) {
return;
} else {
throw new TableNotExistException(getName(), tablePath);
}
}
Path path = inferTablePath(catalogPathStr, tablePath);
try {
fs.delete(path, true);
} catch (IOException e) {
throw new CatalogException(
String.format("Dropping table %s occur exception.", tablePath), e);
}
}
@Override
public void renameTable(ObjectPath tablePath, String newTableName, boolean ignoreIfNotExists)
throws TableNotExistException, TableAlreadyExistException, CatalogException {
throw new UnsupportedOperationException("renameTable is not implemented.");
}
@Override
public void createTable(
ObjectPath tablePath, CatalogBaseTable catalogTable, boolean ignoreIfExists)
throws TableAlreadyExistException, DatabaseNotExistException, CatalogException {
if (!databaseExists(tablePath.getDatabaseName())) {
throw new DatabaseNotExistException(getName(), tablePath.getDatabaseName());
}
if (tableExists(tablePath)) {
if (ignoreIfExists) {
return;
} else {
throw new TableAlreadyExistException(getName(), tablePath);
}
}
if (catalogTable instanceof CatalogView) {
throw new UnsupportedOperationException(
"TestFilesystem catalog doesn't support to CREATE VIEW.");
}
Tuple4<Path, Path, Path, String> tableSchemaTuple =
getTableJsonInfo(tablePath, catalogTable);
Path path = tableSchemaTuple.f0;
Path tableSchemaPath = tableSchemaTuple.f1;
Path tableDataPath = tableSchemaTuple.f2;
String jsonSchema = tableSchemaTuple.f3;
try {
if (!fs.exists(path)) {
fs.mkdirs(path);
}
if (!fs.exists(tableSchemaPath)) {
fs.mkdirs(tableSchemaPath);
}
if (isFileSystemTable(catalogTable.getOptions()) && !fs.exists(tableDataPath)) {
fs.mkdirs(tableDataPath);
}
// write table schema
Path tableSchemaFilePath =
tableSchemaFilePath(tableSchemaPath, tablePath.getObjectName());
try (FSDataOutputStream os =
fs.create(tableSchemaFilePath, FileSystem.WriteMode.NO_OVERWRITE)) {
os.write(jsonSchema.getBytes(StandardCharsets.UTF_8));
}
} catch (IOException e) {
throw new CatalogException(
String.format("Create table %s occur exception.", tablePath), e);
}
}
@Override
public void alterTable(
ObjectPath tablePath, CatalogBaseTable newTable, boolean ignoreIfNotExists)
throws TableNotExistException, CatalogException {
throw new UnsupportedOperationException("alterTable is not implemented");
}
@Override
public void alterTable(
ObjectPath tablePath,
CatalogBaseTable newTable,
List<TableChange> tableChanges,
boolean ignoreIfNotExists)
throws TableNotExistException, CatalogException {
if (ignoreIfNotExists && !tableExists(tablePath)) {
return;
}
Tuple4<Path, Path, Path, String> tableSchemaInfo = getTableJsonInfo(tablePath, newTable);
Path tableSchemaPath = tableSchemaInfo.f1;
String jsonSchema = tableSchemaInfo.f3;
try {
if (!fs.exists(tableSchemaPath)) {
throw new CatalogException(
String.format(
"Table %s schema file %s doesn't exists.",
tablePath, tableSchemaPath));
}
// write new table schema
Path tableSchemaFilePath =
tableSchemaFilePath(tableSchemaPath, tablePath.getObjectName());
try (FSDataOutputStream os =
fs.create(tableSchemaFilePath, FileSystem.WriteMode.OVERWRITE)) {
os.write(jsonSchema.getBytes(StandardCharsets.UTF_8));
}
} catch (IOException e) {
throw new CatalogException(
String.format("Altering table %s occur exception.", tablePath), e);
}
}
@Override
public List<CatalogPartitionSpec> listPartitions(ObjectPath tablePath)
throws TableNotExistException, TableNotPartitionedException, CatalogException {
return Collections.emptyList();
}
@Override
public List<CatalogPartitionSpec> listPartitions(
ObjectPath tablePath, CatalogPartitionSpec partitionSpec)
throws TableNotExistException,
TableNotPartitionedException,
PartitionSpecInvalidException,
CatalogException {
return Collections.emptyList();
}
@Override
public List<CatalogPartitionSpec> listPartitionsByFilter(
ObjectPath tablePath, List<Expression> filters)
throws TableNotExistException, TableNotPartitionedException, CatalogException {
return Collections.emptyList();
}
@Override
public CatalogPartition getPartition(ObjectPath tablePath, CatalogPartitionSpec partitionSpec)
throws PartitionNotExistException, CatalogException {
throw new PartitionNotExistException(getName(), tablePath, partitionSpec);
}
@Override
public boolean partitionExists(ObjectPath tablePath, CatalogPartitionSpec partitionSpec)
throws CatalogException {
return false;
}
@Override
public void createPartition(
ObjectPath tablePath,
CatalogPartitionSpec partitionSpec,
CatalogPartition partition,
boolean ignoreIfExists)
throws TableNotExistException,
TableNotPartitionedException,
PartitionSpecInvalidException,
PartitionAlreadyExistsException,
CatalogException {
throw new UnsupportedOperationException("createPartition is not implemented.");
}
@Override
public void dropPartition(
ObjectPath tablePath, CatalogPartitionSpec partitionSpec, boolean ignoreIfNotExists)
throws PartitionNotExistException, CatalogException {
throw new UnsupportedOperationException("dropPartition is not implemented.");
}
@Override
public void alterPartition(
ObjectPath tablePath,
CatalogPartitionSpec partitionSpec,
CatalogPartition newPartition,
boolean ignoreIfNotExists)
throws PartitionNotExistException, CatalogException {
throw new UnsupportedOperationException("alterPartition is not implemented.");
}
@Override
public List<String> listFunctions(String dbName)
throws DatabaseNotExistException, CatalogException {
return Collections.emptyList();
}
@Override
public CatalogFunction getFunction(ObjectPath functionPath)
throws FunctionNotExistException, CatalogException {
throw new FunctionNotExistException(getName(), functionPath);
}
@Override
public boolean functionExists(ObjectPath functionPath) throws CatalogException {
return false;
}
@Override
public void createFunction(
ObjectPath functionPath, CatalogFunction function, boolean ignoreIfExists)
throws FunctionAlreadyExistException, DatabaseNotExistException, CatalogException {
throw new UnsupportedOperationException("createFunction is not implemented.");
}
@Override
public void alterFunction(
ObjectPath functionPath, CatalogFunction newFunction, boolean ignoreIfNotExists)
throws FunctionNotExistException, CatalogException {
throw new UnsupportedOperationException("alterFunction is not implemented.");
}
@Override
public void dropFunction(ObjectPath functionPath, boolean ignoreIfNotExists)
throws FunctionNotExistException, CatalogException {
throw new UnsupportedOperationException("dropFunction is not implemented.");
}
@Override
public CatalogTableStatistics getTableStatistics(ObjectPath tablePath)
throws TableNotExistException, CatalogException {
return CatalogTableStatistics.UNKNOWN;
}
@Override
public CatalogColumnStatistics getTableColumnStatistics(ObjectPath tablePath)
throws TableNotExistException, CatalogException {
return CatalogColumnStatistics.UNKNOWN;
}
@Override
public CatalogTableStatistics getPartitionStatistics(
ObjectPath tablePath, CatalogPartitionSpec partitionSpec)
throws PartitionNotExistException, CatalogException {
return CatalogTableStatistics.UNKNOWN;
}
@Override
public CatalogColumnStatistics getPartitionColumnStatistics(
ObjectPath tablePath, CatalogPartitionSpec partitionSpec)
throws PartitionNotExistException, CatalogException {
return CatalogColumnStatistics.UNKNOWN;
}
@Override
public void alterTableStatistics(
ObjectPath tablePath, CatalogTableStatistics tableStatistics, boolean ignoreIfNotExists)
throws TableNotExistException, CatalogException {
throw new UnsupportedOperationException("alterTableStatistics is not implemented.");
}
@Override
public void alterTableColumnStatistics(
ObjectPath tablePath,
CatalogColumnStatistics columnStatistics,
boolean ignoreIfNotExists)
throws TableNotExistException, CatalogException, TablePartitionedException {
throw new UnsupportedOperationException("alterTableColumnStatistics is not implemented.");
}
@Override
public void alterPartitionStatistics(
ObjectPath tablePath,
CatalogPartitionSpec partitionSpec,
CatalogTableStatistics partitionStatistics,
boolean ignoreIfNotExists)
throws PartitionNotExistException, CatalogException {
throw new UnsupportedOperationException("alterPartitionStatistics is not implemented.");
}
@Override
public void alterPartitionColumnStatistics(
ObjectPath tablePath,
CatalogPartitionSpec partitionSpec,
CatalogColumnStatistics columnStatistics,
boolean ignoreIfNotExists)
throws PartitionNotExistException, CatalogException {
throw new UnsupportedOperationException(
"alterPartitionColumnStatistics is not implemented.");
}
private Tuple4<Path, Path, Path, String> getTableJsonInfo(
ObjectPath tablePath, CatalogBaseTable catalogTable) {
final Path path = inferTablePath(catalogPathStr, tablePath);
final Path tableSchemaPath = inferTableSchemaPath(catalogPathStr, tablePath);
final Path tableDataPathStr = inferTableDataPath(catalogPathStr, tablePath);
ResolvedCatalogBaseTable<?> resolvedCatalogBaseTable =
(ResolvedCatalogBaseTable<?>) catalogTable;
Map<String, String> catalogTableInfo = serializeTable(resolvedCatalogBaseTable);
CatalogBaseTable.TableKind tableKind = catalogTable.getTableKind();
FileSystemTableInfo tableInfo = new FileSystemTableInfo(tableKind, catalogTableInfo);
String jsonSchema = JsonSerdeUtil.toJson(tableInfo);
return Tuple4.of(path, tableSchemaPath, tableDataPathStr, jsonSchema);
}
/** Read file to UTF_8 decoding. */
private String readFileUtf8(Path path) throws IOException {
try (FSDataInputStream in = path.getFileSystem().open(path)) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}
private Path inferTablePath(String catalogPath, ObjectPath tablePath) {
return new Path(
String.format(
"%s/%s/%s",
catalogPath, tablePath.getDatabaseName(), tablePath.getObjectName()));
}
private Path inferTableDataPath(String catalogPath, ObjectPath tablePath) {
return new Path(
String.format(
"%s/%s/%s/%s",
catalogPath,
tablePath.getDatabaseName(),
tablePath.getObjectName(),
DATA_PATH));
}
private Path inferTableSchemaPath(String catalogPath, ObjectPath tablePath) {
return new Path(
String.format(
"%s/%s/%s/%s",
catalogPath,
tablePath.getDatabaseName(),
tablePath.getObjectName(),
SCHEMA_PATH));
}
private Path tableSchemaFilePath(Path tableSchemaPath, String tableName) {
return new Path(tableSchemaPath, tableName + "_schema" + SCHEMA_FILE_EXTENSION);
}
private Map<String, String> serializeTable(
ResolvedCatalogBaseTable<?> resolvedCatalogBaseTable) {
final DefaultSqlFactory sqlFactory = DefaultSqlFactory.INSTANCE;
if (resolvedCatalogBaseTable instanceof ResolvedCatalogTable) {
return CatalogPropertiesUtil.serializeCatalogTable(
(ResolvedCatalogTable) resolvedCatalogBaseTable, sqlFactory);
} else if (resolvedCatalogBaseTable instanceof ResolvedCatalogMaterializedTable) {
return CatalogPropertiesUtil.serializeCatalogMaterializedTable(
(ResolvedCatalogMaterializedTable) resolvedCatalogBaseTable, sqlFactory);
}
throw new IllegalArgumentException(
"Unknown kind of resolved catalog base table: "
+ resolvedCatalogBaseTable.getClass());
}
private CatalogBaseTable deserializeTable(
CatalogBaseTable.TableKind tableKind,
Map<String, String> properties,
String tableDataPath) {
if (CatalogBaseTable.TableKind.TABLE == tableKind) {
CatalogTable catalogTable = CatalogPropertiesUtil.deserializeCatalogTable(properties);
Map<String, String> options = new HashMap<>(catalogTable.getOptions());
if (isFileSystemTable(catalogTable.getOptions())) {
// put table data path
options.put(FileSystemConnectorOptions.PATH.key(), tableDataPath);
}
return catalogTable.copy(options);
} else if (CatalogBaseTable.TableKind.MATERIALIZED_TABLE == tableKind) {
CatalogMaterializedTable catalogMaterializedTable =
CatalogPropertiesUtil.deserializeCatalogMaterializedTable(properties);
Map<String, String> options = new HashMap<>(catalogMaterializedTable.getOptions());
if (isFileSystemTable(catalogMaterializedTable.getOptions())) {
// put table data path
options.put(FileSystemConnectorOptions.PATH.key(), tableDataPath);
}
return catalogMaterializedTable.copy(options);
}
throw new IllegalArgumentException("Unknown catalog base table kind: " + tableKind);
}
/** The pojo | TestFileSystemCatalog |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/merge/MergeUnsavedEntitiesTest.java | {
"start": 3375,
"end": 4350
} | class ____ {
@Id
private Long id;
private Long version;
@OneToMany(mappedBy = "parent", cascade = { MERGE }, orphanRemoval = true, fetch = FetchType.LAZY)
private List<Child> children = new ArrayList<>();
public Parent() {
}
public Parent(Long id, Long version) {
this.id = id;
this.version = version;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public List<Child> getChildren() {
return children;
}
public void setChildren(List<Child> children) {
this.children = children;
}
public void addChild(Child child) {
children.add( child );
child.setParent( this );
}
public void removeChild(Child child) {
children.remove( child );
child.setParent( null );
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}
@Entity(name = "Child")
@Table(name = "child")
public static | Parent |
java | apache__flink | flink-core/src/test/java/org/apache/flink/api/java/typeutils/EitherTypeInfoTest.java | {
"start": 1070,
"end": 1660
} | class ____ extends TypeInformationTestBase<EitherTypeInfo<?, ?>> {
@Override
protected EitherTypeInfo<?, ?>[] getTestData() {
return new EitherTypeInfo<?, ?>[] {
new EitherTypeInfo<>(BasicTypeInfo.INT_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO),
new EitherTypeInfo<>(
BasicTypeInfo.INT_TYPE_INFO,
new TupleTypeInfo<Tuple2<Double, Long>>(
TypeExtractor.getForClass(Double.class),
TypeExtractor.getForClass(String.class)))
};
}
}
| EitherTypeInfoTest |
java | google__guava | guava-tests/test/com/google/common/util/concurrent/AbstractFutureDefaultAtomicHelperTest.java | {
"start": 1188,
"end": 1797
} | class ____ extends TestCase {
public void testUsingExpectedAtomicHelper() throws Exception {
if (isJava8() || isAndroid()) {
assertThat(AbstractFutureState.atomicHelperTypeForTest()).isEqualTo("UnsafeAtomicHelper");
} else {
assertThat(AbstractFutureState.atomicHelperTypeForTest()).isEqualTo("VarHandleAtomicHelper");
}
}
private static boolean isJava8() {
return JAVA_SPECIFICATION_VERSION.value().equals("1.8");
}
private static boolean isAndroid() {
return System.getProperty("java.runtime.name", "").contains("Android");
}
}
| AbstractFutureDefaultAtomicHelperTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/issues/StopRouteImpactsErrorHandlerTest.java | {
"start": 1128,
"end": 3151
} | class ____ extends ContextTestSupport {
@Test
public void testIssue() throws Exception {
RouteDefinition testRoute = context.getRouteDefinition("TestRoute");
AdviceWith.adviceWith(testRoute, context, new AdviceWithRouteBuilder() {
@Override
public void configure() {
interceptSendToEndpoint("seda:*").skipSendToOriginalEndpoint().to("log:seda")
.throwException(new IllegalArgumentException("Forced"));
}
});
RouteDefinition smtpRoute = context.getRouteDefinition("smtpRoute");
AdviceWith.adviceWith(smtpRoute, context, new AdviceWithRouteBuilder() {
@Override
public void configure() {
interceptSendToEndpoint("smtp*").to("log:smtp").skipSendToOriginalEndpoint().to("mock:smtp");
}
});
// we should fail and end up sending to smtp
getMockEndpoint("mock:smtp").expectedMessageCount(1);
// stopping a route after advice with causes problem with error handlers
context.getRouteController().stopRoute("pollRoute");
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
context.addComponent("smtp", context.getComponent("mock"));
errorHandler(deadLetterChannel("direct:emailSupport").maximumRedeliveries(2).redeliveryDelay(0));
from("direct:emailSupport").routeId("smtpRoute").errorHandler(deadLetterChannel("log:dead?level=ERROR"))
.to("smtp://smtpServer");
from("timer://someTimer?delay=15000&fixedRate=true&period=5000").routeId("pollRoute").to("log:level=INFO");
from("direct:start").routeId("TestRoute").to("seda:foo");
}
};
}
}
| StopRouteImpactsErrorHandlerTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesServicesEndpointBuilderFactory.java | {
"start": 1473,
"end": 1631
} | interface ____ {
/**
* Builder for endpoint consumers for the Kubernetes Services component.
*/
public | KubernetesServicesEndpointBuilderFactory |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/MathRoundIntLongTest.java | {
"start": 4960,
"end": 5170
} | class ____ {
void f() {
int y = Math.round(1 + 3) * 3;
}
}
""")
.addOutputLines(
"Test.java",
"""
| Test |
java | spring-projects__spring-framework | spring-jdbc/src/test/java/org/springframework/jdbc/object/StoredProcedureTests.java | {
"start": 19798,
"end": 20052
} | class ____ extends StoredProcedure {
public UnnamedParameterStoredProcedure(DataSource ds) {
super(ds, "unnamed_parameter_sp");
declareParameter(new SqlParameter(Types.INTEGER));
compile();
}
}
private static | UnnamedParameterStoredProcedure |
java | elastic__elasticsearch | x-pack/plugin/profiling/src/main/java/org/elasticsearch/xpack/profiling/persistence/ProfilingIndexTemplateRegistry.java | {
"start": 1698,
"end": 15567
} | class ____ extends IndexTemplateRegistry {
private static final Logger logger = LogManager.getLogger(ProfilingIndexTemplateRegistry.class);
// history (please add a comment why you increased the version here)
// version 1: initial
// version 2: Added 'profiling.host.machine' keyword mapping to profiling-hosts
// version 3: Add optional component template 'profiling-ilm@custom' to all ILM-managed index templates
// version 4: Added 'service.name' keyword mapping to profiling-events
// version 5: Add optional component template '<idx-name>@custom' to all index templates that reference component templates
// version 6: Added 'host.arch' keyword mapping to profiling-hosts
// version 7: Added 'host.type', 'cloud.provider', 'cloud.region' keyword mappings to profiling-hosts
// version 8: Changed from disabled _source to synthetic _source for profiling-events-* and profiling-metrics
// version 9: Changed sort order for profiling-events-*
// version 10: changed mapping profiling-events @timestamp to 'date_nanos' from 'date'
// version 11: Added 'profiling.agent.protocol' keyword mapping to profiling-hosts
// version 12: Added 'profiling.agent.env_https_proxy' keyword mapping to profiling-hosts
// version 13: Added 'container.id' keyword mapping to profiling-events
// version 14: Stop using using _source.mode attribute in index templates
// version 15: Use LogsDB mode for profiling-events-* (~30% smaller storage footprint)
// version 16: Added 'profiling.executable.name' keyword mapping to profiling-events
public static final int INDEX_TEMPLATE_VERSION = 15;
// history for individual indices / index templates. Only bump these for breaking changes that require to create a new index
public static final int PROFILING_EVENTS_VERSION = 6;
public static final int PROFILING_EXECUTABLES_VERSION = 1;
public static final int PROFILING_METRICS_VERSION = 2;
public static final int PROFILING_HOSTS_VERSION = 2;
public static final int PROFILING_STACKFRAMES_VERSION = 1;
public static final int PROFILING_STACKTRACES_VERSION = 1;
public static final int PROFILING_SYMBOLS_VERSION = 1;
public static final int PROFILING_RETURNPADS_PRIVATE_VERSION = 1;
public static final int PROFILING_SQ_EXECUTABLES_VERSION = 1;
public static final int PROFILING_SQ_LEAFFRAMES_VERSION = 1;
public static final String PROFILING_TEMPLATE_VERSION_VARIABLE = "xpack.profiling.template.version";
private volatile boolean templatesEnabled;
public ProfilingIndexTemplateRegistry(
Settings nodeSettings,
ClusterService clusterService,
ThreadPool threadPool,
Client client,
NamedXContentRegistry xContentRegistry
) {
super(nodeSettings, clusterService, threadPool, client, xContentRegistry);
}
public void setTemplatesEnabled(boolean templatesEnabled) {
this.templatesEnabled = templatesEnabled;
}
public void close() {
clusterService.removeListener(this);
}
@Override
protected String getOrigin() {
return ClientHelper.PROFILING_ORIGIN;
}
@Override
protected boolean requiresMasterNode() {
return true;
}
private static final List<LifecyclePolicyConfig> LIFECYCLE_POLICY_CONFIGS = List.of(
new LifecyclePolicyConfig(
"profiling-60-days",
"/profiling/ilm-policy/profiling-60-days.json",
Map.of(PROFILING_TEMPLATE_VERSION_VARIABLE, String.valueOf(INDEX_TEMPLATE_VERSION))
)
);
@Override
protected List<LifecyclePolicyConfig> getLifecycleConfigs() {
return LIFECYCLE_POLICY_CONFIGS;
}
@Override
protected List<LifecyclePolicy> getLifecyclePolicies() {
return templatesEnabled ? lifecyclePolicies : Collections.emptyList();
}
private static final Map<String, ComponentTemplate> COMPONENT_TEMPLATE_CONFIGS;
static {
final Map<String, ComponentTemplate> componentTemplates = new HashMap<>();
for (IndexTemplateConfig config : List.of(
new IndexTemplateConfig(
"profiling-events",
"/profiling/component-template/profiling-events.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE,
indexVersion("events", PROFILING_EVENTS_VERSION)
),
new IndexTemplateConfig(
"profiling-executables",
"/profiling/component-template/profiling-executables.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE,
indexVersion("executables", PROFILING_EXECUTABLES_VERSION)
),
new IndexTemplateConfig(
"profiling-ilm",
"/profiling/component-template/profiling-ilm.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE
),
new IndexTemplateConfig(
"profiling-hot-tier",
"/profiling/component-template/profiling-hot-tier.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE
),
new IndexTemplateConfig(
"profiling-metrics",
"/profiling/component-template/profiling-metrics.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE,
indexVersion("metrics", PROFILING_METRICS_VERSION)
),
new IndexTemplateConfig(
"profiling-hosts",
"/profiling/component-template/profiling-hosts.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE,
indexVersion("hosts", PROFILING_HOSTS_VERSION)
),
new IndexTemplateConfig(
"profiling-stackframes",
"/profiling/component-template/profiling-stackframes.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE,
indexVersion("stackframes", PROFILING_STACKFRAMES_VERSION)
),
new IndexTemplateConfig(
"profiling-stacktraces",
"/profiling/component-template/profiling-stacktraces.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE,
indexVersion("stacktraces", PROFILING_STACKTRACES_VERSION)
),
new IndexTemplateConfig(
"profiling-symbols",
"/profiling/component-template/profiling-symbols.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE,
indexVersion("symbols", PROFILING_SYMBOLS_VERSION)
)
)) {
try (var parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY, config.loadBytes())) {
componentTemplates.put(config.getTemplateName(), ComponentTemplate.parse(parser));
} catch (IOException e) {
throw new AssertionError(e);
}
}
COMPONENT_TEMPLATE_CONFIGS = Collections.unmodifiableMap(componentTemplates);
}
private static Map<String, String> indexVersion(String index, int version) {
return Map.of(String.format(Locale.ROOT, "xpack.profiling.index.%s.version", index), String.valueOf(version));
}
@Override
protected Map<String, ComponentTemplate> getComponentTemplateConfigs() {
return templatesEnabled ? COMPONENT_TEMPLATE_CONFIGS : Collections.emptyMap();
}
private static final Map<String, ComposableIndexTemplate> COMPOSABLE_INDEX_TEMPLATE_CONFIGS = parseComposableTemplates(
new IndexTemplateConfig(
"profiling-events",
"/profiling/index-template/profiling-events.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE
),
new IndexTemplateConfig(
"profiling-metrics",
"/profiling/index-template/profiling-metrics.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE
),
new IndexTemplateConfig(
"profiling-hosts",
"/profiling/index-template/profiling-hosts.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE
),
new IndexTemplateConfig(
"profiling-executables",
"/profiling/index-template/profiling-executables.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE
),
new IndexTemplateConfig(
"profiling-stackframes",
"/profiling/index-template/profiling-stackframes.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE
),
new IndexTemplateConfig(
"profiling-stacktraces",
"/profiling/index-template/profiling-stacktraces.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE
),
// templates for regular indices
new IndexTemplateConfig(
"profiling-returnpads-private",
"/profiling/index-template/profiling-returnpads-private.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE,
indexVersion("returnpads.private", PROFILING_RETURNPADS_PRIVATE_VERSION)
),
new IndexTemplateConfig(
"profiling-sq-executables",
"/profiling/index-template/profiling-sq-executables.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE,
indexVersion("sq.executables", PROFILING_SQ_EXECUTABLES_VERSION)
),
new IndexTemplateConfig(
"profiling-sq-leafframes",
"/profiling/index-template/profiling-sq-leafframes.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE,
indexVersion("sq.leafframes", PROFILING_SQ_LEAFFRAMES_VERSION)
),
new IndexTemplateConfig(
"profiling-symbols-global",
"/profiling/index-template/profiling-symbols-global.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE
),
new IndexTemplateConfig(
"profiling-symbols-private",
"/profiling/index-template/profiling-symbols-private.json",
INDEX_TEMPLATE_VERSION,
PROFILING_TEMPLATE_VERSION_VARIABLE
)
);
@Override
protected Map<String, ComposableIndexTemplate> getComposableTemplateConfigs() {
return templatesEnabled ? COMPOSABLE_INDEX_TEMPLATE_CONFIGS : Collections.emptyMap();
}
@Override
protected boolean isUpgradeRequired(LifecyclePolicy currentPolicy, LifecyclePolicy newPolicy) {
try {
return getVersion(currentPolicy, "current") < getVersion(newPolicy, "new");
} catch (IllegalArgumentException ex) {
logger.warn("Cannot determine whether lifecycle policy upgrade is required.", ex);
// don't attempt an upgrade on invalid data
return false;
}
}
private static int getVersion(LifecyclePolicy policy, String logicalVersion) {
Map<String, Object> meta = policy.getMetadata();
try {
return meta != null ? Integer.parseInt(meta.getOrDefault("version", Integer.MIN_VALUE).toString()) : Integer.MIN_VALUE;
} catch (NumberFormatException ex) {
throw new IllegalArgumentException(
String.format(Locale.ROOT, "Invalid version metadata for %s lifecycle policy [%s]", logicalVersion, policy.getName()),
ex
);
}
}
/**
* Determines whether all resources (component templates, composable templates and lifecycle policies) have been created. This method
* also checks whether resources have been created for the expected version.
*
* @param state Current cluster state.
* @param settings Current cluster settings.
* @return <code>true</code> if and only if all resources managed by this registry have been created and are current.
*/
public static boolean isAllResourcesCreated(ClusterState state, Settings settings) {
for (String name : COMPONENT_TEMPLATE_CONFIGS.keySet()) {
ComponentTemplate componentTemplate = state.metadata().getProject().componentTemplates().get(name);
if (componentTemplate == null || componentTemplate.version() < INDEX_TEMPLATE_VERSION) {
return false;
}
}
for (String name : COMPOSABLE_INDEX_TEMPLATE_CONFIGS.keySet()) {
ComposableIndexTemplate composableIndexTemplate = state.metadata().getProject().templatesV2().get(name);
if (composableIndexTemplate == null || composableIndexTemplate.version() < INDEX_TEMPLATE_VERSION) {
return false;
}
}
if (isDataStreamsLifecycleOnlyMode(settings) == false) {
IndexLifecycleMetadata ilmMetadata = state.metadata().getProject().custom(IndexLifecycleMetadata.TYPE);
if (ilmMetadata == null) {
return false;
}
for (LifecyclePolicyConfig lifecyclePolicy : LIFECYCLE_POLICY_CONFIGS) {
LifecyclePolicy existingPolicy = ilmMetadata.getPolicies().get(lifecyclePolicy.getPolicyName());
if (existingPolicy == null || getVersion(existingPolicy, "current") < INDEX_TEMPLATE_VERSION) {
return false;
}
}
}
return true;
}
}
| ProfilingIndexTemplateRegistry |
java | apache__hadoop | hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-blockgen/src/main/java/org/apache/hadoop/tools/dynamometer/blockgenerator/XMLParser.java | {
"start": 5434,
"end": 6129
} | enum ____ {
DEFAULT,
INODE_SECTION,
INODE,
FILE,
FILE_WITH_REPLICATION;
private final Set<State> allowedTransitions = new HashSet<>();
static {
DEFAULT.addTransitions(DEFAULT, INODE_SECTION);
INODE_SECTION.addTransitions(DEFAULT, INODE);
INODE.addTransitions(INODE_SECTION, FILE);
FILE.addTransitions(INODE_SECTION, FILE_WITH_REPLICATION);
FILE_WITH_REPLICATION.addTransitions(INODE_SECTION);
}
private void addTransitions(State... nextState) {
allowedTransitions.addAll(Arrays.asList(nextState));
}
boolean transitionAllowed(State nextState) {
return allowedTransitions.contains(nextState);
}
}
}
| State |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/verification/DescriptionTest.java | {
"start": 640,
"end": 892
} | class ____ {
@Mock private VerificationMode mockVerificationMode;
@Mock private VerificationData mockVerificationData;
@Before
public void setUp() {
openMocks(this);
}
/**
* Test of verify method, of | DescriptionTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/sql/ast/spi/StandardSqlAstTranslator.java | {
"start": 568,
"end": 804
} | class ____<T extends JdbcOperation> extends AbstractSqlAstTranslator<T> {
public StandardSqlAstTranslator(SessionFactoryImplementor sessionFactory, Statement statement) {
super( sessionFactory, statement );
}
}
| StandardSqlAstTranslator |
java | quarkusio__quarkus | extensions/vertx/deployment/src/test/java/io/quarkus/vertx/CodecRegistrationTest.java | {
"start": 9674,
"end": 9883
} | class ____ {
private final String name;
CustomType5(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
| CustomType5 |
java | hibernate__hibernate-orm | hibernate-spatial/src/test/java/org/hibernate/spatial/testing/dialects/hana/HANATestSupport.java | {
"start": 275,
"end": 458
} | class ____ extends TestSupport {
@Override
public TestData createTestData(TestDataPurpose purpose) {
return TestData.fromFile( "hana/test-hana-data-set.xml" );
}
}
| HANATestSupport |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cid/keymanytoone/NestedKeyManyToOneTest.java | {
"start": 1375,
"end": 1579
} | class ____ implements Serializable {
Long basicEntity;
Long key2;
}
}
@Entity(name = "NestedIdClassEntity")
@IdClass(NestedIdClassEntity.NestedIdClassEntityId.class)
public static | IdClassEntityId |
java | apache__flink | flink-libraries/flink-state-processing-api/src/main/java/org/apache/flink/state/table/StateValueColumnConfiguration.java | {
"start": 1116,
"end": 2630
} | class ____ implements Serializable {
private final int columnIndex;
private final String stateName;
private final SavepointConnectorOptions.StateType stateType;
@Nullable private final TypeInformation mapKeyTypeInfo;
@Nullable private final TypeInformation valueTypeInfo;
@Nullable private StateDescriptor stateDescriptor;
public StateValueColumnConfiguration(
int columnIndex,
final String stateName,
final SavepointConnectorOptions.StateType stateType,
@Nullable final TypeInformation mapKeyTypeInfo,
final TypeInformation valueTypeInfo) {
this.columnIndex = columnIndex;
this.stateName = stateName;
this.stateType = stateType;
this.mapKeyTypeInfo = mapKeyTypeInfo;
this.valueTypeInfo = valueTypeInfo;
}
public int getColumnIndex() {
return columnIndex;
}
public String getStateName() {
return stateName;
}
public SavepointConnectorOptions.StateType getStateType() {
return stateType;
}
@Nullable
public TypeInformation getMapKeyTypeInfo() {
return mapKeyTypeInfo;
}
public TypeInformation getValueTypeInfo() {
return valueTypeInfo;
}
public void setStateDescriptor(StateDescriptor stateDescriptor) {
this.stateDescriptor = stateDescriptor;
}
@Nullable
public StateDescriptor getStateDescriptor() {
return stateDescriptor;
}
}
| StateValueColumnConfiguration |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/support/profile/ProfilerTest.java | {
"start": 260,
"end": 1775
} | class ____ extends TestCase {
public void test_profile() throws Exception {
for (int i = 0; i < 10; ++i) {
req();
}
}
private void req() {
Profiler.initLocal();
Profiler.enter("/", Profiler.PROFILE_TYPE_WEB);
for (int i = 0; i < 100; ++i) {
execA();
}
assertEquals(2, Profiler.getStatsMap().size());
{
ProfileEntryReqStat stat = Profiler.getStatsMap().get(new ProfileEntryKey("/", "com.xxx.a(int)",
Profiler.PROFILE_TYPE_SPRING));
assertEquals(100, stat.getExecuteCount());
assertEquals(100, stat.getExecuteTimeNanos());
}
{
ProfileEntryReqStat stat = Profiler.getStatsMap().get(new ProfileEntryKey("com.xxx.a(int)",
"com.xxx.b(int)",
Profiler.PROFILE_TYPE_SPRING));
assertEquals(1000 * 100, stat.getExecuteCount());
assertEquals(1000 * 100, stat.getExecuteTimeNanos());
}
Profiler.release(1);
assertEquals(3, Profiler.getStatsMap().size());
Profiler.removeLocal();
}
private void execA() {
Profiler.enter("com.xxx.a(int)", Profiler.PROFILE_TYPE_SPRING);
for (int i = 0; i < 1000; ++i) {
execB();
}
Profiler.release(1);
}
private void execB() {
Profiler.enter("com.xxx.b(int)", Profiler.PROFILE_TYPE_SPRING);
Profiler.release(1);
}
}
| ProfilerTest |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/pkg/builditem/DeploymentResultBuildItem.java | {
"start": 825,
"end": 2058
} | class ____ extends SimpleBuildItem {
/**
* The name of the main deployed resource (e.g., Deployment, StatefulSet, or DeploymentConfig).
*/
private final String name;
/**
* The labels associated with the deployed resource.
* <p>
* These labels provide metadata that can be used for resource selection, grouping,
* or integration with other tools and processes.
* </p>
*/
private final Map<String, String> labels;
/**
* Constructs a new {@link DeploymentResultBuildItem}.
*
* @param name the name of the main deployed resource
* @param labels a map of labels associated with the deployed resource
*/
public DeploymentResultBuildItem(String name, Map<String, String> labels) {
this.name = name;
this.labels = labels;
}
/**
* Returns the name of the main deployed resource.
*
* @return the resource name
*/
public String getName() {
return this.name;
}
/**
* Returns the labels associated with the deployed resource.
*
* @return a map of resource labels
*/
public Map<String, String> getLabels() {
return this.labels;
}
} | DeploymentResultBuildItem |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/job/checkpoints/CheckpointHandlers.java | {
"start": 4746,
"end": 7301
} | class ____
extends AbstractRestHandler<
RestfulGateway,
CheckpointTriggerRequestBody,
TriggerResponse,
CheckpointTriggerMessageParameters> {
public CheckpointTriggerHandler(
final GatewayRetriever<? extends RestfulGateway> leaderRetriever,
final Duration timeout,
final Map<String, String> responseHeaders) {
super(
leaderRetriever,
timeout,
responseHeaders,
CheckpointTriggerHeaders.getInstance());
}
private static AsynchronousJobOperationKey createOperationKey(
final HandlerRequest<CheckpointTriggerRequestBody> request) {
final JobID jobId = request.getPathParameter(JobIDPathParameter.class);
return AsynchronousJobOperationKey.of(
request.getRequestBody().getTriggerId().orElseGet(TriggerId::new), jobId);
}
@Override
protected CompletableFuture<TriggerResponse> handleRequest(
@Nonnull HandlerRequest<CheckpointTriggerRequestBody> request,
@Nonnull RestfulGateway gateway)
throws RestHandlerException {
final AsynchronousJobOperationKey operationKey = createOperationKey(request);
CheckpointType checkpointType = request.getRequestBody().getCheckpointType();
if (checkpointType == CheckpointType.INCREMENTAL) {
throw new IllegalStateException(
"Flink does not support triggering incremental checkpoint explicitly."
+ " See FLINK-33723.");
}
return gateway.triggerCheckpoint(operationKey, checkpointType, RpcUtils.INF_TIMEOUT)
.handle(
(acknowledge, throwable) -> {
if (throwable == null) {
return new TriggerResponse(operationKey.getTriggerId());
} else {
throw new CompletionException(
createInternalServerError(
throwable, operationKey, "triggering"));
}
});
}
}
/** HTTP handler to query for the status of the checkpoint. */
public static | CheckpointTriggerHandler |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/iterable/IterableAssert_areAtLeast_Test.java | {
"start": 1104,
"end": 1599
} | class ____ extends IterableAssertBaseTest {
private static Condition<Object> condition;
@BeforeAll
static void beforeOnce() {
condition = new TestCondition<>();
}
@Override
protected ConcreteIterableAssert<Object> invoke_api_method() {
return assertions.areAtLeast(2, condition);
}
@Override
protected void verify_internal_effects() {
verify(iterables).assertAreAtLeast(getInfo(assertions), getActual(assertions), 2, condition);
}
}
| IterableAssert_areAtLeast_Test |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/logging/logback/RollingPolicySystemProperty.java | {
"start": 872,
"end": 2533
} | enum ____ {
/**
* Logging system property for the rolled-over log file name pattern.
*/
FILE_NAME_PATTERN("file-name-pattern", "logging.pattern.rolling-file-name"),
/**
* Logging system property for the clean history on start flag.
*/
CLEAN_HISTORY_ON_START("clean-history-on-start", "logging.file.clean-history-on-start"),
/**
* Logging system property for the file log max size.
*/
MAX_FILE_SIZE("max-file-size", "logging.file.max-size"),
/**
* Logging system property for the file total size cap.
*/
TOTAL_SIZE_CAP("total-size-cap", "logging.file.total-size-cap"),
/**
* Logging system property for the file log max history.
*/
MAX_HISTORY("max-history", "logging.file.max-history");
private final String environmentVariableName;
private final String applicationPropertyName;
private final String deprecatedApplicationPropertyName;
RollingPolicySystemProperty(String applicationPropertyName, String deprecatedApplicationPropertyName) {
this.environmentVariableName = "LOGBACK_ROLLINGPOLICY_" + name();
this.applicationPropertyName = "logging.logback.rollingpolicy." + applicationPropertyName;
this.deprecatedApplicationPropertyName = deprecatedApplicationPropertyName;
}
/**
* Return the name of environment variable that can be used to access this property.
* @return the environment variable name
*/
public String getEnvironmentVariableName() {
return this.environmentVariableName;
}
String getApplicationPropertyName() {
return this.applicationPropertyName;
}
String getDeprecatedApplicationPropertyName() {
return this.deprecatedApplicationPropertyName;
}
}
| RollingPolicySystemProperty |
java | apache__kafka | streams/src/test/java/org/apache/kafka/streams/processor/internals/GlobalStreamThreadTest.java | {
"start": 3543,
"end": 18567
} | class ____ {
private final InternalTopologyBuilder builder = new InternalTopologyBuilder();
private final MockConsumer<byte[], byte[]> mockConsumer = new MockConsumer<>(AutoOffsetResetStrategy.NONE.name());
private final MockTime time = new MockTime();
private final MockStateRestoreListener stateRestoreListener = new MockStateRestoreListener();
private GlobalStreamThread globalStreamThread;
private StreamsConfig config;
private String baseDirectoryName;
private static final String GLOBAL_STORE_TOPIC_NAME = "foo";
private static final String GLOBAL_STORE_NAME = "bar";
private final TopicPartition topicPartition = new TopicPartition(GLOBAL_STORE_TOPIC_NAME, 0);
@BeforeEach
public void before() {
final MaterializedInternal<Object, Object, KeyValueStore<Bytes, byte[]>> materialized =
new MaterializedInternal<>(Materialized.with(null, null),
new InternalNameProvider() {
@Override
public String newProcessorName(final String prefix) {
return "processorName";
}
@Override
public String newStoreName(final String prefix) {
return GLOBAL_STORE_NAME;
}
},
"store-"
);
final ProcessorSupplier<Object, Object, Void, Void> processorSupplier = () ->
new ContextualProcessor<>() {
@Override
public void process(final Record<Object, Object> record) {
}
};
final StoreFactory storeFactory =
new KeyValueStoreMaterializer<>(materialized).withLoggingDisabled();
final StoreBuilder<?> storeBuilder = new StoreFactory.FactoryWrappingStoreBuilder<>(storeFactory);
builder.addGlobalStore(
"sourceName",
null,
null,
null,
GLOBAL_STORE_TOPIC_NAME,
"processorName",
new StoreDelegatingProcessorSupplier<>(processorSupplier, Set.of(storeBuilder)),
false
);
baseDirectoryName = TestUtils.tempDirectory().getAbsolutePath();
final HashMap<String, Object> properties = getStreamProperties();
config = new StreamsConfig(properties);
globalStreamThread = new GlobalStreamThread(
builder.rewriteTopology(config).buildGlobalStateTopology(),
config,
mockConsumer,
new StateDirectory(config, time, true, false),
0,
new StreamsMetricsImpl(new Metrics(), "test-client", time),
time,
"clientId",
stateRestoreListener,
e -> { }
);
}
@Test
public void shouldThrowStreamsExceptionOnStartupIfThereIsAStreamsException() throws Exception {
// should throw as the MockConsumer hasn't been configured and there are no
// partitions available
final StateStore globalStore = builder.globalStateStores().get(GLOBAL_STORE_NAME);
assertThrows(StreamsException.class,
() -> globalStreamThread.start(),
"Should have thrown StreamsException if start up failed.");
globalStreamThread.join();
assertThat(globalStore.isOpen(), is(false));
assertFalse(globalStreamThread.stillRunning());
}
@Test
public void shouldThrowStreamsExceptionOnStartupIfExceptionOccurred() throws Exception {
final MockConsumer<byte[], byte[]> mockConsumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
@Override
public List<PartitionInfo> partitionsFor(final String topic) {
throw new RuntimeException("KABOOM!");
}
};
final StateStore globalStore = builder.globalStateStores().get(GLOBAL_STORE_NAME);
globalStreamThread = new GlobalStreamThread(
builder.buildGlobalStateTopology(),
config,
mockConsumer,
new StateDirectory(config, time, true, false),
0,
new StreamsMetricsImpl(new Metrics(), "test-client", time),
time,
"clientId",
stateRestoreListener,
e -> { }
);
try {
globalStreamThread.start();
fail("Should have thrown StreamsException if start up failed");
} catch (final StreamsException e) {
assertThat(e.getCause(), instanceOf(RuntimeException.class));
assertThat(e.getCause().getMessage(), equalTo("KABOOM!"));
}
globalStreamThread.join();
assertThat(globalStore.isOpen(), is(false));
assertFalse(globalStreamThread.stillRunning());
}
@Test
public void shouldBeRunningAfterSuccessfulStart() throws Exception {
initializeConsumer();
startAndSwallowError();
assertTrue(globalStreamThread.stillRunning());
globalStreamThread.shutdown();
globalStreamThread.join();
}
@Test
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void shouldStopRunningWhenClosedByUser() throws Exception {
initializeConsumer();
startAndSwallowError();
globalStreamThread.shutdown();
globalStreamThread.join();
assertEquals(GlobalStreamThread.State.DEAD, globalStreamThread.state());
}
@Test
public void shouldCloseStateStoresOnClose() throws Exception {
initializeConsumer();
startAndSwallowError();
final StateStore globalStore = builder.globalStateStores().get(GLOBAL_STORE_NAME);
assertTrue(globalStore.isOpen());
globalStreamThread.shutdown();
globalStreamThread.join();
assertFalse(globalStore.isOpen());
}
@Test
public void shouldStayDeadAfterTwoCloses() throws Exception {
initializeConsumer();
startAndSwallowError();
globalStreamThread.shutdown();
globalStreamThread.join();
globalStreamThread.shutdown();
assertEquals(GlobalStreamThread.State.DEAD, globalStreamThread.state());
}
@Test
public void shouldTransitionToRunningOnStart() throws Exception {
initializeConsumer();
startAndSwallowError();
TestUtils.waitForCondition(
() -> globalStreamThread.state() == RUNNING,
10 * 1000,
"Thread never started.");
globalStreamThread.shutdown();
}
@Test
public void shouldDieOnInvalidOffsetExceptionDuringStartup() throws Exception {
final StateStore globalStore = builder.globalStateStores().get(GLOBAL_STORE_NAME);
initializeConsumer();
mockConsumer.setPollException(new InvalidOffsetException("Try Again!") {
@Override
public Set<TopicPartition> partitions() {
return Collections.singleton(topicPartition);
}
});
startAndSwallowError();
TestUtils.waitForCondition(
() -> globalStreamThread.state() == DEAD,
10 * 1000,
"GlobalStreamThread should have died."
);
globalStreamThread.join();
assertThat(globalStore.isOpen(), is(false));
assertFalse(new File(baseDirectoryName + File.separator + "testAppId" + File.separator + "global").exists());
}
@Test
public void shouldDieOnInvalidOffsetExceptionWhileRunning() throws Exception {
final StateStore globalStore = builder.globalStateStores().get(GLOBAL_STORE_NAME);
initializeConsumer();
startAndSwallowError();
TestUtils.waitForCondition(
() -> globalStreamThread.state() == RUNNING,
10 * 1000,
"Thread never started.");
mockConsumer.updateEndOffsets(Collections.singletonMap(topicPartition, 1L));
mockConsumer.addRecord(record(GLOBAL_STORE_TOPIC_NAME, 0, 0L, "K1".getBytes(), "V1".getBytes()));
TestUtils.waitForCondition(
() -> mockConsumer.position(topicPartition) == 1L,
10 * 1000,
"Input record never consumed");
mockConsumer.setPollException(new InvalidOffsetException("Try Again!") {
@Override
public Set<TopicPartition> partitions() {
return Collections.singleton(topicPartition);
}
});
TestUtils.waitForCondition(
() -> globalStreamThread.state() == DEAD,
10 * 1000,
"GlobalStreamThread should have died."
);
globalStreamThread.join();
assertThat(globalStore.isOpen(), is(false));
assertFalse(new File(baseDirectoryName + File.separator + "testAppId" + File.separator + "global").exists());
}
@Test
public void shouldGetGlobalConsumerClientInstanceId() throws Exception {
initializeConsumer();
startAndSwallowError();
final Uuid instanceId = Uuid.randomUuid();
mockConsumer.setClientInstanceId(instanceId);
try {
final KafkaFuture<Uuid> future = globalStreamThread.globalConsumerInstanceId(Duration.ZERO);
final Uuid result = future.get();
assertThat(result, equalTo(instanceId));
} finally {
globalStreamThread.shutdown();
globalStreamThread.join();
}
}
@Test
public void shouldGetGlobalConsumerClientInstanceIdWithInternalTimeoutException() throws Exception {
initializeConsumer();
startAndSwallowError();
final Uuid instanceId = Uuid.randomUuid();
mockConsumer.setClientInstanceId(instanceId);
mockConsumer.injectTimeoutException(5);
try {
final KafkaFuture<Uuid> future = globalStreamThread.globalConsumerInstanceId(Duration.ZERO);
final Uuid result = future.get();
assertThat(result, equalTo(instanceId));
} finally {
globalStreamThread.shutdown();
globalStreamThread.join();
}
}
@Test
public void shouldReturnNullIfTelemetryDisabled() throws Exception {
initializeConsumer();
mockConsumer.disableTelemetry();
startAndSwallowError();
try {
final KafkaFuture<Uuid> future = globalStreamThread.globalConsumerInstanceId(Duration.ZERO);
final Uuid result = future.get();
assertThat(result, equalTo(null));
} finally {
globalStreamThread.shutdown();
globalStreamThread.join();
}
}
@Test
public void shouldReturnErrorIfInstanceIdNotInitialized() throws Exception {
initializeConsumer();
startAndSwallowError();
try {
final KafkaFuture<Uuid> future = globalStreamThread.globalConsumerInstanceId(Duration.ZERO);
final ExecutionException error = assertThrows(ExecutionException.class, future::get);
assertThat(error.getCause(), instanceOf(UnsupportedOperationException.class));
assertThat(error.getCause().getMessage(), equalTo("clientInstanceId not set"));
} finally {
globalStreamThread.shutdown();
globalStreamThread.join();
}
}
@Test
public void shouldTimeOutOnGlobalConsumerInstanceId() throws Exception {
initializeConsumer();
startAndSwallowError();
final Uuid instanceId = Uuid.randomUuid();
mockConsumer.setClientInstanceId(instanceId);
mockConsumer.injectTimeoutException(-1);
try {
final KafkaFuture<Uuid> future = globalStreamThread.globalConsumerInstanceId(Duration.ZERO);
time.sleep(1L);
final ExecutionException error = assertThrows(ExecutionException.class, future::get);
assertThat(error.getCause(), instanceOf(TimeoutException.class));
assertThat(
error.getCause().getMessage(),
equalTo("Could not retrieve global consumer client instance id.")
);
} finally {
globalStreamThread.shutdown();
globalStreamThread.join();
}
}
@Test
public void shouldThrowStreamsExceptionOnStartupIfThrowableOccurred() throws Exception {
final String exceptionMessage = "Throwable occurred!";
final MockConsumer<byte[], byte[]> consumer = new MockConsumer<>(AutoOffsetResetStrategy.EARLIEST.name()) {
@Override
public List<PartitionInfo> partitionsFor(final String topic) {
throw new ExceptionInInitializerError(exceptionMessage);
}
};
final StateStore globalStore = builder.globalStateStores().get(GLOBAL_STORE_NAME);
globalStreamThread = new GlobalStreamThread(
builder.buildGlobalStateTopology(),
config,
consumer,
new StateDirectory(config, time, true, false),
0,
new StreamsMetricsImpl(new Metrics(), "test-client", time),
time,
"clientId",
stateRestoreListener,
e -> { }
);
try {
globalStreamThread.start();
fail("Should have thrown StreamsException if start up failed");
} catch (final StreamsException e) {
assertThat(e.getCause(), instanceOf(Throwable.class));
assertThat(e.getCause().getMessage(), equalTo(exceptionMessage));
}
globalStreamThread.join();
assertThat(globalStore.isOpen(), is(false));
assertFalse(globalStreamThread.stillRunning());
}
private HashMap<String, Object> getStreamProperties() {
final HashMap<String, Object> properties = new HashMap<>();
properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "blah");
properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "testAppId");
properties.put(StreamsConfig.STATE_DIR_CONFIG, baseDirectoryName);
properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.ByteArraySerde.class.getName());
properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.ByteArraySerde.class.getName());
return properties;
}
private void initializeConsumer() {
mockConsumer.updatePartitions(
GLOBAL_STORE_TOPIC_NAME,
Collections.singletonList(new PartitionInfo(
GLOBAL_STORE_TOPIC_NAME,
0,
null,
new Node[0],
new Node[0])));
mockConsumer.updateBeginningOffsets(Collections.singletonMap(topicPartition, 0L));
mockConsumer.updateEndOffsets(Collections.singletonMap(topicPartition, 0L));
mockConsumer.assign(Collections.singleton(topicPartition));
}
private void startAndSwallowError() {
try {
globalStreamThread.start();
} catch (final IllegalStateException ignored) {
}
}
}
| GlobalStreamThreadTest |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/EsqlBaseParser.java | {
"start": 261621,
"end": 262558
} | class ____ extends ConstantContext {
public TerminalNode NULL() { return getToken(EsqlBaseParser.NULL, 0); }
@SuppressWarnings("this-escape")
public NullLiteralContext(ConstantContext ctx) { copyFrom(ctx); }
@Override
public void enterRule(ParseTreeListener listener) {
if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).enterNullLiteral(this);
}
@Override
public void exitRule(ParseTreeListener listener) {
if ( listener instanceof EsqlBaseParserListener ) ((EsqlBaseParserListener)listener).exitNullLiteral(this);
}
@Override
public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
if ( visitor instanceof EsqlBaseParserVisitor ) return ((EsqlBaseParserVisitor<? extends T>)visitor).visitNullLiteral(this);
else return visitor.visitChildren(this);
}
}
@SuppressWarnings("CheckReturnValue")
public static | NullLiteralContext |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joincolumn/embedded/StringToCharArrayInEmbeddedJoinColumnTest.java | {
"start": 1203,
"end": 2764
} | class ____ {
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction( session -> {
Vehicle vehicle = new Vehicle();
vehicle.setId( 1L );
vehicle.setCharArrayProp( "2020".toCharArray() );
session.persist( vehicle );
VehicleInvoice invoice = new VehicleInvoice();
invoice.setId( new VehicleInvoiceId( "2020", 2020 ) );
invoice.setVehicle( vehicle );
vehicle.getInvoices().add( invoice );
session.persist( invoice );
} );
}
@AfterAll
public void tearDown(SessionFactoryScope scope) {
scope.inTransaction( session -> {
session.createMutationQuery( "delete from VehicleInvoice" ).executeUpdate();
session.createMutationQuery( "delete from Vehicle" ).executeUpdate();
} );
}
@Test
public void testAssociation(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final VehicleInvoice vehicleInvoice = session.createQuery(
"from VehicleInvoice",
VehicleInvoice.class
).getSingleResult();
assertEquals( 1L, vehicleInvoice.getVehicle().getId() );
assertEquals( "2020", new String( vehicleInvoice.getVehicle().getCharArrayProp() ) );
} );
}
@Test
public void testInverse(SessionFactoryScope scope) {
scope.inTransaction( session -> {
final Vehicle vehicle = session.createQuery(
"from Vehicle",
Vehicle.class
).getSingleResult();
assertEquals( 1, vehicle.getInvoices().size() );
assertEquals( "2020", vehicle.getInvoices().get( 0 ).getId().getStringProp() );
} );
}
@Embeddable
public static | StringToCharArrayInEmbeddedJoinColumnTest |
java | apache__flink | flink-core/src/test/java/org/apache/flink/testutils/serialization/types/AsciiStringType.java | {
"start": 1084,
"end": 2428
} | class ____ implements SerializationTestType {
private static final int MAX_LEN = 1500;
public String value;
public AsciiStringType() {
this.value = "";
}
private AsciiStringType(String value) {
this.value = value;
}
@Override
public AsciiStringType getRandom(Random rnd) {
final StringBuilder bld = new StringBuilder();
final int len = rnd.nextInt(MAX_LEN + 1);
for (int i = 0; i < len; i++) {
// 1--127
bld.append((char) (rnd.nextInt(126) + 1));
}
return new AsciiStringType(bld.toString());
}
@Override
public int length() {
return value.getBytes(ConfigConstants.DEFAULT_CHARSET).length + 2;
}
@Override
public void write(DataOutputView out) throws IOException {
out.writeUTF(this.value);
}
@Override
public void read(DataInputView in) throws IOException {
this.value = in.readUTF();
}
@Override
public int hashCode() {
return this.value.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AsciiStringType) {
AsciiStringType other = (AsciiStringType) obj;
return this.value.equals(other.value);
} else {
return false;
}
}
}
| AsciiStringType |
java | apache__camel | components/camel-aws/camel-aws-bedrock/src/main/java/org/apache/camel/component/aws2/bedrock/runtime/stream/ClaudeStreamParser.java | {
"start": 1680,
"end": 4224
} | class ____ implements StreamResponseParser {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override
public String extractText(String chunk) throws JsonProcessingException {
if (chunk == null || chunk.trim().isEmpty()) {
return "";
}
JsonNode node = MAPPER.readTree(chunk);
JsonNode type = node.get("type");
if (type != null && "content_block_delta".equals(type.asText())) {
JsonNode delta = node.get("delta");
if (delta != null) {
JsonNode deltaType = delta.get("type");
if (deltaType != null && "text_delta".equals(deltaType.asText())) {
JsonNode text = delta.get("text");
return text != null && !text.isNull() ? text.asText() : "";
}
}
}
return "";
}
@Override
public String extractCompletionReason(String chunk) throws JsonProcessingException {
if (chunk == null || chunk.trim().isEmpty()) {
return null;
}
JsonNode node = MAPPER.readTree(chunk);
JsonNode type = node.get("type");
if (type != null && "message_delta".equals(type.asText())) {
JsonNode delta = node.get("delta");
if (delta != null) {
JsonNode stopReason = delta.get("stop_reason");
return stopReason != null && !stopReason.isNull() ? stopReason.asText() : null;
}
}
return null;
}
@Override
public Integer extractTokenCount(String chunk) throws JsonProcessingException {
if (chunk == null || chunk.trim().isEmpty()) {
return null;
}
JsonNode node = MAPPER.readTree(chunk);
JsonNode type = node.get("type");
if (type != null && "message_delta".equals(type.asText())) {
JsonNode usage = node.get("usage");
if (usage != null) {
JsonNode outputTokens = usage.get("output_tokens");
return outputTokens != null && !outputTokens.isNull() ? outputTokens.asInt() : null;
}
}
return null;
}
@Override
public boolean isFinalChunk(String chunk) throws JsonProcessingException {
if (chunk == null || chunk.trim().isEmpty()) {
return false;
}
JsonNode node = MAPPER.readTree(chunk);
JsonNode type = node.get("type");
return type != null && "message_stop".equals(type.asText());
}
}
| ClaudeStreamParser |
java | apache__camel | core/camel-management/src/test/java/org/apache/camel/management/TwoManagedNamePatternTest.java | {
"start": 1361,
"end": 2949
} | class ____ extends TestSupport {
private CamelContext camel1;
private CamelContext camel2;
protected CamelContext createCamelContext(String name, String pattern) {
DefaultCamelContext context = new DefaultCamelContext();
context.getCamelContextExtension().setName(name);
context.getManagementNameStrategy().setNamePattern(pattern);
return context;
}
@Test
public void testManagedNamePattern() throws Exception {
camel1 = createCamelContext("foo", "aaa-#name#");
camel2 = createCamelContext("bar", "bbb-#name#");
camel1.start();
camel2.start();
MBeanServer mbeanServer = camel1.getManagementStrategy().getManagementAgent().getMBeanServer();
ObjectName on = ObjectName.getInstance("org.apache.camel:context=aaa-foo,type=context,name=\"foo\"");
assertTrue(mbeanServer.isRegistered(on), "Should be registered");
ObjectName on2 = ObjectName.getInstance("org.apache.camel:context=bbb-bar,type=context,name=\"bar\"");
assertTrue(mbeanServer.isRegistered(on2), "Should be registered");
camel1.stop();
camel2.stop();
assertFalse(mbeanServer.isRegistered(on), "Should be unregistered");
assertFalse(mbeanServer.isRegistered(on2), "Should be unregistered");
}
@Override
@AfterEach
public void tearDown() throws Exception {
if (camel1 != null) {
camel1.stop();
}
if (camel2 != null) {
camel2.stop();
}
super.tearDown();
}
}
| TwoManagedNamePatternTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/internal/BinaryFloatDdlType.java | {
"start": 264,
"end": 906
} | class ____ extends DdlTypeImpl {
//needed for converting precision from decimal to binary digits
private static final double LOG_BASE2OF10 = log(10)/log(2);
public BinaryFloatDdlType(Dialect dialect) {
this( "float($p)", dialect );
}
public BinaryFloatDdlType(String typeNamePattern, Dialect dialect) {
super( SqlTypes.FLOAT, typeNamePattern, dialect );
}
@Override
public String getTypeName(Long size, Integer precision, Integer scale) {
if ( precision != null ) {
return super.getTypeName( size, (int) ( precision / LOG_BASE2OF10 ), scale );
}
return super.getTypeName( size, precision, scale );
}
}
| BinaryFloatDdlType |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSEditLogOp.java | {
"start": 158278,
"end": 162442
} | class ____ extends Reader {
/**
* The minimum length of a length-prefixed Op.
*
* The minimum Op has:
* 1-byte opcode
* 4-byte length
* 8-byte txid
* 0-byte body
* 4-byte checksum
*/
private static final int MIN_OP_LENGTH = 17;
/**
* The op id length.
*
* Not included in the stored length.
*/
private static final int OP_ID_LENGTH = 1;
/**
* The checksum length.
*
* Not included in the stored length.
*/
private static final int CHECKSUM_LENGTH = 4;
private final Checksum checksum;
LengthPrefixedReader(DataInputStream in, StreamLimiter limiter,
int logVersion) {
super(in, limiter, logVersion);
this.checksum = DataChecksum.newCrc32();
}
@Override
public FSEditLogOp decodeOp() throws IOException {
long txid = decodeOpFrame();
if (txid == HdfsServerConstants.INVALID_TXID) {
return null;
}
in.reset();
in.mark(maxOpSize);
FSEditLogOpCodes opCode = FSEditLogOpCodes.fromByte(in.readByte());
FSEditLogOp op = cache.get(opCode);
if (op == null) {
throw new IOException("Read invalid opcode " + opCode);
}
op.setTransactionId(txid);
IOUtils.skipFully(in, 4 + 8); // skip length and txid
op.readFields(in, logVersion);
// skip over the checksum, which we validated above.
IOUtils.skipFully(in, CHECKSUM_LENGTH);
return op;
}
@Override
public long scanOp() throws IOException {
return decodeOpFrame();
}
/**
* Decode the opcode "frame". This includes reading the opcode and
* transaction ID, and validating the checksum and length. It does not
* include reading the opcode-specific fields.
* The input stream will be advanced to the end of the op at the end of this
* function.
*
* @return An op with the txid set, but none of the other fields
* filled in, or null if we hit EOF.
*/
private long decodeOpFrame() throws IOException {
limiter.setLimit(maxOpSize);
in.mark(maxOpSize);
byte opCodeByte;
try {
opCodeByte = in.readByte();
} catch (EOFException eof) {
// EOF at an opcode boundary is expected.
return HdfsServerConstants.INVALID_TXID;
}
if (opCodeByte == FSEditLogOpCodes.OP_INVALID.getOpCode()) {
verifyTerminator();
return HdfsServerConstants.INVALID_TXID;
}
// Here, we verify that the Op size makes sense and that the
// data matches its checksum before attempting to construct an Op.
// This is important because otherwise we may encounter an
// OutOfMemoryException which could bring down the NameNode or
// JournalNode when reading garbage data.
int opLength = in.readInt() + OP_ID_LENGTH + CHECKSUM_LENGTH;
if (opLength > maxOpSize) {
throw new IOException("Op " + (int)opCodeByte + " has size " +
opLength + ", but maxOpSize = " + maxOpSize);
} else if (opLength < MIN_OP_LENGTH) {
throw new IOException("Op " + (int)opCodeByte + " has size " +
opLength + ", but the minimum op size is " + MIN_OP_LENGTH);
}
long txid = in.readLong();
// Verify checksum
in.reset();
in.mark(maxOpSize);
checksum.reset();
for (int rem = opLength - CHECKSUM_LENGTH; rem > 0;) {
int toRead = Math.min(temp.length, rem);
IOUtils.readFully(in, temp, 0, toRead);
checksum.update(temp, 0, toRead);
rem -= toRead;
}
int expectedChecksum = in.readInt();
int calculatedChecksum = (int)checksum.getValue();
if (expectedChecksum != calculatedChecksum) {
throw new ChecksumException(
"Transaction is corrupt. Calculated checksum is " +
calculatedChecksum + " but read checksum " +
expectedChecksum, txid);
}
return txid;
}
}
/**
* Read edit logs which have a checksum and a transaction ID, but not a
* length.
*/
private static | LengthPrefixedReader |
java | apache__camel | components/camel-csimple-joor/src/test/java/org/apache/camel/language/csimple/joor/FooBean.java | {
"start": 859,
"end": 977
} | class ____ {
public String doSomething(String name) {
return "Hi " + name + ". Camel rocks!";
}
}
| FooBean |
java | spring-projects__spring-boot | module/spring-boot-transaction/src/test/java/org/springframework/boot/transaction/autoconfigure/TransactionAutoConfigurationTests.java | {
"start": 8053,
"end": 8251
} | class ____ {
@Bean
PlatformTransactionManager transactionManager() {
return mock(PlatformTransactionManager.class);
}
}
@Configuration
static | SinglePlatformTransactionManagerConfiguration |
java | apache__flink | flink-rpc/flink-rpc-core/src/main/java/org/apache/flink/runtime/rpc/exceptions/FencingTokenException.java | {
"start": 1020,
"end": 1413
} | class ____ extends RpcException {
private static final long serialVersionUID = -500634972988881467L;
public FencingTokenException(String message) {
super(message);
}
public FencingTokenException(String message, Throwable cause) {
super(message, cause);
}
public FencingTokenException(Throwable cause) {
super(cause);
}
}
| FencingTokenException |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/support/AbstractDirtiesContextTestExecutionListener.java | {
"start": 6210,
"end": 6810
} | class ____ required for a context to
* be marked dirty in the current phase; never {@code null}
* @throws Exception allows any exception to propagate
* @since 4.2
* @see #dirtyContext
*/
@SuppressWarnings("NullAway") // Dataflow analysis limitation
protected void beforeOrAfterTestClass(TestContext testContext, ClassMode requiredClassMode) throws Exception {
Assert.notNull(testContext, "TestContext must not be null");
Assert.notNull(requiredClassMode, "requiredClassMode must not be null");
Class<?> testClass = testContext.getTestClass();
Assert.notNull(testClass, "The test | mode |
java | processing__processing4 | core/src/processing/data/XML.java | {
"start": 1641,
"end": 1859
} | class ____ for the Processing XML library,
* representing a single node of an <b>XML</b> tree
* @see PApplet#loadXML(String)
* @see PApplet#parseXML(String)
* @see PApplet#saveXML(XML, String)
*/
public | used |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/io/CheckpointableInputFormat.java | {
"start": 1266,
"end": 2457
} | interface ____<S extends InputSplit, T extends Serializable> {
/**
* Returns the split currently being read, along with its current state. This will be used to
* restore the state of the reading channel when recovering from a task failure. In the case of
* a simple text file, the state can correspond to the last read offset in the split.
*
* @return The state of the channel.
* @throws IOException Thrown if the creation of the state object failed.
*/
T getCurrentState() throws IOException;
/**
* Restores the state of a parallel instance reading from an {@link InputFormat}. This is
* necessary when recovering from a task failure. When this method is called, the input format
* it guaranteed to be configured.
*
* <p><b>NOTE: </b> The caller has to make sure that the provided split is the one to whom the
* state belongs.
*
* @param split The split to be opened.
* @param state The state from which to start from. This can contain the offset, but also other
* data, depending on the input format.
*/
void reopen(S split, T state) throws IOException;
}
| CheckpointableInputFormat |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/operators/drivers/GatheringCollector.java | {
"start": 1021,
"end": 1555
} | class ____<T> implements Collector<T> {
private final List<T> list = new ArrayList<T>();
private final TypeSerializer<T> serializer;
public GatheringCollector(TypeSerializer<T> serializer) {
this.serializer = serializer;
}
public List<T> getList() {
return list;
}
@Override
public void collect(T record) {
T copy = this.serializer.createInstance();
this.list.add(this.serializer.copy(record, copy));
}
@Override
public void close() {}
}
| GatheringCollector |
java | spring-projects__spring-boot | module/spring-boot-data-mongodb-test/src/dockerTest/java/org/springframework/boot/data/mongodb/test/autoconfigure/ExampleReactiveRepository.java | {
"start": 893,
"end": 991
} | interface ____ extends ReactiveMongoRepository<ExampleDocument, String> {
}
| ExampleReactiveRepository |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/load/engine/bitmap_recycle/ArrayPool.java | {
"start": 1039,
"end": 1405
} | class ____ no guarantees about the contents of the returned array.
*
* @see #getExact(int, Class)
*/
<T> T get(int size, Class<T> arrayClass);
/**
* Returns a non-null array of the given type with a length exactly equal to the given size.
*
* <p>If an array of the given size isn't in the pool, a new one will be allocated.
*
* <p>This | makes |
java | spring-projects__spring-boot | module/spring-boot-jdbc/src/test/java/org/springframework/boot/jdbc/metrics/DataSourcePoolMetricsTests.java | {
"start": 2185,
"end": 2479
} | class ____ {
DataSourceConfig(DataSource dataSource, Collection<DataSourcePoolMetadataProvider> metadataProviders,
MeterRegistry registry) {
new DataSourcePoolMetrics(dataSource, metadataProviders, "data.source", Collections.emptyList())
.bindTo(registry);
}
}
}
| DataSourceConfig |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/NetworkClient.java | {
"start": 61578,
"end": 61925
} | class ____ {
public final int requestVersion;
public final boolean isPartialUpdate;
private InProgressData(int requestVersion, boolean isPartialUpdate) {
this.requestVersion = requestVersion;
this.isPartialUpdate = isPartialUpdate;
}
}
}
| InProgressData |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/config/builder/api/ComponentBuilder.java | {
"start": 1185,
"end": 3140
} | interface ____<T extends ComponentBuilder<T>> extends Builder<Component> {
/**
* Adds a String attribute.
* @param key The attribute key.
* @param value The value of the attribute.
* @return This ComponentBuilder.
*/
T addAttribute(String key, String value);
/**
* Adds a logging Level attribute.
* @param key The attribute key.
* @param level The logging Level.
* @return This ComponentBuilder.
*/
T addAttribute(String key, Level level);
/**
* Adds an enumeration attribute.
* @param key The attribute key.
* @param value The enumeration.
* @return This ComponentBuilder.
*/
T addAttribute(String key, Enum<?> value);
/**
* Adds an integer attribute.
* @param key The attribute key.
* @param value The integer value.
* @return This ComponentBuilder.
*/
T addAttribute(String key, int value);
/**
* Adds a boolean attribute.
* @param key The attribute key.
* @param value The boolean value.
* @return This ComponentBuilder.
*/
T addAttribute(String key, boolean value);
/**
* Adds an Object attribute.
* @param key The attribute key.
* @param value The object value.
* @return This ComponentBuilder.
*/
T addAttribute(String key, Object value);
/**
* Adds a sub component.
* @param builder The Assembler for the subcomponent with all of its attributes and sub-components set.
* @return This ComponentBuilder (<em>not</em> the argument).
*/
T addComponent(ComponentBuilder<?> builder);
/**
* Returns the name of the component, if any.
* @return The component's name or null if it doesn't have one.
*/
String getName();
/**
* Retrieves the ConfigurationBuilder.
* @return The ConfigurationBuilder.
*/
ConfigurationBuilder<? extends Configuration> getBuilder();
}
| ComponentBuilder |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionPropertyHolder.java | {
"start": 1630,
"end": 8192
} | class ____ extends AbstractPropertyHolder {
private final Collection collection;
// assume true, the constructor will opt out where appropriate
private boolean canElementBeConverted = true;
private boolean canKeyBeConverted = true;
private final Map<String,AttributeConversionInfo> elementAttributeConversionInfoMap;
private final Map<String,AttributeConversionInfo> keyAttributeConversionInfoMap;
public CollectionPropertyHolder(
Collection collection,
String path,
ClassDetails clazzToProcess,
MemberDetails property,
PropertyHolder parentPropertyHolder,
MetadataBuildingContext context) {
super( path, parentPropertyHolder, clazzToProcess, context );
this.collection = collection;
setCurrentProperty( property );
this.elementAttributeConversionInfoMap = new HashMap<>();
this.keyAttributeConversionInfoMap = new HashMap<>();
}
public Collection getCollectionBinding() {
return collection;
}
private void buildAttributeConversionInfoMaps(
MemberDetails collectionProperty,
boolean isComposite,
Map<String,AttributeConversionInfo> elementAttributeConversionInfoMap,
Map<String,AttributeConversionInfo> keyAttributeConversionInfoMap) {
collectionProperty.forEachAnnotationUsage( Convert.class, getSourceModelContext(),
usage -> applyLocalConvert(
usage,
collectionProperty,
isComposite,
elementAttributeConversionInfoMap,
keyAttributeConversionInfoMap
) );
}
private void applyLocalConvert(
Convert convertAnnotation,
MemberDetails collectionProperty,
boolean isComposite,
Map<String,AttributeConversionInfo> elementAttributeConversionInfoMap,
Map<String,AttributeConversionInfo> keyAttributeConversionInfoMap) {
// IMPL NOTE: the rules here are quite more lenient than what JPA says. For example, JPA says that @Convert
// on a Map of basic types should default to "value" but it should explicitly specify 'attributeName' of "key"
// (or prefixed with "key." for embedded paths) to be applied on the key. However, we try to see if conversion
// of either is disabled for whatever reason. For example, if the Map is annotated with @Enumerated, the
// elements cannot be converted, and so any @Convert likely meant the key, so we apply it to the key
final var info = new AttributeConversionInfo( convertAnnotation, collectionProperty );
final String attributeName = info.getAttributeName();
if ( collection.isMap() ) {
logSpecNoncompliance( attributeName, collection.getRole() );
}
if ( isEmpty( attributeName ) ) {
// the @Convert did not name an attribute...
if ( canElementBeConverted && canKeyBeConverted ) {
if ( !isComposite ) {
// if element is of basic type default to "value"
elementAttributeConversionInfoMap.put( "", info );
}
else {
throwMissingAttributeName();
}
}
else if ( canKeyBeConverted ) {
keyAttributeConversionInfoMap.put( "", info );
}
else if ( canElementBeConverted ) {
elementAttributeConversionInfoMap.put( "", info );
}
// if neither, we should not be here...
}
else {
// the @Convert named an attribute...
// we have different "resolution rules" based on whether element and key can be converted
final String keyPath;
final String elementPath;
if ( canElementBeConverted && canKeyBeConverted ) {
keyPath = removePrefix( attributeName, "key" );
elementPath = removePrefix( attributeName, "value" );
if ( keyPath == null && elementPath == null ) {
// specified attributeName needs to have 'key.' or 'value.' prefix
throwMissingAttributeName();
}
}
else if ( canKeyBeConverted ) {
keyPath = removePrefix( attributeName, "key", attributeName );
elementPath = null;
}
else {
keyPath = null;
elementPath = removePrefix( attributeName, "value", attributeName );
}
if ( keyPath != null ) {
keyAttributeConversionInfoMap.put( keyPath, info );
}
else if ( elementPath != null ) {
elementAttributeConversionInfoMap.put( elementPath, info );
}
else {
// specified attributeName needs to have 'key.' or 'value.' prefix
throw new IllegalStateException(
String.format(
Locale.ROOT,
"Could not determine how to apply @Convert(attributeName='%s') to collection [%s]",
attributeName,
collection.getRole()
)
);
}
}
}
private void throwMissingAttributeName() {
throw new IllegalStateException( "'@Convert' annotation for map [" + collection.getRole()
+ "] must specify 'attributeName=\"key\"' or 'attributeName=\"value\"'" );
}
private static void logSpecNoncompliance(String attributeName, String role) {
final boolean specCompliant = isNotEmpty( attributeName )
&& (attributeName.startsWith( "key" ) || attributeName.startsWith( "value" ) );
if ( !specCompliant ) {
BOOT_LOGGER.nonCompliantMapConversion( role );
}
}
/**
* Check if path has the given prefix and remove it.
*
* @param path Path.
* @param prefix Prefix.
* @return Path without prefix, or null, if path did not have the prefix.
*/
private String removePrefix(String path, String prefix) {
return removePrefix( path, prefix, null );
}
private String removePrefix(String path, String prefix, String defaultValue) {
if ( path.equals(prefix) ) {
return "";
}
else if ( path.startsWith(prefix + ".") ) {
return path.substring( prefix.length() + 1 );
}
else {
return defaultValue;
}
}
@Override
protected String normalizeCompositePath(String attributeName) {
return attributeName;
}
@Override
protected String normalizeCompositePathForLogging(String attributeName) {
return collection.getRole() + '.' + attributeName;
}
@Override
public void startingProperty(MemberDetails property) {
// for now, nothing to do...
}
@Override
protected AttributeConversionInfo locateAttributeConversionInfo(MemberDetails attributeMember) {
// nothing to do
return null;
}
@Override
protected AttributeConversionInfo locateAttributeConversionInfo(String path) {
final String key = removePrefix( path, "key" );
if ( key != null ) {
return keyAttributeConversionInfoMap.get( key );
}
final String element = removePrefix( path, "element" );
if ( element != null ) {
return elementAttributeConversionInfoMap.get( element );
}
return elementAttributeConversionInfoMap.get( path );
}
@Override
public String getClassName() {
throw new AssertionFailure( "Collection property holder does not have a | CollectionPropertyHolder |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/core/userdetails/UserDetailsChecker.java | {
"start": 1130,
"end": 1543
} | interface ____ only be used for checks on the persistent
* data associated with the user. It should not involved in making any authentication
* decisions based on a submitted authentication request.
*
* @author Luke Taylor
* @since 2.0
* @see org.springframework.security.authentication.AccountStatusUserDetailsChecker
* @see org.springframework.security.authentication.AccountStatusException
*/
public | should |
java | google__dagger | hilt-compiler/main/java/dagger/hilt/android/processor/internal/bindvalue/KspBindValueProcessor.java | {
"start": 1568,
"end": 1775
} | class ____ implements SymbolProcessorProvider {
@Override
public SymbolProcessor create(SymbolProcessorEnvironment environment) {
return new KspBindValueProcessor(environment);
}
}
}
| Provider |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCodeGenerator.java | {
"start": 1997,
"end": 8314
} | class ____ {
public static final String DEFAULT_EXCEPTION_TERM = "e";
public static final String DEFAULT_DELEGATING_FUTURE_TERM = "f";
/**
* Creates a generated function which produces an {@link AsyncFunction} which executes the calc
* projections.
*
* @param name The name used to generate the underlying function name
* @param inputType The RowType of the input RowData
* @param returnType The RowType of the resulting RowData
* @param retainHeader If the header of the row should be retained
* @param calcProjection The list of projections to be executed by this function
* @param tableConfig The table configuration
* @param classLoader The classloader to use while resolving classes
* @return A {@link GeneratedFunction} returning an {@link AsyncFunction} executing the given
* list of projections
*/
public static GeneratedFunction<AsyncFunction<RowData, RowData>> generateFunction(
String name,
RowType inputType,
RowType returnType,
List<RexNode> calcProjection,
boolean retainHeader,
ReadableConfig tableConfig,
ClassLoader classLoader) {
CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig, classLoader);
String processCode =
generateProcessCode(
ctx,
inputType,
returnType,
calcProjection,
retainHeader,
CodeGenUtils.DEFAULT_INPUT1_TERM(),
CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
DEFAULT_EXCEPTION_TERM,
CodeGenUtils.DEFAULT_OUT_RECORD_TERM(),
DEFAULT_DELEGATING_FUTURE_TERM);
return FunctionCodeGenerator.generateFunction(
ctx,
name,
getFunctionClass(),
processCode,
returnType,
inputType,
CodeGenUtils.DEFAULT_INPUT1_TERM(),
JavaScalaConversionUtil.toScala(Optional.empty()),
JavaScalaConversionUtil.toScala(Optional.empty()),
CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
CodeGenUtils.DEFAULT_CONTEXT_TERM());
}
@SuppressWarnings("unchecked")
private static Class<AsyncFunction<RowData, RowData>> getFunctionClass() {
return (Class<AsyncFunction<RowData, RowData>>) (Object) AsyncFunction.class;
}
private static String generateProcessCode(
CodeGeneratorContext ctx,
RowType inputType,
RowType outRowType,
List<RexNode> projection,
boolean retainHeader,
String inputTerm,
String collectorTerm,
String errorTerm,
String recordTerm,
String delegatingFutureTerm) {
projection.forEach(n -> n.accept(new AsyncScalarFunctionsValidator()));
ExprCodeGenerator exprGenerator =
new ExprCodeGenerator(ctx, false)
.bindInput(
inputType,
inputTerm,
JavaScalaConversionUtil.toScala(Optional.empty()));
List<GeneratedExpression> projectionExprs =
projection.stream()
.map(exprGenerator::generateExpression)
.collect(Collectors.toList());
int index = 0;
StringBuilder metadataInvocations = new StringBuilder();
StringBuilder asyncInvocation = new StringBuilder();
if (retainHeader) {
metadataInvocations.append(
String.format("%s.setRowKind(rowKind);\n", delegatingFutureTerm));
}
for (GeneratedExpression fieldExpr : projectionExprs) {
if (fieldExpr.resultTerm().isEmpty()) {
asyncInvocation.append(fieldExpr.code());
metadataInvocations.append(
String.format("%s.addAsyncIndex(%d);\n", delegatingFutureTerm, index));
} else {
metadataInvocations.append(fieldExpr.code());
metadataInvocations.append(
String.format(
"%s.addSynchronousResult(%d, %s);\n",
delegatingFutureTerm, index, fieldExpr.resultTerm()));
}
index++;
}
Map<String, String> values = new HashMap<>();
values.put("delegatingFutureTerm", delegatingFutureTerm);
values.put("delegatingFutureType", DelegatingAsyncResultFuture.class.getCanonicalName());
values.put("collectorTerm", collectorTerm);
values.put("typeTerm", GenericRowData.class.getCanonicalName());
values.put("recordTerm", recordTerm);
values.put("inputTerm", inputTerm);
values.put("fieldCount", Integer.toString(LogicalTypeChecks.getFieldCount(outRowType)));
values.put("metadataInvocations", metadataInvocations.toString());
values.put("asyncInvocation", asyncInvocation.toString());
values.put("errorTerm", errorTerm);
return StringSubstitutor.replace(
String.join(
"\n",
new String[] {
"final ${delegatingFutureType} ${delegatingFutureTerm} ",
" = new ${delegatingFutureType}(${collectorTerm}, ${fieldCount});",
"final org.apache.flink.types.RowKind rowKind = ${inputTerm}.getRowKind();\n",
"try {",
// Ensure that metadata setup come first so that we know that they're
// available when the async callback occurs.
" ${metadataInvocations}",
" ${asyncInvocation}",
"",
"} catch (Throwable ${errorTerm}) {",
" ${collectorTerm}.completeExceptionally(${errorTerm});",
"}"
}),
values);
}
private static | AsyncCodeGenerator |
java | apache__flink | flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/stream/compact/CompactBulkReader.java | {
"start": 2301,
"end": 3380
} | class ____<T> implements CompactReader.Factory<T> {
private static final long serialVersionUID = 1L;
private final BulkFormat<T, FileSourceSplit> format;
public Factory(BulkFormat<T, FileSourceSplit> format) {
this.format = format;
}
@Override
public CompactReader<T> create(CompactContext context) throws IOException {
final String splitId = UUID.randomUUID().toString();
final FileStatus fileStatus = context.getFileSystem().getFileStatus(context.getPath());
return new CompactBulkReader<>(
format.createReader(
context.getConfig(),
new FileSourceSplit(
splitId,
context.getPath(),
0,
fileStatus.getLen(),
fileStatus.getModificationTime(),
fileStatus.getLen())));
}
}
}
| Factory |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/viewfs/TestFcCreateMkdirLocalFs.java | {
"start": 997,
"end": 1404
} | class ____ extends
FileContextCreateMkdirBaseTest {
@Override
@BeforeEach
public void setUp() throws Exception {
fc = ViewFsTestSetup.setupForViewFsLocalFs(fileContextTestHelper);
super.setUp();
}
@Override
@AfterEach
public void tearDown() throws Exception {
super.tearDown();
ViewFsTestSetup.tearDownForViewFsLocalFs(fileContextTestHelper);
}
} | TestFcCreateMkdirLocalFs |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/optimizer/rules/logical/OptimizerRules.java | {
"start": 4515,
"end": 4854
} | interface ____<SubPlan extends LogicalPlan> {
/**
* the local version of the rule. {@code null} if the rule should not be applied locally.
*/
Rule<SubPlan, LogicalPlan> local();
}
/**
* This rule should only be applied on the coordinator plan, not for a local plan.
*/
public | LocalAware |
java | spring-projects__spring-boot | buildSrc/src/main/java/org/springframework/boot/build/architecture/AutoConfigurationChecker.java | {
"start": 2467,
"end": 4402
} | class ____ {
private static final String SPRING_BOOT_ROOT_PACKAGE = "org.springframework.boot";
private static final String IMPORT = "org.springframework.context.annotation.Import";
private static final String CONFIGURATION = "org.springframework.context.annotation.Configuration";
private final Map<String, JavaClass> classes = new HashMap<>();
void add(JavaClass autoConfiguration) {
if (!autoConfiguration.isMetaAnnotatedWith(CONFIGURATION)) {
return;
}
if (this.classes.putIfAbsent(autoConfiguration.getName(), autoConfiguration) != null) {
return;
}
processImports(autoConfiguration, this.classes);
}
JavaClasses getConfigurations() {
// TODO: Find a way without reflection
Method method = ReflectionUtils.findMethod(JavaClasses.class, "of", Iterable.class);
ReflectionUtils.makeAccessible(method);
return (JavaClasses) ReflectionUtils.invokeMethod(method, null, this.classes.values());
}
private void processImports(JavaClass javaClass, Map<String, JavaClass> result) {
JavaClass[] importedClasses = getImportedClasses(javaClass);
for (JavaClass importedClass : importedClasses) {
if (!isBootClass(importedClass)) {
continue;
}
if (result.putIfAbsent(importedClass.getName(), importedClass) != null) {
continue;
}
// Recursively find other imported classes
processImports(importedClass, result);
}
}
private JavaClass[] getImportedClasses(JavaClass javaClass) {
if (!javaClass.isAnnotatedWith(IMPORT)) {
return new JavaClass[0];
}
JavaAnnotation<JavaClass> imports = javaClass.getAnnotationOfType(IMPORT);
return (JavaClass[]) imports.get("value").orElse(new JavaClass[0]);
}
private boolean isBootClass(JavaClass javaClass) {
String pkg = javaClass.getPackage().getName();
return pkg.equals(SPRING_BOOT_ROOT_PACKAGE) || pkg.startsWith(SPRING_BOOT_ROOT_PACKAGE + ".");
}
}
}
| AutoConfigurations |
java | google__auto | value/src/test/java/com/google/auto/value/processor/AutoBuilderCompilationTest.java | {
"start": 16583,
"end": 16651
} | class ____ {",
" @AutoBuilder",
" abstract | Baz |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/routing/IndexRouting.java | {
"start": 12978,
"end": 13118
} | class ____ strategies that determine the shard by extracting and hashing fields from the document source.
*/
public abstract static | for |
java | micronaut-projects__micronaut-core | http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/forms/UploadTest.java | {
"start": 1751,
"end": 3004
} | class ____ {
private static final String SPEC_NAME = "UploadTest";
@Test
public void inputStream() throws Exception {
Path tmp = Files.createTempFile("UploadTest", ".txt");
try {
Files.writeString(tmp, "foo");
TestScenario.builder()
.specName(SPEC_NAME)
.request(HttpRequest.POST("/upload/input-stream", MultipartBody.builder().addPart("file", tmp.toFile()).build()).contentType(MediaType.MULTIPART_FORM_DATA))
.assertion((server, request) ->
AssertionUtils.assertDoesNotThrow(server, request, HttpResponseAssertion.builder()
.status(HttpStatus.OK)
.assertResponse(httpResponse -> {
Optional<String> bodyOptional = httpResponse.getBody(String.class);
assertTrue(bodyOptional.isPresent());
assertEquals("foo", bodyOptional.get());
})
.build()))
.run();
} finally {
Files.deleteIfExists(tmp);
}
}
@Controller("/upload")
@Requires(property = "spec.name", value = SPEC_NAME)
public static | UploadTest |
java | quarkusio__quarkus | extensions/reactive-mysql-client/deployment/src/test/java/io/quarkus/reactive/mysql/client/ChangingCredentialsProvider.java | {
"start": 195,
"end": 400
} | class ____ extends ChangingCredentialsProviderBase {
public ChangingCredentialsProvider() {
super("hibernate_orm_test", "hibernate_orm_test", "user2", "user2");
}
}
| ChangingCredentialsProvider |
java | apache__logging-log4j2 | log4j-1.2-api/src/main/java/org/apache/log4j/config/PropertiesConfiguration.java | {
"start": 2230,
"end": 7936
} | class ____ extends Log4j1Configuration {
private static final String CATEGORY_PREFIX = "log4j.category.";
private static final String LOGGER_PREFIX = "log4j.logger.";
private static final String ADDITIVITY_PREFIX = "log4j.additivity.";
private static final String ROOT_CATEGORY_PREFIX = "log4j.rootCategory";
private static final String ROOT_LOGGER_PREFIX = "log4j.rootLogger";
private static final String APPENDER_PREFIX = "log4j.appender.";
private static final String LOGGER_REF = "logger-ref";
private static final String ROOT_REF = "root-ref";
private static final String APPENDER_REF_TAG = "appender-ref";
/**
* If property set to true, then hierarchy will be reset before configuration.
*/
private static final String RESET_KEY = "log4j.reset";
public static final String THRESHOLD_KEY = "log4j.threshold";
public static final String DEBUG_KEY = "log4j.debug";
private static final String INTERNAL_ROOT_NAME = "root";
private final Map<String, Appender> registry = new HashMap<>();
private Properties properties;
/**
* Constructs a new instance.
*
* @param loggerContext The LoggerContext.
* @param source The ConfigurationSource.
* @param monitorIntervalSeconds The monitoring interval in seconds.
*/
public PropertiesConfiguration(
final LoggerContext loggerContext, final ConfigurationSource source, final int monitorIntervalSeconds) {
super(loggerContext, source, monitorIntervalSeconds);
}
/**
* Constructs a new instance.
*
* @param loggerContext The LoggerContext.
* @param properties The ConfigurationSource, may be null.
*/
public PropertiesConfiguration(final LoggerContext loggerContext, final Properties properties) {
super(loggerContext, ConfigurationSource.NULL_SOURCE, 0);
this.properties = properties;
}
/**
* Constructs a new instance.
*
* @param loggerContext The LoggerContext.
* @param properties The ConfigurationSource.
*/
public PropertiesConfiguration(org.apache.logging.log4j.spi.LoggerContext loggerContext, Properties properties) {
this((LoggerContext) loggerContext, properties);
}
@Override
public void doConfigure() {
if (properties == null) {
properties = new Properties();
final InputStream inputStream = getConfigurationSource().getInputStream();
if (inputStream != null) {
try {
properties.load(inputStream);
} catch (final Exception e) {
LOGGER.error(
"Could not read configuration file [{}].",
getConfigurationSource().toString(),
e);
return;
}
}
}
// If we reach here, then the config file is alright.
doConfigure(properties);
}
@Override
public Configuration reconfigure() {
try {
final ConfigurationSource source = getConfigurationSource().resetInputStream();
if (source == null) {
return null;
}
final Configuration config =
new PropertiesConfigurationFactory().getConfiguration(getLoggerContext(), source);
return config == null || config.getState() != State.INITIALIZING ? null : config;
} catch (final IOException ex) {
LOGGER.error("Cannot locate file {}: {}", getConfigurationSource(), ex);
}
return null;
}
/**
* Reads a configuration from a file. <b>The existing configuration is not cleared nor reset.</b> If you require a
* different behavior, then call {@link LogManager#resetConfiguration resetConfiguration} method before calling
* <code>doConfigure</code>.
* <p>
* The configuration file consists of statements in the format <code>key=value</code>. The syntax of different
* configuration elements are discussed below.
* </p>
* <p>
* The level value can consist of the string values OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL or a <em>custom level</em>
* value. A custom level value can be specified in the form level#classname. By default the repository-wide threshold is
* set to the lowest possible value, namely the level <code>ALL</code>.
* </p>
*
* <h3>Appender configuration</h3>
* <p>
* Appender configuration syntax is:
* </p>
* <pre>
* # For appender named <i>appenderName</i>, set its class.
* # Note: The appender name can contain dots.
* log4j.appender.appenderName=fully.qualified.name.of.appender.class
*
* # Set appender specific options.
* log4j.appender.appenderName.option1=value1
* ...
* log4j.appender.appenderName.optionN=valueN
* </pre>
* <p>
* For each named appender you can configure its {@link Layout}. The syntax for configuring an appender's layout is:
* </p>
* <pre>
* log4j.appender.appenderName.layout=fully.qualified.name.of.layout.class
* log4j.appender.appenderName.layout.option1=value1
* ....
* log4j.appender.appenderName.layout.optionN=valueN
* </pre>
* <p>
* The syntax for adding {@link Filter}s to an appender is:
* </p>
* <pre>
* log4j.appender.appenderName.filter.ID=fully.qualified.name.of.filter.class
* log4j.appender.appenderName.filter.ID.option1=value1
* ...
* log4j.appender.appenderName.filter.ID.optionN=valueN
* </pre>
* <p>
* The first line defines the | PropertiesConfiguration |
java | apache__flink | flink-state-backends/flink-statebackend-rocksdb/src/test/java/org/apache/flink/state/rocksdb/RocksDBAutoCompactionIngestRestoreTest.java | {
"start": 2380,
"end": 7088
} | class ____ {
@TempDir private java.nio.file.Path tempFolder;
private static final int MAX_PARALLELISM = 10;
@Test
public void testAutoCompactionEnabledWithIngestDBRestore() throws Exception {
// Create two subtask snapshots and merge them to trigger the multi-state-handle scenario
// required for reproducing the ingest DB restore path
OperatorSubtaskState operatorSubtaskState =
AbstractStreamOperatorTestHarness.repackageState(
createSubtaskSnapshot(0), createSubtaskSnapshot(1));
OperatorSubtaskState initState =
AbstractStreamOperatorTestHarness.repartitionOperatorState(
operatorSubtaskState, MAX_PARALLELISM, 2, 1, 0);
// Restore with ingest DB mode and verify auto-compaction
try (KeyedOneInputStreamOperatorTestHarness<String, Tuple2<String, String>, String>
harness = createTestHarness(new TestKeyedFunction(), MAX_PARALLELISM, 1, 0)) {
EmbeddedRocksDBStateBackend stateBackend = createStateBackend(true);
harness.setStateBackend(stateBackend);
harness.setCheckpointStorage(
new FileSystemCheckpointStorage(
"file://" + tempFolder.resolve("checkpoint-restore").toAbsolutePath()));
harness.initializeState(initState);
harness.open();
verifyAutoCompactionEnabled(harness);
}
}
private OperatorSubtaskState createSubtaskSnapshot(int subtaskIndex) throws Exception {
try (KeyedOneInputStreamOperatorTestHarness<String, Tuple2<String, String>, String>
harness =
createTestHarness(
new TestKeyedFunction(), MAX_PARALLELISM, 2, subtaskIndex)) {
harness.setStateBackend(createStateBackend(false));
harness.setCheckpointStorage(
new FileSystemCheckpointStorage(
"file://"
+ tempFolder
.resolve("checkpoint-subtask" + subtaskIndex)
.toAbsolutePath()));
harness.open();
// Create an empty snapshot - data content doesn't matter for this test
return harness.snapshot(0, 0);
}
}
private void verifyAutoCompactionEnabled(
KeyedOneInputStreamOperatorTestHarness<String, Tuple2<String, String>, String> harness)
throws Exception {
KeyedStateBackend<String> backend = harness.getOperator().getKeyedStateBackend();
assertThat(backend).isNotNull();
LinkedHashMap<String, RocksDbKvStateInfo> kvStateInformation =
((RocksDBKeyedStateBackend<String>) backend).getKvStateInformation();
assertThat(kvStateInformation).as("kvStateInformation should not be empty").isNotEmpty();
for (RocksDbKvStateInfo stateInfo : kvStateInformation.values()) {
ColumnFamilyHandle handle = stateInfo.columnFamilyHandle;
assertThat(handle).isNotNull();
ColumnFamilyDescriptor descriptor = handle.getDescriptor();
ColumnFamilyOptions options = descriptor.getOptions();
assertThat(options.disableAutoCompactions())
.as(
"Production DB should have auto-compaction enabled for column family: "
+ stateInfo.metaInfo.getName())
.isFalse();
}
}
private KeyedOneInputStreamOperatorTestHarness<String, Tuple2<String, String>, String>
createTestHarness(
TestKeyedFunction keyedFunction,
int maxParallelism,
int parallelism,
int subtaskIndex)
throws Exception {
return new KeyedOneInputStreamOperatorTestHarness<>(
new KeyedProcessOperator<>(keyedFunction),
tuple2 -> tuple2.f0,
BasicTypeInfo.STRING_TYPE_INFO,
maxParallelism,
parallelism,
subtaskIndex);
}
private EmbeddedRocksDBStateBackend createStateBackend(boolean useIngestDbRestoreMode) {
Configuration config = new Configuration();
config.set(RocksDBConfigurableOptions.USE_INGEST_DB_RESTORE_MODE, useIngestDbRestoreMode);
EmbeddedRocksDBStateBackend stateBackend = new EmbeddedRocksDBStateBackend(true);
return stateBackend.configure(config, getClass().getClassLoader());
}
private static | RocksDBAutoCompactionIngestRestoreTest |
java | google__dagger | hilt-compiler/main/java/dagger/hilt/android/processor/internal/bindvalue/BindValueMetadata.java | {
"start": 3135,
"end": 7009
} | class ____ {
abstract XFieldElement fieldElement();
abstract ClassName annotationName();
abstract Optional<XAnnotation> qualifier();
abstract Optional<XAnnotation> mapKey();
abstract Optional<XMethodElement> getterElement();
static BindValueElement create(XElement element) {
ImmutableList<ClassName> bindValues =
BindValueProcessingStep.getBindValueAnnotations(element);
ProcessorErrors.checkState(
bindValues.size() == 1,
element,
"Fields can be annotated with only one of @BindValue, @BindValueIntoMap,"
+ " @BindElementsIntoSet, @BindValueIntoSet. Found: %s",
bindValues.stream().map(m -> "@" + m.simpleName()).collect(toImmutableList()));
ClassName annotationClassName = getOnlyElement(bindValues);
ProcessorErrors.checkState(
XElementKt.isField(element),
element,
"@%s can only be used with fields. Found: %s",
annotationClassName.simpleName(),
XElements.toStableString(element));
XFieldElement field = asField(element);
Optional<XMethodElement> propertyGetter = Optional.ofNullable(field.getGetter());
if (propertyGetter.isPresent()) {
ProcessorErrors.checkState(
!propertyGetter.get().isPrivate(),
field,
"@%s field getter cannot be private. Found: %s",
annotationClassName.simpleName(),
XElements.toStableString(field));
} else {
ProcessorErrors.checkState(
!XElements.isPrivate(field),
field,
"@%s fields cannot be private. Found: %s",
annotationClassName.simpleName(),
XElements.toStableString(field));
}
ProcessorErrors.checkState(
!Processors.isAnnotatedWithInject(field),
field,
"@%s fields cannot be used with @Inject annotation. Found %s",
annotationClassName.simpleName(),
XElements.toStableString(field));
ImmutableList<XAnnotation> qualifiers = Processors.getQualifierAnnotations(field);
ProcessorErrors.checkState(
qualifiers.size() <= 1,
field,
"@%s fields cannot have more than one qualifier. Found %s",
annotationClassName.simpleName(),
qualifiers.stream().map(XAnnotations::toStableString).collect(toImmutableList()));
ImmutableList<XAnnotation> mapKeys = Processors.getMapKeyAnnotations(field);
Optional<XAnnotation> optionalMapKeys;
if (BIND_VALUE_INTO_MAP_ANNOTATIONS.contains(annotationClassName)) {
ProcessorErrors.checkState(
mapKeys.size() == 1,
field,
"@BindValueIntoMap fields must have exactly one @MapKey. Found %s",
mapKeys.stream().map(XAnnotations::toStableString).collect(toImmutableList()));
optionalMapKeys = Optional.of(mapKeys.get(0));
} else {
ProcessorErrors.checkState(
mapKeys.isEmpty(),
field,
"@MapKey can only be used on @BindValueIntoMap fields, not @%s fields",
annotationClassName.simpleName());
optionalMapKeys = Optional.empty();
}
ImmutableList<XAnnotation> scopes = Processors.getScopeAnnotations(field);
ProcessorErrors.checkState(
scopes.isEmpty(),
field,
"@%s fields cannot be scoped. Found %s",
annotationClassName.simpleName(),
scopes.stream().map(XAnnotations::toStableString).collect(toImmutableList()));
return new AutoValue_BindValueMetadata_BindValueElement(
field,
annotationClassName,
qualifiers.isEmpty()
? Optional.<XAnnotation>empty()
: Optional.<XAnnotation>of(qualifiers.get(0)),
optionalMapKeys,
propertyGetter);
}
}
}
| BindValueElement |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/bytecode/internal/bytebuddy/ByteBuddyState.java | {
"start": 5813,
"end": 5882
} | class ____ by ByteBuddy.
*
* @param referenceClass The main | generated |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/node/JsonNodeBigIntegerValueTest.java | {
"start": 492,
"end": 10940
} | class ____
extends NodeTestBase
{
private final JsonNodeFactory NODES = newJsonMapper().getNodeFactory();
// // // bigIntegerValue() tests
@Test
public void bigIntegerValueFromNumberIntOk()
{
// Integer types, byte/short/int/long/BigInteger
_assertBigIntegerValue(BigInteger.ONE, NODES.numberNode((byte) 1));
_assertBigIntegerValue(BigInteger.ONE, NODES.numberNode((short) 1));
_assertBigIntegerValue(BigInteger.ONE, NODES.numberNode(1));
_assertBigIntegerValue(BigInteger.ONE, NODES.numberNode(1L));
_assertBigIntegerValue(BigInteger.ONE, NODES.numberNode(BigInteger.ONE));
}
@Test
public void bigIntegerValueFromNumberFPOk()
{
_assertBigIntegerValue(BigInteger.ONE, NODES.numberNode(1.0f));
_assertBigIntegerValue(bigInt(100_000), NODES.numberNode(100_000.0f));
_assertBigIntegerValue(bigInt(-100_000), NODES.numberNode(-100_000.0f));
_assertBigIntegerValue(BigInteger.ONE, NODES.numberNode(1.0d));
_assertBigIntegerValue(bigInt(100_000_000), NODES.numberNode(100_000_000.0d));
_assertBigIntegerValue(bigInt(-100_000_000), NODES.numberNode(-100_000_000.0d));
_assertBigIntegerValue(BigInteger.ONE,
NODES.numberNode(BigDecimal.valueOf(1.0d)));
_assertBigIntegerValue(bigInt(Long.MIN_VALUE),
NODES.numberNode(new BigDecimal(Long.MIN_VALUE+".0")));
_assertBigIntegerValue(bigInt(Long.MAX_VALUE),
NODES.numberNode(new BigDecimal(Long.MAX_VALUE+".0")));
}
// NOTE: BigInteger has unlimited range so cannot fail for Under-/Overflow (hence no tests)
// ... but there are NaNs:
@Test
public void bigIntegerValueFromNumberFPFailForNaN()
{
_assertFailBigIntegerForNaN(NODES.numberNode(Float.NaN));
_assertFailBigIntegerForNaN(NODES.numberNode(Float.NEGATIVE_INFINITY));
_assertFailBigIntegerForNaN(NODES.numberNode(Float.POSITIVE_INFINITY));
_assertFailBigIntegerForNaN(NODES.numberNode(Double.NaN));
_assertFailBigIntegerForNaN(NODES.numberNode(Double.NEGATIVE_INFINITY));
_assertFailBigIntegerForNaN(NODES.numberNode(Double.POSITIVE_INFINITY));
}
@Test
public void bigIntegerValueFromNumberFPFailFraction()
{
_assertFailBigIntegerValueForFraction(NODES.numberNode(100.5f));
_assertFailBigIntegerValueForFraction(NODES.numberNode(-0.25f));
_assertFailBigIntegerValueForFraction(NODES.numberNode(100.5d));
_assertFailBigIntegerValueForFraction(NODES.numberNode(-0.25d));
_assertFailBigIntegerValueForFraction(NODES.numberNode(BigDecimal.valueOf(100.5d)));
_assertFailBigIntegerValueForFraction(NODES.numberNode(BigDecimal.valueOf(-0.25d)));
}
@Test
public void bigIntegerValueFromNonNumberScalarFail()
{
_assertFailBigIntegerForNonNumber(NODES.booleanNode(true));
_assertFailBigIntegerForNonNumber(NODES.binaryNode(new byte[3]));
_assertFailBigIntegerForNonNumber(NODES.stringNode("123"));
_assertFailBigIntegerForNonNumber(NODES.rawValueNode(new RawValue("abc")));
_assertFailBigIntegerForNonNumber(NODES.pojoNode(Boolean.TRUE));
}
@Test
public void bigIntegerValueFromStructuralFail()
{
_assertFailBigIntegerForNonNumber(NODES.arrayNode(3));
_assertFailBigIntegerForNonNumber(NODES.objectNode());
}
@Test
public void bigIntegerValueFromMiscOtherFail()
{
_assertFailBigIntegerForNonNumber(NODES.nullNode());
_assertFailBigIntegerForNonNumber(NODES.missingNode());
}
// // // asBigInteger()
// // // BigInteger + bigIntegerValue()
@Test
public void asBigIntegerFromNumberIntOk()
{
// Integer types, byte/short/int/long/BigInteger
_assertAsBigInteger(BigInteger.ONE, NODES.numberNode((byte) 1));
_assertAsBigInteger(BigInteger.ONE, NODES.numberNode((short) 1));
_assertAsBigInteger(BigInteger.ONE, NODES.numberNode(1));
_assertAsBigInteger(BigInteger.ONE, NODES.numberNode(1L));
_assertAsBigInteger(BigInteger.ONE, NODES.numberNode(BigInteger.ONE));
}
// NOTE: BigInteger has unlimited range so cannot fail for Under-/Overflow (hence no tests)
@Test
public void asBigIntegerFromNumberFPOk()
{
_assertAsBigInteger(BigInteger.ONE, NODES.numberNode(1.0f));
_assertAsBigInteger(bigInt(100_000), NODES.numberNode(100_000.0f));
_assertAsBigInteger(bigInt(-100_000), NODES.numberNode(-100_000.0f));
_assertAsBigInteger(BigInteger.ONE, NODES.numberNode(1.0d));
_assertAsBigInteger(bigInt(100_000_000), NODES.numberNode(100_000_000.0d));
_assertAsBigInteger(bigInt(-100_000_000), NODES.numberNode(-100_000_000.0d));
_assertAsBigInteger(BigInteger.ONE,
NODES.numberNode(BigDecimal.valueOf(1.0d)));
_assertAsBigInteger(bigInt(Long.MIN_VALUE),
NODES.numberNode(new BigDecimal(Long.MIN_VALUE+".0")));
_assertAsBigInteger(bigInt(Long.MAX_VALUE),
NODES.numberNode(new BigDecimal(Long.MAX_VALUE+".0")));
}
// NOTE: unlike with "bigIntegerValue()", fractions ok: will be rounded
@Test
public void asBigIntegerFromNumberFPFraction()
{
final BigInteger B100 = bigInt(100);
final BigInteger B_MINUS_1 = bigInt(-1);
_assertAsBigInteger(B100, NODES.numberNode(100.75f));
_assertAsBigInteger(B_MINUS_1, NODES.numberNode(-1.25f));
_assertAsBigInteger(B100, NODES.numberNode(100.75d));
_assertAsBigInteger(B_MINUS_1, NODES.numberNode(-1.25d));
_assertAsBigInteger(B100, NODES.numberNode(BigDecimal.valueOf(100.75d)));
_assertAsBigInteger(B_MINUS_1, NODES.numberNode(BigDecimal.valueOf(-1.25d)));
}
@Test
public void asBigIntegerFromNonNumberScalar()
{
// First failing cases
_assertAsBigIntegerFailForNonNumber(NODES.binaryNode(new byte[3]));
_assertAsBigIntegerFailForNonNumber(NODES.booleanNode(true));
_assertAsBigIntegerFailForNonNumber(NODES.rawValueNode(new RawValue("abc")));
_assertAsBigIntegerFailForNonNumber(NODES.pojoNode(Boolean.TRUE));
_assertAsBigIntegerFailForNonNumber(NODES.stringNode("E000"),
"not valid String representation of `BigInteger`");
// Then passing
_assertAsBigInteger(BigInteger.TEN, NODES.pojoNode(BigInteger.TEN));
_assertAsBigInteger(BigInteger.TEN, NODES.pojoNode(Integer.valueOf(10)));
_assertAsBigInteger(BigInteger.TEN, NODES.pojoNode(Long.valueOf(10)));
_assertAsBigInteger(BigInteger.TEN, NODES.stringNode("10"));
_assertAsBigInteger(BigInteger.valueOf(-99), NODES.stringNode("-99"));
}
@Test
public void asBigIntegerFromStructuralFail()
{
_assertAsBigIntegerFailForNonNumber(NODES.arrayNode(3));
_assertAsBigIntegerFailForNonNumber(NODES.objectNode());
}
@Test
public void asBigIntegerFromMiscOther()
{
// NullNode becomes 0, not fail
_assertAsBigInteger(BigInteger.ZERO, NODES.nullNode());
// But MissingNode still fails
_assertAsBigIntegerFailForNonNumber(NODES.missingNode());
}
// // // Shared helper methods
private void _assertBigIntegerValue(BigInteger expected, JsonNode node) {
assertEquals(expected, node.bigIntegerValue());
// and then defaulting
assertEquals(expected, node.bigIntegerValue(BigInteger.valueOf(9999999L)));
assertEquals(expected, node.bigIntegerValueOpt().get());
}
private void _assertFailBigIntegerValueForFraction(JsonNode node) {
Exception e = assertThrows(JsonNodeException.class,
() -> node.bigIntegerValue(),
"For ("+node.getClass().getSimpleName()+") value: "+node);
assertThat(e.getMessage())
.contains("cannot convert value")
.contains("to `java.math.BigInteger`: value has fractional part");
// Verify default value handling
assertEquals(BigInteger.ONE, node.bigIntegerValue(BigInteger.ONE));
assertFalse(node.bigIntegerValueOpt().isPresent());
}
private void _assertFailBigIntegerForNonNumber(JsonNode node) {
Exception e = assertThrows(JsonNodeException.class,
() -> node.bigIntegerValue(),
"For ("+node.getClass().getSimpleName()+") value: "+node);
assertThat(e.getMessage())
.contains("cannot convert value")
.contains("value type not numeric");
// Verify default value handling
assertEquals(BigInteger.ONE, node.bigIntegerValue(BigInteger.ONE));
assertFalse(node.bigIntegerValueOpt().isPresent());
}
private void _assertFailBigIntegerForNaN(JsonNode node) {
Exception e = assertThrows(JsonNodeException.class,
() -> node.bigIntegerValue(),
"For ("+node.getClass().getSimpleName()+") value: "+node);
assertThat(e.getMessage())
.contains("cannot convert value")
.contains("value non-Finite ('NaN')");
// Verify default value handling
assertEquals(BigInteger.ONE, node.bigIntegerValue(BigInteger.ONE));
assertFalse(node.bigIntegerValueOpt().isPresent());
}
private void _assertAsBigInteger(BigInteger expected, JsonNode node) {
assertEquals(expected, node.asBigInteger());
// and then defaulting
assertEquals(expected, node.asBigInteger(BigInteger.valueOf(9999999L)));
assertEquals(expected, node.asBigIntegerOpt().get());
}
private void _assertAsBigIntegerFailForNonNumber(JsonNode node) {
_assertAsBigIntegerFailForNonNumber(node, "value type not numeric");
}
private void _assertAsBigIntegerFailForNonNumber(JsonNode node, String extraMsg) {
Exception e = assertThrows(JsonNodeException.class,
() -> node.asBigInteger(),
"For ("+node.getClass().getSimpleName()+") value: "+node);
assertThat(e.getMessage())
.contains("cannot convert value");
// Verify default value handling
assertEquals(BigInteger.ONE, node.asBigInteger(BigInteger.ONE));
assertFalse(node.asBigIntegerOpt().isPresent());
}
}
| JsonNodeBigIntegerValueTest |
java | mockito__mockito | mockito-core/src/main/java/org/mockito/internal/util/collections/HashCodeAndEqualsMockWrapper.java | {
"start": 760,
"end": 2107
} | class ____ {
private final Object mockInstance;
public HashCodeAndEqualsMockWrapper(Object mockInstance) {
this.mockInstance = mockInstance;
}
public Object get() {
return mockInstance;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof HashCodeAndEqualsMockWrapper)) {
return false;
}
HashCodeAndEqualsMockWrapper that = (HashCodeAndEqualsMockWrapper) o;
return mockInstance == that.mockInstance;
}
@Override
public int hashCode() {
return System.identityHashCode(mockInstance);
}
public static HashCodeAndEqualsMockWrapper of(Object mock) {
return new HashCodeAndEqualsMockWrapper(mock);
}
@Override
public String toString() {
return "HashCodeAndEqualsMockWrapper{"
+ "mockInstance="
+ (MockUtil.isMock(mockInstance)
? MockUtil.getMockName(mockInstance)
: typeInstanceString())
+ '}';
}
private String typeInstanceString() {
return mockInstance.getClass().getSimpleName()
+ "("
+ System.identityHashCode(mockInstance)
+ ")";
}
}
| HashCodeAndEqualsMockWrapper |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/schedulers/Schedulers.java | {
"start": 3492,
"end": 3611
} | class ____ {
static final Scheduler DEFAULT = new ComputationScheduler();
}
static final | ComputationHolder |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapreduce/TestMapCollection.java | {
"start": 1698,
"end": 3619
} | class ____ implements Writable, Configurable {
private int len;
protected boolean disableRead;
private byte[] b;
private final Random r;
protected final byte fillChar;
public FillWritable(byte fillChar) {
this.fillChar = fillChar;
r = new Random();
final long seed = r.nextLong();
LOG.info("seed: " + seed);
r.setSeed(seed);
}
@Override
public Configuration getConf() {
return null;
}
public void setLength(int len) {
this.len = len;
}
public int compareTo(FillWritable o) {
if (o == this) return 0;
return len - o.len;
}
@Override
public int hashCode() {
return 37 * len;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof FillWritable)) return false;
return 0 == compareTo((FillWritable)o);
}
@Override
public void readFields(DataInput in) throws IOException {
if (disableRead) {
return;
}
len = WritableUtils.readVInt(in);
for (int i = 0; i < len; ++i) {
assertEquals(fillChar, in.readByte(), "Invalid byte at " + i);
}
}
@Override
public void write(DataOutput out) throws IOException {
if (0 == len) {
return;
}
int written = 0;
if (!disableRead) {
WritableUtils.writeVInt(out, len);
written -= WritableUtils.getVIntSize(len);
}
if (len > 1024) {
if (null == b || b.length < len) {
b = new byte[2 * len];
}
Arrays.fill(b, fillChar);
do {
final int write = Math.min(len - written, r.nextInt(len));
out.write(b, 0, write);
written += write;
} while (written < len);
assertEquals(len, written);
} else {
for (int i = written; i < len; ++i) {
out.write(fillChar);
}
}
}
}
public static | FillWritable |
java | apache__rocketmq | client/src/test/java/org/apache/rocketmq/client/impl/consumer/PullAPIWrapperTest.java | {
"start": 3409,
"end": 10813
} | class ____ {
@Mock
private MQClientInstance mQClientFactory;
@Mock
private MQClientAPIImpl mqClientAPIImpl;
private PullAPIWrapper pullAPIWrapper;
private final String defaultGroup = "defaultGroup";
private final String defaultBroker = "defaultBroker";
private final String defaultTopic = "defaultTopic";
private final String defaultBrokerAddr = "127.0.0.1:10911";
private final long defaultTimeout = 3000L;
@Before
public void init() throws Exception {
ClientConfig clientConfig = mock(ClientConfig.class);
when(mQClientFactory.getClientConfig()).thenReturn(clientConfig);
MQClientAPIImpl mqClientAPIImpl = mock(MQClientAPIImpl.class);
when(mQClientFactory.getMQClientAPIImpl()).thenReturn(mqClientAPIImpl);
when(mQClientFactory.getTopicRouteTable()).thenReturn(createTopicRouteTable());
FindBrokerResult findBrokerResult = mock(FindBrokerResult.class);
when(findBrokerResult.getBrokerAddr()).thenReturn(defaultBrokerAddr);
when(mQClientFactory.findBrokerAddressInSubscribe(any(), anyLong(), anyBoolean())).thenReturn(findBrokerResult);
pullAPIWrapper = new PullAPIWrapper(mQClientFactory, defaultGroup, false);
ArrayList<FilterMessageHook> filterMessageHookList = new ArrayList<>();
filterMessageHookList.add(mock(FilterMessageHook.class));
FieldUtils.writeDeclaredField(pullAPIWrapper, "filterMessageHookList", filterMessageHookList, true);
}
@Test
public void testProcessPullResult() throws Exception {
PullResultExt pullResult = mock(PullResultExt.class);
when(pullResult.getPullStatus()).thenReturn(PullStatus.FOUND);
when(pullResult.getMessageBinary()).thenReturn(MessageDecoder.encode(createMessageExt(), false));
SubscriptionData subscriptionData = mock(SubscriptionData.class);
PullResult actual = pullAPIWrapper.processPullResult(createMessageQueue(), pullResult, subscriptionData);
assertNotNull(actual);
assertEquals(0, actual.getNextBeginOffset());
assertEquals(0, actual.getMsgFoundList().size());
}
@Test
public void testExecuteHook() throws IllegalAccessException {
FilterMessageContext filterMessageContext = mock(FilterMessageContext.class);
ArrayList<FilterMessageHook> filterMessageHookList = new ArrayList<>();
FilterMessageHook filterMessageHook = mock(FilterMessageHook.class);
filterMessageHookList.add(filterMessageHook);
FieldUtils.writeDeclaredField(pullAPIWrapper, "filterMessageHookList", filterMessageHookList, true);
pullAPIWrapper.executeHook(filterMessageContext);
verify(filterMessageHook, times(1)).filterMessage(any(FilterMessageContext.class));
}
@Test
public void testPullKernelImpl() throws Exception {
PullCallback pullCallback = mock(PullCallback.class);
when(mQClientFactory.getMQClientAPIImpl()).thenReturn(mqClientAPIImpl);
PullResult actual = pullAPIWrapper.pullKernelImpl(createMessageQueue(),
"",
"",
1L,
1L,
1,
1,
PullSysFlag.buildSysFlag(false, false, false, true),
1L,
System.currentTimeMillis(),
defaultTimeout, CommunicationMode.ASYNC, pullCallback);
assertNull(actual);
verify(mqClientAPIImpl, times(1)).pullMessage(eq(defaultBroker),
any(PullMessageRequestHeader.class),
eq(defaultTimeout),
any(CommunicationMode.class),
any(PullCallback.class));
}
@Test
public void testSetConnectBrokerByUser() {
pullAPIWrapper.setConnectBrokerByUser(true);
assertTrue(pullAPIWrapper.isConnectBrokerByUser());
}
@Test
public void testRandomNum() {
int randomNum = pullAPIWrapper.randomNum();
assertTrue(randomNum > 0);
}
@Test
public void testSetDefaultBrokerId() {
pullAPIWrapper.setDefaultBrokerId(MixAll.MASTER_ID);
assertEquals(MixAll.MASTER_ID, pullAPIWrapper.getDefaultBrokerId());
}
@Test
public void testPopAsync() throws RemotingException, InterruptedException, MQClientException {
PopCallback popCallback = mock(PopCallback.class);
when(mQClientFactory.getMQClientAPIImpl()).thenReturn(mqClientAPIImpl);
pullAPIWrapper.popAsync(createMessageQueue(),
System.currentTimeMillis(),
1,
defaultGroup,
defaultTimeout,
popCallback,
true,
1,
false,
"",
"");
verify(mqClientAPIImpl, times(1)).popMessageAsync(eq(defaultBroker),
eq(defaultBrokerAddr),
any(PopMessageRequestHeader.class),
eq(13000L),
any(PopCallback.class));
}
private ConcurrentMap<String, TopicRouteData> createTopicRouteTable() {
TopicRouteData topicRouteData = new TopicRouteData();
List<BrokerData> brokerDatas = new ArrayList<>();
BrokerData brokerData = new BrokerData();
brokerData.setBrokerName(defaultBroker);
HashMap<Long, String> brokerAddrs = new HashMap<>();
brokerAddrs.put(MixAll.MASTER_ID, defaultBroker);
brokerData.setBrokerAddrs(brokerAddrs);
brokerDatas.add(brokerData);
topicRouteData.setBrokerDatas(brokerDatas);
HashMap<String, List<String>> filterServerTable = new HashMap<>();
List<String> filterServers = new ArrayList<>();
filterServers.add(defaultBroker);
filterServerTable.put(defaultBrokerAddr, filterServers);
topicRouteData.setFilterServerTable(filterServerTable);
ConcurrentMap<String, TopicRouteData> result = new ConcurrentHashMap<>();
result.put(defaultTopic, topicRouteData);
return result;
}
private MessageQueue createMessageQueue() {
MessageQueue result = new MessageQueue();
result.setQueueId(0);
result.setBrokerName(defaultBroker);
result.setTopic(defaultTopic);
return result;
}
private MessageExt createMessageExt() {
MessageExt result = new MessageExt();
result.setBody("body".getBytes(StandardCharsets.UTF_8));
result.setTopic(defaultTopic);
result.setBrokerName(defaultBroker);
result.putUserProperty("key", "value");
result.getProperties().put(MessageConst.PROPERTY_PRODUCER_GROUP, defaultGroup);
result.getProperties().put(MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX, "TX1");
long curTime = System.currentTimeMillis();
result.setBornTimestamp(curTime - 1000);
result.getProperties().put(MessageConst.PROPERTY_POP_CK, curTime + " " + curTime + " " + curTime + " " + curTime);
result.setKeys("keys");
result.setSysFlag(MessageSysFlag.INNER_BATCH_FLAG);
result.setSysFlag(result.getSysFlag() | MessageSysFlag.NEED_UNWRAP_FLAG);
SocketAddress bornHost = new InetSocketAddress("127.0.0.1", 12911);
SocketAddress storeHost = new InetSocketAddress("127.0.0.1", 10911);
result.setBornHost(bornHost);
result.setStoreHost(storeHost);
return result;
}
}
| PullAPIWrapperTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/rest/FromRestGetHttpErrorCodeTest.java | {
"start": 1209,
"end": 2804
} | class ____ extends ContextTestSupport {
@Override
protected Registry createCamelRegistry() throws Exception {
Registry jndi = super.createCamelRegistry();
jndi.bind("dummy-rest", new DummyRestConsumerFactory());
return jndi;
}
@Test
public void testFromRestModel() {
String out = template.requestBody("seda:get-say-bye", "I was here", String.class);
assertEquals("Bye World", out);
Exchange reply = template.request("seda:get-say-bye", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setBody("Kaboom");
}
});
assertNotNull(reply);
assertEquals(404, reply.getMessage().getHeader(Exchange.HTTP_RESPONSE_CODE));
assertEquals("text/plain", reply.getMessage().getHeader(Exchange.CONTENT_TYPE));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
restConfiguration().host("localhost");
rest("/say/bye").get().to("direct:bye");
from("direct:bye")
.choice().when(body().contains("Kaboom"))
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(404))
.setHeader(Exchange.CONTENT_TYPE, constant("text/plain")).setBody(constant("The data is invalid"))
.otherwise().transform().constant("Bye World");
}
};
}
}
| FromRestGetHttpErrorCodeTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/internal/util/SerializationHelper.java | {
"start": 6902,
"end": 8493
} | class ____ used.
* <p>
* Delegates to {@link #deserialize(byte[], ClassLoader)}
*
* @param objectData the serialized object, must not be null
*
* @return the deserialized object
*
* @throws IllegalArgumentException if <code>objectData</code> is <code>null</code>
* @throws SerializationException (runtime) if the serialization fails
*/
public static Object deserialize(byte[] objectData) throws SerializationException {
return doDeserialize( wrap( objectData ), defaultClassLoader(), hibernateClassLoader(), null );
}
private static InputStream wrap(byte[] objectData) {
if ( objectData == null ) {
throw new IllegalArgumentException( "The byte[] must not be null" );
}
return new ByteArrayInputStream( objectData );
}
/**
* Deserializes an object from an array of bytes.
* <p>
* Delegates to {@link #deserialize(InputStream, ClassLoader)} using a
* {@link ByteArrayInputStream} to wrap the array.
*
* @param objectData the serialized object, must not be null
* @param loader The classloader to use
*
* @return the deserialized object
*
* @throws IllegalArgumentException if <code>objectData</code> is <code>null</code>
* @throws SerializationException (runtime) if the serialization fails
*/
public static Object deserialize(byte[] objectData, ClassLoader loader) throws SerializationException {
return doDeserialize( wrap( objectData ), loader, defaultClassLoader(), hibernateClassLoader() );
}
/**
* By default, to resolve the classes being deserialized JDK serialization uses the
* classes loader which loaded the | is |
java | grpc__grpc-java | gcp-observability/src/main/java/io/grpc/gcp/observability/ObservabilityConfig.java | {
"start": 830,
"end": 1608
} | interface ____ {
/** Is Cloud Logging enabled. */
boolean isEnableCloudLogging();
/** Is Cloud Monitoring enabled. */
boolean isEnableCloudMonitoring();
/** Is Cloud Tracing enabled. */
boolean isEnableCloudTracing();
/** Get project ID - where logs will go. */
String getProjectId();
/** Get filters for client logging. */
List<LogFilter> getClientLogFilters();
/** Get filters for server logging. */
List<LogFilter> getServerLogFilters();
/** Get sampler for TraceConfig - when Cloud Tracing is enabled. */
Sampler getSampler();
/** Map of all custom tags used for logging, metrics and traces. */
Map<String, String> getCustomTags();
/**
* POJO for representing a filter used in configuration.
*/
@ThreadSafe
| ObservabilityConfig |
java | google__gson | gson/src/test/java/com/google/gson/functional/UncategorizedTest.java | {
"start": 3924,
"end": 3985
} | class ____ {
OperationType opType;
}
private static | Base |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/util/TimeWindowUtilTest.java | {
"start": 1361,
"end": 7492
} | class ____ {
private static final ZoneId UTC_ZONE_ID = TimeZone.getTimeZone("UTC").toZoneId();
@Test
void testShiftedTimeZone() {
ZoneId zoneId = ZoneId.of("Asia/Shanghai");
assertThat(toEpochMillsForTimer(utcMills("1970-01-01T00:00:01"), zoneId))
.isEqualTo(-28799000L);
assertThat(toEpochMillsForTimer(utcMills("1970-01-01T07:59:59.999"), zoneId))
.isEqualTo(-1L);
assertThat(toEpochMillsForTimer(utcMills("1970-01-01T08:00:01"), zoneId)).isEqualTo(1000L);
assertThat(toEpochMillsForTimer(utcMills("1970-01-01T08:00:00.001"), zoneId)).isEqualTo(1L);
assertThat(toEpochMills(utcMills("1970-01-01T00:00:01"), zoneId)).isEqualTo(-28799000L);
assertThat(toEpochMills(utcMills("1970-01-01T07:59:59.999"), zoneId)).isEqualTo(-1L);
assertThat(toEpochMills(utcMills("1970-01-01T08:00:01"), zoneId)).isEqualTo(1000L);
assertThat(toEpochMills(utcMills("1970-01-01T08:00:00.001"), zoneId)).isEqualTo(1L);
}
@Test
void testDaylightSaving() {
ZoneId zoneId = ZoneId.of("America/Los_Angeles");
/*
* The DaylightTime in Los_Angele start at time 2021-03-14 02:00:00
* <pre>
* 2021-03-14 00:00:00 -> epoch1 = 1615708800000L;
* 2021-03-14 01:00:00 -> epoch2 = 1615712400000L;
* 2021-03-14 03:00:00 -> epoch3 = 1615716000000L; skip one hour (2021-03-14 02:00:00)
* 2021-03-14 04:00:00 -> epoch4 = 1615719600000L;
*/
assertThat(toEpochMillsForTimer(utcMills("2021-03-14T00:00:00"), zoneId))
.isEqualTo(1615708800000L);
assertThat(toEpochMillsForTimer(utcMills("2021-03-14T01:00:00"), zoneId))
.isEqualTo(1615712400000L);
assertThat(toEpochMillsForTimer(utcMills("2021-03-14T02:00:00"), zoneId))
.isEqualTo(1615716000000L);
assertThat(toEpochMillsForTimer(utcMills("2021-03-14T02:30:00"), zoneId))
.isEqualTo(1615716000000L);
assertThat(toEpochMillsForTimer(utcMills("2021-03-14T02:59:59"), zoneId))
.isEqualTo(1615716000000L);
assertThat(toEpochMillsForTimer(utcMills("2021-03-14T03:00:00"), zoneId))
.isEqualTo(1615716000000L);
assertThat(toEpochMillsForTimer(utcMills("2021-03-14T03:30:00"), zoneId))
.isEqualTo(1615717800000L);
assertThat(toEpochMillsForTimer(utcMills("2021-03-14T03:59:59"), zoneId))
.isEqualTo(1615719599000L);
assertThat(toEpochMills(utcMills("2021-03-14T00:00:00"), zoneId)).isEqualTo(1615708800000L);
assertThat(toEpochMills(utcMills("2021-03-14T01:00:00"), zoneId)).isEqualTo(1615712400000L);
assertThat(toEpochMills(utcMills("2021-03-14T02:00:00"), zoneId)).isEqualTo(1615716000000L);
assertThat(toEpochMills(utcMills("2021-03-14T02:30:00"), zoneId)).isEqualTo(1615717800000L);
assertThat(toEpochMills(utcMills("2021-03-14T02:59:59"), zoneId)).isEqualTo(1615719599000L);
assertThat(toEpochMills(utcMills("2021-03-14T03:30:00"), zoneId)).isEqualTo(1615717800000L);
assertThat(toEpochMills(utcMills("2021-03-14T03:00:00"), zoneId)).isEqualTo(1615716000000L);
/*
* The DaylightTime in Los_Angele end at time 2021-11-07 01:00:00
* <pre>
* 2021-11-07 00:00:00 -> epoch0 = 1636268400000L; 2021-11-07 00:00:00
* 2021-11-07 01:00:00 -> epoch1 = 1636272000000L; the first local timestamp 2021-11-07 01:00:00
* 2021-11-07 01:00:00 -> epoch2 = 1636275600000L; back to local timestamp 2021-11-07 01:00:00
* 2021-11-07 02:00:00 -> epoch3 = 1636279200000L; 2021-11-07 02:00:00
*/
assertThat(toUtcTimestampMills(1636272000000L, zoneId))
.isEqualTo(utcMills("2021-11-07T01:00:00"));
assertThat(toUtcTimestampMills(1636275600000L, zoneId))
.isEqualTo(utcMills("2021-11-07T01:00:00"));
assertThat(toUtcTimestampMills(1636272001000L, zoneId))
.isEqualTo(utcMills("2021-11-07T01:00:01"));
assertThat(toUtcTimestampMills(1636275599000L, zoneId))
.isEqualTo(utcMills("2021-11-07T01:59:59"));
assertThat(toEpochMillsForTimer(utcMills("2021-11-07T00:00:00"), zoneId))
.isEqualTo(1636268400000L);
assertThat(toEpochMillsForTimer(utcMills("2021-11-07T01:00:00"), zoneId))
.isEqualTo(1636275600000L);
assertThat(toEpochMillsForTimer(utcMills("2021-11-07T02:00:00"), zoneId))
.isEqualTo(1636279200000L);
assertThat(toEpochMillsForTimer(utcMills("2021-11-07T00:00:01"), zoneId))
.isEqualTo(1636268401000L);
assertThat(toEpochMillsForTimer(utcMills("2021-11-07T01:59:59"), zoneId))
.isEqualTo(1636279199000L);
assertThat(toEpochMillsForTimer(utcMills("2021-11-07T02:00:01"), zoneId))
.isEqualTo(1636279201000L);
assertThat(toEpochMills(utcMills("2021-11-07T00:00:00"), zoneId)).isEqualTo(1636268400000L);
assertThat(toEpochMills(utcMills("2021-11-07T01:00:00"), zoneId)).isEqualTo(1636272000000L);
assertThat(toEpochMills(utcMills("2021-11-07T02:00:00"), zoneId)).isEqualTo(1636279200000L);
assertThat(toEpochMills(utcMills("2021-11-07T00:00:01"), zoneId)).isEqualTo(1636268401000L);
assertThat(toEpochMills(utcMills("2021-11-07T01:59:59"), zoneId)).isEqualTo(1636275599000L);
assertThat(toEpochMills(utcMills("2021-11-07T02:00:01"), zoneId)).isEqualTo(1636279201000L);
}
@Test
void testMaxWatermark() {
ZoneId zoneId = ZoneId.of("Asia/Shanghai");
assertThat(toUtcTimestampMills(Long.MAX_VALUE, zoneId)).isEqualTo(Long.MAX_VALUE);
assertThat(toEpochMillsForTimer(Long.MAX_VALUE, zoneId)).isEqualTo(Long.MAX_VALUE);
assertThat(toEpochMills(Long.MAX_VALUE, zoneId)).isEqualTo(Long.MAX_VALUE);
}
private static long utcMills(String utcDateTime) {
return LocalDateTime.parse(utcDateTime).atZone(UTC_ZONE_ID).toInstant().toEpochMilli();
}
}
| TimeWindowUtilTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/A.java | {
"start": 384,
"end": 1181
} | class ____ implements java.io.Serializable {
@Id
protected String id;
protected String name;
protected int value;
@ElementCollection
protected Set<AddressEntry> address = new HashSet();
public A() {
}
public A(String id, String name, int value) {
this.id = id;
this.name = name;
this.value = value;
}
// Default to table A_AddressEntry
public Set<AddressEntry> getAddress() {
return address;
}
public void setAddress(Set<AddressEntry> addr) {
this.address = addr;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int val) {
this.value = val;
}
}
| A |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/spies/SpyingOnRealObjectsTest.java | {
"start": 4952,
"end": 5010
} | class ____ is not visible to Mockito");
}
}
}
| that |
java | apache__commons-lang | src/main/java/org/apache/commons/lang3/Functions.java | {
"start": 6715,
"end": 7109
} | interface ____ {@link Function} that declares a {@link Throwable}.
*
* <p>TODO for 4.0: Move to org.apache.commons.lang3.function.</p>
*
* @param <I> Input type 1.
* @param <R> Return type.
* @param <T> Thrown exception.
* @deprecated Use {@link org.apache.commons.lang3.function.FailableFunction}.
*/
@Deprecated
@FunctionalInterface
public | like |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/xcontent/XContentHelper.java | {
"start": 2118,
"end": 25454
} | class ____ {
/**
* Creates a parser based on the bytes provided
* @deprecated use {@link #createParser(XContentParserConfiguration, BytesReference, XContentType)}
* to avoid content type auto-detection
*/
@Deprecated
public static XContentParser createParser(NamedXContentRegistry registry, DeprecationHandler deprecation, BytesReference bytes)
throws IOException {
return createParser(XContentParserConfiguration.EMPTY.withRegistry(registry).withDeprecationHandler(deprecation), bytes);
}
/**
* Creates a parser based on the bytes provided
* @deprecated use {@link #createParser(XContentParserConfiguration, BytesReference, XContentType)}
* to avoid content type auto-detection
*/
@Deprecated
public static XContentParser createParser(XContentParserConfiguration config, BytesReference bytes) throws IOException {
Compressor compressor = CompressorFactory.compressorForUnknownXContentType(bytes);
if (compressor != null) {
InputStream compressedInput = compressor.threadLocalInputStream(bytes.streamInput());
if (compressedInput.markSupported() == false) {
compressedInput = new BufferedInputStream(compressedInput);
}
final XContentType contentType = XContentFactory.xContentType(compressedInput);
return XContentFactory.xContent(contentType).createParser(config, compressedInput);
} else {
return createParserNotCompressed(config, bytes, xContentType(bytes));
}
}
/**
* Same as {@link #createParser(XContentParserConfiguration, BytesReference, XContentType)} but only supports uncompressed
* {@code bytes}.
*/
public static XContentParser createParserNotCompressed(
XContentParserConfiguration config,
BytesReference bytes,
XContentType xContentType
) throws IOException {
XContent xContent = xContentType.xContent();
if (bytes.hasArray()) {
return xContent.createParser(config, bytes.array(), bytes.arrayOffset(), bytes.length());
}
return xContent.createParser(config, bytes.streamInput());
}
/**
* Creates a parser for the bytes provided
* @deprecated use {@link #createParser(XContentParserConfiguration, BytesReference, XContentType)}
*/
@Deprecated
public static XContentParser createParser(
NamedXContentRegistry registry,
DeprecationHandler deprecation,
BytesReference bytes,
XContentType xContentType
) throws IOException {
return createParser(
XContentParserConfiguration.EMPTY.withRegistry(registry).withDeprecationHandler(deprecation),
bytes,
xContentType
);
}
/**
* Creates a parser for the bytes using the supplied content-type
*/
public static XContentParser createParser(XContentParserConfiguration config, BytesReference bytes, XContentType xContentType)
throws IOException {
Objects.requireNonNull(xContentType);
Compressor compressor = CompressorFactory.compressor(bytes);
if (compressor != null) {
return XContentFactory.xContent(xContentType).createParser(config, compressor.threadLocalInputStream(bytes.streamInput()));
} else {
// TODO now that we have config we make a method on bytes to do this building without needing this check everywhere
return createParserNotCompressed(config, bytes, xContentType);
}
}
/**
* Converts the given bytes into a map that is optionally ordered.
* <p>
* Important: This can lose precision on numbers with a decimal point. It
* converts numbers like {@code "n": 1234.567} to a {@code double} which
* only has 52 bits of precision in the mantissa. This will come up most
* frequently when folks write nanosecond precision dates as a decimal
* number.
* @deprecated this method relies on auto-detection of content type. Use {@link #convertToMap(BytesReference, boolean, XContentType)}
* instead with the proper {@link XContentType}
*/
@Deprecated
public static Tuple<XContentType, Map<String, Object>> convertToMap(BytesReference bytes, boolean ordered)
throws ElasticsearchParseException {
return parseToType(ordered ? XContentParser::mapOrdered : XContentParser::map, bytes, null, XContentParserConfiguration.EMPTY);
}
/**
* Exactly the same as {@link XContentHelper#convertToMap(BytesReference, boolean, XContentType, Set, Set)} but
* none of the fields are filtered
*/
public static Tuple<XContentType, Map<String, Object>> convertToMap(
BytesReference bytes,
boolean ordered,
XContentType xContentType,
XContentParserDecorator parserDecorator
) {
return parseToType(
ordered ? XContentParser::mapOrdered : XContentParser::map,
bytes,
xContentType,
XContentParserConfiguration.EMPTY,
parserDecorator
);
}
public static Tuple<XContentType, Map<String, Object>> convertToMap(BytesReference bytes, boolean ordered, XContentType xContentType) {
return parseToType(
ordered ? XContentParser::mapOrdered : XContentParser::map,
bytes,
xContentType,
XContentParserConfiguration.EMPTY
);
}
/**
* Converts the given bytes into a map that is optionally ordered. The provided {@link XContentType} must be non-null.
* <p>
* Important: This can lose precision on numbers with a decimal point. It
* converts numbers like {@code "n": 1234.567} to a {@code double} which
* only has 52 bits of precision in the mantissa. This will come up most
* frequently when folks write nanosecond precision dates as a decimal
* number.
*/
public static Tuple<XContentType, Map<String, Object>> convertToMap(
BytesReference bytes,
boolean ordered,
XContentType xContentType,
@Nullable Set<String> include,
@Nullable Set<String> exclude
) throws ElasticsearchParseException {
XContentParserConfiguration config = XContentParserConfiguration.EMPTY;
if (include != null || exclude != null) {
config = config.withFiltering(null, include, exclude, false);
}
return parseToType(ordered ? XContentParser::mapOrdered : XContentParser::map, bytes, xContentType, config);
}
/**
* Creates a parser based on the given {@link BytesReference} and uses {@param extractor} to get a parsed object.
* @deprecated if {@param xContentType} is null, this method relies on auto-detection of content type. Provide a non-null XContentType
* instead.
*/
@Deprecated
public static <T> Tuple<XContentType, T> parseToType(
CheckedFunction<XContentParser, T, IOException> extractor,
BytesReference bytes,
@Nullable XContentType xContentType,
@Nullable XContentParserConfiguration config
) throws ElasticsearchParseException {
return parseToType(extractor, bytes, xContentType, config, XContentParserDecorator.NOOP);
}
public static <T> Tuple<XContentType, T> parseToType(
CheckedFunction<XContentParser, T, IOException> extractor,
BytesReference bytes,
@Nullable XContentType xContentType,
@Nullable XContentParserConfiguration config,
XContentParserDecorator parserDecorator
) throws ElasticsearchParseException {
config = config != null ? config : XContentParserConfiguration.EMPTY;
try (
XContentParser parser = parserDecorator.decorate(
xContentType != null ? createParser(config, bytes, xContentType) : createParser(config, bytes)
)
) {
Tuple<XContentType, T> xContentTypeTTuple = new Tuple<>(parser.contentType(), extractor.apply(parser));
return xContentTypeTTuple;
} catch (IOException e) {
throw new ElasticsearchParseException("Failed to parse content to type", e);
}
}
/**
* Convert a string in some {@link XContent} format to a {@link Map}. Throws an {@link ElasticsearchParseException} if there is any
* error.
*/
public static Map<String, Object> convertToMap(XContent xContent, String string, boolean ordered) throws ElasticsearchParseException {
try (XContentParser parser = xContent.createParser(XContentParserConfiguration.EMPTY, string)) {
return ordered ? parser.mapOrdered() : parser.map();
} catch (IOException e) {
throw new ElasticsearchParseException("Failed to parse content to map", e);
}
}
/**
* The same as {@link XContentHelper#convertToMap(XContent, byte[], int, int, boolean, Set, Set)} but none of the
* fields are filtered.
*/
public static Map<String, Object> convertToMap(XContent xContent, InputStream input, boolean ordered)
throws ElasticsearchParseException {
return convertToMap(xContent, input, ordered, null, null);
}
/**
* Convert a string in some {@link XContent} format to a {@link Map}. Throws an {@link ElasticsearchParseException} if there is any
* error. Note that unlike {@link #convertToMap(BytesReference, boolean)}, this doesn't automatically uncompress the input.
*
* Additionally, fields may be included or excluded from the parsing.
*/
public static Map<String, Object> convertToMap(
XContent xContent,
InputStream input,
boolean ordered,
@Nullable Set<String> include,
@Nullable Set<String> exclude
) throws ElasticsearchParseException {
try (
XContentParser parser = xContent.createParser(
XContentParserConfiguration.EMPTY.withFiltering(null, include, exclude, false),
input
)
) {
return ordered ? parser.mapOrdered() : parser.map();
} catch (IOException e) {
throw new ElasticsearchParseException("Failed to parse content to map", e);
}
}
/**
* Convert a byte array in some {@link XContent} format to a {@link Map}. Throws an {@link ElasticsearchParseException} if there is any
* error. Note that unlike {@link #convertToMap(BytesReference, boolean)}, this doesn't automatically uncompress the input.
*/
public static Map<String, Object> convertToMap(XContent xContent, byte[] bytes, int offset, int length, boolean ordered)
throws ElasticsearchParseException {
return convertToMap(xContent, bytes, offset, length, ordered, null, null);
}
/**
* Convert a byte array in some {@link XContent} format to a {@link Map}. Throws an {@link ElasticsearchParseException} if there is any
* error. Note that unlike {@link #convertToMap(BytesReference, boolean)}, this doesn't automatically uncompress the input.
*
* Unlike {@link XContentHelper#convertToMap(XContent, byte[], int, int, boolean)} this optionally accepts fields to include or exclude
* during XContent parsing.
*/
public static Map<String, Object> convertToMap(
XContent xContent,
byte[] bytes,
int offset,
int length,
boolean ordered,
@Nullable Set<String> include,
@Nullable Set<String> exclude
) throws ElasticsearchParseException {
try (
XContentParser parser = xContent.createParser(
XContentParserConfiguration.EMPTY.withFiltering(null, include, exclude, false),
bytes,
offset,
length
)
) {
return ordered ? parser.mapOrdered() : parser.map();
} catch (IOException e) {
throw new ElasticsearchParseException("Failed to parse content to map", e);
}
}
@Deprecated
public static String convertToJson(BytesReference bytes, boolean reformatJson) throws IOException {
return convertToJson(bytes, reformatJson, false);
}
@Deprecated
public static String convertToJson(BytesReference bytes, boolean reformatJson, boolean prettyPrint) throws IOException {
return convertToJson(bytes, reformatJson, prettyPrint, xContentType(bytes));
}
public static String convertToJson(BytesReference bytes, boolean reformatJson, XContentType xContentType) throws IOException {
return convertToJson(bytes, reformatJson, false, xContentType);
}
/**
* Accepts a JSON string, parses it and prints it without pretty-printing it. This is useful
* where a piece of JSON is formatted for legibility, but needs to be stripped of unnecessary
* whitespace e.g. for comparison in a test.
*
* @param json the JSON to format
* @return reformatted JSON
* @throws IOException if the reformatting fails, e.g. because the JSON is not well-formed
*/
public static String stripWhitespace(String json) throws IOException {
return convertToJson(new BytesArray(json), true, XContentType.JSON);
}
public static String convertToJson(BytesReference bytes, boolean reformatJson, boolean prettyPrint, XContentType xContentType)
throws IOException {
Objects.requireNonNull(xContentType);
if (xContentType.canonical() == XContentType.JSON && reformatJson == false) {
return bytes.utf8ToString();
}
try (var parser = createParserNotCompressed(XContentParserConfiguration.EMPTY, bytes, xContentType)) {
return toJsonString(prettyPrint, parser);
}
}
private static String toJsonString(boolean prettyPrint, XContentParser parser) throws IOException {
parser.nextToken();
XContentBuilder builder = XContentFactory.jsonBuilder();
if (prettyPrint) {
builder.prettyPrint();
}
builder.copyCurrentStructure(parser);
return Strings.toString(builder);
}
/**
* Updates the provided changes into the source. If the key exists in the changes, it overrides the one in source
* unless both are Maps, in which case it recursively updated it.
*
* @param source the original map to be updated
* @param changes the changes to update into updated
* @param checkUpdatesAreUnequal should this method check if updates to the same key (that are not both maps) are
* unequal? This is just a .equals check on the objects, but that can take some time on long strings.
* @return true if the source map was modified
*/
public static boolean update(Map<String, Object> source, Map<String, Object> changes, boolean checkUpdatesAreUnequal) {
boolean modified = false;
for (Map.Entry<String, Object> changesEntry : changes.entrySet()) {
if (source.containsKey(changesEntry.getKey()) == false) {
// safe to copy, change does not exist in source
source.put(changesEntry.getKey(), changesEntry.getValue());
modified = true;
continue;
}
Object old = source.get(changesEntry.getKey());
if (old instanceof Map && changesEntry.getValue() instanceof Map) {
// recursive merge maps
modified |= update(
(Map<String, Object>) source.get(changesEntry.getKey()),
(Map<String, Object>) changesEntry.getValue(),
checkUpdatesAreUnequal && modified == false
);
continue;
}
// update the field
source.put(changesEntry.getKey(), changesEntry.getValue());
if (modified) {
continue;
}
if (checkUpdatesAreUnequal == false) {
modified = true;
continue;
}
modified = Objects.equals(old, changesEntry.getValue()) == false;
}
return modified;
}
/**
* Merges the defaults provided as the second parameter into the content of the first. Only does recursive merge for inner maps.
*/
public static void mergeDefaults(Map<String, Object> content, Map<String, Object> defaults) {
merge(content, defaults, null);
}
/**
* Merges the map provided as the second parameter into the content of the first. Only does recursive merge for inner maps.
* If a non-null {@link CustomMerge} is provided, it is applied whenever a merge is required, meaning - whenever both the first and
* the second map has values for the same key. Otherwise, values from the first map will always have precedence, meaning - if the
* first map contains a key, its value will not be overridden.
* @param first the map which serves as the merge base
* @param second the map of which contents are merged into the base map
* @param customMerge a custom merge rule to apply whenever a key has concrete values (i.e. not a map or a collection) in both maps
*/
public static void merge(Map<String, Object> first, Map<String, Object> second, @Nullable CustomMerge customMerge) {
merge(null, first, second, customMerge);
}
/**
* Merges the map provided as the second parameter into the content of the first. Only does recursive merge for inner maps.
* If a non-null {@link CustomMerge} is provided, it is applied whenever a merge is required, meaning - whenever both the first and
* the second map has values for the same key. Otherwise, values from the first map will always have precedence, meaning - if the
* first map contains a key, its value will not be overridden.
*
* @param parent used for recursion to maintain knowledge about the common parent of the currently merged sub-maps, if such exists
* @param first the map which serves as the merge base
* @param second the map of which contents are merged into the base map
* @param customMerge a custom merge rule to apply whenever a key has concrete values (i.e. not a map or a collection) in both maps
*/
public static void merge(
@Nullable String parent,
Map<String, Object> first,
Map<String, Object> second,
@Nullable CustomMerge customMerge
) {
for (Map.Entry<String, Object> toMergeEntry : second.entrySet()) {
if (first.containsKey(toMergeEntry.getKey()) == false) {
// copy it over, it does not exist in the content
first.put(toMergeEntry.getKey(), toMergeEntry.getValue());
} else {
// has values in both maps, merge compound ones (maps)
Object baseValue = first.get(toMergeEntry.getKey());
if (baseValue instanceof Map && toMergeEntry.getValue() instanceof Map) {
Map<String, Object> mergedValue = null;
if (customMerge != null) {
Object tmp = customMerge.merge(parent, toMergeEntry.getKey(), baseValue, toMergeEntry.getValue());
if (tmp != null && tmp instanceof Map == false) {
throw new IllegalStateException("merging of values for [" + toMergeEntry.getKey() + "] must yield a map");
}
mergedValue = (Map<String, Object>) tmp;
}
if (mergedValue != null) {
first.put(toMergeEntry.getKey(), mergedValue);
} else {
// if custom merge does not yield a value to be used, continue recursive merge
merge(
toMergeEntry.getKey(),
(Map<String, Object>) baseValue,
(Map<String, Object>) toMergeEntry.getValue(),
customMerge
);
}
} else if (baseValue instanceof List && toMergeEntry.getValue() instanceof List) {
List<Object> listToMerge = (List<Object>) toMergeEntry.getValue();
List<Object> baseList = (List<Object>) baseValue;
if (allListValuesAreMapsOfOne(listToMerge) && allListValuesAreMapsOfOne(baseList)) {
// all are in the form of [ {"key1" : {}}, {"key2" : {}} ], merge based on keys
Map<String, Map<String, Object>> processed = new LinkedHashMap<>();
for (Object o : baseList) {
Map<String, Object> map = (Map<String, Object>) o;
Map.Entry<String, Object> entry = map.entrySet().iterator().next();
processed.put(entry.getKey(), map);
}
for (Object o : listToMerge) {
Map<String, Object> map = (Map<String, Object>) o;
Map.Entry<String, Object> entry = map.entrySet().iterator().next();
if (processed.containsKey(entry.getKey())) {
merge(toMergeEntry.getKey(), processed.get(entry.getKey()), map, customMerge);
} else {
// append the second list's entries after the first list's entries.
processed.put(entry.getKey(), map);
}
}
first.put(toMergeEntry.getKey(), new ArrayList<>(processed.values()));
} else {
// if both are lists, simply combine them, first the second list's values, then the first's
// just make sure not to add the same value twice
// custom merge is not applicable here
List<Object> mergedList = new ArrayList<>(listToMerge);
for (Object o : baseList) {
if (mergedList.contains(o) == false) {
mergedList.add(o);
}
}
first.put(toMergeEntry.getKey(), mergedList);
}
} else if (customMerge != null) {
Object mergedValue = customMerge.merge(parent, toMergeEntry.getKey(), baseValue, toMergeEntry.getValue());
if (mergedValue != null) {
first.put(toMergeEntry.getKey(), mergedValue);
}
}
}
}
}
private static boolean allListValuesAreMapsOfOne(List<Object> list) {
for (Object o : list) {
if ((o instanceof Map) == false) {
return false;
}
if (((Map) o).size() != 1) {
return false;
}
}
return true;
}
/**
* A {@code FunctionalInterface} that can be used in order to customize map merges.
*/
@FunctionalInterface
public | XContentHelper |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/multipart/PartItem.java | {
"start": 307,
"end": 1819
} | class ____ {
private final MultivaluedMap<String, Object> headers;
private final Object entity;
private final String genericType;
private final MediaType mediaType;
private final String filename;
public PartItem(Object entity, String genericType, MediaType mediaType) {
this(entity, genericType, mediaType, null, new QuarkusMultivaluedHashMap<>());
}
public PartItem(Object entity, String genericType, MediaType mediaType, String filename) {
this(entity, genericType, mediaType, filename, new QuarkusMultivaluedHashMap<>());
}
public PartItem(Object entity, String genericType, MediaType mediaType, MultivaluedMap<String, Object> headers) {
this(entity, genericType, mediaType, null, headers);
}
public PartItem(Object entity, String genericType, MediaType mediaType, String filename,
MultivaluedMap<String, Object> headers) {
this.entity = entity;
this.genericType = genericType;
this.mediaType = mediaType;
this.filename = filename;
this.headers = headers != null ? headers : new QuarkusMultivaluedHashMap<>();
}
public MultivaluedMap<String, Object> getHeaders() {
return headers;
}
public Object getEntity() {
return entity;
}
public String getGenericType() {
return genericType;
}
public MediaType getMediaType() {
return mediaType;
}
public String getFilename() {
return filename;
}
}
| PartItem |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/datetime/BaseDateTimeFormatFunction.java | {
"start": 1201,
"end": 2553
} | class ____ extends BinaryDateTimeFunction {
public BaseDateTimeFormatFunction(Source source, Expression timestamp, Expression pattern, ZoneId zoneId) {
super(source, timestamp, pattern, zoneId);
}
@Override
public DataType dataType() {
return DataTypes.KEYWORD;
}
@Override
protected TypeResolution resolveType() {
TypeResolution resolution = isDateOrTime(left(), sourceText(), FIRST);
if (resolution.unresolved()) {
return resolution;
}
resolution = isString(right(), sourceText(), SECOND);
if (resolution.unresolved()) {
return resolution;
}
return TypeResolution.TYPE_RESOLVED;
}
@Override
protected NodeInfo<? extends Expression> info() {
return NodeInfo.create(this, ctor(), left(), right(), zoneId());
}
@Override
public Object fold() {
return formatter().format(left().fold(), right().fold(), zoneId());
}
@Override
protected Pipe createPipe(Pipe timestamp, Pipe pattern, ZoneId zoneId) {
return new DateTimeFormatPipe(source(), this, timestamp, pattern, zoneId, formatter());
}
protected abstract Formatter formatter();
protected abstract NodeCtor3<Expression, Expression, ZoneId, BaseDateTimeFormatFunction> ctor();
}
| BaseDateTimeFormatFunction |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/NumericTermsAggregator.java | {
"start": 19358,
"end": 22111
} | class ____ extends StandardTermsResultStrategy<DoubleTerms, DoubleTerms.Bucket> {
DoubleTermsResults(boolean showTermDocCountError, Aggregator aggregator) {
super(showTermDocCountError, aggregator);
}
@Override
String describe() {
return "double_terms";
}
@Override
SortedNumericLongValues getValues(LeafReaderContext ctx) throws IOException {
return FieldData.toSortableLongBits(valuesSource.doubleValues(ctx));
}
@Override
ObjectArray<DoubleTerms.Bucket[]> buildTopBucketsPerOrd(long size) {
return bigArrays().newObjectArray(size);
}
@Override
DoubleTerms.Bucket[] buildBuckets(int size) {
return new DoubleTerms.Bucket[size];
}
@Override
DoubleTerms.Bucket buildEmptyBucket() {
return new DoubleTerms.Bucket(0, 0, null, showTermDocCountError, 0, format);
}
@Override
BucketUpdater<DoubleTerms.Bucket> bucketUpdater(long owningBucketOrd) {
return (DoubleTerms.Bucket spare, BucketOrdsEnum ordsEnum, long docCount) -> {
spare.term = NumericUtils.sortableLongToDouble(ordsEnum.value());
spare.docCount = docCount;
};
}
@Override
DoubleTerms buildResult(long owningBucketOrd, long otherDocCount, DoubleTerms.Bucket[] topBuckets) {
final BucketOrder reduceOrder;
if (isKeyOrder(order) == false) {
reduceOrder = InternalOrder.key(true);
Arrays.sort(topBuckets, reduceOrder.comparator());
} else {
reduceOrder = order;
}
return new DoubleTerms(
name,
reduceOrder,
order,
bucketCountThresholds.getRequiredSize(),
bucketCountThresholds.getMinDocCount(),
metadata(),
format,
bucketCountThresholds.getShardSize(),
showTermDocCountError,
otherDocCount,
Arrays.asList(topBuckets),
null
);
}
@Override
DoubleTerms buildEmptyResult() {
return new DoubleTerms(
name,
order,
order,
bucketCountThresholds.getRequiredSize(),
bucketCountThresholds.getMinDocCount(),
metadata(),
format,
bucketCountThresholds.getShardSize(),
showTermDocCountError,
0,
emptyList(),
0L
);
}
}
| DoubleTermsResults |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/RescalingParallelismQueryParameter.java | {
"start": 954,
"end": 1574
} | class ____ extends MessageQueryParameter<Integer> {
public static final String KEY = "parallelism";
public RescalingParallelismQueryParameter() {
super(KEY, MessageParameterRequisiteness.MANDATORY);
}
@Override
public Integer convertStringToValue(String value) {
return Integer.valueOf(value);
}
@Override
public String convertValueToString(Integer value) {
return value.toString();
}
@Override
public String getDescription() {
return "Positive integer value that specifies the desired parallelism.";
}
}
| RescalingParallelismQueryParameter |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/support/GenericXmlContextLoaderResourceLocationsTests.java | {
"start": 4965,
"end": 5075
} | class ____ {
}
@ContextConfiguration("file:/testing/directory/context.xml")
| ExplicitClasspathLocationsTestCase |
java | apache__logging-log4j2 | log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/resolver/EventResolverInterceptor.java | {
"start": 1005,
"end": 1334
} | interface ____ extends TemplateResolverInterceptor<LogEvent, EventResolverContext> {
@Override
default Class<LogEvent> getValueClass() {
return LogEvent.class;
}
@Override
default Class<EventResolverContext> getContextClass() {
return EventResolverContext.class;
}
}
| EventResolverInterceptor |
java | grpc__grpc-java | api/src/main/java/io/grpc/ServerInterceptors.java | {
"start": 7351,
"end": 12126
} | class ____ extends BufferedInputStream
implements KnownLength {
KnownLengthBufferedInputStream(InputStream in) {
super(in);
}
}
/**
* Create a new {@code ServerServiceDefinition} whose {@link MethodDescriptor} serializes to
* and from T for all methods. The {@code ServerCallHandler} created will automatically
* convert back to the original types for request and response before calling the existing
* {@code ServerCallHandler}. Calling this method combined with the intercept methods will
* allow the developer to choose whether to intercept messages of T, or the modeled types
* of their application. This can also be chained to allow for interceptors to handle messages
* as multiple different T types within the chain if the added cost of serialization is not
* a concern.
*
* @param serviceDef the service definition to convert messages to T
* @return a wrapped version of {@code serviceDef} with the T conversion applied.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1712")
public static <T> ServerServiceDefinition useMarshalledMessages(
final ServerServiceDefinition serviceDef,
final MethodDescriptor.Marshaller<T> marshaller) {
return useMarshalledMessages(serviceDef, marshaller, marshaller);
}
/**
* Create a new {@code ServerServiceDefinition} with {@link MethodDescriptor} for deserializing
* requests and separate {@link MethodDescriptor} for serializing responses. The {@code
* ServerCallHandler} created will automatically convert back to the original types for request
* and response before calling the existing {@code ServerCallHandler}. Calling this method
* combined with the intercept methods will allow the developer to choose whether to intercept
* messages of ReqT/RespT, or the modeled types of their application. This can also be chained
* to allow for interceptors to handle messages as multiple different ReqT/RespT types within
* the chain if the added cost of serialization is not a concern.
*
* @param serviceDef the service definition to add request and response marshallers to.
* @param requestMarshaller request marshaller
* @param responseMarshaller response marshaller
* @param <ReqT> the request payload type
* @param <RespT> the response payload type.
* @return a wrapped version of {@code serviceDef} with the ReqT and RespT conversion applied.
*/
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/9870")
public static <ReqT, RespT> ServerServiceDefinition useMarshalledMessages(
final ServerServiceDefinition serviceDef,
final MethodDescriptor.Marshaller<ReqT> requestMarshaller,
final MethodDescriptor.Marshaller<RespT> responseMarshaller) {
List<ServerMethodDefinition<?, ?>> wrappedMethods =
new ArrayList<>();
List<MethodDescriptor<?, ?>> wrappedDescriptors =
new ArrayList<>();
// Wrap the descriptors
for (final ServerMethodDefinition<?, ?> definition : serviceDef.getMethods()) {
final MethodDescriptor<?, ?> originalMethodDescriptor = definition.getMethodDescriptor();
final MethodDescriptor<ReqT, RespT> wrappedMethodDescriptor =
originalMethodDescriptor.toBuilder(requestMarshaller, responseMarshaller).build();
wrappedDescriptors.add(wrappedMethodDescriptor);
wrappedMethods.add(wrapMethod(definition, wrappedMethodDescriptor));
}
// Build the new service descriptor
final ServiceDescriptor.Builder serviceDescriptorBuilder =
ServiceDescriptor.newBuilder(serviceDef.getServiceDescriptor().getName())
.setSchemaDescriptor(serviceDef.getServiceDescriptor().getSchemaDescriptor());
for (MethodDescriptor<?, ?> wrappedDescriptor : wrappedDescriptors) {
serviceDescriptorBuilder.addMethod(wrappedDescriptor);
}
// Create the new service definition.
final ServerServiceDefinition.Builder serviceBuilder =
ServerServiceDefinition.builder(serviceDescriptorBuilder.build());
for (ServerMethodDefinition<?, ?> definition : wrappedMethods) {
serviceBuilder.addMethod(definition);
}
return serviceBuilder.build();
}
private static <ReqT, RespT> void wrapAndAddMethod(
ServerServiceDefinition.Builder serviceDefBuilder, ServerMethodDefinition<ReqT, RespT> method,
List<? extends ServerInterceptor> interceptors) {
ServerCallHandler<ReqT, RespT> callHandler = method.getServerCallHandler();
for (ServerInterceptor interceptor : interceptors) {
callHandler = InterceptCallHandler.create(interceptor, callHandler);
}
serviceDefBuilder.addMethod(method.withServerCallHandler(callHandler));
}
static final | KnownLengthBufferedInputStream |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ClientProtocol.java | {
"start": 3995,
"end": 4389
} | class ____ ALSO related protocol buffer
* wire protocol definition in ClientNamenodeProtocol.proto.
*
* For more details on protocol buffer wire protocol, please see
* .../org/apache/hadoop/hdfs/protocolPB/overview.html
*
* The log of historical changes can be retrieved from the svn).
* 69: Eliminate overloaded method names.
*
* 69L is the last version id when this | and |
java | junit-team__junit5 | junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/UriSelector.java | {
"start": 1197,
"end": 2300
} | class ____ implements DiscoverySelector {
private final URI uri;
UriSelector(URI uri) {
this.uri = uri;
}
/**
* Get the selected {@link URI}.
*/
public URI getUri() {
return this.uri;
}
/**
* @since 1.3
*/
@API(status = STABLE, since = "1.3")
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UriSelector that = (UriSelector) o;
return Objects.equals(this.uri, that.uri);
}
/**
* @since 1.3
*/
@API(status = STABLE, since = "1.3")
@Override
public int hashCode() {
return this.uri.hashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this).append("uri", this.uri).toString();
}
@Override
public Optional<DiscoverySelectorIdentifier> toIdentifier() {
return Optional.of(DiscoverySelectorIdentifier.create(IdentifierParser.PREFIX, this.uri.toString()));
}
/**
* The {@link DiscoverySelectorIdentifierParser} for {@link UriSelector
* UriSelectors}.
*/
@API(status = INTERNAL, since = "1.11")
public static | UriSelector |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_2233/ProgramAggregate.java | {
"start": 289,
"end": 578
} | class ____ {
private final Collection<Program> programs;
public ProgramAggregate(Collection<Program> programs) {
this.programs = programs;
}
public Optional<Collection<Program>> getPrograms() {
return Optional.ofNullable( programs );
}
}
| ProgramAggregate |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/jpa/spi/NativeQueryTupleTransformer.java | {
"start": 1072,
"end": 1508
} | class ____<X> implements TupleElement<X> {
private final Class<? extends X> javaType;
private final String alias;
public NativeTupleElementImpl(Class<? extends X> javaType, String alias) {
this.javaType = javaType;
this.alias = alias;
}
@Override
public Class<? extends X> getJavaType() {
return javaType;
}
@Override
public String getAlias() {
return alias;
}
}
private static | NativeTupleElementImpl |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/single/SingleRetryTest.java | {
"start": 1007,
"end": 5164
} | class ____ extends RxJavaTest {
@Test
public void retryTimesPredicateWithMatchingPredicate() {
final AtomicInteger atomicInteger = new AtomicInteger(3);
final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0);
Single.fromCallable(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
numberOfSubscribeCalls.incrementAndGet();
if (atomicInteger.decrementAndGet() != 0) {
throw new RuntimeException();
}
throw new IllegalArgumentException();
}
})
.retry(Integer.MAX_VALUE, new Predicate<Throwable>() {
@Override public boolean test(final Throwable throwable) throws Exception {
return !(throwable instanceof IllegalArgumentException);
}
})
.test()
.assertFailure(IllegalArgumentException.class);
assertEquals(3, numberOfSubscribeCalls.get());
}
@Test
public void retryTimesPredicateWithMatchingRetryAmount() {
final AtomicInteger atomicInteger = new AtomicInteger(3);
final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0);
Single.fromCallable(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
numberOfSubscribeCalls.incrementAndGet();
if (atomicInteger.decrementAndGet() != 0) {
throw new RuntimeException();
}
return true;
}
})
.retry(2, Functions.alwaysTrue())
.test()
.assertResult(true);
assertEquals(3, numberOfSubscribeCalls.get());
}
@Test
public void retryTimesPredicateWithNotMatchingRetryAmount() {
final AtomicInteger atomicInteger = new AtomicInteger(3);
final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0);
Single.fromCallable(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
numberOfSubscribeCalls.incrementAndGet();
if (atomicInteger.decrementAndGet() != 0) {
throw new RuntimeException();
}
return true;
}
})
.retry(1, Functions.alwaysTrue())
.test()
.assertFailure(RuntimeException.class);
assertEquals(2, numberOfSubscribeCalls.get());
}
@Test
public void retryTimesPredicateWithZeroRetries() {
final AtomicInteger atomicInteger = new AtomicInteger(2);
final AtomicInteger numberOfSubscribeCalls = new AtomicInteger(0);
Single.fromCallable(new Callable<Boolean>() {
@Override public Boolean call() throws Exception {
numberOfSubscribeCalls.incrementAndGet();
if (atomicInteger.decrementAndGet() != 0) {
throw new RuntimeException();
}
return true;
}
})
.retry(0, Functions.alwaysTrue())
.test()
.assertFailure(RuntimeException.class);
assertEquals(1, numberOfSubscribeCalls.get());
}
@Test
public void untilTrueJust() {
Single.just(1)
.retryUntil(() -> true)
.test()
.assertResult(1);
}
@Test
public void untilFalseJust() {
Single.just(1)
.retryUntil(() -> false)
.test()
.assertResult(1);
}
@Test
public void untilTrueError() {
Single.error(new TestException())
.retryUntil(() -> true)
.test()
.assertFailure(TestException.class);
}
@Test
public void untilFalseError() {
AtomicInteger counter = new AtomicInteger();
Single.defer(() -> {
if (counter.getAndIncrement() == 0) {
return Single.error(new TestException());
}
return Single.just(1);
})
.retryUntil(() -> false)
.test()
.assertResult(1);
}
}
| SingleRetryTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/OrderedFieldTest.java | {
"start": 581,
"end": 673
} | interface ____ {
public int getId();
public void setId(int value);
}
}
| Model |
java | quarkusio__quarkus | integration-tests/grpc-hibernate/src/main/java/com/example/grpc/hibernate/RawTestService.java | {
"start": 544,
"end": 3692
} | class ____ extends TestRawGrpc.TestRawImplBase {
private static final Logger log = Logger.getLogger(RawTestService.class);
private static final TestOuterClass.Empty EMPTY = TestOuterClass.Empty.getDefaultInstance();
@Inject
EntityManager entityManager;
@Inject
ItemDao dao;
@Inject
ContextChecker contextChecker;
ManagedContext requestContext;
@PostConstruct
public void setUp() {
requestContext = Arc.container().requestContext();
}
@Override
@Transactional
public void add(TestOuterClass.Item request, StreamObserver<TestOuterClass.Empty> responseObserver) {
contextChecker.newContextId("RawTestService#add");
Item item = new Item();
item.text = request.getText();
entityManager.persist(item);
responseObserver.onNext(EMPTY);
responseObserver.onCompleted();
}
@Override
@Blocking
@Transactional
public void clear(TestOuterClass.Empty request, StreamObserver<TestOuterClass.Empty> responseObserver) {
contextChecker.newContextId("RawTestService#clear");
entityManager.createQuery("DELETE from Item")
.executeUpdate();
responseObserver.onNext(EMPTY);
responseObserver.onCompleted();
}
@Override
public void getAll(TestOuterClass.Empty request, StreamObserver<TestOuterClass.Item> responseObserver) {
contextChecker.newContextId("RawTestService#getAll");
List<Item> items = entityManager.createQuery("from Item", Item.class)
.getResultList();
for (Item item : items) {
responseObserver.onNext(TestOuterClass.Item.newBuilder().setText(item.text).build());
}
responseObserver.onCompleted();
}
@Override
public StreamObserver<TestOuterClass.Item> bidi(StreamObserver<TestOuterClass.Item> responseObserver) {
int contextId = contextChecker.newContextId("RawTestService#bidi");
return new StreamObserver<TestOuterClass.Item>() {
@Override
public void onNext(TestOuterClass.Item value) {
if (contextChecker.requestContextId() != contextId) {
throw new RuntimeException("Different context for onNext and RawTestService#bidi method");
}
Item newItem = new Item();
newItem.text = value.getText();
dao.add(newItem);
responseObserver.onNext(value);
}
@Override
public void onError(Throwable t) {
log.error("bidi onError", t);
}
@Override
public void onCompleted() {
if (contextChecker.requestContextId() != contextId) {
throw new RuntimeException("Different context for onCompleted and RawTestService#bidi method");
}
if (!requestContext.isActive()) {
throw new RuntimeException("Request context not active for `onCompleted`");
}
responseObserver.onCompleted();
}
};
}
}
| RawTestService |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/util/ChecksTest.java | {
"start": 299,
"end": 1329
} | class ____ {
@Test
public void checkNotNull_not_null() {
assertEquals("abc", Checks.checkNotNull("abc", "someValue"));
}
@Test
public void checkNotNull_not_null_additional_message() {
assertEquals("abc", Checks.checkNotNull("abc", "someValue", "Oh no!"));
}
@Test
public void checkNotNull_null() {
assertThatThrownBy(
() -> {
Checks.checkNotNull(null, "someValue");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("someValue should not be null");
}
@Test
public void checkNotNull_null_additonal_message() {
assertThatThrownBy(
() -> {
Checks.checkNotNull(null, "someValue", "Oh no!");
})
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("someValue should not be null. Oh no!");
}
}
| ChecksTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/WildcardImportTest.java | {
"start": 4658,
"end": 5012
} | class ____ {
void m() {
System.err.println(UTF_8);
}
}
""")
.doTest();
}
@Test
public void positive() {
testHelper
.addInputLines(
"in/test/Test.java",
"""
package test;
import java.util.*;
public | Test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.