language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/expressions/parser/ast/operator/binary/OrOperator.java
{ "start": 1024, "end": 1431 }
class ____ extends LogicalOperator { public OrOperator(ExpressionNode leftOperand, ExpressionNode rightOperand) { super(leftOperand, rightOperand); } @Override public ExpressionDef generateExpression(ExpressionCompilationContext ctx) { return leftOperand.compile(ctx).isTrue() .or( rightOperand.compile(ctx).isTrue() ); } }
OrOperator
java
apache__camel
core/camel-support/src/main/java/org/apache/camel/support/component/ApiMethodHelper.java
{ "start": 1424, "end": 23104 }
class ____<T extends Enum<T> & ApiMethod> { private static final Logger LOG = LoggerFactory.getLogger(ApiMethodHelper.class); // maps method name to ApiMethod private final Map<String, List<T>> methodMap; // maps method name to method arguments of the form Class type1, String name1, Class type2, String name2,... private final Map<String, List<Object>> argumentsMap; // maps argument name to argument type private final Map<String, Class<?>> validArguments; // maps aliases to actual method names private final Map<String, Set<String>> aliasesMap; // nullable args private final List<String> nullableArguments; /** * Create a helper to work with a {@link ApiMethod}, using optional method aliases. * * @param apiMethodEnum {@link ApiMethod} enumeration class * @param aliases Aliases mapped to actual method names * @param nullableArguments names of arguments that default to null value */ public ApiMethodHelper(Class<T> apiMethodEnum, Map<String, String> aliases, List<String> nullableArguments) { Map<String, List<T>> tmpMethodMap = new HashMap<>(); Map<String, List<Object>> tmpArgumentsMap = new HashMap<>(); Map<String, Class<?>> tmpValidArguments = new HashMap<>(); Map<String, Set<String>> tmpAliasesMap = new HashMap<>(); // validate ApiMethod Enum if (apiMethodEnum == null) { throw new IllegalArgumentException("ApiMethod enumeration cannot be null"); } if (nullableArguments != null && !nullableArguments.isEmpty()) { this.nullableArguments = Collections.unmodifiableList(new ArrayList<>(nullableArguments)); } else { this.nullableArguments = Collections.emptyList(); } final Map<Pattern, String> aliasPatterns = new HashMap<>(); for (Map.Entry<String, String> alias : aliases.entrySet()) { if (alias.getKey() == null || alias.getValue() == null) { throw new IllegalArgumentException("Alias pattern and replacement cannot be null"); } aliasPatterns.put(Pattern.compile(alias.getKey()), alias.getValue()); } LOG.debug("Processing {}", apiMethodEnum.getName()); final T[] methods = apiMethodEnum.getEnumConstants(); // load lookup maps for (T method : methods) { final String name = method.getName(); // add method name aliases for (Map.Entry<Pattern, String> aliasEntry : aliasPatterns.entrySet()) { final Matcher matcher = aliasEntry.getKey().matcher(name); if (matcher.find()) { // add method name alias String alias = matcher.replaceAll(aliasEntry.getValue()); // convert first character to lowercase ObjectHelper.notNullOrEmpty(alias, "alias"); final char firstChar = alias.charAt(0); if (!Character.isLowerCase(firstChar)) { final StringBuilder builder = new StringBuilder(alias.length() + 2); builder.append(Character.toLowerCase(firstChar)).append(alias, 1, alias.length()); alias = builder.toString(); } Set<String> names = tmpAliasesMap.computeIfAbsent(alias, k -> new HashSet<>()); names.add(name); } } // map method name to Enum List<T> overloads = tmpMethodMap.get(name); if (overloads == null) { overloads = new ArrayList<>(); tmpMethodMap.put(method.getName(), overloads); } overloads.add(method); // add arguments for this method List<Object> arguments = tmpArgumentsMap.get(name); if (arguments == null) { arguments = new ArrayList<>(); tmpArgumentsMap.put(name, arguments); } // process all arguments for this method final int nArgs = method.getArgNames().size(); final String[] argNames = method.getArgNames().toArray(new String[nArgs]); final Class<?>[] argTypes = method.getArgTypes().toArray(new Class[nArgs]); for (int i = 0; i < nArgs; i++) { final String argName = argNames[i]; final Class<?> argType = argTypes[i]; if (!arguments.contains(argName)) { arguments.add(argType); arguments.add(argName); } // also collect argument names for all methods, and detect clashes here final Class<?> previousType = tmpValidArguments.get(argName); if (previousType != null && previousType != argType) { throw new IllegalArgumentException( String.format( "Argument %s has ambiguous types (%s, %s) across methods!", name, previousType, argType)); } else if (previousType == null) { tmpValidArguments.put(argName, argType); } } } // validate nullableArguments if (!tmpValidArguments.keySet().containsAll(this.nullableArguments)) { List<String> unknowns = new ArrayList<>(this.nullableArguments); unknowns.removeAll(tmpValidArguments.keySet()); throw new IllegalArgumentException("Unknown nullable arguments " + unknowns); } // validate aliases for (Map.Entry<String, Set<String>> entry : tmpAliasesMap.entrySet()) { // look for aliases that match multiple methods final Set<String> methodNames = entry.getValue(); if (methodNames.size() > 1) { // get mapped methods final List<T> aliasedMethods = new ArrayList<>(); for (String methodName : methodNames) { List<T> mappedMethods = tmpMethodMap.get(methodName); aliasedMethods.addAll(mappedMethods); } // look for argument overlap for (T method : aliasedMethods) { final List<String> argNames = new ArrayList<>(method.getArgNames()); argNames.removeAll(this.nullableArguments); final Set<T> ambiguousMethods = new HashSet<>(); for (T otherMethod : aliasedMethods) { if (method != otherMethod) { final List<String> otherArgsNames = new ArrayList<>(otherMethod.getArgNames()); otherArgsNames.removeAll(this.nullableArguments); if (argNames.equals(otherArgsNames)) { ambiguousMethods.add(method); ambiguousMethods.add(otherMethod); } } } if (!ambiguousMethods.isEmpty()) { throw new IllegalArgumentException( String.format("Ambiguous alias %s for methods %s", entry.getKey(), ambiguousMethods)); } } } } this.methodMap = Collections.unmodifiableMap(tmpMethodMap); this.argumentsMap = Collections.unmodifiableMap(tmpArgumentsMap); this.validArguments = Collections.unmodifiableMap(tmpValidArguments); this.aliasesMap = Collections.unmodifiableMap(tmpAliasesMap); LOG.debug("Found {} unique method names in {} methods", tmpMethodMap.size(), methods.length); } /** * Gets methods that match the given name and arguments. * <p/> * Note that the args list is a required subset of arguments for returned methods. * * @param name case sensitive method name or alias to lookup * @return non-null unmodifiable list of methods that take all of the given arguments, empty if there is no * match */ public List<ApiMethod> getCandidateMethods(String name) { return getCandidateMethods(name, Collections.emptyList()); } /** * Gets methods that match the given name and arguments. * <p/> * Note that the args list is a required subset of arguments for returned methods. * * @param name case sensitive method name or alias to lookup * @param argNames unordered required argument names * @return non-null unmodifiable list of methods that take all of the given arguments, empty if there is no * match */ public List<ApiMethod> getCandidateMethods(String name, Collection<String> argNames) { List<T> methods = methodMap.get(name); if (methods == null) { if (aliasesMap.containsKey(name)) { methods = new ArrayList<>(); for (String method : aliasesMap.get(name)) { methods.addAll(methodMap.get(method)); } } } if (methods == null) { LOG.debug("No matching method for method {}", name); return Collections.emptyList(); } int nArgs = argNames != null ? argNames.size() : 0; if (nArgs == 0) { LOG.debug("Found {} methods for method {}", methods.size(), name); return Collections.unmodifiableList(methods); } else { final List<ApiMethod> filteredSet = filterMethods(methods, MatchType.SUBSET, argNames); if (LOG.isDebugEnabled()) { LOG.debug("Found {} filtered methods for {}", filteredSet.size(), name + argNames.toString().replace('[', '(').replace(']', ')')); } return filteredSet; } } /** * Filters a list of methods to those that take the given set of arguments. * * @param methods list of methods to filter * @param matchType whether the arguments are an exact match, a subset or a super set of method args * @return methods with arguments that satisfy the match type. * <p/> * For SUPER_SET match, if methods with exact match are found, methods that take a subset are * ignored */ public List<ApiMethod> filterMethods(List<? extends ApiMethod> methods, MatchType matchType) { return filterMethods(methods, matchType, Collections.emptyList()); } /** * Filters a list of methods to those that take the given set of arguments. * * @param methods list of methods to filter * @param matchType whether the arguments are an exact match, a subset or a super set of method args * @param argNames argument names to filter the list * @return methods with arguments that satisfy the match type. * <p/> * For SUPER_SET match, if methods with exact match are found, methods that take a subset are * ignored */ public List<ApiMethod> filterMethods(List<? extends ApiMethod> methods, MatchType matchType, Collection<String> argNames) { // list of methods that have all args in the given names List<ApiMethod> result = new ArrayList<>(); List<ApiMethod> extraArgs = null; List<ApiMethod> nullArgs = null; for (ApiMethod method : methods) { final List<String> methodArgs = method.getArgNames(); final HashSet<String> stringHashSet = new HashSet<>(methodArgs); // remove all the setter arguments from the input so we can match the mandatory arguments // for selecting the correct api method based on its method signature final Collection<String> methodArgNames = new ArrayList<>(argNames); methodArgNames.removeAll(method.getSetterArgNames()); // original arguments // supplied arguments with missing nullable arguments final List<String> withNullableArgsList; if (!nullableArguments.isEmpty()) { withNullableArgsList = new ArrayList<>(methodArgNames); withNullableArgsList.addAll(nullableArguments); } else { withNullableArgsList = null; } switch (matchType) { case EXACT: // method must take all args, and no more if (stringHashSet.containsAll(methodArgNames) && methodArgNames.containsAll(methodArgs)) { result.add(method); } break; case SUBSET: // all args are required, method may take more if (stringHashSet.containsAll(methodArgNames)) { result.add(method); } break; default: case SUPER_SET: // all method args must be present if (methodArgNames.containsAll(methodArgs)) { if (stringHashSet.containsAll(methodArgNames)) { // prefer exact match to avoid unused args result.add(method); } else if (result.isEmpty()) { // if result is empty, add method to extra args list if (extraArgs == null) { extraArgs = new ArrayList<>(); } // method takes a subset, unused args extraArgs.add(method); } } else if (result.isEmpty() && extraArgs == null) { // avoid looking for nullable args by checking for empty result and extraArgs if (withNullableArgsList != null && new HashSet<>(withNullableArgsList).containsAll(methodArgs)) { if (nullArgs == null) { nullArgs = new ArrayList<>(); } nullArgs.add(method); } } break; } } List<ApiMethod> methodList = result.isEmpty() ? extraArgs == null ? nullArgs : extraArgs : result; // preference order is exact match, matches with extra args, matches with null args return methodList != null ? Collections.unmodifiableList(methodList) : Collections.emptyList(); } /** * Gets argument types and names for all overloaded methods and aliases with the given name. * * @param name method name, either an exact name or an alias, exact matches are checked first * @return list of arguments of the form Class type1, String name1, Class type2, String name2,... */ public List<Object> getArguments(final String name) throws IllegalArgumentException { List<Object> arguments = argumentsMap.get(name); if (arguments == null) { if (aliasesMap.containsKey(name)) { arguments = new ArrayList<>(); for (String method : aliasesMap.get(name)) { arguments.addAll(argumentsMap.get(method)); } } } if (arguments == null) { throw new IllegalArgumentException(name); } return Collections.unmodifiableList(arguments); } /** * Get missing properties. * * @param methodName method name * @param argNames available arguments * @return Set of missing argument names */ public Set<String> getMissingProperties(String methodName, Set<String> argNames) { final List<Object> argsWithTypes = getArguments(methodName); final Set<String> missingArgs = new HashSet<>(); for (int i = 1; i < argsWithTypes.size(); i += 2) { final String name = (String) argsWithTypes.get(i); if (!argNames.contains(name)) { missingArgs.add(name); } } return missingArgs; } /** * Returns alias map. * * @return alias names mapped to method names. */ public Map<String, Set<String>> getAliases() { return aliasesMap; } /** * Returns argument types and names used by all methods. * * @return map with argument names as keys, and types as values */ public Map<String, Class<?>> allArguments() { return validArguments; } /** * Returns argument names that can be set to null if not specified. * * @return list of argument names */ public List<String> getNullableArguments() { return nullableArguments; } /** * Get the type for the given argument name. * * @param argName argument name * @return argument type */ public Class<?> getType(String argName) throws IllegalArgumentException { final Class<?> type = validArguments.get(argName); if (type == null) { throw new IllegalArgumentException(argName); } return type; } // this method is always called with Enum value lists, so the cast inside is safe // the alternative of trying to convert ApiMethod and associated classes to generic classes would a bear!!! @SuppressWarnings("unchecked") public static ApiMethod getHighestPriorityMethod(List<? extends ApiMethod> filteredMethods) { Comparable<ApiMethod> highest = null; for (ApiMethod method : filteredMethods) { if (highest == null || highest.compareTo(method) <= 0) { highest = (Comparable<ApiMethod>) method; } } return (ApiMethod) highest; } /** * Invokes given method with argument values from given properties. * * @param proxy Proxy object for invoke * @param method method to invoke * @param properties Map of arguments * @return result of method invocation * @throws org.apache.camel.RuntimeCamelException on errors */ public static Object invokeMethod(Object proxy, ApiMethod method, Map<String, Object> properties) throws RuntimeCamelException { if (LOG.isDebugEnabled()) { LOG.debug("Invoking {} with arguments {}", method.getName(), properties); } final List<String> argNames = method.getArgNames(); final Object[] values = new Object[argNames.size()]; final List<Class<?>> argTypes = method.getArgTypes(); final Class<?>[] types = argTypes.toArray(new Class[0]); int index = 0; for (String name : argNames) { Object value = properties.get(name); // is the parameter an array type? if (value != null && types[index].isArray()) { Class<?> type = types[index]; if (value instanceof Collection<?> collection) { // convert collection to array Object array = Array.newInstance(type.getComponentType(), collection.size()); if (array instanceof Object[] objects) { collection.toArray(objects); } else { int i = 0; for (Object el : collection) { Array.set(array, i++, el); } } value = array; } else if (value.getClass().isArray() && type.getComponentType().isAssignableFrom(value.getClass().getComponentType())) { // convert derived array to super array if needed if (type.getComponentType() != value.getClass().getComponentType()) { final int size = Array.getLength(value); Object array = Array.newInstance(type.getComponentType(), size); for (int i = 0; i < size; i++) { Array.set(array, i, Array.get(value, i)); } value = array; } } else { throw new IllegalArgumentException( String.format("Cannot convert %s to %s", value.getClass(), type)); } } values[index++] = value; } try { return method.getMethod().invoke(proxy, values); } catch (InvocationTargetException e) { final Throwable cause = e.getCause(); String message = cause != null ? cause.getMessage() : e.getMessage(); throw new RuntimeCamelException( String.format("Error invoking %s with %s: %s", method.getName(), properties, message), cause != null ? cause : e); } catch (Exception e) { throw new RuntimeCamelException( String.format("Error invoking %s with %s: %s", method.getName(), properties, e.getMessage()), e); } } public
ApiMethodHelper
java
junit-team__junit5
junit-jupiter-api/src/main/java/org/junit/jupiter/api/BeforeEach.java
{ "start": 1800, "end": 1989 }
interface ____ * methods</em> are inherited as long as they are not overridden, and * {@code @BeforeEach} default methods will be executed before {@code @BeforeEach} * methods in the
default
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/function/client/ClientResponse.java
{ "start": 9058, "end": 9778 }
interface ____ { /** * Return the length of the body in bytes, as specified by the * {@code Content-Length} header. */ OptionalLong contentLength(); /** * Return the {@linkplain MediaType media type} of the body, as specified * by the {@code Content-Type} header. */ Optional<MediaType> contentType(); /** * Return the header value(s), if any, for the header of the given name. * <p>Return an empty list if no header values are found. * @param headerName the header name */ List<String> header(String headerName); /** * Return the headers as an {@link HttpHeaders} instance. */ HttpHeaders asHttpHeaders(); } /** * Defines a builder for a response. */
Headers
java
alibaba__nacos
test/naming-test/src/test/java/com/alibaba/nacos/test/naming/RestAPINamingITCase.java
{ "start": 1601, "end": 9229 }
class ____ extends NamingBase { @LocalServerPort private int port; @BeforeEach void setUp() throws Exception { String url = String.format("http://localhost:%d/", port); this.base = new URL(url); isNamingServerReady(); //prepareData(); } @AfterEach void cleanup() throws Exception { //removeData(); } @Test void metrics() throws Exception { ResponseEntity<String> response = request("/nacos/v1/ns/operator/metrics", Params.newParams().appendParam("onlyStatus", "false").done(), String.class); assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); assertNotNull(json.get("serviceCount")); assertNotNull(json.get("instanceCount")); assertNotNull(json.get("responsibleInstanceCount")); assertNotNull(json.get("clientCount")); assertNotNull(json.get("connectionBasedClientCount")); assertNotNull(json.get("ephemeralIpPortClientCount")); assertNotNull(json.get("persistentIpPortClientCount")); assertNotNull(json.get("responsibleClientCount")); } /** * @TCDescription : 根据serviceName创建服务 * @TestStep : * @ExpectResult : */ @Test void createService() throws Exception { String serviceName = NamingBase.randomDomainName(); ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") .done(), String.class, HttpMethod.POST); assertTrue(response.getStatusCode().is2xxSuccessful()); assertEquals("ok", response.getBody()); namingServiceDelete(serviceName); } /** * @TCDescription : 根据serviceName获取服务信息 * @TestStep : * @ExpectResult : */ @Test void getService() throws Exception { String serviceName = NamingBase.randomDomainName(); ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") .done(), String.class, HttpMethod.POST); assertTrue(response.getStatusCode().is2xxSuccessful()); assertEquals("ok", response.getBody()); //get service response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") .done(), String.class); assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); assertEquals(serviceName, json.get("name").asText()); namingServiceDelete(serviceName); } /** * @TCDescription : 获取服务list信息 * @TestStep : * @ExpectResult : */ @Test void listService() throws Exception { String serviceName = NamingBase.randomDomainName(); //get service ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/list", Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1") .appendParam("pageSize", "150").done(), String.class); assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); int count = json.get("count").asInt(); assertTrue(count >= 0); response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") .done(), String.class, HttpMethod.POST); assertTrue(response.getStatusCode().is2xxSuccessful()); assertEquals("ok", response.getBody()); response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service/list", Params.newParams().appendParam("serviceName", serviceName).appendParam("pageNo", "1") .appendParam("pageSize", "150").done(), String.class); assertTrue(response.getStatusCode().is2xxSuccessful()); json = JacksonUtils.toObj(response.getBody()); assertEquals(count + 1, json.get("count").asInt()); namingServiceDelete(serviceName); } /** * @TCDescription : 更新serviceName获取服务信息 * @TestStep : * @ExpectResult : */ @Test void updateService() throws Exception { String serviceName = NamingBase.randomDomainName(); ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.6") .done(), String.class, HttpMethod.POST); assertTrue(response.getStatusCode().is2xxSuccessful()); assertEquals("ok", response.getBody()); //update service response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", Params.newParams().appendParam("serviceName", serviceName).appendParam("healthCheckMode", "server") .appendParam("protectThreshold", "0.3").done(), String.class, HttpMethod.PUT); assertTrue(response.getStatusCode().is2xxSuccessful()); assertEquals("ok", response.getBody()); //get service response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", Params.newParams().appendParam("serviceName", serviceName).done(), String.class); assertTrue(response.getStatusCode().is2xxSuccessful()); JsonNode json = JacksonUtils.toObj(response.getBody()); assertEquals(0.3f, json.get("protectThreshold").floatValue(), 0.0f); namingServiceDelete(serviceName); } @Test @Disabled void testInvalidNamespace() { String serviceName = NamingBase.randomDomainName(); ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.6") .appendParam("namespaceId", "..invalid-namespace").done(), String.class, HttpMethod.POST); assertTrue(response.getStatusCode().is4xxClientError()); response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.6") .appendParam("namespaceId", "/invalid-namespace").done(), String.class, HttpMethod.POST); assertTrue(response.getStatusCode().is4xxClientError()); } private void namingServiceDelete(String serviceName) { //delete service ResponseEntity<String> response = request(NamingBase.NAMING_CONTROLLER_PATH + "/service", Params.newParams().appendParam("serviceName", serviceName).appendParam("protectThreshold", "0.3") .done(), String.class, HttpMethod.DELETE); assertTrue(response.getStatusCode().is2xxSuccessful()); assertEquals("ok", response.getBody()); } }
RestAPINamingITCase
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/BulkTypeConverters.java
{ "start": 1311, "end": 1464 }
class ____ then used at runtime as an optimized and really fast way of using all those type * converters by the {@link TypeConverterRegistry}. */ public
is
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/TaskExecutionState.java
{ "start": 1196, "end": 1486 }
class ____ an update about a task's execution state. * * <p><b>NOTE:</b> The exception that may be attached to the state update is not necessarily a Flink * or core Java exception, but may be an exception from the user code. As such, it cannot be * deserialized without a special
represents
java
apache__rocketmq
store/src/main/java/org/apache/rocketmq/store/SelectMappedBufferResult.java
{ "start": 927, "end": 2419 }
class ____ { private final long startOffset; private final ByteBuffer byteBuffer; private int size; protected MappedFile mappedFile; private boolean isInCache = true; public SelectMappedBufferResult(long startOffset, ByteBuffer byteBuffer, int size, MappedFile mappedFile) { this.startOffset = startOffset; this.byteBuffer = byteBuffer; this.size = size; this.mappedFile = mappedFile; } public ByteBuffer getByteBuffer() { return byteBuffer; } public int getSize() { return size; } public void setSize(final int s) { this.size = s; this.byteBuffer.limit(this.size); } public MappedFile getMappedFile() { return mappedFile; } public synchronized void release() { if (this.mappedFile != null) { this.mappedFile.release(); this.mappedFile = null; } } public synchronized boolean hasReleased() { return this.mappedFile == null; } public long getStartOffset() { return startOffset; } public boolean isInMem() { if (mappedFile == null) { return true; } long pos = startOffset - mappedFile.getFileFromOffset(); return mappedFile.isLoaded(pos, size); } public boolean isInCache() { return isInCache; } public void setInCache(boolean inCache) { isInCache = inCache; } }
SelectMappedBufferResult
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/vectors/TestQueryVectorBuilderPlugin.java
{ "start": 1140, "end": 1220 }
class ____ implements SearchPlugin { public static
TestQueryVectorBuilderPlugin
java
google__gson
gson/src/main/java/com/google/gson/ToNumberStrategy.java
{ "start": 2705, "end": 3080 }
interface ____ { /** * Reads a number from the given JSON reader. A strategy is supposed to read a single value from * the reader, and the read value is guaranteed never to be {@code null}. * * @param in JSON reader to read a number from * @return number read from the JSON reader. */ Number readNumber(JsonReader in) throws IOException; }
ToNumberStrategy
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/service/connection/ConnectionDetailsNotFoundException.java
{ "start": 905, "end": 1294 }
class ____ extends RuntimeException { <S> ConnectionDetailsNotFoundException(S source) { this("No ConnectionDetails found for source '%s'".formatted(source)); } public ConnectionDetailsNotFoundException(String message) { super(message); } public ConnectionDetailsNotFoundException(String message, Throwable cause) { super(message, cause); } }
ConnectionDetailsNotFoundException
java
quarkusio__quarkus
extensions/micrometer/runtime/src/main/java/io/quarkus/micrometer/runtime/binder/vertx/VertxUdpMetrics.java
{ "start": 442, "end": 2225 }
class ____ implements DatagramSocketMetrics { private volatile Tags tags; private final Meter.MeterProvider<DistributionSummary> read; private final Meter.MeterProvider<DistributionSummary> sent; private final Meter.MeterProvider<Counter> exceptions; public VertxUdpMetrics(MeterRegistry registry, String prefix, Tags tags) { this.tags = tags; read = DistributionSummary.builder(prefix + ".bytes.read") .description("Number of bytes read") .withRegistry(registry); sent = DistributionSummary.builder(prefix + ".bytes.written") .description("Number of bytes written") .withRegistry(registry); exceptions = Counter.builder(prefix + ".errors") .description("Number of exceptions") .withRegistry(registry); } @Override public void listening(String localName, SocketAddress localAddress) { tags = tags.and("address", NetworkMetrics.toString(localAddress)); } @Override public void bytesRead(Void socketMetric, SocketAddress remoteAddress, long numberOfBytes) { read.withTags(tags.and("remote-address", NetworkMetrics.toString(remoteAddress))) .record(numberOfBytes); } @Override public void bytesWritten(Void socketMetric, SocketAddress remoteAddress, long numberOfBytes) { sent.withTags(tags.and("remote-address", NetworkMetrics.toString(remoteAddress))) .record(numberOfBytes); } @Override public void exceptionOccurred(Void socketMetric, SocketAddress remoteAddress, Throwable t) { Tags copy = this.tags.and(Tag.of("class", t.getClass().getName())); exceptions.withTags(copy).increment(); } }
VertxUdpMetrics
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/foreach/noqualifier/MyEach3User.java
{ "start": 239, "end": 447 }
class ____ { private final List<MyEach3> beans; public MyEach3User(List<MyEach3> beans) { this.beans = beans; } public List<MyEach3> getAll() { return beans; } }
MyEach3User
java
quarkusio__quarkus
extensions/mongodb-client/deployment/src/test/java/io/quarkus/mongodb/NamedReactiveMongoClientConfigTest.java
{ "start": 1242, "end": 4357 }
class ____ extends MongoWithReplicasTestBase { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar.addClasses(MongoTestBase.class)) .withConfigurationResource("application-named-mongoclient.properties"); @Inject @MongoClientName("cluster1") ReactiveMongoClient client; @Inject @MongoClientName("cluster2") ReactiveMongoClient client2; @Inject @Any MongoHealthCheck health; @AfterEach void cleanup() { if (client != null) { client.close(); } if (client2 != null) { client2.close(); } } @Test public void testNamedDataSourceInjection() { assertProperConnection(client, 27018); assertProperConnection(client2, 27019); assertThat(client.listDatabases().collect().first().await().indefinitely()).isNotEmpty(); assertThat(client2.listDatabases().collect().first().await().indefinitely()).isNotEmpty(); assertNoDefaultClient(); checkHealth(); } public void checkHealth() { org.eclipse.microprofile.health.HealthCheckResponse response = health.call(); assertThat(response.getStatus()).isEqualTo(HealthCheckResponse.Status.UP); assertThat(response.getData()).isNotEmpty(); assertThat(response.getData().get()).hasSize(2).contains(entry("cluster1", "OK"), entry("cluster2", "OK")); } private void assertProperConnection(ReactiveMongoClient client, int expectedPort) { assertThat(ClientProxy.unwrap(client)).isInstanceOfSatisfying(ReactiveMongoClientImpl.class, rc -> { Field mongoClientField; try { mongoClientField = ReactiveMongoClientImpl.class.getDeclaredField("client"); } catch (NoSuchFieldException e) { throw new RuntimeException(e); } mongoClientField.setAccessible(true); MongoClient c; try { c = (MongoClientImpl) mongoClientField.get(rc); } catch (IllegalAccessException e) { throw new RuntimeException(e); } assertThat(c.getClusterDescription().getClusterSettings().getHosts()).singleElement().satisfies(sa -> { assertThat(sa.getPort()).isEqualTo(expectedPort); }); }); } private void assertNoDefaultClient() { boolean hasDefault = false; for (InstanceHandle<ReactiveMongoClient> handle : Arc.container().select(ReactiveMongoClient.class).handles()) { InjectableBean<ReactiveMongoClient> bean = handle.getBean(); for (Annotation qualifier : bean.getQualifiers()) { if (qualifier.annotationType().equals(Default.class)) { hasDefault = true; } } } Assertions.assertFalse(hasDefault, "The default reactive mongo client should not have been present as it is not used in any injection point"); } }
NamedReactiveMongoClientConfigTest
java
apache__kafka
metadata/src/test/java/org/apache/kafka/image/writer/RaftSnapshotWriterTest.java
{ "start": 1267, "end": 2314 }
class ____ { @Test public void testFreezeAndClose() { FakeSnapshotWriter snapshotWriter = new FakeSnapshotWriter(); RaftSnapshotWriter writer = new RaftSnapshotWriter(snapshotWriter, 2); writer.write(testRecord(0)); writer.write(testRecord(1)); writer.write(testRecord(2)); writer.close(true); assertTrue(snapshotWriter.isFrozen()); assertTrue(snapshotWriter.isClosed()); assertEquals(List.of( List.of(testRecord(0), testRecord(1)), List.of(testRecord(2))), snapshotWriter.batches()); } @Test public void testCloseWithoutFreeze() { FakeSnapshotWriter snapshotWriter = new FakeSnapshotWriter(); RaftSnapshotWriter writer = new RaftSnapshotWriter(snapshotWriter, 2); writer.write(testRecord(0)); writer.close(); assertFalse(snapshotWriter.isFrozen()); assertTrue(snapshotWriter.isClosed()); assertEquals(List.of(), snapshotWriter.batches()); } }
RaftSnapshotWriterTest
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/deployment/DeploymentTest.java
{ "start": 36704, "end": 38064 }
class ____ extends AbstractVerticle { @Override public void stop(Promise<Void> stopPromise) { vertx.deployVerticle(ChildVerticle.class.getName()) .<Void>mapEmpty() .onComplete(stopPromise); } } vertx.deployVerticle(new ParentVerticle()).onComplete(onSuccess(id -> vertx.undeploy(id).onComplete(onFailure(u -> testComplete())))); await(); } @Test public void testUndeployAllFailureInUndeploy() throws Exception { int numVerticles = 10; List<MyVerticle> verticles = new ArrayList<>(); CountDownLatch latch = new CountDownLatch(numVerticles); for (int i = 0; i < numVerticles; i++) { MyVerticle verticle = new MyVerticle(MyVerticle.NOOP, MyVerticle.THROW_EXCEPTION); verticles.add(verticle); vertx.deployVerticle(verticle).onComplete(onSuccess(v -> { latch.countDown(); })); } awaitLatch(latch); vertx.close().onComplete(onSuccess(v -> { for (MyVerticle verticle: verticles) { assertFalse(verticle.stopCalled); } testComplete(); })); await(); vertx = null; } @Test public void testUndeployAllNoDeployments() throws Exception { vertx.close().onComplete(onSuccess(v -> testComplete())); await(); vertx = null; } @Test public void testGetInstanceCount() {
ParentVerticle
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/Compatibility.java
{ "start": 1760, "end": 4779 }
class ____ null return true; } if ( to.isAssignableFrom( from ) ) { return true; } // if to/from are primitive or primitive wrappers we need to check a little deeper if ( to.isPrimitive() ) { if ( from.isPrimitive() ) { return areAssignmentCompatiblePrimitive( to, from ); } else if ( isWrapper( from ) ) { return areAssignmentCompatiblePrimitive( to, primitiveEquivalent( from ) ); } } return false; } private static boolean areAssignmentCompatiblePrimitive(Class<?> to, Class<?> from) { assert to != null; assert from != null; assert to.isPrimitive(); assert from.isPrimitive(); // technically any number can be assigned to any other number, although potentially with loss of precision if ( to == boolean.class ) { return from == boolean.class; } else if ( to == char.class ) { return from == char.class; } else if ( to == byte.class ) { return from == byte.class; } else if ( isIntegralTypePrimitive( to ) ) { return from == byte.class || isCompatibleIntegralTypePrimitive( to, from ) // this would for sure cause loss of precision || isFloatingTypePrimitive( from ); } else if ( isFloatingTypePrimitive( to ) ) { return from == byte.class || isIntegralTypePrimitive( from ) || isCompatibleFloatingTypePrimitive( to, from ); } return false; } public static boolean isIntegralType(Class<?> potentialIntegral) { if ( potentialIntegral.isPrimitive() ) { return isIntegralTypePrimitive( potentialIntegral ); } return isWrapper( potentialIntegral ) && isIntegralTypePrimitive( primitiveEquivalent( potentialIntegral ) ); } private static boolean isIntegralTypePrimitive(Class<?> potentialIntegral) { assert potentialIntegral.isPrimitive(); return potentialIntegral == short.class || potentialIntegral == int.class || potentialIntegral == long.class; } private static boolean isCompatibleIntegralTypePrimitive(Class<?> to, Class<?> from) { assert isIntegralTypePrimitive( to ); assert from.isPrimitive(); if ( to == short.class ) { return from == short.class; } else if ( to == int.class ) { return from == short.class || from == int.class; } else { return isIntegralTypePrimitive( from ); } } public static boolean isFloatingType(Class<?> potentialFloating) { if ( potentialFloating.isPrimitive() ) { return isFloatingTypePrimitive( potentialFloating ); } return isWrapper( potentialFloating ) && isFloatingTypePrimitive( primitiveEquivalent( potentialFloating ) ); } private static boolean isFloatingTypePrimitive(Class<?> potentialFloating) { assert potentialFloating.isPrimitive(); return potentialFloating == float.class || potentialFloating == double.class; } private static boolean isCompatibleFloatingTypePrimitive(Class<?> to, Class<?> from) { assert isFloatingTypePrimitive( to ); assert from.isPrimitive(); return to == float.class ? from == float.class : isFloatingTypePrimitive( from ); } }
of
java
quarkusio__quarkus
extensions/spring-web/resteasy-reactive/runtime/src/main/java/io/quarkus/spring/web/resteasy/reactive/runtime/SpringMultiValueMapParamExtractor.java
{ "start": 418, "end": 837 }
class ____ implements ParameterExtractor { @Override public Object extractParameter(ResteasyReactiveRequestContext context) { Map<String, List<String>> parametersMap = context.serverRequest().getQueryParamsMap(); MultiValueMap<String, String> springMap = new LinkedMultiValueMap<>(); parametersMap.forEach(springMap::put); return springMap; } }
SpringMultiValueMapParamExtractor
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/FluxCallableTest.java
{ "start": 888, "end": 2298 }
class ____ { @Test public void callableReturnsNull() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Mono.<Integer>fromCallable(() -> null).log().flux() .subscribe(ts); ts.assertNoValues() .assertNoError() .assertComplete(); } @Test public void normal() { AssertSubscriber<Integer> ts = AssertSubscriber.create(); Mono.fromCallable(() -> 1) .flux() .subscribe(ts); ts.assertValues(1) .assertComplete() .assertNoError(); } @Test public void normalBackpressured() { AssertSubscriber<Integer> ts = AssertSubscriber.create(0); Mono.fromCallable(() -> 1) .flux() .subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertNoError(); ts.request(1); ts.assertValues(1) .assertComplete() .assertNoError(); } @Test public void callableThrows() { AssertSubscriber<Object> ts = AssertSubscriber.create(); Mono.fromCallable(() -> { throw new IOException("forced failure"); }) .flux() .subscribe(ts); ts.assertNoValues() .assertNotComplete() .assertError(IOException.class) .assertErrorMessage("forced failure"); } @Test public void scanOperator(){ FluxCallable<Integer> test = new FluxCallable<>(() -> 1 ); assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC); } }
FluxCallableTest
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/statement/MySqlShowFunctionStatusStatement.java
{ "start": 794, "end": 1433 }
class ____ extends MySqlStatementImpl implements MySqlShowStatement { private SQLExpr like; private SQLExpr where; public SQLExpr getLike() { return like; } public void setLike(SQLExpr like) { this.like = like; } public SQLExpr getWhere() { return where; } public void setWhere(SQLExpr where) { this.where = where; } public void accept0(MySqlASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, like); acceptChild(visitor, where); } visitor.endVisit(this); } }
MySqlShowFunctionStatusStatement
java
google__guice
extensions/dagger-adapter/test/com/google/inject/daggeradapter/BindsTest.java
{ "start": 3940, "end": 5018 }
interface ____ { @Provides @JakartaProvidesQualifier static String provides() { return "jakarta qualified!"; } @Binds @JakartaBindsQualifier String bindsToProvides(@JakartaProvidesQualifier String provides); @Binds String unqualifiedToBinds(@JakartaBindsQualifier String binds); } public void testJakartaQualifiers() { Injector injector = Guice.createInjector(DaggerAdapter.from(JakartaQualifiedBinds.class)); Binding<String> stringBinding = injector.getBinding(String.class); assertThat(stringBinding).hasProvidedValueThat().isEqualTo("jakarta qualified!"); assertThat(stringBinding) .hasSource(JakartaQualifiedBinds.class, "unqualifiedToBinds", String.class); Binding<String> qualifiedBinds = injector.getBinding(Key.get(String.class, JakartaBindsQualifier.class)); assertThat(qualifiedBinds).hasProvidedValueThat().isEqualTo("jakarta qualified!"); assertThat(qualifiedBinds) .hasSource(JakartaQualifiedBinds.class, "bindsToProvides", String.class); } }
JakartaQualifiedBinds
java
spring-projects__spring-framework
spring-jms/src/main/java/org/springframework/jms/listener/AbstractJmsListeningContainer.java
{ "start": 1452, "end": 1748 }
class ____ all containers which need to implement listening * based on a JMS Connection (either shared or freshly obtained for each attempt). * Inherits basic Connection and Session configuration handling from the * {@link org.springframework.jms.support.JmsAccessor} base class. * * <p>This
for
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/CamelSpringXSDValidateTest.java
{ "start": 1279, "end": 1930 }
class ____ { @Test public void testValidateXSD() throws Exception { Resource r = new FileSystemResource("target/classes/camel-spring.xsd"); Resource r2 = new ClassPathResource("org/springframework/beans/factory/xml/spring-beans.xsd"); XmlValidator val = XmlValidatorFactory.createValidator(new Resource[] { r, r2 }, XmlValidatorFactory.SCHEMA_W3C_XML); Resource r3 = new ClassPathResource("org/apache/camel/spring/processor/choice.xml"); SAXParseException[] err = val.validate(new BytesSource(r3.getContentAsByteArray())); Assertions.assertEquals(0, err.length); } }
CamelSpringXSDValidateTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/sql/internal/StandardSqmTranslator.java
{ "start": 663, "end": 1240 }
class ____<T extends Statement> extends BaseSqmToSqlAstConverter<T> { public StandardSqmTranslator( SqmStatement<?> statement, QueryOptions queryOptions, DomainParameterXref domainParameterXref, QueryParameterBindings domainParameterBindings, LoadQueryInfluencers fetchInfluencers, SqlAstCreationContext creationContext, boolean deduplicateSelectionItems) { super( creationContext, statement, queryOptions, fetchInfluencers, domainParameterXref, domainParameterBindings, deduplicateSelectionItems ); } }
StandardSqmTranslator
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FromFtpAsyncProcessIT.java
{ "start": 1397, "end": 3153 }
class ____ extends FtpServerTestSupport { private String getFtpUrl() { return "ftp://admin@localhost:{{ftp.server.port}}/async/?password=admin&delete=true"; } @Test public void testFtpAsyncProcess() throws Exception { template.sendBodyAndHeader("file:{{ftp.root.dir}}/async", "Hello World", Exchange.FILE_NAME, "hello.txt"); template.sendBodyAndHeader("file:{{ftp.root.dir}}/async", "Bye World", Exchange.FILE_NAME, "bye.txt"); getMockEndpoint("mock:result").expectedMessageCount(2); getMockEndpoint("mock:result").expectedHeaderReceived("foo", 123); // the log file should log that all the ftp client work is done in the // same thread (fully synchronous) // as the ftp client is not thread safe and must process fully // synchronous context.getRouteController().startRoute("foo"); MockEndpoint.assertIsSatisfied(context); // give time for files to be deleted on ftp server File hello = service.ftpFile("async/hello.txt").toFile(); await().atMost(1, TimeUnit.SECONDS) .untilAsserted(() -> assertFalse(hello.exists(), "File should not exist " + hello)); File bye = service.ftpFile("async/bye.txt").toFile(); await().atMost(1, TimeUnit.SECONDS) .untilAsserted(() -> assertFalse(bye.exists(), "File should not exist " + bye)); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(getFtpUrl()).routeId("foo").noAutoStartup().process(new MyAsyncProcessor()).to("mock:result"); } }; } private static
FromFtpAsyncProcessIT
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java
{ "start": 80347, "end": 81171 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((requests) -> requests .requestMatchers("/requires-read-scope").hasAuthority("message:read")) .oauth2ResourceServer((server) -> server .jwt((jwt) -> jwt .jwtAuthenticationConverter(getJwtAuthenticationConverter()))); return http.build(); // @formatter:on } Converter<Jwt, AbstractAuthenticationToken> getJwtAuthenticationConverter() { JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); converter.setJwtGrantedAuthoritiesConverter( (jwt) -> Collections.singletonList(new SimpleGrantedAuthority("message:read"))); return converter; } } @Configuration @EnableWebSecurity static
CustomAuthorityMappingConfig
java
google__guava
android/guava/src/com/google/common/collect/Synchronized.java
{ "start": 11276, "end": 11909 }
class ____<E extends @Nullable Object> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list, @Nullable Object mutex) { super(list, mutex); } @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; } static <E extends @Nullable Object> Multiset<E> multiset( Multiset<E> multiset, @Nullable Object mutex) { if (multiset instanceof SynchronizedMultiset || multiset instanceof ImmutableMultiset) { return multiset; } return new SynchronizedMultiset<>(multiset, mutex); } static final
SynchronizedRandomAccessList
java
quarkusio__quarkus
extensions/micrometer/deployment/src/test/java/io/quarkus/micrometer/deployment/pathparams/HttpPathParamLimitWithProgrammaticRoutes400Test.java
{ "start": 502, "end": 2792 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withConfigurationResource("test-logging.properties") .overrideConfigKey("quarkus.micrometer.binder-enabled-default", "false") .overrideConfigKey("quarkus.micrometer.binder.http-client.enabled", "true") .overrideConfigKey("quarkus.micrometer.binder.http-server.enabled", "true") .overrideConfigKey("quarkus.micrometer.binder.vertx.enabled", "true") .overrideConfigKey("quarkus.redis.devservices.enabled", "false") .withApplicationRoot((jar) -> jar .addClasses(Util.class, Resource.class)); @Inject MeterRegistry registry; public static final int COUNT = 101; @Test void testWithProgrammaticRoutes400() throws InterruptedException { registry.clear(); // Verify OK response for (int i = 0; i < COUNT; i++) { RestAssured.get("/programmatic").then().statusCode(200); RestAssured.get("/programmatic/foo-" + i).then().statusCode(200); } // Verify metrics Util.waitForMeters(registry.find("http.server.requests").timers(), COUNT); Assertions.assertEquals(COUNT, registry.find("http.server.requests") .tag("uri", "/programmatic").timers().iterator().next().count()); Assertions.assertEquals(COUNT, registry.find("http.server.requests") .tag("uri", "/programmatic/{message}").timers().iterator().next().count()); // Verify 405 responses for (int i = 0; i < COUNT; i++) { RestAssured.get("/bad").then().statusCode(400); RestAssured.get("/bad/foo-" + i).then().statusCode(400); } Util.waitForMeters(registry.find("http.server.requests").timers(), COUNT * 2); Assertions.assertEquals(COUNT, registry.find("http.server.requests") .tag("uri", "/bad").tag("method", "GET").timers().iterator().next().count()); Assertions.assertEquals(COUNT, registry.find("http.server.requests") .tag("method", "GET").timers().iterator().next().count()); } @Singleton public static
HttpPathParamLimitWithProgrammaticRoutes400Test
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/websocketx/extensions/compression/PerMessageDeflateClientExtensionHandshaker.java
{ "start": 1697, "end": 13268 }
class ____ implements WebSocketClientExtensionHandshaker { private final int compressionLevel; private final boolean allowClientWindowSize; private final int requestedServerWindowSize; private final boolean allowClientNoContext; private final boolean requestedServerNoContext; private final WebSocketExtensionFilterProvider extensionFilterProvider; private final int maxAllocation; /** * Constructor with default configuration. * @deprecated * Use {@link PerMessageDeflateClientExtensionHandshaker# * PerMessageDeflateClientExtensionHandshaker(int)}. */ @Deprecated public PerMessageDeflateClientExtensionHandshaker() { this(0); } /** * Constructor with default configuration. * @param maxAllocation * Maximum size of the decompression buffer. Must be &gt;= 0. If zero, maximum size is not limited. */ public PerMessageDeflateClientExtensionHandshaker(int maxAllocation) { this(6, ZlibCodecFactory.isSupportingWindowSizeAndMemLevel(), MAX_WINDOW_SIZE, false, false, maxAllocation); } /** * Constructor with custom configuration. * * @param compressionLevel * Compression level between 0 and 9 (default is 6). * @param allowClientWindowSize * allows WebSocket server to customize the client inflater window size * (default is false). * @param requestedServerWindowSize * indicates the requested sever window size to use if server inflater is customizable. * @param allowClientNoContext * allows WebSocket server to activate client_no_context_takeover * (default is false). * @param requestedServerNoContext * indicates if client needs to activate server_no_context_takeover * if server is compatible with (default is false). * @deprecated * Use {@link PerMessageDeflateClientExtensionHandshaker#PerMessageDeflateClientExtensionHandshaker( * int, boolean, int, boolean, boolean, int)}. */ @Deprecated public PerMessageDeflateClientExtensionHandshaker(int compressionLevel, boolean allowClientWindowSize, int requestedServerWindowSize, boolean allowClientNoContext, boolean requestedServerNoContext) { this(compressionLevel, allowClientWindowSize, requestedServerWindowSize, allowClientNoContext, requestedServerNoContext, 0); } /** * Constructor with custom configuration. * * @param compressionLevel * Compression level between 0 and 9 (default is 6). * @param allowClientWindowSize * allows WebSocket server to customize the client inflater window size * (default is false). * @param requestedServerWindowSize * indicates the requested sever window size to use if server inflater is customizable. * @param allowClientNoContext * allows WebSocket server to activate client_no_context_takeover * (default is false). * @param requestedServerNoContext * indicates if client needs to activate server_no_context_takeover * if server is compatible with (default is false). * @param maxAllocation * Maximum size of the decompression buffer. Must be &gt;= 0. If zero, maximum size is not limited. */ public PerMessageDeflateClientExtensionHandshaker(int compressionLevel, boolean allowClientWindowSize, int requestedServerWindowSize, boolean allowClientNoContext, boolean requestedServerNoContext, int maxAllocation) { this(compressionLevel, allowClientWindowSize, requestedServerWindowSize, allowClientNoContext, requestedServerNoContext, WebSocketExtensionFilterProvider.DEFAULT, maxAllocation); } /** * Constructor with custom configuration. * * @param compressionLevel * Compression level between 0 and 9 (default is 6). * @param allowClientWindowSize * allows WebSocket server to customize the client inflater window size * (default is false). * @param requestedServerWindowSize * indicates the requested sever window size to use if server inflater is customizable. * @param allowClientNoContext * allows WebSocket server to activate client_no_context_takeover * (default is false). * @param requestedServerNoContext * indicates if client needs to activate server_no_context_takeover * if server is compatible with (default is false). * @param extensionFilterProvider * provides client extension filters for per message deflate encoder and decoder. * @deprecated * Use {@link PerMessageDeflateClientExtensionHandshaker#PerMessageDeflateClientExtensionHandshaker( * int, boolean, int, boolean, boolean, WebSocketExtensionFilterProvider, int)}. */ @Deprecated public PerMessageDeflateClientExtensionHandshaker(int compressionLevel, boolean allowClientWindowSize, int requestedServerWindowSize, boolean allowClientNoContext, boolean requestedServerNoContext, WebSocketExtensionFilterProvider extensionFilterProvider) { this(compressionLevel, allowClientWindowSize, requestedServerWindowSize, allowClientNoContext, requestedServerNoContext, extensionFilterProvider, 0); } /** * Constructor with custom configuration. * * @param compressionLevel * Compression level between 0 and 9 (default is 6). * @param allowClientWindowSize * allows WebSocket server to customize the client inflater window size * (default is false). * @param requestedServerWindowSize * indicates the requested sever window size to use if server inflater is customizable. * @param allowClientNoContext * allows WebSocket server to activate client_no_context_takeover * (default is false). * @param requestedServerNoContext * indicates if client needs to activate server_no_context_takeover * if server is compatible with (default is false). * @param extensionFilterProvider * provides client extension filters for per message deflate encoder and decoder. * @param maxAllocation * Maximum size of the decompression buffer. Must be &gt;= 0. If zero, maximum size is not limited. */ public PerMessageDeflateClientExtensionHandshaker(int compressionLevel, boolean allowClientWindowSize, int requestedServerWindowSize, boolean allowClientNoContext, boolean requestedServerNoContext, WebSocketExtensionFilterProvider extensionFilterProvider, int maxAllocation) { if (requestedServerWindowSize > MAX_WINDOW_SIZE || requestedServerWindowSize < MIN_WINDOW_SIZE) { throw new IllegalArgumentException( "requestedServerWindowSize: " + requestedServerWindowSize + " (expected: 8-15)"); } if (compressionLevel < 0 || compressionLevel > 9) { throw new IllegalArgumentException( "compressionLevel: " + compressionLevel + " (expected: 0-9)"); } this.compressionLevel = compressionLevel; this.allowClientWindowSize = allowClientWindowSize; this.requestedServerWindowSize = requestedServerWindowSize; this.allowClientNoContext = allowClientNoContext; this.requestedServerNoContext = requestedServerNoContext; this.extensionFilterProvider = checkNotNull(extensionFilterProvider, "extensionFilterProvider"); this.maxAllocation = checkPositiveOrZero(maxAllocation, "maxAllocation"); } @Override public WebSocketExtensionData newRequestData() { HashMap<String, String> parameters = new HashMap<String, String>(4); if (requestedServerNoContext) { parameters.put(SERVER_NO_CONTEXT, null); } if (allowClientNoContext) { parameters.put(CLIENT_NO_CONTEXT, null); } if (requestedServerWindowSize != MAX_WINDOW_SIZE) { parameters.put(SERVER_MAX_WINDOW, Integer.toString(requestedServerWindowSize)); } if (allowClientWindowSize) { parameters.put(CLIENT_MAX_WINDOW, null); } return new WebSocketExtensionData(PERMESSAGE_DEFLATE_EXTENSION, parameters); } @Override public WebSocketClientExtension handshakeExtension(WebSocketExtensionData extensionData) { if (!PERMESSAGE_DEFLATE_EXTENSION.equals(extensionData.name())) { return null; } boolean succeed = true; int clientWindowSize = MAX_WINDOW_SIZE; int serverWindowSize = MAX_WINDOW_SIZE; boolean serverNoContext = false; boolean clientNoContext = false; Iterator<Entry<String, String>> parametersIterator = extensionData.parameters().entrySet().iterator(); while (succeed && parametersIterator.hasNext()) { Entry<String, String> parameter = parametersIterator.next(); if (CLIENT_MAX_WINDOW.equalsIgnoreCase(parameter.getKey())) { // allowed client_window_size_bits if (allowClientWindowSize) { clientWindowSize = Integer.parseInt(parameter.getValue()); if (clientWindowSize > MAX_WINDOW_SIZE || clientWindowSize < MIN_WINDOW_SIZE) { succeed = false; } } else { succeed = false; } } else if (SERVER_MAX_WINDOW.equalsIgnoreCase(parameter.getKey())) { // acknowledged server_window_size_bits serverWindowSize = Integer.parseInt(parameter.getValue()); if (serverWindowSize > MAX_WINDOW_SIZE || serverWindowSize < MIN_WINDOW_SIZE) { succeed = false; } } else if (CLIENT_NO_CONTEXT.equalsIgnoreCase(parameter.getKey())) { // allowed client_no_context_takeover if (allowClientNoContext) { clientNoContext = true; } else { succeed = false; } } else if (SERVER_NO_CONTEXT.equalsIgnoreCase(parameter.getKey())) { // acknowledged server_no_context_takeover serverNoContext = true; } else { // unknown parameter succeed = false; } } if ((requestedServerNoContext && !serverNoContext) || requestedServerWindowSize < serverWindowSize) { succeed = false; } if (succeed) { return new PermessageDeflateExtension(serverNoContext, serverWindowSize, clientNoContext, clientWindowSize, extensionFilterProvider, maxAllocation); } else { return null; } } private final
PerMessageDeflateClientExtensionHandshaker
java
apache__avro
lang/java/mapred/src/test/java/org/apache/avro/hadoop/util/TestAvroCharSequenceComparator.java
{ "start": 1119, "end": 3764 }
class ____ { private AvroCharSequenceComparator<CharSequence> mComparator; @BeforeEach public void setup() { mComparator = new AvroCharSequenceComparator<>(); } @Test void compareString() { assertEquals(0, mComparator.compare("", "")); assertThat(mComparator.compare("", "a"), lessThan(0)); assertThat(mComparator.compare("a", ""), greaterThan(0)); assertEquals(0, mComparator.compare("a", "a")); assertThat(mComparator.compare("a", "b"), lessThan(0)); assertThat(mComparator.compare("b", "a"), greaterThan(0)); assertEquals(0, mComparator.compare("ab", "ab")); assertThat(mComparator.compare("a", "aa"), lessThan(0)); assertThat(mComparator.compare("aa", "a"), greaterThan(0)); assertThat(mComparator.compare("abc", "abcdef"), lessThan(0)); assertThat(mComparator.compare("abcdef", "abc"), greaterThan(0)); } @Test void compareUtf8() { assertEquals(0, mComparator.compare(new Utf8(""), new Utf8(""))); assertThat(mComparator.compare(new Utf8(""), new Utf8("a")), lessThan(0)); assertThat(mComparator.compare(new Utf8("a"), new Utf8("")), greaterThan(0)); assertEquals(0, mComparator.compare(new Utf8("a"), new Utf8("a"))); assertThat(mComparator.compare(new Utf8("a"), new Utf8("b")), lessThan(0)); assertThat(mComparator.compare(new Utf8("b"), new Utf8("a")), greaterThan(0)); assertEquals(0, mComparator.compare(new Utf8("ab"), new Utf8("ab"))); assertThat(mComparator.compare(new Utf8("a"), new Utf8("aa")), lessThan(0)); assertThat(mComparator.compare(new Utf8("aa"), new Utf8("a")), greaterThan(0)); assertThat(mComparator.compare(new Utf8("abc"), new Utf8("abcdef")), lessThan(0)); assertThat(mComparator.compare(new Utf8("abcdef"), new Utf8("abc")), greaterThan(0)); } @Test void compareUtf8ToString() { assertEquals(0, mComparator.compare(new Utf8(""), "")); assertThat(mComparator.compare(new Utf8(""), "a"), lessThan(0)); assertThat(mComparator.compare(new Utf8("a"), ""), greaterThan(0)); assertEquals(0, mComparator.compare(new Utf8("a"), "a")); assertThat(mComparator.compare(new Utf8("a"), "b"), lessThan(0)); assertThat(mComparator.compare(new Utf8("b"), "a"), greaterThan(0)); assertEquals(0, mComparator.compare(new Utf8("ab"), "ab")); assertThat(mComparator.compare(new Utf8("a"), "aa"), lessThan(0)); assertThat(mComparator.compare(new Utf8("aa"), "a"), greaterThan(0)); assertThat(mComparator.compare(new Utf8("abc"), "abcdef"), lessThan(0)); assertThat(mComparator.compare(new Utf8("abcdef"), "abc"), greaterThan(0)); } }
TestAvroCharSequenceComparator
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RBlockingQueueReactive.java
{ "start": 6844, "end": 9559 }
class ____ an element of this queue * prevents it from being added to the specified collection * @throws NullPointerException if the specified collection is null * @throws IllegalArgumentException if the specified collection is this * queue, or some property of an element of this queue prevents * it from being added to the specified collection */ Mono<Integer> drainTo(Collection<? super V> c); /** * Retrieves and removes last available tail element of this queue and adds it at the head of <code>queueName</code>, * waiting up to the specified wait time if necessary for an element to become available. * * @param queueName - names of destination queue * @param timeout how long to wait before giving up, in units of * {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the * {@code timeout} parameter * @return the tail of this queue, or {@code null} if the * specified waiting time elapses before an element is available */ Mono<V> pollLastAndOfferFirstTo(String queueName, long timeout, TimeUnit unit); /** * Retrieves and removes the head of this queue in async mode, waiting up to the * specified wait time if necessary for an element to become available. * * @param timeout how long to wait before giving up, in units of * {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the * {@code timeout} parameter * @return the head of this queue, or {@code null} if the * specified waiting time elapses before an element is available */ Mono<V> poll(long timeout, TimeUnit unit); /** * Retrieves and removes last available tail element of <b>any</b> queue and adds it at the head of <code>queueName</code>, * waiting if necessary for an element to become available * in any of defined queues <b>including</b> queue itself. * * @param queueName - names of destination queue * @return the tail of this queue, or {@code null} if the * specified waiting time elapses before an element is available */ Mono<V> takeLastAndOfferFirstTo(String queueName); /** * Retrieves and removes the head of this queue in async mode, waiting if necessary * until an element becomes available. * * @return the head of this queue */ Mono<V> take(); /** * Inserts the specified element into this queue in async mode, waiting if necessary * for space to become available. * * @param e the element to add * @throws ClassCastException if the
of
java
apache__camel
components/camel-fhir/camel-fhir-component/src/test/java/org/apache/camel/component/fhir/FhirCapabilitiesIT.java
{ "start": 1545, "end": 1649 }
class ____ won't be generated * again if the generator MOJO finds it under src/test/java. */ public
source
java
google__dagger
javatests/dagger/hilt/android/processor/internal/androidentrypoint/AndroidEntryPointProcessorTest.java
{ "start": 6303, "end": 6861 }
class ____ extends ComponentActivity { }"); HiltCompilerTests.hiltCompiler(testActivity) .compile( (CompilationResultSubject subject) -> { // TODO(b/288210593): Add this check back to KSP once this bug is fixed. if (HiltCompilerTests.backend(subject) == XProcessingEnv.Backend.KSP) { subject.hasErrorCount(0); } else { subject.hasErrorCount(1); subject .hasErrorContaining( "@AndroidEntryPoint
MyActivity
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/dev/RuntimeUpdatesProcessor.java
{ "start": 64066, "end": 65891 }
class ____ { final Map<Path, Long> classFileChangeTimeStamps = new ConcurrentHashMap<>(); final Map<Path, Path> classFilePathToSourceFilePath = new ConcurrentHashMap<>(); volatile Map<Path, WatchedPath> watchedPaths = new ConcurrentHashMap<>(); // The current paths and predicates from all HotDeploymentWatchedFileBuildItems volatile Map<String, Boolean> watchedFilePaths; volatile List<Entry<Predicate<String>, Boolean>> watchedFilePredicates; public void merge(TimestampSet other) { classFileChangeTimeStamps.putAll(other.classFileChangeTimeStamps); classFilePathToSourceFilePath.putAll(other.classFilePathToSourceFilePath); Map<Path, WatchedPath> newVal = new HashMap<>(watchedPaths); newVal.putAll(other.watchedPaths); watchedPaths = newVal; } boolean isRestartNeeded(String changedFile) { // First try to match all existing watched paths for (WatchedPath path : watchedPaths.values()) { if (path.matches(changedFile)) { return path.restartNeeded; } } // Then try to match a new file that was added to a resource root Boolean ret = watchedFilePaths != null ? watchedFilePaths.get(changedFile) : null; if (ret == null) { ret = Boolean.FALSE; if (watchedFilePredicates != null) { for (Entry<Predicate<String>, Boolean> e : watchedFilePredicates) { if (e.getKey().test(changedFile)) { ret = ret || e.getValue(); } } } } return ret; } } private static
TimestampSet
java
micronaut-projects__micronaut-core
management/src/main/java/io/micronaut/management/endpoint/loggers/ManagedLoggingSystem.java
{ "start": 866, "end": 1442 }
interface ____ extends io.micronaut.logging.LoggingSystem { /** * Returns all existing loggers. * * @return A {@link Collection} of {@link LoggerConfiguration} instances for all existing loggers */ @NonNull Collection<LoggerConfiguration> getLoggers(); /** * Returns a {@link LoggerConfiguration} for the logger found by name (or created if not found). * * @param name the logger name * @return the logger configuration */ @NonNull LoggerConfiguration getLogger(@NotBlank String name); }
ManagedLoggingSystem
java
apache__maven
impl/maven-impl/src/main/java/org/apache/maven/impl/model/profile/PackagingProfileActivator.java
{ "start": 1381, "end": 2257 }
class ____ implements ProfileActivator { @Override public boolean isActive(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) { return getActivationPackaging(profile).map(p -> isPackaging(context, p)).orElse(false); } @Override public boolean presentInConfig(Profile profile, ProfileActivationContext context, ModelProblemCollector problems) { return getActivationPackaging(profile).isPresent(); } private static boolean isPackaging(ProfileActivationContext context, String p) { String packaging = context.getModelPackaging(); return Objects.equals(p, packaging); } private static Optional<String> getActivationPackaging(Profile profile) { return Optional.ofNullable(profile).map(Profile::getActivation).map(Activation::getPackaging); } }
PackagingProfileActivator
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/ref/RefTest7.java
{ "start": 137, "end": 867 }
class ____ extends TestCase { public void test_bug_for_juqkai() throws Exception { VO vo = new VO(); C c = new C(); vo.setA(new A(c)); vo.setB(new B(c)); VO[] root = new VO[] { vo }; String text = JSON.toJSONString(root); System.out.println(text); VO[] array2 = JSON.parseObject(text, VO[].class); Assert.assertEquals(1, array2.length); Assert.assertNotNull(array2[0].getA()); Assert.assertNotNull(array2[0].getB()); Assert.assertNotNull(array2[0].getA().getC()); Assert.assertNotNull(array2[0].getB().getC()); Assert.assertSame(array2[0].getA().getC(), array2[0].getB().getC()); } public static
RefTest7
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/TestSchedulingWithAllocationRequestId.java
{ "start": 2239, "end": 10583 }
class ____ extends ParameterizedSchedulerTestBase { private static final Logger LOG = LoggerFactory.getLogger(TestSchedulingWithAllocationRequestId.class); private static final int GB = 1024; public void initTestSchedulingWithAllocationRequestId(SchedulerType type) throws IOException { initParameterizedSchedulerTestBase(type); } @Override public YarnConfiguration getConf() { YarnConfiguration conf = super.getConf(); if (getSchedulerType().equals(SchedulerType.FAIR)) { // Some tests here rely on being able to assign multiple containers with // a single heartbeat conf.setBoolean(FairSchedulerConfiguration.ASSIGN_MULTIPLE, true); } return conf; } @Timeout(10) @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testMultipleAllocationRequestIds(SchedulerType type) throws Exception { initParameterizedSchedulerTestBase(type); YarnConfiguration conf = getConf(); MockRM rm = new MockRM(conf); try { rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 4 * GB); MockNM nm2 = rm.registerNode("127.0.0.2:5678", 4 * GB); RMApp app1 = MockRMAppSubmitter.submitWithMemory(2048, rm); // kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); // send requests for containers with id 10 & 20 am1.allocate(am1.createReq( new String[] {"127.0.0.1"}, 2 * GB, 1, 1, 10L), null); am1.allocate(am1.createReq( new String[] {"127.0.0.2"}, 2 * GB, 1, 2, 20L), null); // check if request id 10 is satisfied AllocateResponse allocResponse = waitForAllocResponse(rm, am1, nm1, 1); List<Container> allocated = allocResponse.getAllocatedContainers(); assertEquals(1, allocated.size()); checkAllocatedContainer(allocated.get(0), 2 * GB, nm1.getNodeId(), 10); // check now if request id 20 is satisfied allocResponse = waitForAllocResponse(rm, am1, nm2, 2); allocated = allocResponse.getAllocatedContainers(); assertEquals(2, allocated.size()); for (Container container : allocated) { checkAllocatedContainer(container, 2 * GB, nm2.getNodeId(), 20); } } finally { if (rm != null) { rm.stop(); } } } @Timeout(10) @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testMultipleAllocationRequestDiffPriority(SchedulerType type) throws Exception { initTestSchedulingWithAllocationRequestId(type); YarnConfiguration conf = getConf(); MockRM rm = new MockRM(conf); try { rm.start(); MockNM nm1 = rm.registerNode("127.0.0.1:1234", 4 * GB); MockNM nm2 = rm.registerNode("127.0.0.2:5678", 4 * GB); RMApp app1 = MockRMAppSubmitter.submitWithMemory(2048, rm); // kick the scheduling nm1.nodeHeartbeat(true); RMAppAttempt attempt1 = app1.getCurrentAppAttempt(); MockAM am1 = rm.sendAMLaunched(attempt1.getAppAttemptId()); am1.registerAppAttempt(); // send requests for containers with id 10 & 20 am1.allocate(am1.createReq( new String[] {"127.0.0.1"}, 2 * GB, 2, 1, 10L), null); am1.allocate(am1.createReq( new String[] {"127.0.0.2"}, 2 * GB, 1, 2, 20L), null); // check if request id 20 is satisfied first AllocateResponse allocResponse = waitForAllocResponse(rm, am1, nm2, 2); List<Container> allocated = allocResponse.getAllocatedContainers(); assertEquals(2, allocated.size()); for (Container container : allocated) { checkAllocatedContainer(container, 2 * GB, nm2.getNodeId(), 20); } // check now if request id 10 is satisfied allocResponse = waitForAllocResponse(rm, am1, nm1, 1); allocated = allocResponse.getAllocatedContainers(); assertEquals(1, allocated.size()); checkAllocatedContainer(allocated.get(0), 2 * GB, nm1.getNodeId(), 10); } finally { if (rm != null) { rm.stop(); } } } private void checkAllocatedContainer(Container allocated, int memory, NodeId nodeId, long allocationRequestId) { assertEquals(memory, allocated.getResource().getMemorySize()); assertEquals(nodeId, allocated.getNodeId()); assertEquals(allocationRequestId, allocated.getAllocationRequestId()); } @Timeout(10) @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testMultipleAppsWithAllocationReqId(SchedulerType type) throws Exception { initTestSchedulingWithAllocationRequestId(type); YarnConfiguration conf = getConf(); MockRM rm = new MockRM(conf); try { rm.start(); // Register node1 String host0 = "host_0"; String host1 = "host_1"; MockNM nm1 = new MockNM(host0 + ":1234", 8 * GB, rm.getResourceTrackerService()); nm1.registerNode(); // Register node2 MockNM nm2 = new MockNM(host1 + ":2351", 8 * GB, rm.getResourceTrackerService()); nm2.registerNode(); // submit 1st app MockRMAppSubmissionData data1 = MockRMAppSubmissionData.Builder.createWithMemory(1 * GB, rm) .withAppName("user_0") .withUser("a1") .build(); RMApp app1 = MockRMAppSubmitter.submit(rm, data1); MockAM am1 = MockRM.launchAndRegisterAM(app1, rm, nm1); // Submit app1 RR with allocationReqId = 5 int numContainers = 1; am1.allocate(am1.createReq( new String[] {host0, host1}, 1 * GB, 1, numContainers, 5L), null); // wait for container to be allocated. AllocateResponse allocResponse = waitForAllocResponse(rm, am1, nm1, 1); List<Container> allocated = allocResponse.getAllocatedContainers(); assertEquals(1, allocated.size()); checkAllocatedContainer(allocated.get(0), 1 * GB, nm1.getNodeId(), 5L); // Submit another application MockRMAppSubmissionData data = MockRMAppSubmissionData.Builder.createWithMemory(1 * GB, rm) .withAppName("user_1") .withUser("a2") .build(); RMApp app2 = MockRMAppSubmitter.submit(rm, data); MockAM am2 = MockRM.launchAndRegisterAM(app2, rm, nm2); // Submit app2 RR with allocationReqId = 5 am2.allocate(am1.createReq( new String[] {host0, host1}, 2 * GB, 1, numContainers, 5L), null); // wait for container to be allocated. allocResponse = waitForAllocResponse(rm, am2, nm2, 1); allocated = allocResponse.getAllocatedContainers(); assertEquals(1, allocated.size()); checkAllocatedContainer(allocated.get(0), 2 * GB, nm2.getNodeId(), 5L); // Now submit app2 RR with allocationReqId = 10 am2.allocate(am1.createReq( new String[] {host0, host1}, 3 * GB, 1, numContainers, 10L), null); // wait for container to be allocated. allocResponse = waitForAllocResponse(rm, am2, nm1, 1); allocated = allocResponse.getAllocatedContainers(); assertEquals(1, allocated.size()); checkAllocatedContainer(allocated.get(0), 3 * GB, nm1.getNodeId(), 10L); // Now submit app1 RR with allocationReqId = 10 am1.allocate(am1.createReq( new String[] {host0, host1}, 4 * GB, 1, numContainers, 10L), null); // wait for container to be allocated. allocResponse = waitForAllocResponse(rm, am1, nm2, 1); allocated = allocResponse.getAllocatedContainers(); assertEquals(1, allocated.size()); checkAllocatedContainer(allocated.get(0), 4 * GB, nm2.getNodeId(), 10L); } finally { if (rm != null) { rm.stop(); } } } private AllocateResponse waitForAllocResponse(MockRM rm, MockAM am, MockNM nm, int size) throws Exception { AllocateResponse allocResponse = am.doHeartbeat(); while (allocResponse.getAllocatedContainers().size() < size) { LOG.info("Waiting for containers to be created for app..."); nm.nodeHeartbeat(true); ((AbstractYarnScheduler) rm.getResourceScheduler()).update(); Thread.sleep(100); allocResponse = am.doHeartbeat(); } return allocResponse; } }
TestSchedulingWithAllocationRequestId
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/interfaceproxy/Folder.java
{ "start": 180, "end": 371 }
interface ____ extends Item { /** * @return Returns the parent. */ public Folder getParent(); /** * @param parent The parent to set. */ public void setParent(Folder parent); }
Folder
java
spring-projects__spring-security
oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/server/authentication/OAuth2LoginAuthenticationWebFilter.java
{ "start": 1693, "end": 3289 }
class ____ extends AuthenticationWebFilter { private final ServerOAuth2AuthorizedClientRepository authorizedClientRepository; /** * Creates an instance * @param authenticationManager the authentication manager to use * @param authorizedClientRepository */ public OAuth2LoginAuthenticationWebFilter(ReactiveAuthenticationManager authenticationManager, ServerOAuth2AuthorizedClientRepository authorizedClientRepository) { super(authenticationManager); Assert.notNull(authorizedClientRepository, "authorizedClientService cannot be null"); this.authorizedClientRepository = authorizedClientRepository; } @Override protected Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) { OAuth2LoginAuthenticationToken authenticationResult = (OAuth2LoginAuthenticationToken) authentication; OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient( authenticationResult.getClientRegistration(), authenticationResult.getName(), authenticationResult.getAccessToken(), authenticationResult.getRefreshToken()); OAuth2AuthenticationToken result = new OAuth2AuthenticationToken(authenticationResult.getPrincipal(), authenticationResult.getAuthorities(), authenticationResult.getClientRegistration().getRegistrationId()); // @formatter:off return this.authorizedClientRepository .saveAuthorizedClient(authorizedClient, authenticationResult, webFilterExchange.getExchange()) .then(super.onAuthenticationSuccess(result, webFilterExchange)); // @formatter:on } }
OAuth2LoginAuthenticationWebFilter
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpsServerTestSupport.java
{ "start": 955, "end": 1039 }
class ____ unit testing using a secure FTP Server (over SSL/TLS) */ public abstract
for
java
elastic__elasticsearch
x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/index/mapper/PointFieldMapper.java
{ "start": 10556, "end": 11826 }
class ____ extends PointParser<CartesianPoint> { CartesianPointParser( String field, CheckedFunction<XContentParser, CartesianPoint, IOException> objectParser, CartesianPoint nullValue, boolean ignoreZValue, boolean ignoreMalformed ) { super(field, objectParser, nullValue, ignoreZValue, ignoreMalformed, true); } @Override protected CartesianPoint validate(CartesianPoint in) { if (ignoreMalformed == false) { if (Double.isFinite(in.getX()) == false) { throw new IllegalArgumentException("illegal x value [" + in.getX() + "] for " + field); } if (Double.isFinite(in.getY()) == false) { throw new IllegalArgumentException("illegal y value [" + in.getY() + "] for " + field); } } return in; } @Override protected CartesianPoint createPoint(double x, double y) { return new CartesianPoint(x, y); } @Override public CartesianPoint normalizeFromSource(CartesianPoint point) { return point; } } /** * Utility
CartesianPointParser
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/WindowStoreIteratorWrapper.java
{ "start": 2568, "end": 3695 }
class ____ implements WindowStoreIterator<byte[]> { final KeyValueIterator<Bytes, byte[]> bytesIterator; final Function<byte[], Long> timestampExtractor; WrappedWindowStoreIterator( final KeyValueIterator<Bytes, byte[]> bytesIterator, final Function<byte[], Long> timestampExtractor) { this.bytesIterator = bytesIterator; this.timestampExtractor = timestampExtractor; } @Override public Long peekNextKey() { return timestampExtractor.apply(bytesIterator.peekNextKey().get()); } @Override public boolean hasNext() { return bytesIterator.hasNext(); } @Override public KeyValue<Long, byte[]> next() { final KeyValue<Bytes, byte[]> next = bytesIterator.next(); final long timestamp = timestampExtractor.apply(next.key.get()); return KeyValue.pair(timestamp, next.value); } @Override public void close() { bytesIterator.close(); } } private static
WrappedWindowStoreIterator
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/BannerTests.java
{ "start": 4184, "end": 4425 }
class ____ implements Banner { @Override public void printBanner(Environment environment, @Nullable Class<?> sourceClass, PrintStream out) { out.println("My Banner"); } } @Configuration(proxyBeanMethods = false) static
DummyBanner
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/ActiveProfilesTestClassScopedExtensionContextNestedTests.java
{ "start": 3289, "end": 3689 }
class ____ { @Autowired List<String> localStrings; @Test void test() { assertThat(strings).containsExactlyInAnyOrder("X", "A1"); assertThat(this.localStrings).containsExactlyInAnyOrder("X", "A1", "Y", "A2"); } @Nested @NestedTestConfiguration(OVERRIDE) @SpringJUnitConfig({ Config1.class, Config2.class, Config3.class }) @ActiveProfiles("3")
InheritedAndExtendedConfigTests
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/sequencedmultisetstate/linked/MetaSqnInfoSerializer.java
{ "start": 2832, "end": 3739 }
class ____ extends CompositeTypeSerializerSnapshot<MetaSqnInfo, MetaSqnInfoSerializer> { @SuppressWarnings("unused") public MetaSqnInfoSerializerSnapshot() {} MetaSqnInfoSerializerSnapshot(MetaSqnInfoSerializer serializer) { super(serializer); } @Override protected int getCurrentOuterSnapshotVersion() { return 0; } @Override protected TypeSerializer<?>[] getNestedSerializers(MetaSqnInfoSerializer outerSerializer) { return new TypeSerializer[] {LongSerializer.INSTANCE, LongSerializer.INSTANCE}; } @Override protected MetaSqnInfoSerializer createOuterSerializerWithNestedSerializers( TypeSerializer<?>[] nestedSerializers) { return new MetaSqnInfoSerializer(null, nestedSerializers); } } }
MetaSqnInfoSerializerSnapshot
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableTakeUntilPredicate.java
{ "start": 986, "end": 1464 }
class ____<T> extends AbstractObservableWithUpstream<T, T> { final Predicate<? super T> predicate; public ObservableTakeUntilPredicate(ObservableSource<T> source, Predicate<? super T> predicate) { super(source); this.predicate = predicate; } @Override public void subscribeActual(Observer<? super T> observer) { source.subscribe(new TakeUntilPredicateObserver<>(observer, predicate)); } static final
ObservableTakeUntilPredicate
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/RestOpenApiEndpointBuilderFactory.java
{ "start": 1454, "end": 1598 }
interface ____ { /** * Builder for endpoint consumers for the REST OpenApi component. */ public
RestOpenApiEndpointBuilderFactory
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/builditem/GeneratedNativeImageClassBuildItem.java
{ "start": 174, "end": 567 }
class ____ extends MultiBuildItem { final String name; final byte[] classData; public GeneratedNativeImageClassBuildItem(String name, byte[] classData) { this.name = name; this.classData = classData; } public String getName() { return name; } public byte[] getClassData() { return classData; } }
GeneratedNativeImageClassBuildItem
java
apache__flink
flink-clients/src/main/java/org/apache/flink/client/deployment/application/executors/WebSubmissionExecutorServiceLoader.java
{ "start": 1470, "end": 2734 }
class ____ implements PipelineExecutorServiceLoader { private final Collection<JobID> submittedJobIds; private final DispatcherGateway dispatcherGateway; /** * Creates an {@link WebSubmissionExecutorServiceLoader}. * * @param submittedJobIds a list that is going to be filled by the {@link EmbeddedExecutor} with * the job ids of the new jobs that will be submitted. This is essentially used to return * the submitted job ids to the caller. * @param dispatcherGateway the dispatcher of the cluster which is going to be used to submit * jobs. */ public WebSubmissionExecutorServiceLoader( final Collection<JobID> submittedJobIds, final DispatcherGateway dispatcherGateway) { this.submittedJobIds = checkNotNull(submittedJobIds); this.dispatcherGateway = checkNotNull(dispatcherGateway); } @Override public PipelineExecutorFactory getExecutorFactory(final Configuration configuration) { return new WebSubmissionExecutorFactory(submittedJobIds, dispatcherGateway); } @Override public Stream<String> getExecutorNames() { return Stream.<String>builder().add(EmbeddedExecutor.NAME).build(); } }
WebSubmissionExecutorServiceLoader
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/scale/ITestS3ADeleteFilesOneByOne.java
{ "start": 1073, "end": 1378 }
class ____ extends ITestS3ADeleteManyFiles { @Override protected Configuration createScaleConfiguration() { Configuration configuration = super.createScaleConfiguration(); configuration.setBoolean(Constants.ENABLE_MULTI_DELETE, false); return configuration; } }
ITestS3ADeleteFilesOneByOne
java
apache__camel
components/camel-zendesk/src/main/java/org/apache/camel/component/zendesk/ZendeskConsumer.java
{ "start": 1054, "end": 1266 }
class ____ extends AbstractApiConsumer<ZendeskApiName, ZendeskConfiguration> { public ZendeskConsumer(ZendeskEndpoint endpoint, Processor processor) { super(endpoint, processor); } }
ZendeskConsumer
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/Wasb.java
{ "start": 1307, "end": 1590 }
class ____ extends DelegateToFileSystem { Wasb(final URI theUri, final Configuration conf) throws IOException, URISyntaxException { super(theUri, new NativeAzureFileSystem(), conf, "wasb", false); } @Override public int getUriDefaultPort() { return -1; } }
Wasb
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletGen.java
{ "start": 1708, "end": 1987 }
class ____ { static final Logger LOG = LoggerFactory.getLogger(HamletGen.class); static final Options opts = new Options(); static { opts.addOption("h", "help", false, "Print this help message"). addOption("s", "spec-class", true, "The
HamletGen
java
quarkusio__quarkus
integration-tests/picocli-native/src/main/java/io/quarkus/it/picocli/DefaultValueProviderCommand.java
{ "start": 213, "end": 439 }
class ____ implements Runnable { @CommandLine.Option(names = "--defaulted") String defaulted; @Override public void run() { System.out.println("default:" + defaulted); } }
DefaultValueProviderCommand
java
apache__flink
flink-clients/src/test/java/org/apache/flink/client/deployment/ClusterClientServiceLoaderTest.java
{ "start": 4319, "end": 4742 }
class ____ extends BaseTestingClusterClientFactory { public static final String ID = AMBIGUOUS_TARGET; @Override public boolean isCompatibleWith(Configuration configuration) { return configuration.get(DeploymentOptions.TARGET).equals(AMBIGUOUS_TARGET); } } /** Test {@link ClusterClientFactory} that has a duplicate. */ public static
FirstCollidingClusterClientFactory
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesTests.java
{ "start": 66305, "end": 66532 }
class ____ { @Bean @ConfigurationPropertiesBinding static Converter<String, Person> personConverter() { return new PersonConverter(); } } @Configuration(proxyBeanMethods = false) static
PersonConverterConfiguration
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/adaptive/BackgroundTask.java
{ "start": 1846, "end": 5216 }
class ____<T> { private final CompletableFuture<Void> terminationFuture; private final CompletableFuture<T> resultFuture; private volatile boolean isAborted = false; private BackgroundTask( CompletableFuture<Void> previousTerminationFuture, SupplierWithException<? extends T, ? extends Exception> task, Executor executor) { resultFuture = previousTerminationFuture.thenApplyAsync( ignored -> { if (!isAborted) { try { return task.get(); } catch (Exception exception) { throw new CompletionException(exception); } } else { throw new CompletionException( new FlinkException("Background task has been aborted.")); } }, executor); terminationFuture = resultFuture.handle((ignored, ignoredThrowable) -> null); } private BackgroundTask() { terminationFuture = FutureUtils.completedVoidFuture(); resultFuture = FutureUtils.completedExceptionally( new FlinkException( "No result has been created because it is a finished background task.")); } /** * Abort the execution of this background task. This method has only an effect if the background * task has not been started yet. */ void abort() { isAborted = true; } public CompletableFuture<T> getResultFuture() { return resultFuture; } CompletableFuture<Void> getTerminationFuture() { return terminationFuture; } /** * Runs the given task after this background task has completed (normally or exceptionally). * * @param task task to run after this background task has completed * @param executor executor to run the task * @param <V> type of the result * @return new {@link BackgroundTask} representing the new task to execute */ <V> BackgroundTask<V> runAfter( SupplierWithException<? extends V, ? extends Exception> task, Executor executor) { return new BackgroundTask<>(terminationFuture, task, executor); } /** * Creates a finished background task which can be used as the start of a background task chain. * * @param <V> type of the background task * @return A finished background task */ static <V> BackgroundTask<V> finishedBackgroundTask() { return new BackgroundTask<>(); } /** * Creates an initial background task. This means that this background task has no predecessor. * * @param task task to run * @param executor executor to run the task * @param <V> type of the result * @return initial {@link BackgroundTask} representing the task to execute */ static <V> BackgroundTask<V> initialBackgroundTask( SupplierWithException<? extends V, ? extends Exception> task, Executor executor) { return new BackgroundTask<>(FutureUtils.completedVoidFuture(), task, executor); } }
BackgroundTask
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/metrics/NameNodeMetrics.java
{ "start": 1979, "end": 15890 }
class ____ { final MetricsRegistry registry = new MetricsRegistry("namenode"); @Metric MutableCounterLong createFileOps; @Metric MutableCounterLong filesCreated; @Metric MutableCounterLong filesAppended; @Metric MutableCounterLong getBlockLocations; @Metric MutableCounterLong filesRenamed; @Metric MutableCounterLong filesTruncated; @Metric MutableCounterLong getListingOps; @Metric MutableCounterLong deleteFileOps; @Metric("Number of files/dirs deleted by delete or rename operations") MutableCounterLong filesDeleted; @Metric MutableCounterLong fileInfoOps; @Metric MutableCounterLong addBlockOps; @Metric MutableCounterLong getAdditionalDatanodeOps; @Metric MutableCounterLong createSymlinkOps; @Metric MutableCounterLong getLinkTargetOps; @Metric MutableCounterLong filesInGetListingOps; @Metric ("Number of successful re-replications") MutableCounterLong successfulReReplications; @Metric ("Number of times we failed to schedule a block re-replication.") MutableCounterLong numTimesReReplicationNotScheduled; @Metric("Number of timed out block re-replications") MutableCounterLong timeoutReReplications; @Metric("Number of allowSnapshot operations") MutableCounterLong allowSnapshotOps; @Metric("Number of disallowSnapshot operations") MutableCounterLong disallowSnapshotOps; @Metric("Number of createSnapshot operations") MutableCounterLong createSnapshotOps; @Metric("Number of deleteSnapshot operations") MutableCounterLong deleteSnapshotOps; @Metric("Number of renameSnapshot operations") MutableCounterLong renameSnapshotOps; @Metric("Number of listSnapshottableDirectory operations") MutableCounterLong listSnapshottableDirOps; @Metric("Number of listSnapshots operations") MutableCounterLong listSnapshotOps; @Metric("Number of snapshotDiffReport operations") MutableCounterLong snapshotDiffReportOps; @Metric("Number of blockReceivedAndDeleted calls") MutableCounterLong blockReceivedAndDeletedOps; @Metric("Number of blockReports and blockReceivedAndDeleted queued") MutableGaugeInt blockOpsQueued; @Metric("Number of blockReports and blockReceivedAndDeleted batch processed") MutableCounterLong blockOpsBatched; @Metric("Number of pending edits") MutableGaugeInt pendingEditsCount; @Metric("Number of delete blocks Queued") MutableGaugeInt deleteBlocksQueued; @Metric("Number of pending deletion blocks") MutableGaugeInt pendingDeleteBlocksCount; @Metric("Number of file system operations") public long totalFileOps(){ return getBlockLocations.value() + createFileOps.value() + filesAppended.value() + addBlockOps.value() + getAdditionalDatanodeOps.value() + filesRenamed.value() + filesTruncated.value() + deleteFileOps.value() + getListingOps.value() + fileInfoOps.value() + getLinkTargetOps.value() + createSnapshotOps.value() + deleteSnapshotOps.value() + allowSnapshotOps.value() + disallowSnapshotOps.value() + renameSnapshotOps.value() + listSnapshottableDirOps.value() + listSnapshotOps.value() + createSymlinkOps.value() + snapshotDiffReportOps.value(); } @Metric("Journal transactions") MutableRate transactions; @Metric("Journal syncs") MutableRate syncs; final MutableQuantiles[] syncsQuantiles; @Metric("Journal transactions batched in sync") MutableCounterLong transactionsBatchedInSync; @Metric("Journal transactions batched in sync") final MutableQuantiles[] numTransactionsBatchedInSync; @Metric("Number of blockReports from individual storages") MutableRate storageBlockReport; final MutableQuantiles[] storageBlockReportQuantiles; @Metric("Cache report") MutableRate cacheReport; final MutableQuantiles[] cacheReportQuantiles; @Metric("Generate EDEK time") private MutableRate generateEDEKTime; private final MutableQuantiles[] generateEDEKTimeQuantiles; @Metric("Warm-up EDEK time") private MutableRate warmUpEDEKTime; private final MutableQuantiles[] warmUpEDEKTimeQuantiles; @Metric("Resource check time") private MutableRate resourceCheckTime; private final MutableQuantiles[] resourceCheckTimeQuantiles; @Metric("Duration in SafeMode at startup in msec") MutableGaugeInt safeModeTime; @Metric("Time loading FS Image at startup in msec") MutableGaugeInt fsImageLoadTime; @Metric("Time tailing edit logs in msec") MutableRate editLogTailTime; private final MutableQuantiles[] editLogTailTimeQuantiles; @Metric MutableRate editLogFetchTime; private final MutableQuantiles[] editLogFetchTimeQuantiles; @Metric(value = "Number of edits loaded", valueName = "Count") MutableStat numEditLogLoaded; private final MutableQuantiles[] numEditLogLoadedQuantiles; @Metric("Time between edit log tailing in msec") MutableRate editLogTailInterval; private final MutableQuantiles[] editLogTailIntervalQuantiles; @Metric("GetImageServlet getEdit") MutableRate getEdit; @Metric("GetImageServlet getImage") MutableRate getImage; @Metric("GetImageServlet getAliasMap") MutableRate getAliasMap; @Metric("GetImageServlet putImage") MutableRate putImage; JvmMetrics jvmMetrics = null; NameNodeMetrics(String processName, String sessionId, int[] intervals, final JvmMetrics jvmMetrics) { this.jvmMetrics = jvmMetrics; registry.tag(ProcessName, processName).tag(SessionId, sessionId); final int len = intervals.length; syncsQuantiles = new MutableQuantiles[len]; numTransactionsBatchedInSync = new MutableQuantiles[len]; storageBlockReportQuantiles = new MutableQuantiles[len]; cacheReportQuantiles = new MutableQuantiles[len]; generateEDEKTimeQuantiles = new MutableQuantiles[len]; warmUpEDEKTimeQuantiles = new MutableQuantiles[len]; resourceCheckTimeQuantiles = new MutableQuantiles[len]; editLogTailTimeQuantiles = new MutableQuantiles[len]; editLogFetchTimeQuantiles = new MutableQuantiles[len]; numEditLogLoadedQuantiles = new MutableQuantiles[len]; editLogTailIntervalQuantiles = new MutableQuantiles[len]; for (int i = 0; i < len; i++) { int interval = intervals[i]; syncsQuantiles[i] = registry.newQuantiles( "syncs" + interval + "s", "Journal syncs", "ops", "latency", interval); numTransactionsBatchedInSync[i] = registry.newQuantiles( "numTransactionsBatchedInSync" + interval + "s", "Number of Transactions batched in sync", "ops", "count", interval); storageBlockReportQuantiles[i] = registry.newQuantiles( "storageBlockReport" + interval + "s", "Storage block report", "ops", "latency", interval); cacheReportQuantiles[i] = registry.newQuantiles( "cacheReport" + interval + "s", "Cache report", "ops", "latency", interval); generateEDEKTimeQuantiles[i] = registry.newQuantiles( "generateEDEKTime" + interval + "s", "Generate EDEK time", "ops", "latency", interval); warmUpEDEKTimeQuantiles[i] = registry.newQuantiles( "warmupEDEKTime" + interval + "s", "Warm up EDEK time", "ops", "latency", interval); resourceCheckTimeQuantiles[i] = registry.newQuantiles( "resourceCheckTime" + interval + "s", "resource check time", "ops", "latency", interval); editLogTailTimeQuantiles[i] = registry.newQuantiles( "editLogTailTime" + interval + "s", "Edit log tailing time", "ops", "latency", interval); editLogFetchTimeQuantiles[i] = registry.newQuantiles( "editLogFetchTime" + interval + "s", "Edit log fetch time", "ops", "latency", interval); numEditLogLoadedQuantiles[i] = registry.newQuantiles( "numEditLogLoaded" + interval + "s", "Number of edits loaded", "ops", "count", interval); editLogTailIntervalQuantiles[i] = registry.newQuantiles( "editLogTailInterval" + interval + "s", "Edit log tailing interval", "ops", "latency", interval); } } public static NameNodeMetrics create(Configuration conf, NamenodeRole r) { String sessionId = conf.get(DFSConfigKeys.DFS_METRICS_SESSION_ID_KEY); String processName = r.toString(); MetricsSystem ms = DefaultMetricsSystem.instance(); JvmMetrics jm = JvmMetrics.create(processName, sessionId, ms); // Percentile measurement is off by default, by watching no intervals int[] intervals = conf.getInts(DFSConfigKeys.DFS_METRICS_PERCENTILES_INTERVALS_KEY); return ms.register(new NameNodeMetrics(processName, sessionId, intervals, jm)); } public JvmMetrics getJvmMetrics() { return jvmMetrics; } public void shutdown() { DefaultMetricsSystem.shutdown(); } public void incrGetBlockLocations() { getBlockLocations.incr(); } public void incrFilesCreated() { filesCreated.incr(); } public void incrCreateFileOps() { createFileOps.incr(); } public void incrFilesAppended() { filesAppended.incr(); } public void incrAddBlockOps() { addBlockOps.incr(); } public void incrGetAdditionalDatanodeOps() { getAdditionalDatanodeOps.incr(); } public void incrFilesRenamed() { filesRenamed.incr(); } public void incrFilesTruncated() { filesTruncated.incr(); } public void incrFilesDeleted(long delta) { filesDeleted.incr(delta); } public void incrDeleteFileOps() { deleteFileOps.incr(); } public void incrGetListingOps() { getListingOps.incr(); } public void incrFilesInGetListingOps(int delta) { filesInGetListingOps.incr(delta); } public void incrFileInfoOps() { fileInfoOps.incr(); } public void incrCreateSymlinkOps() { createSymlinkOps.incr(); } public void incrGetLinkTargetOps() { getLinkTargetOps.incr(); } public void incrAllowSnapshotOps() { allowSnapshotOps.incr(); } public void incrDisAllowSnapshotOps() { disallowSnapshotOps.incr(); } public void incrCreateSnapshotOps() { createSnapshotOps.incr(); } public void incrDeleteSnapshotOps() { deleteSnapshotOps.incr(); } public void incrRenameSnapshotOps() { renameSnapshotOps.incr(); } public void incrListSnapshottableDirOps() { listSnapshottableDirOps.incr(); } public void incrListSnapshotsOps() { listSnapshotOps.incr(); } public void incrSnapshotDiffReportOps() { snapshotDiffReportOps.incr(); } public void incrBlockReceivedAndDeletedOps() { blockReceivedAndDeletedOps.incr(); } public void setBlockOpsQueued(int size) { blockOpsQueued.set(size); } public void setDeleteBlocksQueued(int size) { deleteBlocksQueued.set(size); } public void incrPendingDeleteBlocksCount(int size) { pendingDeleteBlocksCount.incr(size); } public void decrPendingDeleteBlocksCount() { pendingDeleteBlocksCount.decr(); } public void addBlockOpsBatched(int count) { blockOpsBatched.incr(count); } public void setPendingEditsCount(int size) { pendingEditsCount.set(size); } public void addTransaction(long latency) { transactions.add(latency); } public void incrTransactionsBatchedInSync(long count) { transactionsBatchedInSync.incr(count); for (MutableQuantiles q : numTransactionsBatchedInSync) { q.add(count); } } public void incSuccessfulReReplications() { successfulReReplications.incr(); } public void incNumTimesReReplicationNotScheduled() { numTimesReReplicationNotScheduled.incr(); } public void incTimeoutReReplications() { timeoutReReplications.incr(); } public void addSync(long elapsed) { syncs.add(elapsed); for (MutableQuantiles q : syncsQuantiles) { q.add(elapsed); } } public void setFsImageLoadTime(long elapsed) { fsImageLoadTime.set((int) elapsed); } public void addStorageBlockReport(long latency) { storageBlockReport.add(latency); for (MutableQuantiles q : storageBlockReportQuantiles) { q.add(latency); } } public void addCacheBlockReport(long latency) { cacheReport.add(latency); for (MutableQuantiles q : cacheReportQuantiles) { q.add(latency); } } public void setSafeModeTime(long elapsed) { safeModeTime.set((int) elapsed); } public void addGetEdit(long latency) { getEdit.add(latency); } public void addGetImage(long latency) { getImage.add(latency); } public void addGetAliasMap(long latency) { getAliasMap.add(latency); } public void addPutImage(long latency) { putImage.add(latency); } public void addGenerateEDEKTime(long latency) { generateEDEKTime.add(latency); for (MutableQuantiles q : generateEDEKTimeQuantiles) { q.add(latency); } } public void addWarmUpEDEKTime(long latency) { warmUpEDEKTime.add(latency); for (MutableQuantiles q : warmUpEDEKTimeQuantiles) { q.add(latency); } } public void addResourceCheckTime(long latency) { resourceCheckTime.add(latency); for (MutableQuantiles q : resourceCheckTimeQuantiles) { q.add(latency); } } public void addEditLogTailTime(long elapsed) { editLogTailTime.add(elapsed); for (MutableQuantiles q : editLogTailTimeQuantiles) { q.add(elapsed); } } public void addEditLogFetchTime(long elapsed) { editLogFetchTime.add(elapsed); for (MutableQuantiles q : editLogFetchTimeQuantiles) { q.add(elapsed); } } public void addNumEditLogLoaded(long loaded) { numEditLogLoaded.add(loaded); for (MutableQuantiles q : numEditLogLoadedQuantiles) { q.add(loaded); } } public void addEditLogTailInterval(long elapsed) { editLogTailInterval.add(elapsed); for (MutableQuantiles q : editLogTailIntervalQuantiles) { q.add(elapsed); } } }
NameNodeMetrics
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/assignment/BalanceSubtopologyGraphConstructor.java
{ "start": 1418, "end": 10804 }
class ____<T> implements RackAwareGraphConstructor<T> { private final List<Set<TaskId>> taskSetsPerTopicGroup; public BalanceSubtopologyGraphConstructor(final List<Set<TaskId>> taskSetsPerTopicGroup) { this.taskSetsPerTopicGroup = taskSetsPerTopicGroup; } @Override public int getSinkNodeID( final List<TaskId> taskIdList, final List<ProcessId> clientList, final Collection<Set<TaskId>> taskSetsPerTopicGroup ) { return clientList.size() + taskIdList.size() + clientList.size() * taskSetsPerTopicGroup.size(); } @Override public int getClientNodeId(final int clientIndex, final List<TaskId> taskIdList, final List<ProcessId> clientList, final int topicGroupIndex) { return taskIdList.size() + clientList.size() * topicGroupIndex + clientIndex; } @Override public int getClientIndex(final int clientNodeId, final List<TaskId> taskIdList, final List<ProcessId> clientList, final int topicGroupIndex) { return clientNodeId - taskIdList.size() - clientList.size() * topicGroupIndex; } private static int getSecondStageClientNodeId(final List<TaskId> taskIdList, final List<ProcessId> clientList, final Collection<Set<TaskId>> tasksForTopicGroup, final int clientIndex) { return taskIdList.size() + clientList.size() * tasksForTopicGroup.size() + clientIndex; } @Override public Graph<Integer> constructTaskGraph( final List<ProcessId> clientList, final List<TaskId> taskIdList, final Map<ProcessId, T> clientStates, final Map<TaskId, ProcessId> taskClientMap, final Map<ProcessId, Integer> originalAssignedTaskNumber, final BiPredicate<T, TaskId> hasAssignedTask, final CostFunction costFunction, final int trafficCost, final int nonOverlapCost, final boolean hasReplica, final boolean isStandby ) { validateTasks(taskIdList); final Graph<Integer> graph = new Graph<>(); for (final TaskId taskId : taskIdList) { for (final Map.Entry<ProcessId, T> clientState : clientStates.entrySet()) { if (hasAssignedTask.test(clientState.getValue(), taskId)) { originalAssignedTaskNumber.merge(clientState.getKey(), 1, Integer::sum); } } } constructEdges( graph, taskIdList, clientList, clientStates, taskClientMap, originalAssignedTaskNumber, hasAssignedTask, costFunction, trafficCost, nonOverlapCost, hasReplica, isStandby ); // Run max flow algorithm to get a solution first final long maxFlow = graph.calculateMaxFlow(); if (maxFlow != taskIdList.size()) { throw new IllegalStateException("max flow calculated: " + maxFlow + " doesn't match taskSize: " + taskIdList.size()); } return graph; } @Override public boolean assignTaskFromMinCostFlow( final Graph<Integer> graph, final List<ProcessId> clientList, final List<TaskId> taskIdList, final Map<ProcessId, T> clientStates, final Map<ProcessId, Integer> originalAssignedTaskNumber, final Map<TaskId, ProcessId> taskClientMap, final BiConsumer<T, TaskId> assignTask, final BiConsumer<T, TaskId> unAssignTask, final BiPredicate<T, TaskId> hasAssignedTask ) { final Set<TaskId> taskIdSet = new HashSet<>(taskIdList); int taskNodeId = 0; int topicGroupIndex = 0; int tasksAssigned = 0; boolean taskMoved = false; for (final Set<TaskId> unorderedTaskIds : taskSetsPerTopicGroup) { final SortedSet<TaskId> taskIds = new TreeSet<>(unorderedTaskIds); for (final TaskId taskId : taskIds) { if (!taskIdSet.contains(taskId)) { continue; } final KeyValue<Boolean, Integer> movedAndAssigned = assignTaskToClient(graph, taskId, taskNodeId, topicGroupIndex, clientStates, clientList, taskIdList, taskClientMap, assignTask, unAssignTask); taskMoved |= movedAndAssigned.key; tasksAssigned += movedAndAssigned.value; taskNodeId++; } topicGroupIndex++; } validateAssignedTask(taskIdList, tasksAssigned, clientStates, originalAssignedTaskNumber, hasAssignedTask); return taskMoved; } private void validateTasks(final List<TaskId> taskIdList) { final Set<TaskId> tasksInSubtopology = taskSetsPerTopicGroup.stream().flatMap( Collection::stream).collect(Collectors.toSet()); for (final TaskId taskId : taskIdList) { if (!tasksInSubtopology.contains(taskId)) { throw new IllegalStateException("Task " + taskId + " not in tasksForTopicGroup"); } } } private void constructEdges( final Graph<Integer> graph, final List<TaskId> taskIdList, final List<ProcessId> clientList, final Map<ProcessId, T> clientStates, final Map<TaskId, ProcessId> taskClientMap, final Map<ProcessId, Integer> originalAssignedTaskNumber, final BiPredicate<T, TaskId> hasAssignedTask, final CostFunction costFunction, final int trafficCost, final int nonOverlapCost, final boolean hasReplica, final boolean isStandby ) { final Set<TaskId> taskIdSet = new HashSet<>(taskIdList); final int sinkId = getSinkNodeID(taskIdList, clientList, taskSetsPerTopicGroup); int taskNodeId = 0; int topicGroupIndex = 0; for (final Set<TaskId> unorderedTaskIds : taskSetsPerTopicGroup) { final SortedSet<TaskId> taskIds = new TreeSet<>(unorderedTaskIds); for (int clientIndex = 0; clientIndex < clientList.size(); clientIndex++) { final ProcessId processId = clientList.get(clientIndex); final int clientNodeId = getClientNodeId(clientIndex, taskIdList, clientList, topicGroupIndex); int startingTaskNodeId = taskNodeId; int validTaskCount = 0; for (final TaskId taskId : taskIds) { // It's possible some taskId is not in the tasks we want to assign. For example, taskIdSet is only stateless tasks, // but the tasks in subtopology map contains all tasks including stateful ones. if (!taskIdSet.contains(taskId)) { continue; } validTaskCount++; final boolean inCurrentAssignment = hasAssignedTask.test(clientStates.get(processId), taskId); graph.addEdge(startingTaskNodeId, clientNodeId, 1, costFunction.getCost(taskId, processId, inCurrentAssignment, trafficCost, nonOverlapCost, isStandby), 0); startingTaskNodeId++; if (inCurrentAssignment) { if (!hasReplica && taskClientMap.containsKey(taskId)) { throw new IllegalArgumentException("Task " + taskId + " assigned to multiple clients " + processId + ", " + taskClientMap.get(taskId)); } taskClientMap.put(taskId, processId); } } if (validTaskCount > 0) { final int secondStageClientNodeId = getSecondStageClientNodeId(taskIdList, clientList, taskSetsPerTopicGroup, clientIndex); final int capacity = originalAssignedTaskNumber.containsKey(processId) ? (int) Math.ceil(originalAssignedTaskNumber.get(processId) * 1.0 / taskIdList.size() * validTaskCount) : 0; graph.addEdge(clientNodeId, secondStageClientNodeId, capacity, 0, 0); } } taskNodeId += (int) taskIds.stream().filter(taskIdSet::contains).count(); topicGroupIndex++; } // Add edges from source to all tasks taskNodeId = 0; for (final Set<TaskId> unorderedTaskIds : taskSetsPerTopicGroup) { final SortedSet<TaskId> taskIds = new TreeSet<>(unorderedTaskIds); for (final TaskId taskId : taskIds) { if (!taskIdSet.contains(taskId)) { continue; } graph.addEdge(SOURCE_ID, taskNodeId, 1, 0, 0); taskNodeId++; } } // Add sink for (int clientIndex = 0; clientIndex < clientList.size(); clientIndex++) { final ProcessId processId = clientList.get(clientIndex); final int capacity = originalAssignedTaskNumber.getOrDefault(processId, 0); final int secondStageClientNodeId = getSecondStageClientNodeId(taskIdList, clientList, taskSetsPerTopicGroup, clientIndex); graph.addEdge(secondStageClientNodeId, sinkId, capacity, 0, 0); } graph.setSourceNode(SOURCE_ID); graph.setSinkNode(sinkId); } }
BalanceSubtopologyGraphConstructor
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/ClassesBaseTest.java
{ "start": 1120, "end": 1186 }
interface ____ { } @MyAnnotation protected static
MyAnnotation
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/metadata/definition/service/ComplexObject.java
{ "start": 1055, "end": 5424 }
class ____ { public ComplexObject() {} public ComplexObject(String var1, int var2, long l, String[] var3, List<Integer> var4, TestEnum testEnum) { this.setInnerObject(new InnerObject()); this.getInnerObject().setInnerA(var1); this.getInnerObject().setInnerB(var2); this.setIntList(var4); this.setStrArrays(var3); this.setTestEnum(testEnum); this.setV(l); InnerObject2 io21 = new InnerObject2(); io21.setInnerA2(var1 + "_21"); io21.setInnerB2(var2 + 100000); InnerObject2 io22 = new InnerObject2(); io22.setInnerA2(var1 + "_22"); io22.setInnerB2(var2 + 200000); this.setInnerObject2(new HashSet<InnerObject2>(Arrays.asList(io21, io22))); InnerObject3 io31 = new InnerObject3(); io31.setInnerA3(var1 + "_31"); InnerObject3 io32 = new InnerObject3(); io32.setInnerA3(var1 + "_32"); InnerObject3 io33 = new InnerObject3(); io33.setInnerA3(var1 + "_33"); this.setInnerObject3(new InnerObject3[] {io31, io32, io33}); this.maps = new HashMap<>(4); this.maps.put(var1 + "_k1", var1 + "_v1"); this.maps.put(var1 + "_k2", var1 + "_v2"); } private InnerObject innerObject; private Set<InnerObject2> innerObject2; private InnerObject3[] innerObject3; private String[] strArrays; private List<Integer> intList; private long v; private TestEnum testEnum; private Map<String, String> maps; public InnerObject getInnerObject() { return innerObject; } public void setInnerObject(InnerObject innerObject) { this.innerObject = innerObject; } public String[] getStrArrays() { return strArrays; } public void setStrArrays(String[] strArrays) { this.strArrays = strArrays; } public List<Integer> getIntList() { return intList; } public void setIntList(List<Integer> intList) { this.intList = intList; } public long getV() { return v; } public void setV(long v) { this.v = v; } public TestEnum getTestEnum() { return testEnum; } public void setTestEnum(TestEnum testEnum) { this.testEnum = testEnum; } public Set<InnerObject2> getInnerObject2() { return innerObject2; } public void setInnerObject2(Set<InnerObject2> innerObject2) { this.innerObject2 = innerObject2; } public InnerObject3[] getInnerObject3() { return innerObject3; } public void setInnerObject3(InnerObject3[] innerObject3) { this.innerObject3 = innerObject3; } public Map<String, String> getMaps() { return maps; } public void setMaps(Map<String, String> maps) { this.maps = maps; } @Override public String toString() { return "ComplexObject{" + "innerObject=" + innerObject + ", innerObject2=" + innerObject2 + ", innerObject3=" + Arrays.toString(innerObject3) + ", strArrays=" + Arrays.toString(strArrays) + ", intList=" + intList + ", v=" + v + ", testEnum=" + testEnum + ", maps=" + maps + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ComplexObject)) return false; ComplexObject that = (ComplexObject) o; return getV() == that.getV() && Objects.equals(getInnerObject(), that.getInnerObject()) && Objects.equals(getInnerObject2(), that.getInnerObject2()) && Arrays.equals(getInnerObject3(), that.getInnerObject3()) && Arrays.equals(getStrArrays(), that.getStrArrays()) && Objects.equals(getIntList(), that.getIntList()) && getTestEnum() == that.getTestEnum() && Objects.equals(getMaps(), that.getMaps()); } @Override public int hashCode() { int result = Objects.hash(getInnerObject(), getInnerObject2(), getIntList(), getV(), getTestEnum(), getMaps()); result = 31 * result + Arrays.hashCode(getInnerObject3()); result = 31 * result + Arrays.hashCode(getStrArrays()); return result; } public
ComplexObject
java
google__guice
extensions/assistedinject/test/com/google/inject/assistedinject/FactoryProvider2Test.java
{ "start": 47922, "end": 48040 }
interface ____<O extends AbstractAssisted, I extends CharSequence> { O create(I string); } } static
Factory
java
alibaba__nacos
ai/src/main/java/com/alibaba/nacos/ai/index/MemoryMcpCacheIndex.java
{ "start": 12248, "end": 13014 }
class ____ { final String key; final McpServerIndexData data; final long createTimeSeconds; volatile CacheNode prev; volatile CacheNode next; CacheNode(String key, McpServerIndexData data, long createTimeSeconds) { this.key = key; this.data = data; this.createTimeSeconds = createTimeSeconds; } boolean isExpired(long expireTimeSeconds) { if (expireTimeSeconds <= 0) { return false; } long currentTimeSeconds = System.currentTimeMillis() / 1000; return (currentTimeSeconds - createTimeSeconds) >= expireTimeSeconds; } } }
CacheNode
java
apache__flink
flink-rpc/flink-rpc-akka/src/main/java/org/apache/flink/runtime/rpc/pekko/SupervisorActor.java
{ "start": 12656, "end": 13295 }
class ____ { private final PropsFactory propsFactory; private final String endpointId; private StartRpcActor(PropsFactory propsFactory, String endpointId) { this.propsFactory = propsFactory; this.endpointId = endpointId; } public String getEndpointId() { return endpointId; } public PropsFactory getPropsFactory() { return propsFactory; } private static StartRpcActor create(PropsFactory propsFactory, String endpointId) { return new StartRpcActor(propsFactory, endpointId); }
StartRpcActor
java
apache__flink
flink-formats/flink-avro/src/test/java/org/apache/flink/formats/avro/testjar/AvroExternalJarProgram.java
{ "start": 4809, "end": 6983 }
class ____ { private final Random rnd = new Random(2389756789345689276L); public MyUser nextUser() { return randomUser(); } private MyUser randomUser() { int numColors = rnd.nextInt(5); ArrayList<Color> colors = new ArrayList<Color>(numColors); for (int i = 0; i < numColors; i++) { colors.add(new Color(randomString(), rnd.nextDouble())); } return new MyUser(randomString(), colors); } private String randomString() { char[] c = new char[this.rnd.nextInt(20) + 5]; for (int i = 0; i < c.length; i++) { c[i] = (char) (this.rnd.nextInt(150) + 40); } return new String(c); } } public static void writeTestData(File testFile, int numRecords) throws IOException { DatumWriter<MyUser> userDatumWriter = new ReflectDatumWriter<MyUser>(MyUser.class); DataFileWriter<MyUser> dataFileWriter = new DataFileWriter<MyUser>(userDatumWriter); dataFileWriter.create(ReflectData.get().getSchema(MyUser.class), testFile); Generator generator = new Generator(); for (int i = 0; i < numRecords; i++) { MyUser user = generator.nextUser(); dataFileWriter.append(user); } dataFileWriter.close(); } // public static void main(String[] args) throws Exception { // String testDataFile = new File("src/test/resources/testdata.avro").getAbsolutePath(); // writeTestData(new File(testDataFile), 50); // } public static void main(String[] args) throws Exception { String inputPath = args[0]; StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); DataStream<MyUser> input = env.createInput(new AvroInputFormat<MyUser>(new Path(inputPath), MyUser.class)); DataStream<Tuple2<String, MyUser>> result = input.map(new NameExtractor()).keyBy(new KeyAssigner()).reduce(new NameGrouper()); result.sinkTo(new DiscardingSink<>()); env.execute(); } }
Generator
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/util/FloatComparator.java
{ "start": 656, "end": 1683 }
class ____ extends NullSafeComparator<Float> { private float precision; public FloatComparator(float epsilon) { this.precision = epsilon; } public float getEpsilon() { return precision; } @Override public int compareNonNull(Float x, Float y) { if (closeEnough(x, y, precision)) return 0; return x < y ? -1 : 1; } private boolean closeEnough(Float x, Float y, float epsilon) { return x.floatValue() == y.floatValue() || Math.abs(x - y) <= epsilon; } @Override public int hashCode() { return 31 + Float.floatToIntBits(precision); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof FloatComparator)) return false; FloatComparator other = (FloatComparator) obj; return Float.floatToIntBits(precision) == Float.floatToIntBits(other.precision); } @Override public String toString() { return "FloatComparator[precision=%s]".formatted(precision); } }
FloatComparator
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/TestResourceUsage.java
{ "start": 1247, "end": 5041 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(TestResourceUsage.class); private String suffix; public static Collection<String[]> getParameters() { return Arrays.asList(new String[][]{{"Pending"}, {"Used"}, {"Reserved"}, {"AMUsed"}, {"AMLimit"}, {"CachedUsed"}, {"CachedPending"}}); } public void initTestResourceUsage(String pSuffix) { this.suffix = pSuffix; } private static void dec(ResourceUsage obj, String suffix, Resource res, String label) throws Exception { executeByName(obj, "dec" + suffix, res, label); } private static void inc(ResourceUsage obj, String suffix, Resource res, String label) throws Exception { executeByName(obj, "inc" + suffix, res, label); } private static void set(ResourceUsage obj, String suffix, Resource res, String label) throws Exception { executeByName(obj, "set" + suffix, res, label); } private static Resource get(ResourceUsage obj, String suffix, String label) throws Exception { return executeByName(obj, "get" + suffix, null, label); } // Use reflection to avoid too much avoid code private static Resource executeByName(ResourceUsage obj, String methodName, Resource arg, String label) throws Exception { // We have 4 kinds of method // 1. getXXX() : Resource // 2. getXXX(label) : Resource // 3. set/inc/decXXX(res) : void // 4. set/inc/decXXX(label, res) : void if (methodName.startsWith("get")) { Resource result; if (label == null) { // 1. Method method = ResourceUsage.class.getDeclaredMethod(methodName); result = (Resource) method.invoke(obj); } else { // 2. Method method = ResourceUsage.class.getDeclaredMethod(methodName, String.class); result = (Resource) method.invoke(obj, label); } return result; } else { if (label == null) { // 3. Method method = ResourceUsage.class.getDeclaredMethod(methodName, Resource.class); method.invoke(obj, arg); } else { // 4. Method method = ResourceUsage.class.getDeclaredMethod(methodName, String.class, Resource.class); method.invoke(obj, label, arg); } return null; } } private void internalTestModifyAndRead(String label) throws Exception { ResourceUsage usage = new ResourceUsage(); Resource res; // First get returns 0 always res = get(usage, suffix, label); check(0, 0, res); // Add 1,1 should returns 1,1 try { inc(usage, suffix, Resource.newInstance(1, 1), label); check(1, 1, get(usage, suffix, label)); } catch (NoSuchMethodException e) { // Few operations need not have to be verified as some resources doesn't // inc/dec apis exposed (For Eg: CachedUsed and CachedPending). } // Set 2,2 set(usage, suffix, Resource.newInstance(2, 2), label); check(2, 2, get(usage, suffix, label)); // dec 2,2 try { dec(usage, suffix, Resource.newInstance(2, 2), label); check(0, 0, get(usage, suffix, label)); } catch (NoSuchMethodException e) { // Few operations need not have to be verified, as some resources doesn't // inc/dec apis exposed (For Eg: CachedUsed and CachedPending). } } void check(int mem, int cpu, Resource res) { assertEquals(mem, res.getMemorySize()); assertEquals(cpu, res.getVirtualCores()); } @ParameterizedTest @MethodSource("getParameters") public void testModifyAndRead(String pSuffix) throws Exception { initTestResourceUsage(pSuffix); LOG.info("Test - " + suffix); internalTestModifyAndRead(null); internalTestModifyAndRead("label"); } }
TestResourceUsage
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/json/impl/GsonImpl.java
{ "start": 1240, "end": 3018 }
class ____ extends AbstractJsonUtilImpl { private volatile Gson gson; @Override public String getName() { return "gson"; } @Override public boolean isJson(String json) { try { JsonElement jsonElement = JsonParser.parseString(json); return jsonElement.isJsonObject() || jsonElement.isJsonArray(); } catch (JsonSyntaxException e) { return false; } } @Override public <T> T toJavaObject(String json, Type type) { return getGson().fromJson(json, type); } @Override public <T> List<T> toJavaList(String json, Class<T> clazz) { Type type = TypeToken.getParameterized(List.class, clazz).getType(); return getGson().fromJson(json, type); } @Override public String toJson(Object obj) { return getGson().toJson(obj); } @Override public String toPrettyJson(Object obj) { return createBuilder().setPrettyPrinting().create().toJson(obj); } @Override public Object convertObject(Object obj, Type type) { Gson gson = getGson(); return gson.fromJson(gson.toJsonTree(obj), type); } @Override public Object convertObject(Object obj, Class<?> clazz) { Gson gson = getGson(); return gson.fromJson(gson.toJsonTree(obj), clazz); } protected Gson getGson() { Gson gson = this.gson; if (gson == null) { synchronized (this) { gson = this.gson; if (gson == null) { this.gson = gson = createBuilder().create(); } } } return gson; } protected GsonBuilder createBuilder() { return new GsonBuilder(); } }
GsonImpl
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/proxy/AbstractSerializableProxy.java
{ "start": 178, "end": 290 }
class ____ the serialized form of {@link AbstractLazyInitializer}. * * @author Gail Badner */ public abstract
for
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToDouble.java
{ "start": 1868, "end": 6119 }
class ____ extends AbstractConvertFunction { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "ToDouble", ToDouble::new); private static final Map<DataType, BuildFactory> EVALUATORS = Map.ofEntries( Map.entry(DOUBLE, (source, fieldEval) -> fieldEval), Map.entry(BOOLEAN, ToDoubleFromBooleanEvaluator.Factory::new), Map.entry(DATETIME, ToDoubleFromLongEvaluator.Factory::new), // CastLongToDoubleEvaluator would be a candidate, but not MV'd Map.entry(KEYWORD, ToDoubleFromStringEvaluator.Factory::new), Map.entry(TEXT, ToDoubleFromStringEvaluator.Factory::new), Map.entry(UNSIGNED_LONG, ToDoubleFromUnsignedLongEvaluator.Factory::new), Map.entry(LONG, ToDoubleFromLongEvaluator.Factory::new), // CastLongToDoubleEvaluator would be a candidate, but not MV'd Map.entry(INTEGER, ToDoubleFromIntEvaluator.Factory::new), // CastIntToDoubleEvaluator would be a candidate, but not MV'd Map.entry(DataType.COUNTER_DOUBLE, (source, field) -> field), Map.entry(DataType.COUNTER_INTEGER, ToDoubleFromIntEvaluator.Factory::new), Map.entry(DataType.COUNTER_LONG, ToDoubleFromLongEvaluator.Factory::new) ); @FunctionInfo( returnType = "double", description = """ Converts an input value to a double value. If the input parameter is of a date type, its value will be interpreted as milliseconds since the {wikipedia}/Unix_time[Unix epoch], converted to double. Boolean `true` will be converted to double `1.0`, `false` to `0.0`.""", examples = @Example(file = "floats", tag = "to_double-str", explanation = """ Note that in this example, the last conversion of the string isn’t possible. When this happens, the result is a `null` value. In this case a _Warning_ header is added to the response. The header will provide information on the source of the failure: `"Line 1:115: evaluation of [TO_DOUBLE(str2)] failed, treating result as null. Only first 20 failures recorded."` A following header will contain the failure reason and the offending value: `"java.lang.NumberFormatException: For input string: \"foo\""`""") ) public ToDouble( Source source, @Param( name = "field", type = { "boolean", "date", "keyword", "text", "double", "long", "unsigned_long", "integer", "counter_double", "counter_integer", "counter_long" }, description = "Input value. The input can be a single- or multi-valued column or an expression." ) Expression field ) { super(source, field); } private ToDouble(StreamInput in) throws IOException { super(in); } @Override public String getWriteableName() { return ENTRY.name; } @Override protected Map<DataType, BuildFactory> factories() { return EVALUATORS; } @Override public DataType dataType() { return DOUBLE; } @Override public Expression replaceChildren(List<Expression> newChildren) { return new ToDouble(source(), newChildren.get(0)); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, ToDouble::new, field()); } @ConvertEvaluator(extraName = "FromBoolean") static double fromBoolean(boolean bool) { return bool ? 1d : 0d; } @ConvertEvaluator(extraName = "FromString", warnExceptions = { InvalidArgumentException.class }) static double fromKeyword(BytesRef in) { return stringToDouble(in.utf8ToString()); } @ConvertEvaluator(extraName = "FromUnsignedLong") static double fromUnsignedLong(long l) { return unsignedLongToDouble(l); } @ConvertEvaluator(extraName = "FromLong") static double fromLong(long l) { return l; } @ConvertEvaluator(extraName = "FromInt") static double fromInt(int i) { return i; } }
ToDouble
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/api/condition/DisabledIfConditionClassLoaderTests.java
{ "start": 998, "end": 2663 }
class ____ { @Test // No need to introduce a "disabled" version of this test, since it would simply be the // logical inverse of this method and would therefore not provide any further benefit. void enabledWithStaticMethodInTypeFromDifferentClassLoader() throws Exception { try (var testClassLoader = TestClassLoader.forClasses(getClass(), StaticConditionMethods.class)) { var testClass = testClassLoader.loadClass(getClass().getName()); assertThat(testClass.getClassLoader()).isSameAs(testClassLoader); ExtensionContext context = mock(); Method annotatedMethod = ReflectionSupport.findMethod(getClass(), "enabledMethod").get(); when(context.getElement()).thenReturn(Optional.of(annotatedMethod)); doReturn(testClass).when(context).getRequiredTestClass(); DisabledIfCondition condition = new DisabledIfCondition(); ConditionEvaluationResult result = condition.evaluateExecutionCondition(context); assertThat(result).isNotNull(); assertThat(result.isDisabled()).isFalse(); Method conditionMethod = condition.getConditionMethod( "org.junit.jupiter.api.condition.StaticConditionMethods#returnsFalse", context); assertThat(conditionMethod).isNotNull(); Class<?> declaringClass = conditionMethod.getDeclaringClass(); assertThat(declaringClass.getClassLoader()).isSameAs(testClassLoader); assertThat(declaringClass.getName()).isEqualTo(StaticConditionMethods.class.getName()); assertThat(declaringClass).isNotEqualTo(StaticConditionMethods.class); } } @DisabledIf("org.junit.jupiter.api.condition.StaticConditionMethods#returnsFalse") private void enabledMethod() { } }
DisabledIfConditionClassLoaderTests
java
quarkusio__quarkus
independent-projects/vertx-utils/src/main/java/io/quarkus/vertx/utils/VertxJavaIoContext.java
{ "start": 211, "end": 1930 }
class ____ { private final RoutingContext context; private final int minChunkSize; private final int outputBufferCapacity; public VertxJavaIoContext(RoutingContext context, int minChunkSize, int outputBufferSize) { this.context = context; this.minChunkSize = minChunkSize; this.outputBufferCapacity = outputBufferSize; } /** * @return the Vert.x routing context */ public RoutingContext getRoutingContext() { return context; } /** * Returns the size of the chunks of memory allocated when writing data in bytes. * * @return the size of the chunks of memory allocated when writing data in bytes */ public int getMinChunkSize() { return minChunkSize; } /** * Returns the capacity of the underlying response buffer in bytes. If a response is larger than this and no * content-length is provided then the request will be chunked. * <p> * Larger values may give slight performance increases for large responses, at the expense of more memory usage. * * @return the capacity of the underlying response buffer in bytes */ public int getOutputBufferCapacity() { return outputBufferCapacity; } /** * You may want to override this method letting it return a non-empty {@link Optional} if your framework needs to * pass a user defined content length to the underlying {@link VertxOutputStream}. * <p> * The default implementation always returns an empty {@link Optional}. * * @return {@link Optional#empty()} */ public Optional<String> getContentLength() { return Optional.empty(); } }
VertxJavaIoContext
java
spring-projects__spring-security
cas/src/main/java/org/springframework/security/cas/jackson2/CasJackson2Module.java
{ "start": 2039, "end": 2608 }
class ____ extends SimpleModule { public CasJackson2Module() { super(CasJackson2Module.class.getName(), new Version(1, 0, 0, null, null, null)); } @Override public void setupModule(SetupContext context) { SecurityJackson2Modules.enableDefaultTyping(context.getOwner()); context.setMixInAnnotations(AssertionImpl.class, AssertionImplMixin.class); context.setMixInAnnotations(AttributePrincipalImpl.class, AttributePrincipalImplMixin.class); context.setMixInAnnotations(CasAuthenticationToken.class, CasAuthenticationTokenMixin.class); } }
CasJackson2Module
java
apache__flink
flink-table/flink-sql-client/src/test/java/org/apache/flink/table/client/util/ClientWrapperClassLoaderTest.java
{ "start": 4479, "end": 5124 }
class ____ after remove jar url from ClassLoader assertClassNotFoundException(GENERATED_UPPER_UDF_CLASS, classLoader); // add jar url to ClassLoader again classLoader.addURL(jarURL); assertEquals(1, classLoader.getURLs().length); final Class<?> clazz3 = Class.forName(GENERATED_UPPER_UDF_CLASS, false, classLoader); final Class<?> clazz4 = Class.forName(GENERATED_UPPER_UDF_CLASS, false, classLoader); assertEquals(clazz3, clazz4); classLoader.close(); } @Test public void testParallelCapable() { // It will be true only if all the super classes (except
loader
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/env/PropertySourcesLocator.java
{ "start": 728, "end": 880 }
interface ____ beans that are capable of locating a {@link PropertySource} instance. * * @author Denis Stepanov * @since 5.0 */ @Experimental public
for
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilderTests.java
{ "start": 25314, "end": 25788 }
class ____ implements RequestPostProcessor { String attr; String value; public RequestAttributePostProcessor attr(String attr) { this.attr = attr; return this; } public RequestAttributePostProcessor value(String value) { this.value = value; return this; } @Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { request.setAttribute(attr, value); return request; } } }
RequestAttributePostProcessor
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 14884, "end": 15054 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return dialect.supportsNullPrecedence(); } } public static
SupportNullPrecedence
java
apache__thrift
lib/java/src/main/java/org/apache/thrift/transport/layered/TFastFramedTransport.java
{ "start": 1454, "end": 6975 }
class ____ extends TTransportFactory { private final int initialCapacity; private final int maxLength; public Factory() { this(DEFAULT_BUF_CAPACITY, TConfiguration.DEFAULT_MAX_FRAME_SIZE); } public Factory(int initialCapacity) { this(initialCapacity, TConfiguration.DEFAULT_MAX_FRAME_SIZE); } public Factory(int initialCapacity, int maxLength) { this.initialCapacity = initialCapacity; this.maxLength = maxLength; } @Override public TTransport getTransport(TTransport trans) throws TTransportException { return new TFastFramedTransport(trans, initialCapacity, maxLength); } } /** How big should the default read and write buffers be? */ public static final int DEFAULT_BUF_CAPACITY = 1024; private final AutoExpandingBufferWriteTransport writeBuffer; private AutoExpandingBufferReadTransport readBuffer; private final int initialBufferCapacity; private final byte[] i32buf = new byte[4]; private final int maxLength; /** * Create a new {@link TFastFramedTransport}. Use the defaults for initial buffer size and max * frame length. * * @param underlying Transport that real reads and writes will go through to. */ public TFastFramedTransport(TTransport underlying) throws TTransportException { this(underlying, DEFAULT_BUF_CAPACITY, TConfiguration.DEFAULT_MAX_FRAME_SIZE); } /** * Create a new {@link TFastFramedTransport}. Use the specified initial buffer capacity and the * default max frame length. * * @param underlying Transport that real reads and writes will go through to. * @param initialBufferCapacity The initial size of the read and write buffers. In practice, it's * not critical to set this unless you know in advance that your messages are going to be very * large. */ public TFastFramedTransport(TTransport underlying, int initialBufferCapacity) throws TTransportException { this(underlying, initialBufferCapacity, TConfiguration.DEFAULT_MAX_FRAME_SIZE); } /** * @param underlying Transport that real reads and writes will go through to. * @param initialBufferCapacity The initial size of the read and write buffers. In practice, it's * not critical to set this unless you know in advance that your messages are going to be very * large. (You can pass TFramedTransportWithReusableBuffer.DEFAULT_BUF_CAPACITY if you're only * using this constructor because you want to set the maxLength.) * @param maxLength The max frame size you are willing to read. You can use this parameter to * limit how much memory can be allocated. */ public TFastFramedTransport(TTransport underlying, int initialBufferCapacity, int maxLength) throws TTransportException { super(underlying); TConfiguration config = Objects.isNull(underlying.getConfiguration()) ? new TConfiguration() : underlying.getConfiguration(); this.maxLength = maxLength; config.setMaxFrameSize(maxLength); this.initialBufferCapacity = initialBufferCapacity; readBuffer = new AutoExpandingBufferReadTransport(config, initialBufferCapacity); writeBuffer = new AutoExpandingBufferWriteTransport(config, initialBufferCapacity, 4); } @Override public void close() { getInnerTransport().close(); } @Override public boolean isOpen() { return getInnerTransport().isOpen(); } @Override public void open() throws TTransportException { getInnerTransport().open(); } @Override public int read(byte[] buf, int off, int len) throws TTransportException { int got = readBuffer.read(buf, off, len); if (got > 0) { return got; } // Read another frame of data readFrame(); return readBuffer.read(buf, off, len); } private void readFrame() throws TTransportException { getInnerTransport().readAll(i32buf, 0, 4); int size = TFramedTransport.decodeFrameSize(i32buf); if (size < 0) { close(); throw new TTransportException( TTransportException.CORRUPTED_DATA, "Read a negative frame size (" + size + ")!"); } if (size > getInnerTransport().getConfiguration().getMaxFrameSize()) { close(); throw new TTransportException( TTransportException.CORRUPTED_DATA, "Frame size (" + size + ") larger than max length (" + maxLength + ")!"); } readBuffer.fill(getInnerTransport(), size); } @Override public void write(byte[] buf, int off, int len) throws TTransportException { writeBuffer.write(buf, off, len); } @Override public void consumeBuffer(int len) { readBuffer.consumeBuffer(len); } /** Only clears the read buffer! */ public void clear() throws TTransportException { readBuffer = new AutoExpandingBufferReadTransport(getConfiguration(), initialBufferCapacity); } @Override public void flush() throws TTransportException { int payloadLength = writeBuffer.getLength() - 4; byte[] data = writeBuffer.getBuf().array(); TFramedTransport.encodeFrameSize(payloadLength, data); getInnerTransport().write(data, 0, payloadLength + 4); writeBuffer.reset(); getInnerTransport().flush(); } @Override public byte[] getBuffer() { return readBuffer.getBuffer(); } @Override public int getBufferPosition() { return readBuffer.getBufferPosition(); } @Override public int getBytesRemainingInBuffer() { return readBuffer.getBytesRemainingInBuffer(); } }
Factory
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/Banner.java
{ "start": 1132, "end": 1389 }
class ____ the application or {@code null} * @param out the output print stream */ void printBanner(Environment environment, @Nullable Class<?> sourceClass, PrintStream out); /** * An enumeration of possible values for configuring the Banner. */
for
java
apache__flink
flink-libraries/flink-cep/src/test/java/org/apache/flink/cep/operator/CEPRescalingTest.java
{ "start": 2183, "end": 19246 }
class ____ { @Test public void testCEPFunctionScalingUp() throws Exception { int maxParallelism = 10; KeySelector<Event, Integer> keySelector = new KeySelector<Event, Integer>() { private static final long serialVersionUID = -4873366487571254798L; @Override public Integer getKey(Event value) throws Exception { return value.getId(); } }; // valid pattern events belong to different keygroups // that will be shipped to different tasks when changing parallelism. Event startEvent1 = new Event(7, "start", 1.0); SubEvent middleEvent1 = new SubEvent(7, "foo", 1.0, 10.0); Event endEvent1 = new Event(7, "end", 1.0); int keygroup = KeyGroupRangeAssignment.assignToKeyGroup( keySelector.getKey(startEvent1), maxParallelism); assertEquals(1, keygroup); assertEquals( 0, KeyGroupRangeAssignment.computeOperatorIndexForKeyGroup( maxParallelism, 2, keygroup)); Event startEvent2 = new Event(10, "start", 1.0); // this will go to task index 2 SubEvent middleEvent2 = new SubEvent(10, "foo", 1.0, 10.0); Event endEvent2 = new Event(10, "end", 1.0); keygroup = KeyGroupRangeAssignment.assignToKeyGroup( keySelector.getKey(startEvent2), maxParallelism); assertEquals(9, keygroup); assertEquals( 1, KeyGroupRangeAssignment.computeOperatorIndexForKeyGroup( maxParallelism, 2, keygroup)); // now we start the test, we go from parallelism 1 to 2. OneInputStreamOperatorTestHarness<Event, Map<String, List<Event>>> harness = null; OneInputStreamOperatorTestHarness<Event, Map<String, List<Event>>> harness1 = null; OneInputStreamOperatorTestHarness<Event, Map<String, List<Event>>> harness2 = null; try { harness = getTestHarness(maxParallelism, 1, 0); harness.open(); harness.processElement(new StreamRecord<>(startEvent1, 1)); // valid element harness.processElement(new StreamRecord<>(new Event(7, "foobar", 1.0), 2)); harness.processElement(new StreamRecord<>(startEvent2, 3)); // valid element harness.processElement(new StreamRecord<Event>(middleEvent2, 4)); // valid element // take a snapshot with some elements in internal sorting queue OperatorSubtaskState snapshot = harness.snapshot(0, 0); harness.close(); // initialize two sub-tasks with the previously snapshotted state to simulate scaling up // we know that the valid element will go to index 0, // so we initialize the two tasks and we put the rest of // the valid elements for the pattern on task 0. OperatorSubtaskState initState1 = AbstractStreamOperatorTestHarness.repartitionOperatorState( snapshot, maxParallelism, 1, 2, 0); OperatorSubtaskState initState2 = AbstractStreamOperatorTestHarness.repartitionOperatorState( snapshot, maxParallelism, 1, 2, 1); harness1 = getTestHarness(maxParallelism, 2, 0); harness1.setup(); harness1.initializeState(initState1); harness1.open(); // if element timestamps are not correctly checkpointed/restored this will lead to // a pruning time underflow exception in NFA harness1.processWatermark(new Watermark(2)); harness1.processElement(new StreamRecord<Event>(middleEvent1, 3)); // valid element harness1.processElement(new StreamRecord<>(endEvent1, 5)); // valid element harness1.processWatermark(new Watermark(Long.MAX_VALUE)); // watermarks and the result assertEquals(3, harness1.getOutput().size()); verifyWatermark(harness1.getOutput().poll(), 2); verifyPattern(harness1.getOutput().poll(), startEvent1, middleEvent1, endEvent1); harness2 = getTestHarness(maxParallelism, 2, 1); harness2.setup(); harness2.initializeState(initState2); harness2.open(); // now we move to the second parallel task harness2.processWatermark(new Watermark(2)); harness2.processElement(new StreamRecord<>(endEvent2, 5)); harness2.processElement(new StreamRecord<>(new Event(42, "start", 1.0), 4)); harness2.processWatermark(new Watermark(Long.MAX_VALUE)); assertEquals(3, harness2.getOutput().size()); verifyWatermark(harness2.getOutput().poll(), 2); verifyPattern(harness2.getOutput().poll(), startEvent2, middleEvent2, endEvent2); } finally { closeSilently(harness); closeSilently(harness1); closeSilently(harness2); } } private static void closeSilently(OneInputStreamOperatorTestHarness<?, ?> harness) { if (harness != null) { try { harness.close(); } catch (Throwable ignored) { } } } @Test public void testCEPFunctionScalingDown() throws Exception { int maxParallelism = 10; KeySelector<Event, Integer> keySelector = new KeySelector<Event, Integer>() { private static final long serialVersionUID = -4873366487571254798L; @Override public Integer getKey(Event value) throws Exception { return value.getId(); } }; // create some valid pattern events on predetermined key groups and task indices Event startEvent1 = new Event(7, "start", 1.0); // this will go to task index 0 SubEvent middleEvent1 = new SubEvent(7, "foo", 1.0, 10.0); Event endEvent1 = new Event(7, "end", 1.0); // verification of the key choice int keygroup = KeyGroupRangeAssignment.assignToKeyGroup( keySelector.getKey(startEvent1), maxParallelism); assertEquals(1, keygroup); assertEquals( 0, KeyGroupRangeAssignment.computeOperatorIndexForKeyGroup( maxParallelism, 3, keygroup)); assertEquals( 0, KeyGroupRangeAssignment.computeOperatorIndexForKeyGroup( maxParallelism, 2, keygroup)); Event startEvent2 = new Event(45, "start", 1.0); // this will go to task index 1 SubEvent middleEvent2 = new SubEvent(45, "foo", 1.0, 10.0); Event endEvent2 = new Event(45, "end", 1.0); keygroup = KeyGroupRangeAssignment.assignToKeyGroup( keySelector.getKey(startEvent2), maxParallelism); assertEquals(6, keygroup); assertEquals( 1, KeyGroupRangeAssignment.computeOperatorIndexForKeyGroup( maxParallelism, 3, keygroup)); assertEquals( 1, KeyGroupRangeAssignment.computeOperatorIndexForKeyGroup( maxParallelism, 2, keygroup)); Event startEvent3 = new Event(90, "start", 1.0); // this will go to task index 0 SubEvent middleEvent3 = new SubEvent(90, "foo", 1.0, 10.0); Event endEvent3 = new Event(90, "end", 1.0); keygroup = KeyGroupRangeAssignment.assignToKeyGroup( keySelector.getKey(startEvent3), maxParallelism); assertEquals(2, keygroup); assertEquals( 0, KeyGroupRangeAssignment.computeOperatorIndexForKeyGroup( maxParallelism, 3, keygroup)); assertEquals( 0, KeyGroupRangeAssignment.computeOperatorIndexForKeyGroup( maxParallelism, 2, keygroup)); Event startEvent4 = new Event(10, "start", 1.0); // this will go to task index 2 SubEvent middleEvent4 = new SubEvent(10, "foo", 1.0, 10.0); Event endEvent4 = new Event(10, "end", 1.0); keygroup = KeyGroupRangeAssignment.assignToKeyGroup( keySelector.getKey(startEvent4), maxParallelism); assertEquals(9, keygroup); assertEquals( 2, KeyGroupRangeAssignment.computeOperatorIndexForKeyGroup( maxParallelism, 3, keygroup)); assertEquals( 1, KeyGroupRangeAssignment.computeOperatorIndexForKeyGroup( maxParallelism, 2, keygroup)); // starting the test, we will go from parallelism of 3 to parallelism of 2 OneInputStreamOperatorTestHarness<Event, Map<String, List<Event>>> harness1 = getTestHarness(maxParallelism, 3, 0); harness1.open(); OneInputStreamOperatorTestHarness<Event, Map<String, List<Event>>> harness2 = getTestHarness(maxParallelism, 3, 1); harness2.open(); OneInputStreamOperatorTestHarness<Event, Map<String, List<Event>>> harness3 = getTestHarness(maxParallelism, 3, 2); harness3.open(); OneInputStreamOperatorTestHarness<Event, Map<String, List<Event>>> harness4 = null; OneInputStreamOperatorTestHarness<Event, Map<String, List<Event>>> harness5 = null; try { harness1.processWatermark(Long.MIN_VALUE); harness2.processWatermark(Long.MIN_VALUE); harness3.processWatermark(Long.MIN_VALUE); harness1.processElement(new StreamRecord<>(startEvent1, 1)); // valid element harness1.processElement(new StreamRecord<>(new Event(7, "foobar", 1.0), 2)); harness1.processElement(new StreamRecord<Event>(middleEvent1, 3)); // valid element harness1.processElement(new StreamRecord<>(endEvent1, 5)); // valid element // till here we have a valid sequence, so after creating the // new instance and sending it a watermark, we expect it to fire, // even with no new elements. harness1.processElement(new StreamRecord<>(startEvent3, 10)); harness1.processElement(new StreamRecord<>(startEvent1, 10)); harness2.processElement(new StreamRecord<>(startEvent2, 7)); harness2.processElement(new StreamRecord<Event>(middleEvent2, 8)); harness3.processElement(new StreamRecord<>(startEvent4, 15)); harness3.processElement(new StreamRecord<Event>(middleEvent4, 16)); harness3.processElement(new StreamRecord<>(endEvent4, 17)); // so far we only have the initial watermark assertEquals(1, harness1.getOutput().size()); verifyWatermark(harness1.getOutput().poll(), Long.MIN_VALUE); assertEquals(1, harness2.getOutput().size()); verifyWatermark(harness2.getOutput().poll(), Long.MIN_VALUE); assertEquals(1, harness3.getOutput().size()); verifyWatermark(harness3.getOutput().poll(), Long.MIN_VALUE); // we take a snapshot and make it look as a single operator // this will be the initial state of all downstream tasks. OperatorSubtaskState snapshot = AbstractStreamOperatorTestHarness.repackageState( harness2.snapshot(0, 0), harness1.snapshot(0, 0), harness3.snapshot(0, 0)); OperatorSubtaskState initState1 = AbstractStreamOperatorTestHarness.repartitionOperatorState( snapshot, maxParallelism, 3, 2, 0); OperatorSubtaskState initState2 = AbstractStreamOperatorTestHarness.repartitionOperatorState( snapshot, maxParallelism, 3, 2, 1); harness4 = getTestHarness(maxParallelism, 2, 0); harness4.setup(); harness4.initializeState(initState1); harness4.open(); harness5 = getTestHarness(maxParallelism, 2, 1); harness5.setup(); harness5.initializeState(initState2); harness5.open(); harness5.processElement(new StreamRecord<>(endEvent2, 11)); harness5.processWatermark(new Watermark(12)); verifyPattern(harness5.getOutput().poll(), startEvent2, middleEvent2, endEvent2); verifyWatermark(harness5.getOutput().poll(), 12); // if element timestamps are not correctly checkpointed/restored this will lead to // a pruning time underflow exception in NFA harness4.processWatermark(new Watermark(12)); assertEquals(2, harness4.getOutput().size()); verifyPattern(harness4.getOutput().poll(), startEvent1, middleEvent1, endEvent1); verifyWatermark(harness4.getOutput().poll(), 12); harness4.processElement(new StreamRecord<Event>(middleEvent3, 15)); // valid element harness4.processElement(new StreamRecord<>(endEvent3, 16)); // valid element harness4.processElement(new StreamRecord<Event>(middleEvent1, 15)); // valid element harness4.processElement(new StreamRecord<>(endEvent1, 16)); // valid element harness4.processWatermark(new Watermark(Long.MAX_VALUE)); harness5.processWatermark(new Watermark(Long.MAX_VALUE)); // verify result assertEquals(3, harness4.getOutput().size()); // check the order of the events in the output Queue<Object> output = harness4.getOutput(); StreamRecord<?> resultRecord = (StreamRecord<?>) output.peek(); assertTrue(resultRecord.getValue() instanceof Map); @SuppressWarnings("unchecked") Map<String, List<Event>> patternMap = (Map<String, List<Event>>) resultRecord.getValue(); if (patternMap.get("start").get(0).getId() == 7) { verifyPattern(harness4.getOutput().poll(), startEvent1, middleEvent1, endEvent1); verifyPattern(harness4.getOutput().poll(), startEvent3, middleEvent3, endEvent3); } else { verifyPattern(harness4.getOutput().poll(), startEvent3, middleEvent3, endEvent3); verifyPattern(harness4.getOutput().poll(), startEvent1, middleEvent1, endEvent1); } // after scaling down this should end up here assertEquals(2, harness5.getOutput().size()); verifyPattern(harness5.getOutput().poll(), startEvent4, middleEvent4, endEvent4); } finally { closeSilently(harness1); closeSilently(harness2); closeSilently(harness3); closeSilently(harness4); closeSilently(harness5); } } private void verifyWatermark(Object outputObject, long timestamp) { assertTrue(outputObject instanceof Watermark); assertEquals(timestamp, ((Watermark) outputObject).getTimestamp()); } private void verifyPattern(Object outputObject, Event start, SubEvent middle, Event end) { assertTrue(outputObject instanceof StreamRecord); StreamRecord<?> resultRecord = (StreamRecord<?>) outputObject; assertTrue(resultRecord.getValue() instanceof Map); @SuppressWarnings("unchecked") Map<String, List<Event>> patternMap = (Map<String, List<Event>>) resultRecord.getValue(); assertEquals(start, patternMap.get("start").get(0)); assertEquals(middle, patternMap.get("middle").get(0)); assertEquals(end, patternMap.get("end").get(0)); } private KeyedOneInputStreamOperatorTestHarness<Integer, Event, Map<String, List<Event>>> getTestHarness(int maxParallelism, int taskParallelism, int subtaskIdx) throws Exception { KeySelector<Event, Integer> keySelector = new TestKeySelector(); KeyedOneInputStreamOperatorTestHarness<Integer, Event, Map<String, List<Event>>> harness = new KeyedOneInputStreamOperatorTestHarness<>( CepOperatorTestUtilities.getKeyedCepOperator(false, new NFAFactory()), keySelector, BasicTypeInfo.INT_TYPE_INFO, maxParallelism, taskParallelism, subtaskIdx); harness.setStateBackend(new EmbeddedRocksDBStateBackend()); harness.setCheckpointStorage(new JobManagerCheckpointStorage()); return harness; } private static
CEPRescalingTest
java
quarkusio__quarkus
extensions/reactive-routes/deployment/src/main/java/io/quarkus/vertx/web/deployment/ReactiveRoutesProcessor.java
{ "start": 81978, "end": 86938 }
class ____ { static Builder builder() { return new Builder(); } final TriPredicate<Type, Set<AnnotationInstance>, IndexView> predicate; final ValueProvider provider; final Route.HandlerType targetHandlerType; final ParamValidator validator; final boolean canEndResponse; ParameterInjector(ParameterInjector.Builder builder) { if (builder.predicate != null) { this.predicate = builder.predicate; } else { this.predicate = new TriPredicate<>() { final List<Type> matchTypes = builder.matchTypes; final List<Type> skipTypes = builder.skipTypes; final List<DotName> requiredAnnotationNames = builder.requiredAnnotationNames; @Override public boolean test(Type paramType, Set<AnnotationInstance> paramAnnotations, IndexView index) { // First iterate over all types that should be skipped if (skipTypes != null) { for (Type skipType : skipTypes) { if (skipType.kind() != paramType.kind()) { continue; } if (skipType.kind() == Kind.CLASS && skipType.name().equals(paramType.name())) { return false; } if (skipType.kind() == Kind.PARAMETERIZED_TYPE && skipType.name().equals(paramType.name()) && skipType.asParameterizedType().arguments() .equals(paramType.asParameterizedType().arguments())) { return false; } } } // Match any of the specified types if (matchTypes != null) { boolean matches = false; for (Type matchType : matchTypes) { if (matchType.kind() != paramType.kind()) { continue; } if (matchType.kind() == Kind.CLASS && matchType.name().equals(paramType.name())) { matches = true; break; } if (matchType.kind() == Kind.PARAMETERIZED_TYPE && matchType.name().equals(paramType.name()) && matchType.asParameterizedType().arguments() .equals(paramType.asParameterizedType().arguments())) { matches = true; break; } } if (!matches) { return false; } } // Find required annotations if specified if (!requiredAnnotationNames.isEmpty()) { for (DotName annotationName : requiredAnnotationNames) { if (!Annotations.contains(paramAnnotations, annotationName)) { return false; } } } return true; } }; } this.provider = builder.provider; this.targetHandlerType = builder.targetHandlerType; this.validator = builder.validator; this.canEndResponse = builder.canEndResponse; } boolean matches(Type paramType, Set<AnnotationInstance> paramAnnotations, IndexView index) { return predicate.test(paramType, paramAnnotations, index); } Route.HandlerType getTargetHandlerType() { return targetHandlerType; } void validate(BeanInfo bean, MethodInfo method, AnnotationInstance routeInstance, Type paramType, Set<AnnotationInstance> paramAnnotations) { if (validator != null) { validator.validate(bean, method, routeInstance, paramType, paramAnnotations); } } LocalVar getValue(MethodParameterInfo methodParam, Set<AnnotationInstance> annotations, Var routingContext, BlockCreator bc, BuildProducer<ReflectiveHierarchyBuildItem> reflectiveHierarchy) { return bc.localVar("value", provider.get(methodParam, annotations, routingContext, bc, reflectiveHierarchy)); } static
ParameterInjector
java
apache__camel
components/camel-ehcache/src/test/java/org/apache/camel/component/ehcache/EhcacheCacheConfigurationTest.java
{ "start": 1784, "end": 6850 }
class ____ extends CamelTestSupport { @EndpointInject("ehcache:myProgrammaticCacheConf?configuration=#myProgrammaticConfiguration") private EhcacheEndpoint ehcacheProgrammaticConf; @EndpointInject("ehcache:myFileCacheConf?keyType=java.lang.String&valueType=java.lang.String&configurationUri=classpath:ehcache/ehcache-file-config.xml") private EhcacheEndpoint ehcacheFileConf; @EndpointInject("ehcache:myUserCacheConf") private EhcacheEndpoint ehcacheUserConf; @EndpointInject("ehcache:myCache?cacheManager=#myCacheManager&keyType=java.lang.String&valueType=java.lang.String") private EhcacheEndpoint ehcacheCacheManager; @BindToRegistry("myProgrammaticConfiguration") private CacheConfiguration<String, String> c = CacheConfigurationBuilder.newCacheConfigurationBuilder( String.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(100, EntryUnit.ENTRIES) .offheap(1, MemoryUnit.MB)) .build(); @BindToRegistry("myCacheManager") private CacheManager el = CacheManagerBuilder.newCacheManagerBuilder() .withCache( "myCache", CacheConfigurationBuilder.newCacheConfigurationBuilder( String.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(100, EntryUnit.ENTRIES) .offheap(1, MemoryUnit.MB))) .build(true); // ***************************** // Test // ***************************** @Test void testProgrammaticConfiguration() throws Exception { Cache<String, String> cache = getCache(ehcacheProgrammaticConf, "myProgrammaticCacheConf"); ResourcePools pools = cache.getRuntimeConfiguration().getResourcePools(); SizedResourcePool h = pools.getPoolForResource(ResourceType.Core.HEAP); assertNotNull(h); assertEquals(100, h.getSize()); assertEquals(EntryUnit.ENTRIES, h.getUnit()); SizedResourcePool o = pools.getPoolForResource(ResourceType.Core.OFFHEAP); assertNotNull(o); assertEquals(1, o.getSize()); assertEquals(MemoryUnit.MB, o.getUnit()); } @Test void testFileConfiguration() throws Exception { Cache<String, String> cache = getCache(ehcacheFileConf, "myFileCacheConf"); ResourcePools pools = cache.getRuntimeConfiguration().getResourcePools(); SizedResourcePool h = pools.getPoolForResource(ResourceType.Core.HEAP); assertNotNull(h); assertEquals(150, h.getSize()); assertEquals(EntryUnit.ENTRIES, h.getUnit()); } @Test void testUserConfiguration() throws Exception { fluentTemplate() .withHeader(EhcacheConstants.ACTION, EhcacheConstants.ACTION_PUT) .withHeader(EhcacheConstants.KEY, "user-key") .withBody("user-val") .to("direct:ehcacheUserConf") .send(); Cache<Object, Object> cache = ehcacheUserConf.getManager().getCache("myUserCacheConf", Object.class, Object.class); assertTrue(cache instanceof UserManagedCache); assertEquals("user-val", cache.get("user-key")); } @Test void testCacheManager() throws Exception { assertEquals( context().getRegistry().lookupByNameAndType("myCacheManager", CacheManager.class), ehcacheCacheManager.getManager().getCacheManager()); Cache<String, String> cache = getCache(ehcacheCacheManager, "myCache"); ResourcePools pools = cache.getRuntimeConfiguration().getResourcePools(); SizedResourcePool h = pools.getPoolForResource(ResourceType.Core.HEAP); assertNotNull(h); assertEquals(100, h.getSize()); assertEquals(EntryUnit.ENTRIES, h.getUnit()); SizedResourcePool o = pools.getPoolForResource(ResourceType.Core.OFFHEAP); assertNotNull(o); assertEquals(1, o.getSize()); assertEquals(MemoryUnit.MB, o.getUnit()); } protected Cache<String, String> getCache(EhcacheEndpoint endpoint, String cacheName) throws Exception { return endpoint.getManager().getCache(cacheName, String.class, String.class); } // **************************** // Route // **************************** @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:ehcacheProgrammaticConf") .to(ehcacheProgrammaticConf); from("direct:ehcacheFileConf") .to(ehcacheFileConf); from("direct:ehcacheUserConf") .to(ehcacheUserConf); from("direct:ehcacheCacheManager") .to(ehcacheCacheManager); } }; } }
EhcacheCacheConfigurationTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/runtime/tasks/TestProcessingTimeService.java
{ "start": 9169, "end": 10204 }
class ____ extends Clock { private final AtomicLong currentTime; public ManualMSClock(long startTime) { this.currentTime = new AtomicLong(startTime); } @Override public long absoluteTimeMillis() { return currentTime.get(); } @Override public long relativeTimeMillis() { return currentTime.get(); } @Override public long relativeTimeNanos() { return currentTime.get() * 1_000_000; } /** * Advances the time by the given duration. Time can also move backwards by supplying a * negative value. This method performs no overflow check. */ public void advanceTime(Duration duration) { currentTime.addAndGet(duration.toMillis()); } /** Sets the time to the given value. */ public void setCurrentTime(long time, TimeUnit timeUnit) { currentTime.set(timeUnit.toMillis(time)); } } }
ManualMSClock
java
alibaba__druid
core/src/test/java/com/alibaba/druid/mysql/MysqlVarantRefTest.java
{ "start": 606, "end": 6227 }
class ____ { @Test public void test() { String sql = "set session tx_variables = 1, session asdfsa = 2 "; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); SQLSetStatement result = (SQLSetStatement) stmtList.get(0); SQLVariantRefExpr resultExpr = (SQLVariantRefExpr) result.getItems().get(0).getTarget(); SQLVariantRefExpr resultExpr2 = (SQLVariantRefExpr) result.getItems().get(1).getTarget(); Assert.assertTrue(resultExpr.isSession()); Assert.assertTrue(resultExpr2.isSession()); } @Test public void test22() { String sql = "set session tx_variables = 1, session asdfsa = 2 "; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); SQLSetStatement result = (SQLSetStatement) stmtList.get(0); String text = SQLUtils.toSQLString(stmtList, DbType.mysql); Assert.assertEquals("SET @@session.tx_variables = 1, @@session.asdfsa = 2", text); } @Test public void test11() { String sql = "set session TRANSACTION ISOLATION LEVEL SERIALIZABLE"; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); MySqlSetTransactionStatement x = (MySqlSetTransactionStatement) stmtList.get(0); Assert.assertTrue(x.getSession()); } @Test public void test12() { String sql = "set TRANSACTION ISOLATION LEVEL SERIALIZABLE"; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); MySqlSetTransactionStatement x = (MySqlSetTransactionStatement) stmtList.get(0); Assert.assertTrue(x.getSession() == null); } @Test public void test2() { String sql = "set session tx_variables = 1, asdfsa = 2 "; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); SQLSetStatement result = (SQLSetStatement) stmtList.get(0); SQLVariantRefExpr resultExpr = (SQLVariantRefExpr) result.getItems().get(0).getTarget(); SQLVariantRefExpr resultExpr2 = (SQLVariantRefExpr) result.getItems().get(1).getTarget(); Assert.assertTrue(resultExpr.isSession()); Assert.assertTrue(!resultExpr2.isSession()); } @Test public void test3() { String sql = "set tx_variables = 1, asdfsa = 2 "; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); SQLSetStatement result = (SQLSetStatement) stmtList.get(0); SQLVariantRefExpr resultExpr = (SQLVariantRefExpr) result.getItems().get(0).getTarget(); SQLVariantRefExpr resultExpr2 = (SQLVariantRefExpr) result.getItems().get(1).getTarget(); Assert.assertTrue(!resultExpr.isSession()); Assert.assertTrue(!resultExpr2.isSession()); } @Test public void test4() { String sql = "set tx_variables = 1,session asdfsa = 2 "; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); SQLSetStatement result = (SQLSetStatement) stmtList.get(0); SQLVariantRefExpr resultExpr = (SQLVariantRefExpr) result.getItems().get(0).getTarget(); SQLVariantRefExpr resultExpr2 = (SQLVariantRefExpr) result.getItems().get(1).getTarget(); Assert.assertTrue(!resultExpr.isSession()); Assert.assertTrue(resultExpr2.isSession()); } @Test public void test5() { String sql = "set tx_variables = 1,session asdfsa = 2,session dfd = 3 "; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); SQLSetStatement result = (SQLSetStatement) stmtList.get(0); SQLVariantRefExpr resultExpr = (SQLVariantRefExpr) result.getItems().get(0).getTarget(); SQLVariantRefExpr resultExpr2 = (SQLVariantRefExpr) result.getItems().get(1).getTarget(); SQLVariantRefExpr resultExpr3 = (SQLVariantRefExpr) result.getItems().get(2).getTarget(); Assert.assertTrue(!resultExpr.isSession()); Assert.assertTrue(resultExpr2.isSession()); Assert.assertTrue(resultExpr3.isSession()); } @Test public void test6() { String sql = "set tx_variables = 1,session asdfsa = 2,session dfd = 3, sdfsdf =3,session adfa =9 "; SQLStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> stmtList = parser.parseStatementList(); SQLSetStatement result = (SQLSetStatement) stmtList.get(0); SQLVariantRefExpr resultExpr = (SQLVariantRefExpr) result.getItems().get(0).getTarget(); SQLVariantRefExpr resultExpr2 = (SQLVariantRefExpr) result.getItems().get(1).getTarget(); SQLVariantRefExpr resultExpr3 = (SQLVariantRefExpr) result.getItems().get(2).getTarget(); SQLVariantRefExpr resultExpr4 = (SQLVariantRefExpr) result.getItems().get(3).getTarget(); SQLVariantRefExpr resultExpr5 = (SQLVariantRefExpr) result.getItems().get(4).getTarget(); Assert.assertTrue(!resultExpr.isSession()); Assert.assertTrue(resultExpr2.isSession()); Assert.assertTrue(resultExpr3.isSession()); Assert.assertTrue(!resultExpr4.isSession()); Assert.assertTrue(resultExpr5.isSession()); } }
MysqlVarantRefTest
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/authorization/OAuth2RefreshTokenGrantTests.java
{ "start": 24122, "end": 25040 }
class ____ extends AuthorizationServerConfiguration { // @formatter:off @Bean SecurityFilterChain authorizationServerSecurityFilterChain( HttpSecurity http, RegisteredClientRepository registeredClientRepository) throws Exception { http .oauth2AuthorizationServer((authorizationServer) -> authorizationServer .clientAuthentication((clientAuthentication) -> clientAuthentication .authenticationConverter( new PublicClientRefreshTokenAuthenticationConverter()) .authenticationProvider( new PublicClientRefreshTokenAuthenticationProvider(registeredClientRepository))) ) .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated() ); return http.build(); } // @formatter:on } @Transient private static final
AuthorizationServerConfigurationWithPublicClientAuthentication
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/HttpServerFunctionalTest.java
{ "start": 1471, "end": 1603 }
class ____ functional tests of the {@link HttpServer2}. * The methods are static for other classes to import statically. */ public
for
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/JdbcEndpointBuilderFactory.java
{ "start": 27758, "end": 28065 }
class ____ extends AbstractEndpointBuilder implements JdbcEndpointBuilder, AdvancedJdbcEndpointBuilder { public JdbcEndpointBuilderImpl(String path) { super(componentName, path); } } return new JdbcEndpointBuilderImpl(path); } }
JdbcEndpointBuilderImpl
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/antora/AggregateContentContribution.java
{ "start": 783, "end": 974 }
class ____ extends ConsumableContentContribution { protected AggregateContentContribution(Project project, String name) { super(project, "aggregate", name); } }
AggregateContentContribution
java
apache__camel
components/camel-aws/camel-aws2-ddb/src/main/java/org/apache/camel/component/aws2/ddbstream/Ddb2StreamConfiguration.java
{ "start": 1197, "end": 9555 }
class ____ implements Cloneable { @UriPath(label = "consumer", description = "Name of the dynamodb table") @Metadata(required = true) private String tableName; @UriParam(label = "security", secret = true, description = "Amazon AWS Access Key") private String accessKey; @UriParam(label = "security", secret = true, description = "Amazon AWS Secret Key") private String secretKey; @UriParam(label = "security", secret = true, description = "Amazon AWS Session Token used when the user needs to assume a IAM role") private String sessionToken; @UriParam(enums = "ap-south-2,ap-south-1,eu-south-1,eu-south-2,us-gov-east-1,me-central-1,il-central-1,ca-central-1,eu-central-1,us-iso-west-1,eu-central-2,eu-isoe-west-1,us-west-1,us-west-2,af-south-1,eu-north-1,eu-west-3,eu-west-2,eu-west-1,ap-northeast-3,ap-northeast-2,ap-northeast-1,me-south-1,sa-east-1,ap-east-1,cn-north-1,ca-west-1,us-gov-west-1,ap-southeast-1,ap-southeast-2,us-iso-east-1,ap-southeast-3,ap-southeast-4,us-east-1,us-east-2,cn-northwest-1,us-isob-east-1,aws-global,aws-cn-global,aws-us-gov-global,aws-iso-global,aws-iso-b-global", description = "The region in which DDBStreams client needs to work") private String region; @UriParam(label = "consumer,advanced", description = "Amazon DynamoDB client to use for all requests for this endpoint") @Metadata(autowired = true) private DynamoDbStreamsClient amazonDynamoDbStreamsClient; @UriParam(label = "consumer", description = "Maximum number of records that will be fetched in each poll") private int maxResultsPerRequest = 100; @UriParam(label = "consumer", description = "Defines where in the DynamoDB stream" + " to start getting records. Note that using FROM_START can cause a" + " significant delay before the stream has caught up to real-time.", defaultValue = "FROM_LATEST") private StreamIteratorType streamIteratorType = StreamIteratorType.FROM_LATEST; @UriParam(label = "proxy", enums = "HTTP,HTTPS", defaultValue = "HTTPS", description = "To define a proxy protocol when instantiating the DDBStreams client") private Protocol proxyProtocol = Protocol.HTTPS; @UriParam(label = "proxy", description = "To define a proxy host when instantiating the DDBStreams client") private String proxyHost; @UriParam(label = "proxy", description = "To define a proxy port when instantiating the DDBStreams client") private Integer proxyPort; @UriParam(label = "security", description = "If we want to trust all certificates in case of overriding the endpoint") private boolean trustAllCertificates; @UriParam(defaultValue = "false", description = "Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option") private boolean overrideEndpoint; @UriParam(description = " Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option") private String uriEndpointOverride; @UriParam(label = "security", description = "Set whether the DynamoDB Streams client should expect to load credentials through a default credentials provider or to expect" + " static credentials to be passed in.") private boolean useDefaultCredentialsProvider; @UriParam(label = "security", description = "Set whether the Cloudtrail client should expect to load credentials through a profile credentials provider.") private boolean useProfileCredentialsProvider; @UriParam(label = "security", description = "Set whether the DDB Streams client should expect to use Session Credentials. This is useful in situation in which the user" + " needs to assume a IAM role for doing operations in DDB.") private boolean useSessionCredentials; @UriParam(label = "security", description = "If using a profile credentials provider this parameter will set the profile name.") private String profileCredentialsName; public DynamoDbStreamsClient getAmazonDynamoDbStreamsClient() { return amazonDynamoDbStreamsClient; } public void setAmazonDynamoDbStreamsClient(DynamoDbStreamsClient amazonDynamoDbStreamsClient) { this.amazonDynamoDbStreamsClient = amazonDynamoDbStreamsClient; } public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public int getMaxResultsPerRequest() { return maxResultsPerRequest; } public void setMaxResultsPerRequest(int maxResultsPerRequest) { this.maxResultsPerRequest = maxResultsPerRequest; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public StreamIteratorType getStreamIteratorType() { return streamIteratorType; } public void setStreamIteratorType(StreamIteratorType streamIteratorType) { this.streamIteratorType = streamIteratorType; } public Protocol getProxyProtocol() { return proxyProtocol; } public void setProxyProtocol(Protocol proxyProtocol) { this.proxyProtocol = proxyProtocol; } public String getProxyHost() { return proxyHost; } public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public Integer getProxyPort() { return proxyPort; } public void setProxyPort(Integer proxyPort) { this.proxyPort = proxyPort; } public boolean isTrustAllCertificates() { return trustAllCertificates; } public void setTrustAllCertificates(boolean trustAllCertificates) { this.trustAllCertificates = trustAllCertificates; } public boolean isOverrideEndpoint() { return overrideEndpoint; } public void setOverrideEndpoint(boolean overrideEndpoint) { this.overrideEndpoint = overrideEndpoint; } public String getUriEndpointOverride() { return uriEndpointOverride; } public void setUriEndpointOverride(String uriEndpointOverride) { this.uriEndpointOverride = uriEndpointOverride; } public void setUseDefaultCredentialsProvider(Boolean useDefaultCredentialsProvider) { this.useDefaultCredentialsProvider = useDefaultCredentialsProvider; } public Boolean isUseDefaultCredentialsProvider() { return useDefaultCredentialsProvider; } public boolean isUseProfileCredentialsProvider() { return useProfileCredentialsProvider; } public void setUseProfileCredentialsProvider(boolean useProfileCredentialsProvider) { this.useProfileCredentialsProvider = useProfileCredentialsProvider; } public String getProfileCredentialsName() { return profileCredentialsName; } public void setProfileCredentialsName(String profileCredentialsName) { this.profileCredentialsName = profileCredentialsName; } public String getSessionToken() { return sessionToken; } public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; } public boolean isUseSessionCredentials() { return useSessionCredentials; } public void setUseSessionCredentials(boolean useSessionCredentials) { this.useSessionCredentials = useSessionCredentials; } // ************************************************* // // ************************************************* public Ddb2StreamConfiguration copy() { try { return (Ddb2StreamConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeCamelException(e); } } public
Ddb2StreamConfiguration
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/util/ThrowableAnalyzerTests.java
{ "start": 7569, "end": 7964 }
class ____ extends Exception { private final Throwable cause; public NonStandardException(String message, Throwable cause) { super(message); this.cause = cause; } public Throwable resolveCause() { return this.cause; } } /** * <code>ThrowableCauseExtractor</code> for handling <code>NonStandardException</code> * instances. */ public static final
NonStandardException
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/socket/WebSocketMessageBrokerSecurityConfigurationTests.java
{ "start": 27141, "end": 27687 }
class ____ { String authenticationPrincipal; MyCustomArgument myCustomArgument; String message; @MessageMapping("/authentication") void authentication(@AuthenticationPrincipal String un) { this.authenticationPrincipal = un; } @MessageMapping("/myCustom") void myCustom(MyCustomArgument myCustomArgument) { this.myCustomArgument = myCustomArgument; } @MessageMapping("/hi") void sayHello(@IsUser("harold") boolean isHarold) { this.message = isHarold ? "Hi, Harold!" : "Hi, Stranger!"; } } static
MyController
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/convert/CoerceNaNStringToNumberTest.java
{ "start": 339, "end": 442 }
class ____ { double _v; public void setV(double v) { _v = v; } } static
DoubleBean
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/component/extension/ComponentVerifierExtension.java
{ "start": 5322, "end": 5409 }
interface ____ a detailed error in case when the verification fails. */
represents
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/reactive/ReactiveOAuth2AuthorizedClientManagerConfigurationTests.java
{ "start": 17556, "end": 18031 }
class ____ extends OAuth2ClientBaseConfig { @Bean ReactiveOAuth2AuthorizedClientService authorizedClientService() { ReactiveOAuth2AuthorizedClientService authorizedClientService = mock( ReactiveOAuth2AuthorizedClientService.class); given(authorizedClientService.loadAuthorizedClient(anyString(), anyString())).willReturn(Mono.empty()); return authorizedClientService; } } @Configuration @EnableWebFluxSecurity static
CustomAuthorizedClientServiceConfig
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java
{ "start": 115035, "end": 115307 }
class ____ extends TestBean { @NotNull private String validCountry; public void setValidCountry(String validCountry) { this.validCountry = validCountry; } public String getValidCountry() { return this.validCountry; } } @Controller static
ValidTestBean
java
google__dagger
dagger-producers/main/java/dagger/producers/Producer.java
{ "start": 789, "end": 1655 }
interface ____ represents the production of a type {@code T}. You can also inject * {@code Producer<T>} instead of {@code T}, which will delay the execution of any code that * produces the {@code T} until {@link #get} is called. * * <p>For example, you might inject {@code Producer} to lazily choose between several different * implementations of some type: <pre><code> * {@literal @Produces ListenableFuture<Heater>} getHeater( * HeaterFlag flag, * {@literal @Electric Producer<Heater>} electricHeater, * {@literal @Gas Producer<Heater>} gasHeater) { * return flag.useElectricHeater() ? electricHeater.get() : gasHeater.get(); * } * </code></pre> * * <p>Here is a complete example that demonstrates how calling {@code get()} will cause each * method to be executed: <pre><code> * * {@literal @}ProducerModule * final
that
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/PartitionWriterFactory.java
{ "start": 1125, "end": 2095 }
interface ____<T> extends Serializable { PartitionWriter<T> create( Context<T> context, PartitionTempFileManager manager, PartitionComputer<T> computer, PartitionWriter.PartitionWriterListener writerListener) throws Exception; /** Util for get a {@link PartitionWriterFactory}. */ static <T> PartitionWriterFactory<T> get( boolean dynamicPartition, boolean grouped, LinkedHashMap<String, String> staticPartitions) { if (dynamicPartition) { return grouped ? GroupedPartitionWriter::new : DynamicPartitionWriter::new; } else { return (PartitionWriterFactory<T>) (context, manager, computer, writerListener) -> new SingleDirectoryWriter<>( context, manager, computer, staticPartitions, writerListener); } } }
PartitionWriterFactory
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/NoOpCheckpointStatsTracker.java
{ "start": 1062, "end": 2601 }
enum ____ implements CheckpointStatsTracker { INSTANCE; @Override public void reportRestoredCheckpoint( long checkpointID, CheckpointProperties properties, String externalPath, long stateSize) {} @Override public void reportCompletedCheckpoint(CompletedCheckpointStats completed) {} @Nullable @Override public PendingCheckpointStats getPendingCheckpointStats(long checkpointId) { return null; } @Override public void reportIncompleteStats( long checkpointId, ExecutionAttemptID attemptId, CheckpointMetrics metrics) {} @Override public void reportInitializationStarted( Set<ExecutionAttemptID> toInitialize, long initializationStartTs) {} @Override public void reportInitializationMetrics( ExecutionAttemptID executionAttemptId, SubTaskInitializationMetrics initializationMetrics) {} @Nullable @Override public PendingCheckpointStats reportPendingCheckpoint( long checkpointId, long triggerTimestamp, CheckpointProperties props, Map<JobVertexID, Integer> vertexToDop) { return null; } @Override public void reportFailedCheckpoint(FailedCheckpointStats failed) {} @Override public void reportFailedCheckpointsWithoutInProgress() {} @Override public CheckpointStatsSnapshot createSnapshot() { return CheckpointStatsSnapshot.empty(); } }
NoOpCheckpointStatsTracker
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableDoFinally.java
{ "start": 4494, "end": 7259 }
class ____<T> extends BasicIntQueueSubscription<T> implements ConditionalSubscriber<T> { private static final long serialVersionUID = 4109457741734051389L; final ConditionalSubscriber<? super T> downstream; final Action onFinally; Subscription upstream; QueueSubscription<T> qs; boolean syncFused; DoFinallyConditionalSubscriber(ConditionalSubscriber<? super T> actual, Action onFinally) { this.downstream = actual; this.onFinally = onFinally; } @SuppressWarnings("unchecked") @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { this.upstream = s; if (s instanceof QueueSubscription) { this.qs = (QueueSubscription<T>)s; } downstream.onSubscribe(this); } } @Override public void onNext(T t) { downstream.onNext(t); } @Override public boolean tryOnNext(T t) { return downstream.tryOnNext(t); } @Override public void onError(Throwable t) { downstream.onError(t); runFinally(); } @Override public void onComplete() { downstream.onComplete(); runFinally(); } @Override public void cancel() { upstream.cancel(); runFinally(); } @Override public void request(long n) { upstream.request(n); } @Override public int requestFusion(int mode) { QueueSubscription<T> qs = this.qs; if (qs != null && (mode & BOUNDARY) == 0) { int m = qs.requestFusion(mode); if (m != NONE) { syncFused = m == SYNC; } return m; } return NONE; } @Override public void clear() { qs.clear(); } @Override public boolean isEmpty() { return qs.isEmpty(); } @Nullable @Override public T poll() throws Throwable { T v = qs.poll(); if (v == null && syncFused) { runFinally(); } return v; } void runFinally() { if (compareAndSet(0, 1)) { try { onFinally.run(); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); RxJavaPlugins.onError(ex); } } } } }
DoFinallyConditionalSubscriber