language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/reflect/MethodUtils.java
{ "start": 23887, "end": 27628 }
class ____ annotation are {@code null}. * @since 3.6 */ public static Method[] getMethodsWithAnnotation(final Class<?> cls, final Class<? extends Annotation> annotationCls, final boolean searchSupers, final boolean ignoreAccess) { return getMethodsListWithAnnotation(cls, annotationCls, searchSupers, ignoreAccess).toArray(ArrayUtils.EMPTY_METHOD_ARRAY); } /** * Gets the hierarchy of overridden methods down to {@code result} respecting generics. * * @param method lowest to consider. * @param interfacesBehavior whether to search interfaces, {@code null} {@code implies} false. * @return a {@code Set<Method>} in ascending order from subclass to superclass. * @throws NullPointerException if the specified method is {@code null}. * @throws SecurityException if an underlying accessible object's method denies the request. * @see SecurityManager#checkPermission * @since 3.2 */ public static Set<Method> getOverrideHierarchy(final Method method, final Interfaces interfacesBehavior) { Objects.requireNonNull(method, "method"); final Set<Method> result = new LinkedHashSet<>(); result.add(method); final Class<?>[] parameterTypes = method.getParameterTypes(); final Class<?> declaringClass = method.getDeclaringClass(); final Iterator<Class<?>> hierarchy = ClassUtils.hierarchy(declaringClass, interfacesBehavior).iterator(); //skip the declaring class :P hierarchy.next(); hierarchyTraversal: while (hierarchy.hasNext()) { final Class<?> c = hierarchy.next(); final Method m = getMatchingAccessibleMethod(c, method.getName(), parameterTypes); if (m == null) { continue; } if (Arrays.equals(m.getParameterTypes(), parameterTypes)) { // matches without generics result.add(m); continue; } // necessary to get arguments every time in the case that we are including interfaces final Map<TypeVariable<?>, Type> typeArguments = TypeUtils.getTypeArguments(declaringClass, m.getDeclaringClass()); for (int i = 0; i < parameterTypes.length; i++) { final Type childType = TypeUtils.unrollVariables(typeArguments, method.getGenericParameterTypes()[i]); final Type parentType = TypeUtils.unrollVariables(typeArguments, m.getGenericParameterTypes()[i]); if (!TypeUtils.equals(childType, parentType)) { continue hierarchyTraversal; } } result.add(m); } return result; } /** * Invokes a method whose parameter types match exactly the object type. * * <p> * This uses reflection to invoke the method obtained from a call to {@link #getAccessibleMethod(Class, String, Class[])}. * </p> * * @param object invoke method on this object. * @param methodName get method with this name. * @return The value returned by the invoked method. * @throws NoSuchMethodException Thrown if there is no such accessible method. * @throws IllegalAccessException Thrown if this found {@code Method} is enforcing Java language access control and the underlying method is * inaccessible. * @throws IllegalArgumentException Thrown if: * <ul> * <li>the found {@code Method} is an instance method and the specified {@code object} argument is not an instance of * the
or
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/test/resources/LazyFoo.java
{ "start": 981, "end": 1116 }
class ____ { @BindToRegistry public String myFoo() { throw new IllegalArgumentException("Cannot load foo driver"); } }
LazyFoo
java
quarkusio__quarkus
integration-tests/funqy-amazon-lambda/src/test/java/io/quarkus/funqy/test/UseNoArgFunExtension.java
{ "start": 90, "end": 225 }
class ____ implements Extension { static { System.setProperty("quarkus.funqy.export", "noArgFun"); } }
UseNoArgFunExtension
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/symbol/FunctionTable.java
{ "start": 1089, "end": 5489 }
class ____ { protected final String functionName; protected final String mangledName; protected final Class<?> returnType; protected final List<Class<?>> typeParameters; protected final boolean isInternal; protected final boolean isStatic; protected final MethodType methodType; protected final Method asmMethod; public LocalFunction( String functionName, Class<?> returnType, List<Class<?>> typeParameters, boolean isInternal, boolean isStatic ) { this(functionName, "", returnType, typeParameters, isInternal, isStatic); } private LocalFunction( String functionName, String mangle, Class<?> returnType, List<Class<?>> typeParameters, boolean isInternal, boolean isStatic ) { this.functionName = Objects.requireNonNull(functionName); this.mangledName = Objects.requireNonNull(mangle) + this.functionName; this.returnType = Objects.requireNonNull(returnType); this.typeParameters = List.copyOf(typeParameters); this.isInternal = isInternal; this.isStatic = isStatic; Class<?> javaReturnType = PainlessLookupUtility.typeToJavaType(returnType); Class<?>[] javaTypeParameters = typeParameters.stream().map(PainlessLookupUtility::typeToJavaType).toArray(Class<?>[]::new); this.methodType = MethodType.methodType(javaReturnType, javaTypeParameters); this.asmMethod = new org.objectweb.asm.commons.Method( mangledName, MethodType.methodType(javaReturnType, javaTypeParameters).toMethodDescriptorString() ); } public String getMangledName() { return mangledName; } public Class<?> getReturnType() { return returnType; } public List<Class<?>> getTypeParameters() { return typeParameters; } public boolean isInternal() { return isInternal; } public boolean isStatic() { return isStatic; } public MethodType getMethodType() { return methodType; } public Method getAsmMethod() { return asmMethod; } } /** * Generates a {@code LocalFunction} key. * @param functionName the name of the {@code LocalFunction} * @param functionArity the number of parameters for the {@code LocalFunction} * @return a {@code LocalFunction} key used for {@code LocalFunction} look up within the {@code FunctionTable} */ public static String buildLocalFunctionKey(String functionName, int functionArity) { return functionName + "/" + functionArity; } protected Map<String, LocalFunction> localFunctions = new HashMap<>(); public LocalFunction addFunction( String functionName, Class<?> returnType, List<Class<?>> typeParameters, boolean isInternal, boolean isStatic ) { String functionKey = buildLocalFunctionKey(functionName, typeParameters.size()); LocalFunction function = new LocalFunction(functionName, returnType, typeParameters, isInternal, isStatic); localFunctions.put(functionKey, function); return function; } public LocalFunction addMangledFunction( String functionName, Class<?> returnType, List<Class<?>> typeParameters, boolean isInternal, boolean isStatic ) { String functionKey = buildLocalFunctionKey(functionName, typeParameters.size()); LocalFunction function = new LocalFunction( functionName, MANGLED_FUNCTION_NAME_PREFIX, returnType, typeParameters, isInternal, isStatic ); localFunctions.put(functionKey, function); return function; } public LocalFunction getFunction(String functionName, int functionArity) { String functionKey = buildLocalFunctionKey(functionName, functionArity); return localFunctions.get(functionKey); } public LocalFunction getFunction(String functionKey) { return localFunctions.get(functionKey); } }
LocalFunction
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ShouldNotContainAnyWhitespaces.java
{ "start": 807, "end": 1429 }
class ____ extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldNotContainAnyWhitespaces}</code>. * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldNotContainAnyWhitespaces(CharSequence actual) { return new ShouldNotContainAnyWhitespaces(actual); } private ShouldNotContainAnyWhitespaces(Object actual) { super("%n" + "Expecting string not to contain any whitespaces but found some, string was:%n" + " %s", actual); } }
ShouldNotContainAnyWhitespaces
java
apache__camel
core/camel-main/src/main/java/org/apache/camel/main/ThreadPoolConfigurationProperties.java
{ "start": 1162, "end": 4551 }
class ____ implements BootstrapCloseable { private MainConfigurationProperties parent; // default values private Integer poolSize; private Integer maxPoolSize; private Long keepAliveTime; private TimeUnit timeUnit; private Integer maxQueueSize; private Boolean allowCoreThreadTimeOut; private ThreadPoolRejectedPolicy rejectedPolicy; // profile specific values private Map<String, ThreadPoolProfileConfigurationProperties> config = new HashMap<>(); public ThreadPoolConfigurationProperties(MainConfigurationProperties parent) { this.parent = parent; } public MainConfigurationProperties end() { return parent; } @Override public void close() { parent = null; config.clear(); config = null; } public Integer getPoolSize() { return poolSize; } /** * Sets the default core pool size (threads to keep minimum in pool) */ public void setPoolSize(Integer poolSize) { this.poolSize = poolSize; } public Integer getMaxPoolSize() { return maxPoolSize; } /** * Sets the default maximum pool size */ public void setMaxPoolSize(Integer maxPoolSize) { this.maxPoolSize = maxPoolSize; } public Long getKeepAliveTime() { return keepAliveTime; } /** * Sets the default keep alive time for inactive threads */ public void setKeepAliveTime(Long keepAliveTime) { this.keepAliveTime = keepAliveTime; } public TimeUnit getTimeUnit() { return timeUnit; } /** * Sets the default time unit used for keep alive time */ public void setTimeUnit(TimeUnit timeUnit) { this.timeUnit = timeUnit; } public Integer getMaxQueueSize() { return maxQueueSize; } /** * Sets the default maximum number of tasks in the work queue. * * Use -1 or an unbounded queue */ public void setMaxQueueSize(Integer maxQueueSize) { this.maxQueueSize = maxQueueSize; } public Boolean getAllowCoreThreadTimeOut() { return allowCoreThreadTimeOut; } /** * Sets default whether to allow core threads to timeout */ public void setAllowCoreThreadTimeOut(Boolean allowCoreThreadTimeOut) { this.allowCoreThreadTimeOut = allowCoreThreadTimeOut; } public ThreadPoolRejectedPolicy getRejectedPolicy() { return rejectedPolicy; } /** * Sets the default handler for tasks which cannot be executed by the thread pool. */ public void setRejectedPolicy(ThreadPoolRejectedPolicy rejectedPolicy) { this.rejectedPolicy = rejectedPolicy; } public Map<String, ThreadPoolProfileConfigurationProperties> getConfig() { return config; } /** * Adds a configuration for a specific thread pool profile (inherits default values) */ public void setConfig(Map<String, ThreadPoolProfileConfigurationProperties> config) { this.config = config; } /** * Adds a configuration for a specific thread pool profile (inherits default values) */ public ThreadPoolConfigurationProperties addConfig(String id, ThreadPoolProfileConfigurationProperties config) { this.config.put(id, config); return this; } }
ThreadPoolConfigurationProperties
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/job/metrics/TaskManagerMetricsHeadersTest.java
{ "start": 1109, "end": 1684 }
class ____ { private final TaskManagerMetricsHeaders taskManagerMetricsHeaders = TaskManagerMetricsHeaders.getInstance(); @Test void testUrl() { assertThat(taskManagerMetricsHeaders.getTargetRestEndpointURL()) .isEqualTo("/taskmanagers/:" + TaskManagerIdPathParameter.KEY + "/metrics"); } @Test void testMessageParameters() { assertThat(taskManagerMetricsHeaders.getUnresolvedMessageParameters()) .isInstanceOf(TaskManagerMetricsMessageParameters.class); } }
TaskManagerMetricsHeadersTest
java
quarkusio__quarkus
extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddSidecarDecorator.java
{ "start": 585, "end": 687 }
class ____ * https://github.com/dekorateio/dekorate/pull/1234 is merged and Dekorate is bumped. */
after
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/metrics/CompensatedSumTests.java
{ "start": 600, "end": 3240 }
class ____ extends ESTestCase { /** * When adding a series of numbers the order of the numbers should not impact the results. * * <p>This test shows that a naive summation comes up with a different result than Kahan * Summation when you start with either a smaller or larger number in some cases and * helps prove our Kahan Summation is working. */ public void testAdd() { final CompensatedSum smallSum = new CompensatedSum(0.001, 0.0); final CompensatedSum largeSum = new CompensatedSum(1000, 0.0); CompensatedSum compensatedResult1 = new CompensatedSum(0.001, 0.0); CompensatedSum compensatedResult2 = new CompensatedSum(1000, 0.0); double naiveResult1 = smallSum.value(); double naiveResult2 = largeSum.value(); for (int i = 0; i < 10; i++) { compensatedResult1.add(smallSum.value()); compensatedResult2.add(smallSum.value()); naiveResult1 += smallSum.value(); naiveResult2 += smallSum.value(); } compensatedResult1.add(largeSum.value()); compensatedResult2.add(smallSum.value()); naiveResult1 += largeSum.value(); naiveResult2 += smallSum.value(); // Kahan summation gave the same result no matter what order we added Assert.assertEquals(1000.011, compensatedResult1.value(), 0.0); Assert.assertEquals(1000.011, compensatedResult2.value(), 0.0); // naive addition gave a small floating point error Assert.assertEquals(1000.011, naiveResult1, 0.0); Assert.assertEquals(1000.0109999999997, naiveResult2, 0.0); Assert.assertEquals(compensatedResult1.value(), compensatedResult2.value(), 0.0); Assert.assertEquals(naiveResult1, naiveResult2, 0.0001); Assert.assertNotEquals(naiveResult1, naiveResult2, 0.0); } public void testDelta() { CompensatedSum compensatedResult1 = new CompensatedSum(0.001, 0.0); for (int i = 0; i < 10; i++) { compensatedResult1.add(0.001); } Assert.assertEquals(0.011, compensatedResult1.value(), 0.0); Assert.assertEquals(Double.parseDouble("8.673617379884035E-19"), compensatedResult1.delta(), 0.0); } public void testInfiniteAndNaN() { CompensatedSum compensatedResult1 = new CompensatedSum(0, 0); double[] doubles = { Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NaN }; for (double d : doubles) { compensatedResult1.add(d); } Assert.assertTrue(Double.isNaN(compensatedResult1.value())); } }
CompensatedSumTests
java
spring-projects__spring-security
docs/src/test/java/org/springframework/security/docs/servlet/authorization/customizingauthorizationmanagers/CustomHttpRequestsAuthorizationManagerFactoryTests.java
{ "start": 4695, "end": 5189 }
class ____ { @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((authorize) -> authorize .anyRequest().authenticated() ); // @formatter:on return http.build(); } @Bean CustomHttpRequestsAuthorizationManagerFactory customHttpRequestsAuthorizationManagerFactory() { return new CustomHttpRequestsAuthorizationManagerFactory(); } } @RestController static
SecurityConfiguration
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurerSessionAuthenticationStrategyTests.java
{ "start": 2958, "end": 3582 }
class ____ { static SessionAuthenticationStrategy customSessionAuthenticationStrategy = mock( SessionAuthenticationStrategy.class); @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .formLogin(withDefaults()) .sessionManagement((management) -> management .sessionAuthenticationStrategy(customSessionAuthenticationStrategy)); // @formatter:on return http.build(); } @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager(PasswordEncodedUser.user()); } } }
CustomSessionAuthenticationStrategyConfig
java
netty__netty
example/src/main/java/io/netty/example/uptime/UptimeClient.java
{ "start": 1320, "end": 2991 }
class ____ { static final String HOST = System.getProperty("host", "127.0.0.1"); static final int PORT = Integer.parseInt(System.getProperty("port", "8080")); // Sleep 5 seconds before a reconnection attempt. static final int RECONNECT_DELAY = Integer.parseInt(System.getProperty("reconnectDelay", "5")); // Reconnect when the server sends nothing for 10 seconds. private static final int READ_TIMEOUT = Integer.parseInt(System.getProperty("readTimeout", "10")); private static final UptimeClientHandler handler = new UptimeClientHandler(); private static final Bootstrap bs = new Bootstrap(); public static void main(String[] args) throws Exception { EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); bs.group(group) .channel(NioSocketChannel.class) .remoteAddress(HOST, PORT) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new IdleStateHandler(READ_TIMEOUT, 0, 0), handler); } }); bs.connect(); } static void connect() { bs.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.cause() != null) { handler.startTime = -1; handler.println("Failed to connect: " + future.cause()); } } }); } }
UptimeClient
java
micronaut-projects__micronaut-core
http-server-netty/src/main/java/io/micronaut/http/server/netty/handler/accesslog/element/ConnectionMetadataImpl.java
{ "start": 2107, "end": 3707 }
class ____ { static String getPath(SocketAddress address) { return ((DomainSocketAddress) address).path(); } } /** * This one is separate from {@link GenericChannelMetadata} because it has special handling for * compatibility. * * @param ch The channel */ @Internal record SocketChannelMetadata(SocketChannel ch) implements ConnectionMetadata { @Override public @NonNull Optional<SocketAddress> localAddress() { return Optional.of(ch.localAddress()); } @Override public @NonNull Optional<SocketAddress> remoteAddress() { return Optional.of(ch.remoteAddress()); } } @Internal record GenericChannelMetadata(Channel ch) implements ConnectionMetadata { @Override public @NonNull Optional<SocketAddress> localAddress() { return Optional.of(ch.localAddress()); } @Override public @NonNull Optional<SocketAddress> remoteAddress() { return Optional.of(ch.remoteAddress()); } } @Internal record QuicChannelMetadata(Channel ch) implements ConnectionMetadata { @Override public @NonNull Optional<SocketAddress> localAddress() { return Optional.ofNullable(((QuicChannel) ch).localSocketAddress()); } @Override public @NonNull Optional<SocketAddress> remoteAddress() { return Optional.ofNullable(((QuicChannel) ch).remoteSocketAddress()); } } @Internal public static final
DomainSocketUtil
java
alibaba__nacos
plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/utils/RemoteServerUtil.java
{ "start": 1356, "end": 4100 }
class ____ { private static List<String> serverAddresses = new LinkedList<>(); private static AtomicInteger index = new AtomicInteger(); private static String remoteServerContextPath = "/nacos"; static { readRemoteServerAddress(); registerWatcher(); initRemoteServerContextPath(); } private static void initRemoteServerContextPath() { remoteServerContextPath = EnvUtil.getProperty("nacos.console.remote.server.context-path", "/nacos"); } private static void registerWatcher() { try { WatchFileCenter.registerWatcher(EnvUtil.getClusterConfFilePath(), new FileWatcher() { @Override public void onChange(FileChangeEvent event) { readRemoteServerAddress(); } @Override public boolean interest(String context) { return true; } }); } catch (Exception ignored) { } } /** * Read nacos server address from cluster.conf. */ public static void readRemoteServerAddress() { try { serverAddresses = EnvUtil.readClusterConf(); } catch (IOException ignored) { } } public static List<String> getServerAddresses() { return new LinkedList<>(serverAddresses); } public static String getOneNacosServerAddress() { int actual = index.getAndUpdate(operand -> (operand + 1) % serverAddresses.size()); return serverAddresses.get(actual); } public static String getRemoteServerContextPath() { return remoteServerContextPath; } /** * Single check http result, if not success, wrapper result as Nacos exception. * * @param result http execute result * @throws NacosException wrapper result as NacosException */ public static void singleCheckResult(HttpRestResult<String> result) throws NacosException { if (result.ok()) { return; } throw new NacosException(result.getCode(), result.getMessage()); } /** * According input {@link AuthConfigs} to build remote server identity header. * * @param authConfigs authConfigs * @return remote server identity header */ public static Header buildServerRemoteHeader(AuthConfigs authConfigs) { Header header = Header.newInstance(); if (StringUtils.isNotBlank(authConfigs.getServerIdentityKey())) { header.addParam(authConfigs.getServerIdentityKey(), authConfigs.getServerIdentityValue()); } return header; } }
RemoteServerUtil
java
apache__camel
components/camel-jira/src/test/java/org/apache/camel/component/jira/Utils.java
{ "start": 2233, "end": 10631 }
class ____ { public static User userAssignee; static { try { userAssignee = new User( null, "user-test", "User Test", "user@test", true, null, buildUserAvatarUris("user-test", 10082L), null); } catch (Exception e) { LoggerFactory.getLogger(Utils.class).debug("Failed to build test user: {}", e.getMessage(), e); } } private static IssueType issueType = new IssueType(null, 1L, "Bug", false, "Bug", null); private Utils() { } public static Issue createIssue(long id) { return createIssueWithComments(id, 0); } public static Issue createIssue( long id, String summary, String key, IssueType issueType, String description, BasicPriority priority, User assignee, Collection<BasicComponent> components, BasicWatchers watchers) { URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + id); return new Issue( summary, selfUri, KEY + "-" + id, id, null, issueType, null, description, priority, null, null, null, assignee, null, null, null, null, null, components, null, null, null, null, null, null, null, watchers, null, null, null, null, null, null); } public static Issue transitionIssueDone(Issue issue, Status status, Resolution resolution) { return new Issue( issue.getSummary(), issue.getSelf(), issue.getKey(), issue.getId(), null, issue.getIssueType(), status, issue.getDescription(), issue.getPriority(), resolution, null, null, issue.getAssignee(), null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); } public static Issue setPriority(Issue issue, Priority p) { return new Issue( issue.getSummary(), issue.getSelf(), issue.getKey(), issue.getId(), null, issue.getIssueType(), issue.getStatus(), issue.getDescription(), p, issue.getResolution(), null, null, issue.getAssignee(), null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); } public static Issue transitionIssueDone(Issue issue) { URI doneStatusUri = URI.create(TEST_JIRA_URL + "/rest/api/2/status/1"); URI doneResolutionUri = URI.create(TEST_JIRA_URL + "/rest/api/2/resolution/1"); StatusCategory sc = new StatusCategory(doneResolutionUri, "statusCategory", 1L, "SC-1", "GREEN"); Status status = new Status(doneStatusUri, 1L, "Done", "Done", null, sc); Resolution resolution = new Resolution(doneResolutionUri, 5L, "Resolution", "Resolution"); return transitionIssueDone(issue, status, resolution); } public static Issue createIssueWithCreationDate(long id, DateTime dateTime) { URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + id); return new Issue( "jira summary test " + id, selfUri, KEY + "-" + id, id, null, issueType, null, "Description " + id, null, null, null, null, userAssignee, dateTime, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); } public static Issue createIssueWithAttachment( long id, String summary, String key, IssueType issueType, String description, BasicPriority priority, User assignee, Collection<Attachment> attachments) { URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + id); return new Issue( summary, selfUri, KEY + "-" + id, id, null, issueType, null, description, priority, null, attachments, null, assignee, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); } public static Issue createIssueWithComments(long id, int numComments) { Collection<Comment> comments = new ArrayList<>(); if (numComments > 0) { for (int idx = 1; idx < numComments + 1; idx++) { Comment c = newComment(id, idx, "A test comment " + idx + " for " + KEY + "-" + id); comments.add(c); } } return createIssueWithComments(id, comments); } public static Issue createIssueWithComments(long id, Collection<Comment> comments) { URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + id); return new Issue( "jira summary test " + id, selfUri, KEY + "-" + id, id, null, issueType, null, "Description " + id, null, null, null, null, userAssignee, DateTime.now(), null, null, null, null, null, null, null, comments, null, null, null, null, null, null, null, null, null, null, null); } public static Issue createIssueWithLinks(long id, Collection<IssueLink> issueLinks) { URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + id); return new Issue( "jira summary test " + id, selfUri, KEY + "-" + id, id, null, issueType, null, "Description " + id, null, null, null, null, userAssignee, null, null, null, null, null, null, null, null, null, null, issueLinks, null, null, null, null, null, null, null, null, null); } public static Issue createIssueWithWorkLogs(long id, Collection<Worklog> worklogs) { URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + id); return new Issue( "jira summary test " + id, selfUri, KEY + "-" + id, id, null, issueType, null, "Description " + id, null, null, null, null, userAssignee, null, null, null, null, null, null, null, null, null, null, null, null, worklogs, null, null, null, null, null, null, null); } public static Comment newComment(long issueId, int newCommentId, String comment) { DateTime now = DateTime.now(); long id = Long.parseLong(issueId + "0" + newCommentId); URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + issueId + "/comment"); return new Comment(selfUri, comment, null, null, now, null, null, id); } public static IssueLink newIssueLink(long issueId, int newLinkId, String comment) { long id = Long.parseLong(issueId + "0" + newLinkId); URI issueUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + id); IssueLinkType relatesTo = new IssueLinkType("Relates", "relates to", IssueLinkType.Direction.OUTBOUND); return new IssueLink(KEY, issueUri, relatesTo); } public static Worklog newWorkLog(long issueId, Integer minutesSpent, String comment) { DateTime now = DateTime.now(); URI issueUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + issueId); URI selfUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/" + issueId + "/comment"); return new Worklog(selfUri, issueUri, null, null, comment, now, null, null, minutesSpent, null); } public static BasicComponent createBasicComponent(Long id, String name) { URI compUri = URI.create(TEST_JIRA_URL + "/rest/api/latest/issue/11/component/1"); return new BasicComponent(compUri, id, name, name + " description"); } private static Map<String, URI> buildUserAvatarUris(String user, Long avatarId) throws Exception { final ImmutableMap.Builder<String, URI> builder = ImmutableMap.builder(); builder.put(S48_48, buildUserAvatarUri(user, avatarId)); return builder.build(); } private static URI buildUserAvatarUri(String userName, Long avatarId) throws Exception { // secure/useravatar?size=small&ownerId=admin&avatarId=10054 final StringBuilder sb = new StringBuilder("secure/useravatar?"); // Optional user name if (StringUtils.isNotBlank(userName)) { sb.append("ownerId=").append(userName).append("&"); } // avatar Id sb.append("avatarId=").append(avatarId); String relativeAvatarUrl = sb.toString(); URI avatarUrl = URI.create(TEST_JIRA_URL + "/" + relativeAvatarUrl); return avatarUrl; } }
Utils
java
playframework__playframework
testkit/play-test/src/main/java/play/test/WithServer.java
{ "start": 640, "end": 1665 }
class ____ { protected Application app; protected int port = -1; // avoid 0, it could mean random port assigned by the OS. protected TestServer testServer; /** * Override this method to setup the application to use. * * @return The application used by the server */ protected Application provideApplication() { return Helpers.fakeApplication(); } /** * Override this method to setup the port to use. * * @return The TCP port used by the server */ protected int providePort() { return play.api.test.Helpers.testServerPort(); } @Before public void startServer() { if (testServer != null) { testServer.stop(); } app = provideApplication(); testServer = Helpers.testServer(providePort(), app); testServer.start(); port = testServer.getRunningHttpPort().getAsInt(); } @After public void stopServer() { if (testServer != null) { testServer.stop(); testServer = null; port = -1; app = null; } } }
WithServer
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/net/PriorityTest.java
{ "start": 984, "end": 1187 }
class ____ { @Test void testP1() { final int p = Priority.getPriority(Facility.AUTH, Level.INFO); assertEquals(38, p, "Expected priority value is 38, got " + p); } }
PriorityTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SqlExceptionHelper.java
{ "start": 6820, "end": 7429 }
class ____ implements WarningHandler { @Override public void handleWarning(SQLWarning warning) { logWarning( "SQL Warning Code: " + warning.getErrorCode() + ", SQLState: " + warning.getSQLState(), warning.getMessage() ); } /** * Delegate to log common details of a {@linkplain SQLWarning warning} * * @param description A description of the warning * @param message The warning message */ protected abstract void logWarning(String description, String message); } /** * Standard SQLWarning handler for logging warnings */ public static
WarningHandlerLoggingSupport
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/googleaistudio/response/GoogleAiStudioCompletionResponseEntityTests.java
{ "start": 831, "end": 7414 }
class ____ extends ESTestCase { public void testFromResponse_CreatesResultsForASingleItem() throws IOException { String responseJson = """ { "candidates": [ { "content": { "parts": [ { "text": "result" } ], "role": "model" }, "finishReason": "STOP", "index": 0, "safetyRatings": [ { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_HATE_SPEECH", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_HARASSMENT", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "NEGLIGIBLE" } ] } ], "usageMetadata": { "promptTokenCount": 4, "candidatesTokenCount": 312, "totalTokenCount": 316 } } """; ChatCompletionResults chatCompletionResults = GoogleAiStudioCompletionResponseEntity.fromResponse( mock(Request.class), new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ); assertThat(chatCompletionResults.getResults().size(), is(1)); assertThat(chatCompletionResults.getResults().get(0).content(), is("result")); } public void testFromResponse_FailsWhenCandidatesFieldIsNotPresent() { String responseJson = """ { "not_candidates": [ { "content": { "parts": [ { "text": "result" } ], "role": "model" }, "finishReason": "STOP", "index": 0, "safetyRatings": [ { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_HATE_SPEECH", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_HARASSMENT", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "NEGLIGIBLE" } ] } ], "usageMetadata": { "promptTokenCount": 4, "candidatesTokenCount": 312, "totalTokenCount": 316 } } """; var thrownException = expectThrows( IllegalStateException.class, () -> GoogleAiStudioCompletionResponseEntity.fromResponse( mock(Request.class), new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ) ); assertThat(thrownException.getMessage(), is("Failed to find required field [candidates] in Google AI Studio completion response")); } public void testFromResponse_FailsWhenTextFieldIsNotAString() { String responseJson = """ { "candidates": [ { "content": { "parts": [ { "text": { "key": "value" } } ], "role": "model" }, "finishReason": "STOP", "index": 0, "safetyRatings": [ { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_HATE_SPEECH", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_HARASSMENT", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "NEGLIGIBLE" } ] } ], "usageMetadata": { "promptTokenCount": 4, "candidatesTokenCount": 312, "totalTokenCount": 316 } } """; var thrownException = expectThrows( ParsingException.class, () -> GoogleAiStudioCompletionResponseEntity.fromResponse( mock(Request.class), new HttpResult(mock(HttpResponse.class), responseJson.getBytes(StandardCharsets.UTF_8)) ) ); assertThat( thrownException.getMessage(), is("Failed to parse object: expecting token of type [VALUE_STRING] but found [START_OBJECT]") ); } }
GoogleAiStudioCompletionResponseEntityTests
java
quarkusio__quarkus
integration-tests/rest-client-reactive-http2/src/main/java/io/quarkus/it/rest/client/http2/multipart/MultipartClient.java
{ "start": 8130, "end": 8376 }
class ____ { @FormParam("file") @PartType(MediaType.APPLICATION_OCTET_STREAM) public Buffer file; @FormParam("number") @PartType(MediaType.TEXT_PLAIN) public int number; }
WithBufferAsTextFile
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/function/RequestPredicates.java
{ "start": 38497, "end": 41906 }
class ____ implements ServerRequest { private final ServerRequest delegate; protected DelegatingServerRequest(ServerRequest delegate) { Assert.notNull(delegate, "Delegate must not be null"); this.delegate = delegate; } @Override public HttpMethod method() { return this.delegate.method(); } @Override public URI uri() { return this.delegate.uri(); } @Override public UriBuilder uriBuilder() { return this.delegate.uriBuilder(); } @Override public String path() { return this.delegate.path(); } @Override public RequestPath requestPath() { return this.delegate.requestPath(); } @Override public Headers headers() { return this.delegate.headers(); } @Override public MultiValueMap<String, Cookie> cookies() { return this.delegate.cookies(); } @Override public Optional<InetSocketAddress> remoteAddress() { return this.delegate.remoteAddress(); } @Override public List<HttpMessageConverter<?>> messageConverters() { return this.delegate.messageConverters(); } @Override public @Nullable ApiVersionStrategy apiVersionStrategy() { return this.delegate.apiVersionStrategy(); } @Override public <T> T body(Class<T> bodyType) throws ServletException, IOException { return this.delegate.body(bodyType); } @Override public <T> T body(ParameterizedTypeReference<T> bodyType) throws ServletException, IOException { return this.delegate.body(bodyType); } @Override public <T> T bind(Class<T> bindType) throws BindException { return this.delegate.bind(bindType); } @Override public <T> T bind(Class<T> bindType, Consumer<WebDataBinder> dataBinderCustomizer) throws BindException { return this.delegate.bind(bindType, dataBinderCustomizer); } @Override public Optional<Object> attribute(String name) { return this.delegate.attribute(name); } @Override public Map<String, Object> attributes() { return this.delegate.attributes(); } @Override public Optional<String> param(String name) { return this.delegate.param(name); } @Override public MultiValueMap<String, String> params() { return this.delegate.params(); } @Override public MultiValueMap<String, Part> multipartData() throws IOException, ServletException { return this.delegate.multipartData(); } @Override public String pathVariable(String name) { return this.delegate.pathVariable(name); } @Override public Map<String, String> pathVariables() { return this.delegate.pathVariables(); } @Override public HttpSession session() { return this.delegate.session(); } @Override public Optional<Principal> principal() { return this.delegate.principal(); } @Override public HttpServletRequest servletRequest() { return this.delegate.servletRequest(); } @Override public Optional<ServerResponse> checkNotModified(Instant lastModified) { return this.delegate.checkNotModified(lastModified); } @Override public Optional<ServerResponse> checkNotModified(String etag) { return this.delegate.checkNotModified(etag); } @Override public Optional<ServerResponse> checkNotModified(Instant lastModified, String etag) { return this.delegate.checkNotModified(lastModified, etag); } @Override public String toString() { return this.delegate.toString(); } } private static
DelegatingServerRequest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ClobTest.java
{ "start": 816, "end": 2242 }
class ____ { @Test public void test(EntityManagerFactoryScope scope) { Integer productId = scope.fromTransaction( entityManager -> { Session session = entityManager.unwrap(Session.class); //tag::basic-clob-persist-example[] String warranty = "My product warranty"; final Product product = new Product(); product.setId(1); product.setName("Mobile phone"); product.setWarranty(ClobProxy.generateProxy(warranty)); entityManager.persist(product); //end::basic-clob-persist-example[] return product.getId(); }); scope.inTransaction( entityManager -> { try { //tag::basic-clob-find-example[] Product product = entityManager.find(Product.class, productId); try (Reader reader = product.getWarranty().getCharacterStream()) { assertEquals("My product warranty", toString(reader)); } //end::basic-clob-find-example[] } catch (Exception e) { fail(e.getMessage()); } }); } private String toString(Reader reader) throws IOException { BufferedReader bufferedReader = new BufferedReader(reader); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int result = bufferedReader.read(); while(result != -1) { byteArrayOutputStream.write((byte) result); result = bufferedReader.read(); } return byteArrayOutputStream.toString(); } //tag::basic-clob-example[] @Entity(name = "Product") public static
ClobTest
java
apache__hadoop
hadoop-tools/hadoop-resourceestimator/src/main/java/org/apache/hadoop/resourceestimator/common/config/ResourceEstimatorUtil.java
{ "start": 1300, "end": 3270 }
class ____ specified * in the configuration object. * * @param conf the yarn configuration * @param configuredClassName the configuration provider key * @param defaultValue the default implementation class * @param type the required interface/base class * @param <T> The type of the instance to create * @return the instances created * @throws ResourceEstimatorException if the provider initialization fails. */ @SuppressWarnings("unchecked") public static <T> T createProviderInstance( Configuration conf, String configuredClassName, String defaultValue, Class<T> type) throws ResourceEstimatorException { String className = conf.get(configuredClassName); if (className == null) { className = defaultValue; } try { Class<?> concreteClass = Class.forName(className); if (type.isAssignableFrom(concreteClass)) { Constructor<T> meth = (Constructor<T>) concreteClass.getDeclaredConstructor(EMPTY_ARRAY); meth.setAccessible(true); return meth.newInstance(); } else { StringBuilder errMsg = new StringBuilder(); errMsg.append("Class: ").append(className).append(" not instance of ") .append(type.getCanonicalName()); throw new ResourceEstimatorException(errMsg.toString()); } } catch (ClassNotFoundException e) { StringBuilder errMsg = new StringBuilder(); errMsg.append("Could not instantiate : ").append(className) .append(" due to exception: ").append(e.getCause()); throw new ResourceEstimatorException(errMsg.toString()); } catch (ReflectiveOperationException e) { StringBuilder errMsg = new StringBuilder(); errMsg.append("Could not instantiate : ").append(className) .append(" due to exception: ").append(e.getCause()); throw new ResourceEstimatorException(errMsg.toString()); } } }
name
java
apache__camel
components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/IncomingVideo.java
{ "start": 1100, "end": 3233 }
class ____ implements Serializable { private static final long serialVersionUID = 5280714879829232835L; @JsonProperty("file_id") private String fileId; private Integer width; private Integer height; @JsonProperty("duration") private Integer durationSeconds; private IncomingPhotoSize thumb; @JsonProperty("mime_type") private String mimeType; @JsonProperty("file_size") private Long fileSize; public IncomingVideo() { } public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } public Integer getWidth() { return width; } public void setWidth(Integer width) { this.width = width; } public Integer getHeight() { return height; } public void setHeight(Integer height) { this.height = height; } public Long getFileSize() { return fileSize; } public void setFileSize(Long fileSize) { this.fileSize = fileSize; } public Integer getDurationSeconds() { return durationSeconds; } public void setDurationSeconds(Integer durationSeconds) { this.durationSeconds = durationSeconds; } public IncomingPhotoSize getThumb() { return thumb; } public void setThumb(IncomingPhotoSize thumb) { this.thumb = thumb; } public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } @Override public String toString() { final StringBuilder sb = new StringBuilder("IncomingVideo{"); sb.append("fileId='").append(fileId).append('\''); sb.append(", width=").append(width); sb.append(", height=").append(height); sb.append(", durationSeconds=").append(durationSeconds); sb.append(", thumb=").append(thumb); sb.append(", mimeType='").append(mimeType).append('\''); sb.append(", fileSize=").append(fileSize); sb.append('}'); return sb.toString(); } }
IncomingVideo
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/CommonsLogWriter.java
{ "start": 855, "end": 1665 }
class ____ extends Writer { private final Log logger; private final StringBuilder buffer = new StringBuilder(); /** * Create a new CommonsLogWriter for the given Commons Logging logger. * @param logger the Commons Logging logger to write to */ public CommonsLogWriter(Log logger) { Assert.notNull(logger, "Logger must not be null"); this.logger = logger; } public void write(char ch) { if (ch == '\n' && this.buffer.length() > 0) { logger.debug(this.buffer.toString()); this.buffer.setLength(0); } else { this.buffer.append(ch); } } @Override public void write(char[] buffer, int offset, int length) { for (int i = 0; i < length; i++) { write(buffer[offset + i]); } } @Override public void flush() { } @Override public void close() { } }
CommonsLogWriter
java
apache__logging-log4j2
log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/util/Recycler.java
{ "start": 871, "end": 943 }
interface ____<V> { V acquire(); void release(V value); }
Recycler
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/session/ForceEagerSessionCreationFilter.java
{ "start": 1153, "end": 1616 }
class ____ extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { HttpSession session = request.getSession(); if (this.logger.isDebugEnabled() && session.isNew()) { this.logger.debug(LogMessage.format("Created session eagerly")); } filterChain.doFilter(request, response); } }
ForceEagerSessionCreationFilter
java
quarkusio__quarkus
devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusTask.java
{ "start": 527, "end": 5888 }
class ____ extends DefaultTask { private static final List<String> WORKER_BUILD_FORK_OPTIONS = List.of("quarkus.", "platform.quarkus.", "gradle.quarkus."); private final transient QuarkusPluginExtension extension; protected final File projectDir; protected final File buildDir; QuarkusTask(String description) { this(description, false); } QuarkusTask(String description, boolean configurationCacheCompatible) { setDescription(description); setGroup("quarkus"); this.extension = getProject().getExtensions().findByType(QuarkusPluginExtension.class); this.projectDir = getProject().getProjectDir(); this.buildDir = getProject().getLayout().getBuildDirectory().getAsFile().get(); // Calling this method tells Gradle that it should not fail the build. Side effect is that the configuration // cache will be at least degraded, but the build will not fail. if (!configurationCacheCompatible) { notCompatibleWithConfigurationCache("The Quarkus Plugin isn't compatible with the configuration cache"); } } @Inject protected abstract WorkerExecutor getWorkerExecutor(); QuarkusPluginExtension extension() { return extension; } WorkQueue workQueue(Map<String, String> configMap, List<Action<? super JavaForkOptions>> forkOptionsSupplier) { WorkerExecutor workerExecutor = getWorkerExecutor(); // Use process isolation by default, unless Gradle's started with its debugging system property or the // system property `gradle.quarkus.gradle-worker.no-process` is set to `true`. if (Boolean.getBoolean("org.gradle.debug") || Boolean.getBoolean("gradle.quarkus.gradle-worker.no-process")) { return workerExecutor.classLoaderIsolation(); } return workerExecutor.processIsolation(processWorkerSpec -> configureProcessWorkerSpec(processWorkerSpec, configMap, forkOptionsSupplier)); } private void configureProcessWorkerSpec(ProcessWorkerSpec processWorkerSpec, Map<String, String> configMap, List<Action<? super JavaForkOptions>> customizations) { JavaForkOptions forkOptions = processWorkerSpec.getForkOptions(); customizations.forEach(a -> a.execute(forkOptions)); // Propagate user.dir to load config sources that use it (instead of the worker user.dir) String userDir = configMap.get("user.dir"); if (userDir != null) { forkOptions.systemProperty("user.dir", userDir); } String quarkusWorkerMaxHeap = System.getProperty("gradle.quarkus.gradle-worker.max-heap"); if (quarkusWorkerMaxHeap != null && forkOptions.getAllJvmArgs().stream().noneMatch(arg -> arg.startsWith("-Xmx"))) { forkOptions.jvmArgs("-Xmx" + quarkusWorkerMaxHeap); } // Pass all environment variables forkOptions.environment(System.getenv()); if (OS.current() == OS.WINDOWS) { // On Windows, gRPC code generation is sometimes(?) unable to find "java.exe". Feels (not proven) that // the grpc code generation tool looks up "java.exe" instead of consulting the 'JAVA_HOME' environment. // Might be, that Gradle's process isolation "loses" some information down to the worker process, so add // both JAVA_HOME and updated PATH environment from the 'java' executable chosen by Gradle (could be from // a different toolchain than the one running the build, in theory at least). // Linux is fine though, so no need to add a hack for Linux. String java = forkOptions.getExecutable(); Path javaBinPath = Paths.get(java).getParent().toAbsolutePath(); String javaBin = javaBinPath.toString(); String javaHome = javaBinPath.getParent().toString(); forkOptions.environment("JAVA_HOME", javaHome); forkOptions.environment("PATH", javaBin + File.pathSeparator + System.getenv("PATH")); } // It's kind of a "very big hammer" here, but this way we ensure that all necessary properties // "quarkus.*" from all configuration sources // are (forcefully) used in the Quarkus build - even properties defined on the QuarkusPluginExtension. // This prevents that settings from e.g. a application.properties takes precedence over an explicit // setting in Gradle project properties, the Quarkus extension or even via the environment or system // properties. // see https://github.com/quarkusio/quarkus/issues/33321 why not all properties are passed as system properties // Note that we MUST NOT mess with the system properties of the JVM running the build! And that is the // main reason why build and code generation happen in a separate process. configMap.entrySet().stream() .filter(e -> WORKER_BUILD_FORK_OPTIONS.stream().anyMatch(e.getKey().toLowerCase()::startsWith)) .forEach(e -> forkOptions.systemProperty(e.getKey(), e.getValue())); // populate worker classpath with additional content? // or maybe remove some dependencies from the plugin and make those exclusively available to the worker? // processWorkerSpec.getClasspath().from(); } }
QuarkusTask
java
google__auto
value/src/it/functional/src/test/java/com/google/auto/value/AutoValueTest.java
{ "start": 84943, "end": 85361 }
class ____ extends AbstractParentWithBuilder.Builder<Builder> { abstract Builder bar(String s); abstract ChildWithBuilder build(); } } @Test public void testInheritedBuilder() { ChildWithBuilder x = ChildWithBuilder.builder().foo("foo").bar("bar").build(); assertThat(x.foo()).isEqualTo("foo"); assertThat(x.bar()).isEqualTo("bar"); } @Retention(RetentionPolicy.RUNTIME) @
Builder
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/action/EsqlQueryRequest.java
{ "start": 9080, "end": 10097 }
class ____ extends CancellableTask { private final Status status; EsqlQueryRequestTask( String query, long id, String type, String action, TaskId parentTaskId, Map<String, String> headers, EsqlQueryStatus status ) { // Pass the query as the description super(id, type, action, query, parentTaskId, headers); this.status = status; } @Override public Status getStatus() { return status; } } // Setter for tests void onSnapshotBuild(boolean onSnapshotBuild) { this.onSnapshotBuild = onSnapshotBuild; } void acceptedPragmaRisks(boolean accepted) { this.acceptedPragmaRisks = accepted; } public void projectRouting(String projectRouting) { this.projectRouting = projectRouting; } public String projectRouting() { return projectRouting; } }
EsqlQueryRequestTask
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/validation/DataBinderConstructTests.java
{ "start": 1252, "end": 9829 }
class ____ { @Test void dataClassBinding() { MapValueResolver valueResolver = new MapValueResolver(Map.of("param1", "value1", "param2", "true")); DataBinder binder = initDataBinder(DataClass.class); binder.construct(valueResolver); DataClass dataClass = getTarget(binder); assertThat(dataClass.param1()).isEqualTo("value1"); assertThat(dataClass.param2()).isEqualTo(true); assertThat(dataClass.param3()).isEqualTo(0); } @Test void dataClassBindingWithOptionalParameter() { MapValueResolver valueResolver = new MapValueResolver(Map.of("param1", "value1", "param2", "true", "optionalParam", "8")); DataBinder binder = initDataBinder(DataClass.class); binder.construct(valueResolver); DataClass dataClass = getTarget(binder); assertThat(dataClass.param1()).isEqualTo("value1"); assertThat(dataClass.param2()).isEqualTo(true); assertThat(dataClass.param3()).isEqualTo(8); } @Test void dataClassBindingWithMissingParameter() { MapValueResolver valueResolver = new MapValueResolver(Map.of("param1", "value1")); DataBinder binder = initDataBinder(DataClass.class); binder.construct(valueResolver); BindingResult bindingResult = binder.getBindingResult(); assertThat(bindingResult.getAllErrors()).hasSize(1); assertThat(bindingResult.getFieldValue("param1")).isEqualTo("value1"); assertThat(bindingResult.getFieldValue("param2")).isNull(); assertThat(bindingResult.getFieldValue("param3")).isNull(); } @Test // gh-31821 void dataClassBindingWithNestedOptionalParameterWithMissingParameter() { MapValueResolver valueResolver = new MapValueResolver(Map.of("param1", "value1")); DataBinder binder = initDataBinder(NestedDataClass.class); binder.construct(valueResolver); NestedDataClass dataClass = getTarget(binder); assertThat(dataClass.param1()).isEqualTo("value1"); assertThat(dataClass.nestedParam2()).isNull(); } @Test void dataClassBindingWithConversionError() { MapValueResolver valueResolver = new MapValueResolver(Map.of("param1", "value1", "param2", "x")); DataBinder binder = initDataBinder(DataClass.class); binder.construct(valueResolver); BindingResult bindingResult = binder.getBindingResult(); assertThat(bindingResult.getAllErrors()).hasSize(1); assertThat(bindingResult.getFieldValue("param1")).isEqualTo("value1"); assertThat(bindingResult.getFieldValue("param2")).isEqualTo("x"); assertThat(bindingResult.getFieldValue("param3")).isNull(); } @Test void dataClassWithListBinding() { MapValueResolver valueResolver = new MapValueResolver(Map.of( "dataClassList[0].param1", "value1", "dataClassList[0].param2", "true", "dataClassList[1].param1", "value2", "dataClassList[1].param2", "true", "dataClassList[2].param1", "value3", "dataClassList[2].param2", "true")); DataBinder binder = initDataBinder(DataClassListRecord.class); binder.construct(valueResolver); DataClassListRecord target = getTarget(binder); List<DataClass> list = target.dataClassList(); assertThat(list).hasSize(3); assertThat(list.get(0).param1()).isEqualTo("value1"); assertThat(list.get(1).param1()).isEqualTo("value2"); assertThat(list.get(2).param1()).isEqualTo("value3"); } @Test // gh-34145 void dataClassWithListBindingWithNonconsecutiveIndices() { MapValueResolver valueResolver = new MapValueResolver(Map.of( "dataClassList[0].param1", "value1", "dataClassList[0].param2", "true", "dataClassList[1].param1", "value2", "dataClassList[1].param2", "true", "dataClassList[3].param1", "value3", "dataClassList[3].param2", "true")); DataBinder binder = initDataBinder(DataClassListRecord.class); binder.construct(valueResolver); DataClassListRecord target = getTarget(binder); List<DataClass> list = target.dataClassList(); assertThat(list.get(0).param1()).isEqualTo("value1"); assertThat(list.get(1).param1()).isEqualTo("value2"); assertThat(list.get(3).param1()).isEqualTo("value3"); } @Test void dataClassWithMapBinding() { MapValueResolver valueResolver = new MapValueResolver(Map.of( "dataClassMap[a].param1", "value1", "dataClassMap[a].param2", "true", "dataClassMap[b].param1", "value2", "dataClassMap[b].param2", "true", "dataClassMap['c'].param1", "value3", "dataClassMap['c'].param2", "true")); DataBinder binder = initDataBinder(DataClassMapRecord.class); binder.construct(valueResolver); DataClassMapRecord target = getTarget(binder); Map<String, DataClass> map = target.dataClassMap(); assertThat(map).hasSize(3); assertThat(map.get("a").param1()).isEqualTo("value1"); assertThat(map.get("b").param1()).isEqualTo("value2"); assertThat(map.get("c").param1()).isEqualTo("value3"); } @Test void dataClassWithArrayBinding() { MapValueResolver valueResolver = new MapValueResolver(Map.of( "dataClassArray[0].param1", "value1", "dataClassArray[0].param2", "true", "dataClassArray[1].param1", "value2", "dataClassArray[1].param2", "true", "dataClassArray[2].param1", "value3", "dataClassArray[2].param2", "true")); DataBinder binder = initDataBinder(DataClassArrayRecord.class); binder.construct(valueResolver); DataClassArrayRecord target = getTarget(binder); DataClass[] array = target.dataClassArray(); assertThat(array).hasSize(3); assertThat(array[0].param1()).isEqualTo("value1"); assertThat(array[1].param1()).isEqualTo("value2"); assertThat(array[2].param1()).isEqualTo("value3"); } @Test void simpleListBinding() { MapValueResolver valueResolver = new MapValueResolver(Map.of("integerList[0]", "1", "integerList[1]", "2")); DataBinder binder = initDataBinder(IntegerListRecord.class); binder.construct(valueResolver); IntegerListRecord target = getTarget(binder); assertThat(target.integerList()).containsExactly(1, 2); } @Test void simpleListBindingEmptyBrackets() { MapValueResolver valueResolver = new MapValueResolver(Map.of("integerList[]", "1")); DataBinder binder = initDataBinder(IntegerListRecord.class); binder.construct(valueResolver); IntegerListRecord target = getTarget(binder); assertThat(target.integerList()).containsExactly(1); } @Test void simpleMapBinding() { MapValueResolver valueResolver = new MapValueResolver(Map.of("integerMap[a]", "1", "integerMap[b]", "2")); DataBinder binder = initDataBinder(IntegerMapRecord.class); binder.construct(valueResolver); IntegerMapRecord target = getTarget(binder); assertThat(target.integerMap()).hasSize(2).containsEntry("a", 1).containsEntry("b", 2); } @Test void simpleArrayBinding() { MapValueResolver valueResolver = new MapValueResolver(Map.of("integerArray[0]", "1", "integerArray[1]", "2")); DataBinder binder = initDataBinder(IntegerArrayRecord.class); binder.construct(valueResolver); IntegerArrayRecord target = getTarget(binder); assertThat(target.integerArray()).containsExactly(1, 2); } @Test void nestedListWithinMap() { MapValueResolver valueResolver = new MapValueResolver(Map.of( "integerListMap[a][0]", "1", "integerListMap[a][1]", "2", "integerListMap[b][0]", "3", "integerListMap[b][1]", "4")); DataBinder binder = initDataBinder(IntegerListMapRecord.class); binder.construct(valueResolver); IntegerListMapRecord target = getTarget(binder); assertThat(target.integerListMap().get("a")).containsExactly(1, 2); assertThat(target.integerListMap().get("b")).containsExactly(3, 4); } @Test void nestedMapWithinList() { MapValueResolver valueResolver = new MapValueResolver(Map.of( "integerMapList[0][a]", "1", "integerMapList[0][b]", "2", "integerMapList[1][a]", "3", "integerMapList[1][b]", "4")); DataBinder binder = initDataBinder(IntegerMapListRecord.class); binder.construct(valueResolver); IntegerMapListRecord target = getTarget(binder); assertThat(target.integerMapList().get(0)).containsOnly(Map.entry("a", 1), Map.entry("b", 2)); assertThat(target.integerMapList().get(1)).containsOnly(Map.entry("a", 3), Map.entry("b", 4)); } @SuppressWarnings("SameParameterValue") private static DataBinder initDataBinder(Class<?> targetType) { DataBinder binder = new DataBinder(null); binder.setTargetType(ResolvableType.forClass(targetType)); binder.setConversionService(new DefaultFormattingConversionService()); return binder; } @SuppressWarnings("unchecked") private static <T> T getTarget(DataBinder dataBinder) { assertThat(dataBinder.getBindingResult().getAllErrors()).isEmpty(); Object target = dataBinder.getTarget(); assertThat(target).isNotNull(); return (T) target; } private static
DataBinderConstructTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/FetchGraphTest.java
{ "start": 30939, "end": 31215 }
class ____ extends BaseEntity { @OneToMany(mappedBy = "g") public Set<DEntity> dEntities = new HashSet<>(); public Set<DEntity> getdEntities() { return dEntities; } public void setdEntities(Set<DEntity> dEntities) { this.dEntities = dEntities; } } }
GEntity
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase/hadoop-yarn-server-timelineservice-hbase-common/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/common/Separator.java
{ "start": 1174, "end": 1993 }
enum ____ { /** * separator in key or column qualifier fields. */ QUALIFIERS("!", "%0$"), /** * separator in values, and/or compound key/column qualifier fields. */ VALUES("=", "%1$"), /** * separator in values, often used to avoid having these in qualifiers and * names. Note that if we use HTML form encoding through URLEncoder, we end up * getting a + for a space, which may already occur in strings, so we don't * want that. */ SPACE(" ", "%2$"), /** * separator in values, often used to avoid having these in qualifiers and * names. */ TAB("\t", "%3$"); // a reserved character that starts each of the encoded values and is encoded // first in order to escape naturally occurring instances of encoded values // although it can be expressed as an
Separator
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/dao/InvalidDataAccessResourceUsageException.java
{ "start": 993, "end": 1572 }
class ____ extends NonTransientDataAccessException { /** * Constructor for InvalidDataAccessResourceUsageException. * @param msg the detail message */ public InvalidDataAccessResourceUsageException(@Nullable String msg) { super(msg); } /** * Constructor for InvalidDataAccessResourceUsageException. * @param msg the detail message * @param cause the root cause from the data access API in use */ public InvalidDataAccessResourceUsageException(@Nullable String msg, @Nullable Throwable cause) { super(msg, cause); } }
InvalidDataAccessResourceUsageException
java
spring-projects__spring-framework
integration-tests/src/test/java/org/springframework/beans/factory/xml/ComponentBeanDefinitionParser.java
{ "start": 1101, "end": 2421 }
class ____ extends AbstractBeanDefinitionParser { @Override protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { return parseComponentElement(element); } private static AbstractBeanDefinition parseComponentElement(Element element) { BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(ComponentFactoryBean.class); factory.addPropertyValue("parent", parseComponent(element)); List<Element> childElements = DomUtils.getChildElementsByTagName(element, "component"); if (!CollectionUtils.isEmpty(childElements)) { parseChildComponents(childElements, factory); } return factory.getBeanDefinition(); } private static BeanDefinition parseComponent(Element element) { BeanDefinitionBuilder component = BeanDefinitionBuilder.rootBeanDefinition(Component.class); component.addPropertyValue("name", element.getAttribute("name")); return component.getBeanDefinition(); } private static void parseChildComponents(List<Element> childElements, BeanDefinitionBuilder factory) { ManagedList<BeanDefinition> children = new ManagedList<>(childElements.size()); for (Element element : childElements) { children.add(parseComponentElement(element)); } factory.addPropertyValue("children", children); } }
ComponentBeanDefinitionParser
java
apache__camel
components/camel-dynamic-router/src/main/java/org/apache/camel/component/dynamicrouter/control/DynamicRouterControlMessage.java
{ "start": 5619, "end": 9487 }
class ____ { private String subscribeChannel; private String subscriptionId; private String destinationUri; private int priority; private String predicateBean; private String predicate; private String expressionLanguage; /** * Instantiates a new {@code DynamicRouterControlMessage.Builder}. */ private Builder() { } /** * Returns a {@code DynamicRouterControlMessage.Builder} object that can be used to create a new * {@code DynamicRouterControlMessage}. * * @return a {@code DynamicRouterControlMessage.Builder} object that can be used to create a new * {@code DynamicRouterControlMessage} */ public static Builder newBuilder() { return new Builder(); } /** * Sets the {@code subscribeChannel} and returns a reference to this Builder enabling method chaining. * * @param val the {@code subscribeChannel} to set * @return a reference to this Builder */ public Builder subscribeChannel(String val) { subscribeChannel = val; return this; } /** * Sets the {@code subscriptionId} and returns a reference to this Builder enabling method chaining. * * @param val the {@code subscriptionId} to set * @return a reference to this Builder */ public Builder subscriptionId(String val) { subscriptionId = val; return this; } /** * Sets the {@code destinationUri} and returns a reference to this Builder enabling method chaining. * * @param val the {@code destinationUri} to set * @return a reference to this Builder */ public Builder destinationUri(String val) { destinationUri = val; return this; } /** * Sets the {@code priority} and returns a reference to this Builder enabling method chaining. * * @param val the {@code priority} to set * @return a reference to this Builder */ public Builder priority(int val) { priority = val; return this; } /** * Sets the {@code predicateBean} and returns a reference to this Builder enabling method chaining. * * @param val the {@code predicateBean} to set * @return a reference to this Builder */ public Builder predicateBean(String val) { predicateBean = val; return this; } /** * Sets the {@code predicate} and returns a reference to this Builder enabling method chaining. * * @param val the {@code predicate} to set * @return a reference to this Builder */ public Builder predicate(String val) { predicate = val; return this; } /** * Sets the {@code expressionLanguage} and returns a reference to this Builder enabling method chaining. * * @param val the {@code expressionLanguage} to set * @return a reference to this Builder */ public Builder expressionLanguage(String val) { expressionLanguage = val; return this; } /** * Returns a {@code DynamicRouterControlMessage} built from the parameters previously set. * * @return a {@code DynamicRouterControlMessage} built with parameters of this * {@code DynamicRouterControlMessage.Builder} */ public DynamicRouterControlMessage build() { return new DynamicRouterControlMessage(this); } } }
Builder
java
apache__camel
test-infra/camel-test-infra-aws-v2/src/main/java/org/apache/camel/test/infra/aws2/services/AWSSNSLocalContainerInfraService.java
{ "start": 1175, "end": 1339 }
class ____ extends AWSLocalContainerInfraService { public AWSSNSLocalContainerInfraService() { super(Service.SNS); } }
AWSSNSLocalContainerInfraService
java
apache__hadoop
hadoop-tools/hadoop-azure-datalake/src/test/java/org/apache/hadoop/fs/adl/TestValidateConfiguration.java
{ "start": 3095, "end": 10736 }
class ____ { @Test public void validateConfigurationKeys() { assertEquals("fs.adl.oauth2.refresh.url", AZURE_AD_REFRESH_URL_KEY); assertEquals("fs.adl.oauth2.access.token.provider", AZURE_AD_TOKEN_PROVIDER_CLASS_KEY); assertEquals("fs.adl.oauth2.client.id", AZURE_AD_CLIENT_ID_KEY); assertEquals("fs.adl.oauth2.refresh.token", AZURE_AD_REFRESH_TOKEN_KEY); assertEquals("fs.adl.oauth2.credential", AZURE_AD_CLIENT_SECRET_KEY); assertEquals("adl.debug.override.localuserasfileowner", ADL_DEBUG_OVERRIDE_LOCAL_USER_AS_OWNER); assertEquals("fs.adl.oauth2.access.token.provider.type", AZURE_AD_TOKEN_PROVIDER_TYPE_KEY); assertEquals("adl.feature.client.cache.readahead", READ_AHEAD_BUFFER_SIZE_KEY); assertEquals("adl.feature.client.cache.drop.behind.writes", WRITE_BUFFER_SIZE_KEY); assertEquals("RefreshToken", TOKEN_PROVIDER_TYPE_REFRESH_TOKEN); assertEquals("ClientCredential", TOKEN_PROVIDER_TYPE_CLIENT_CRED); assertEquals("adl.enable.client.latency.tracker", LATENCY_TRACKER_KEY); assertEquals(true, LATENCY_TRACKER_DEFAULT); assertEquals(true, ADL_EXPERIMENT_POSITIONAL_READ_DEFAULT); assertEquals("adl.feature.experiment.positional.read.enable", ADL_EXPERIMENT_POSITIONAL_READ_KEY); assertEquals(1, ADL_REPLICATION_FACTOR); assertEquals(256 * 1024 * 1024, ADL_BLOCK_SIZE); assertEquals(false, ADL_DEBUG_SET_LOCAL_USER_AS_OWNER_DEFAULT); assertEquals(4 * 1024 * 1024, DEFAULT_READ_AHEAD_BUFFER_SIZE); assertEquals(4 * 1024 * 1024, DEFAULT_WRITE_AHEAD_BUFFER_SIZE); assertEquals("adl.feature.ownerandgroup.enableupn", ADL_ENABLEUPN_FOR_OWNERGROUP_KEY); assertEquals(false, ADL_ENABLEUPN_FOR_OWNERGROUP_DEFAULT); } @Test public void testSetDeprecatedKeys() throws ClassNotFoundException { Configuration conf = new Configuration(true); setDeprecatedKeys(conf); // Force AdlFileSystem static initialization to register deprecated keys. Class.forName(AdlFileSystem.class.getName()); assertDeprecatedKeys(conf); } @Test public void testLoadDeprecatedKeys() throws IOException, ClassNotFoundException { Configuration saveConf = new Configuration(false); setDeprecatedKeys(saveConf); final File testRootDir = GenericTestUtils.getTestDir(); File confXml = new File(testRootDir, "testLoadDeprecatedKeys.xml"); OutputStream out = new FileOutputStream(confXml); saveConf.writeXml(out); out.close(); Configuration conf = new Configuration(true); conf.addResource(confXml.toURI().toURL()); // Trigger loading the configuration resources by getting any key. conf.get("dummy.key"); // Force AdlFileSystem static initialization to register deprecated keys. Class.forName(AdlFileSystem.class.getName()); assertDeprecatedKeys(conf); } @Test public void testGetAccountNameFromFQDN() { assertEquals("dummy", AdlFileSystem. getAccountNameFromFQDN("dummy.azuredatalakestore.net")); assertEquals("localhost", AdlFileSystem. getAccountNameFromFQDN("localhost")); } @Test public void testPropagateAccountOptionsDefault() { Configuration conf = new Configuration(false); conf.set("fs.adl.oauth2.client.id", "defaultClientId"); conf.set("fs.adl.oauth2.credential", "defaultCredential"); conf.set("some.other.config", "someValue"); Configuration propagatedConf = AdlFileSystem.propagateAccountOptions(conf, "dummy"); assertEquals("defaultClientId", propagatedConf.get(AZURE_AD_CLIENT_ID_KEY)); assertEquals("defaultCredential", propagatedConf.get(AZURE_AD_CLIENT_SECRET_KEY)); assertEquals("someValue", propagatedConf.get("some.other.config")); } @Test public void testPropagateAccountOptionsSpecified() { Configuration conf = new Configuration(false); conf.set("fs.adl.account.dummy.oauth2.client.id", "dummyClientId"); conf.set("fs.adl.account.dummy.oauth2.credential", "dummyCredential"); conf.set("some.other.config", "someValue"); Configuration propagatedConf = AdlFileSystem.propagateAccountOptions(conf, "dummy"); assertEquals("dummyClientId", propagatedConf.get(AZURE_AD_CLIENT_ID_KEY)); assertEquals("dummyCredential", propagatedConf.get(AZURE_AD_CLIENT_SECRET_KEY)); assertEquals("someValue", propagatedConf.get("some.other.config")); propagatedConf = AdlFileSystem.propagateAccountOptions(conf, "anotherDummy"); assertEquals(null, propagatedConf.get(AZURE_AD_CLIENT_ID_KEY)); assertEquals(null, propagatedConf.get(AZURE_AD_CLIENT_SECRET_KEY)); assertEquals("someValue", propagatedConf.get("some.other.config")); } @Test public void testPropagateAccountOptionsAll() { Configuration conf = new Configuration(false); conf.set("fs.adl.oauth2.client.id", "defaultClientId"); conf.set("fs.adl.oauth2.credential", "defaultCredential"); conf.set("some.other.config", "someValue"); conf.set("fs.adl.account.dummy1.oauth2.client.id", "dummyClientId1"); conf.set("fs.adl.account.dummy1.oauth2.credential", "dummyCredential1"); conf.set("fs.adl.account.dummy2.oauth2.client.id", "dummyClientId2"); conf.set("fs.adl.account.dummy2.oauth2.credential", "dummyCredential2"); Configuration propagatedConf = AdlFileSystem.propagateAccountOptions(conf, "dummy1"); assertEquals("dummyClientId1", propagatedConf.get(AZURE_AD_CLIENT_ID_KEY)); assertEquals("dummyCredential1", propagatedConf.get(AZURE_AD_CLIENT_SECRET_KEY)); assertEquals("someValue", propagatedConf.get("some.other.config")); propagatedConf = AdlFileSystem.propagateAccountOptions(conf, "dummy2"); assertEquals("dummyClientId2", propagatedConf.get(AZURE_AD_CLIENT_ID_KEY)); assertEquals("dummyCredential2", propagatedConf.get(AZURE_AD_CLIENT_SECRET_KEY)); assertEquals("someValue", propagatedConf.get("some.other.config")); propagatedConf = AdlFileSystem.propagateAccountOptions(conf, "anotherDummy"); assertEquals("defaultClientId", propagatedConf.get(AZURE_AD_CLIENT_ID_KEY)); assertEquals("defaultCredential", propagatedConf.get(AZURE_AD_CLIENT_SECRET_KEY)); assertEquals("someValue", propagatedConf.get("some.other.config")); } private void setDeprecatedKeys(Configuration conf) { conf.set("dfs.adls.oauth2.access.token.provider.type", "dummyType"); conf.set("dfs.adls.oauth2.client.id", "dummyClientId"); conf.set("dfs.adls.oauth2.refresh.token", "dummyRefreshToken"); conf.set("dfs.adls.oauth2.refresh.url", "dummyRefreshUrl"); conf.set("dfs.adls.oauth2.credential", "dummyCredential"); conf.set("dfs.adls.oauth2.access.token.provider", "dummyClass"); conf.set("adl.dfs.enable.client.latency.tracker", "dummyTracker"); } private void assertDeprecatedKeys(Configuration conf) { assertEquals("dummyType", conf.get(AZURE_AD_TOKEN_PROVIDER_TYPE_KEY)); assertEquals("dummyClientId", conf.get(AZURE_AD_CLIENT_ID_KEY)); assertEquals("dummyRefreshToken", conf.get(AZURE_AD_REFRESH_TOKEN_KEY)); assertEquals("dummyRefreshUrl", conf.get(AZURE_AD_REFRESH_URL_KEY)); assertEquals("dummyCredential", conf.get(AZURE_AD_CLIENT_SECRET_KEY)); assertEquals("dummyClass", conf.get(AZURE_AD_TOKEN_PROVIDER_CLASS_KEY)); assertEquals("dummyTracker", conf.get(LATENCY_TRACKER_KEY)); } }
TestValidateConfiguration
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/builder/Builder.java
{ "start": 1599, "end": 2093 }
interface ____ { // // Be nice to whittle this down to Session, maybe add task segments to the session. The session really is // the place to store reactor related information. // void build( MavenSession session, ReactorContext reactorContext, ProjectBuildList projectBuilds, List<TaskSegment> taskSegments, ReactorBuildStatus reactorBuildStatus) throws ExecutionException, InterruptedException; }
Builder
java
elastic__elasticsearch
x-pack/plugin/esql/qa/testFixtures/src/main/java/org/elasticsearch/xpack/esql/generator/command/pipe/EvalGenerator.java
{ "start": 817, "end": 4312 }
class ____ implements CommandGenerator { public static final String EVAL = "eval"; public static final String NEW_COLUMNS = "new_columns"; public static final CommandGenerator INSTANCE = new EvalGenerator(); @Override public CommandDescription generate( List<CommandDescription> previousCommands, List<Column> previousOutput, QuerySchema schema, QueryExecutor executor ) { StringBuilder cmd = new StringBuilder(" | eval "); int nFields = randomIntBetween(1, 10); Map<String, Column> usablePrevious = previousOutput.stream().collect(Collectors.toMap(Column::name, c -> c)); // TODO pass newly created fields to next expressions var newColumns = new ArrayList<>(); for (int i = 0; i < nFields; i++) { String name; if (randomBoolean()) { name = EsqlQueryGenerator.randomIdentifier(); } else { name = EsqlQueryGenerator.randomName(previousOutput); if (name == null) { name = EsqlQueryGenerator.randomIdentifier(); } } String expression = EsqlQueryGenerator.expression(usablePrevious.values().stream().toList(), true); if (i > 0) { cmd.append(","); } cmd.append(" "); cmd.append(name); newColumns.remove(unquote(name)); newColumns.add(unquote(name)); cmd.append(" = "); cmd.append(expression); // there could be collisions in many ways, remove all of them usablePrevious.remove(name); usablePrevious.remove("`" + name + "`"); usablePrevious.remove(unquote(name)); } String cmdString = cmd.toString(); return new CommandDescription(EVAL, this, cmdString, Map.ofEntries(Map.entry(NEW_COLUMNS, newColumns))); } @Override @SuppressWarnings("unchecked") public ValidationResult validateOutput( List<CommandDescription> previousCommands, CommandDescription commandDescription, List<Column> previousColumns, List<List<Object>> previousOutput, List<Column> columns, List<List<Object>> output ) { List<String> expectedColumns = (List<String>) commandDescription.context().get(NEW_COLUMNS); List<String> resultColNames = columns.stream().map(Column::name).toList(); List<String> lastColumns = resultColNames.subList(resultColNames.size() - expectedColumns.size(), resultColNames.size()); lastColumns = lastColumns.stream().map(EvalGenerator::unquote).toList(); // expected column names are unquoted already if (columns.size() < expectedColumns.size() || lastColumns.equals(expectedColumns) == false) { return new ValidationResult( false, "Expecting the following as last columns [" + String.join(", ", expectedColumns) + "] but got [" + String.join(", ", resultColNames) + "]" ); } return CommandGenerator.expectSameRowCount(previousCommands, previousOutput, output); } private static String unquote(String colName) { if (colName.startsWith("`") && colName.endsWith("`")) { return colName.substring(1, colName.length() - 1); } return colName; } }
EvalGenerator
java
apache__flink
flink-dstl/flink-dstl-dfs/src/main/java/org/apache/flink/changelog/fs/UploadResult.java
{ "start": 1174, "end": 3535 }
class ____ { public final StreamStateHandle streamStateHandle; @Nullable public final StreamStateHandle localStreamHandle; public final long offset; public final long localOffset; public final SequenceNumber sequenceNumber; public final long size; public UploadResult( StreamStateHandle streamStateHandle, long offset, SequenceNumber sequenceNumber, long size) { this(streamStateHandle, null, offset, offset, sequenceNumber, size); } public UploadResult( StreamStateHandle streamStateHandle, @Nullable StreamStateHandle localStreamHandle, long offset, long localOffset, SequenceNumber sequenceNumber, long size) { this.streamStateHandle = checkNotNull(streamStateHandle); this.localStreamHandle = localStreamHandle; this.offset = offset; this.localOffset = localOffset; this.sequenceNumber = checkNotNull(sequenceNumber); this.size = size; } public static UploadResult of( StreamStateHandle handle, StreamStateHandle localHandle, StateChangeSet changeSet, long offset, long localOffset) { return new UploadResult( handle, localHandle, offset, localOffset, changeSet.getSequenceNumber(), changeSet.getSize()); } public StreamStateHandle getStreamStateHandle() { return streamStateHandle; } public StreamStateHandle getLocalStreamHandleStateHandle() { return localStreamHandle; } public long getOffset() { return offset; } public long getLocalOffset() { return localOffset; } public SequenceNumber getSequenceNumber() { return sequenceNumber; } public long getSize() { return size; } @Override public String toString() { return "streamStateHandle=" + streamStateHandle + "localStreamHandle" + localStreamHandle + ", size=" + size + ", offset=" + offset + ", sequenceNumber=" + sequenceNumber; } }
UploadResult
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/instantiation/DynamicInstantiationWithJoinAndGroupByAndParameterTest.java
{ "start": 1064, "end": 2502 }
class ____ { private static final String PARTNER_NUMBER = "1111111111"; @BeforeAll public void setUp(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { final UserEntity user1 = new UserEntity( "John", "Tester" ); entityManager.persist( user1 ); entityManager.persist( new Action( PARTNER_NUMBER, "Test 1", user1 ) ); entityManager.persist( new Action( PARTNER_NUMBER, "Test 2", user1 ) ); } ); } @AfterAll public void tearDown(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { entityManager.createQuery( "delete from Action" ).executeUpdate(); entityManager.createQuery( "delete from UserEntity" ).executeUpdate(); } ); } @Test public void testIt(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { TypedQuery<UserStatistic> query = entityManager.createQuery( "select new " + getClass().getName() + "$UserStatistic(u, count(a))" + " from Action a inner join a.user u" + " where a.partnerNumber = :partnerNumber" + " group by u", UserStatistic.class ); query.setParameter( "partnerNumber", PARTNER_NUMBER ); UserStatistic result = query.getSingleResult(); assertEquals( "John Tester", result.getName() ); assertEquals( 2, result.getCount() ); } ); } @Entity(name = "UserEntity") @Table(name = "UserEntity") public static
DynamicInstantiationWithJoinAndGroupByAndParameterTest
java
google__error-prone
check_api/src/main/java/com/google/errorprone/matchers/Enclosing.java
{ "start": 2458, "end": 3589 }
class ____<T extends Tree> implements Matcher<T> { private final Matcher<BlockTree> blockTreeMatcher; private final Matcher<CaseTree> caseTreeMatcher; public BlockOrCase(Matcher<BlockTree> blockTreeMatcher, Matcher<CaseTree> caseTreeMatcher) { this.blockTreeMatcher = blockTreeMatcher; this.caseTreeMatcher = caseTreeMatcher; } @Override public boolean matches(T unused, VisitorState state) { TreePath pathToEnclosing = state.findPathToEnclosing(CaseTree.class, BlockTree.class); if (pathToEnclosing == null) { return false; } Tree enclosing = pathToEnclosing.getLeaf(); state = state.withPath(pathToEnclosing); if (enclosing instanceof BlockTree blockTree) { return blockTreeMatcher.matches(blockTree, state); } else if (enclosing instanceof CaseTree caseTree) { return caseTreeMatcher.matches(caseTree, state); } else { // findEnclosing given two types must return something of one of those types throw new IllegalStateException("enclosing tree not a BlockTree or CaseTree"); } } } }
BlockOrCase
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/rank/random/RandomRankBuilder.java
{ "start": 2033, "end": 3258 }
class ____ extends RankBuilder { public static final String NAME = "random_reranker"; static final ConstructingObjectParser<RandomRankBuilder, Void> PARSER = new ConstructingObjectParser<>(NAME, args -> { Integer rankWindowSize = args[0] == null ? DEFAULT_RANK_WINDOW_SIZE : (Integer) args[0]; String field = (String) args[1]; Integer seed = (Integer) args[2]; return new RandomRankBuilder(rankWindowSize, field, seed); }); static { PARSER.declareInt(optionalConstructorArg(), RANK_WINDOW_SIZE_FIELD); PARSER.declareString(constructorArg(), FIELD_FIELD); PARSER.declareInt(optionalConstructorArg(), SEED_FIELD); } private final String field; private final Integer seed; public RandomRankBuilder(int rankWindowSize, String field, Integer seed) { super(rankWindowSize); if (field == null || field.isEmpty()) { throw new IllegalArgumentException("field is required"); } this.field = field; this.seed = seed; } public RandomRankBuilder(StreamInput in) throws IOException { super(in); // rankWindowSize deserialization is handled by the parent
RandomRankBuilder
java
google__dagger
javatests/dagger/internal/codegen/InjectConstructorFactoryGeneratorTest.java
{ "start": 12382, "end": 12692 }
class ____ {", " @Inject Usage(GenericClass<Foo> genericClass) {}", "}"); Source genericClass = CompilerTests.javaSource( "test.GenericClass", "package test;", "", "import javax.inject.Inject;", "", "
Usage
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/dns/impl/RecordDecoder.java
{ "start": 1269, "end": 9428 }
class ____ { private static final Logger log = LoggerFactory.getLogger(RecordDecoder.class); /** * Decodes MX (mail exchanger) resource records. */ static Function<DnsRecord, MxRecord> MX = record -> { if (record.type() == DnsRecordType.MX) { ByteBuf packet = ((DnsRawRecord)record).content(); int priority = packet.readShort(); String name = RecordDecoder.readName(packet); long ttl = record.timeToLive(); return new MxRecordImpl(ttl, priority, name); } else { return null; } }; /** * Decodes any record that simply returns a domain name, such as NS (name * server) and CNAME (canonical name) resource records. */ static Function<DnsRecord, String> DOMAIN = record -> { if (record instanceof DnsPtrRecord) { String val = ((DnsPtrRecord)record).hostname(); if (val.endsWith(".")) { val = val.substring(0, val.length() - 1); } return val; } else { ByteBuf content = ((DnsRawRecord) record).content(); return RecordDecoder.getName(content, content.readerIndex()); } }; /** * Decodes A resource records into IPv4 addresses. */ static Function<DnsRecord, String> A = address(DnsRecordType.A, 4); /** * Decodes AAAA resource records into IPv6 addresses. */ static Function<DnsRecord, String> AAAA = address(DnsRecordType.AAAA, 16); /** * Decodes SRV (service) resource records. */ static Function<DnsRecord, SrvRecord> SRV = record -> { if (record.type() == DnsRecordType.SRV) { ByteBuf packet = ((DnsRawRecord)record).content(); int priority = packet.readShort(); int weight = packet.readShort(); int port = packet.readUnsignedShort(); long ttl = record.timeToLive(); String target = RecordDecoder.readName(packet); String[] parts = record.name().split("\\.", 3); String service = parts[0]; String protocol = parts[1]; String name = parts[2]; return new SrvRecordImpl(ttl, priority, weight, port, name, protocol, service, target); } else { return null; } }; /** * Decodes SOA (start of authority) resource records. */ static Function<DnsRecord, StartOfAuthorityRecord> SOA = record -> { if (record.type() == DnsRecordType.SOA) { ByteBuf packet = ((DnsRawRecord)record).content(); String mName = RecordDecoder.readName(packet); String rName = RecordDecoder.readName(packet); long serial = packet.readUnsignedInt(); int refresh = packet.readInt(); int retry = packet.readInt(); int expire = packet.readInt(); long minimum = packet.readUnsignedInt(); return new StartOfAuthorityRecord(mName, rName, serial, refresh, retry, expire, minimum); } else { return null; } }; static Function<DnsRecord, List<String>> TXT = record -> { if (record.type() == DnsRecordType.TXT) { List<String> list = new ArrayList<>(); ByteBuf data = ((DnsRawRecord)record).content(); int index = data.readerIndex(); while (index < data.writerIndex()) { int len = data.getUnsignedByte(index++); list.add(data.toString(index, len, CharsetUtil.UTF_8)); index += len; } return list; } else { return null; } }; static Function<DnsRecord, String> address(DnsRecordType type, int octets) { return record -> { if (record.type() == type) { ByteBuf data = ((DnsRawRecord)record).content(); int size = data.readableBytes(); if (size != octets) { throw new DecoderException("Invalid content length, or reader index when decoding address [index: " + data.readerIndex() + ", expected length: " + octets + ", actual: " + size + "]."); } byte[] address = new byte[octets]; data.getBytes(data.readerIndex(), address); try { return InetAddress.getByAddress(address).getHostAddress(); } catch (UnknownHostException e) { throw new DecoderException("Could not convert address " + data.toString(data.readerIndex(), size, CharsetUtil.UTF_8) + " to InetAddress."); } } else { return null; } }; } /** * Retrieves a domain name given a buffer containing a DNS packet. If the * name contains a pointer, the position of the buffer will be set to * directly after the pointer's index after the name has been read. * * @param buf the byte buffer containing the DNS packet * @return the domain name for an entry */ static String readName(ByteBuf buf) { int position = -1; StringBuilder name = new StringBuilder(); for (int len = buf.readUnsignedByte(); buf.isReadable() && len != 0; len = buf.readUnsignedByte()) { boolean pointer = (len & 0xc0) == 0xc0; if (pointer) { if (position == -1) { position = buf.readerIndex() + 1; } buf.readerIndex((len & 0x3f) << 8 | buf.readUnsignedByte()); } else { name.append(buf.toString(buf.readerIndex(), len, CharsetUtil.UTF_8)).append("."); buf.skipBytes(len); } } if (position != -1) { buf.readerIndex(position); } if (name.length() == 0) { return null; } return name.substring(0, name.length() - 1); } /** * Retrieves a domain name given a buffer containing a DNS packet without * advancing the readerIndex for the buffer. * * @param buf the byte buffer containing the DNS packet * @param offset the position at which the name begins * @return the domain name for an entry */ static String getName(ByteBuf buf, int offset) { StringBuilder name = new StringBuilder(); for (int len = buf.getUnsignedByte(offset++); buf.writerIndex() > offset && len != 0; len = buf .getUnsignedByte(offset++)) { boolean pointer = (len & 0xc0) == 0xc0; if (pointer) { offset = (len & 0x3f) << 8 | buf.getUnsignedByte(offset++); } else { name.append(buf.toString(offset, len, CharsetUtil.UTF_8)).append("."); offset += len; } } if (name.length() == 0) { return null; } return name.substring(0, name.length() - 1); } private static final Map<DnsRecordType, Function<DnsRecord, ?>> decoders = new HashMap<>(); static { decoders.put(DnsRecordType.A, RecordDecoder.A); decoders.put(DnsRecordType.AAAA, RecordDecoder.AAAA); decoders.put(DnsRecordType.MX, RecordDecoder.MX); decoders.put(DnsRecordType.TXT, RecordDecoder.TXT); decoders.put(DnsRecordType.SRV, RecordDecoder.SRV); decoders.put(DnsRecordType.NS, RecordDecoder.DOMAIN); decoders.put(DnsRecordType.CNAME, RecordDecoder.DOMAIN); decoders.put(DnsRecordType.PTR, RecordDecoder.DOMAIN); decoders.put(DnsRecordType.SOA, RecordDecoder.SOA); } /** * Decodes a resource record and returns the result. * * @param record * @return the decoded resource record */ @SuppressWarnings("unchecked") static <T> T decode(DnsRecord record) { DnsRecordType type = record.type(); Function<DnsRecord, ?> decoder = decoders.get(type); if (decoder == null) { throw new DecoderException("DNS record decoding error occurred: Unsupported resource record type [id: " + type + "]."); } T result = null; try { result = (T) decoder.apply(record); } catch (Exception e) { log.error(e.getMessage(), e.getCause()); } return result; } }
RecordDecoder
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/resource/ExtensionResource.java
{ "start": 389, "end": 1950 }
class ____ { @GET @Produces("*/*") public String getDefault() { return "default"; } @GET @Produces("application/xml") public String getXml(@Context HttpHeaders headers) { @SuppressWarnings("unused") List<Locale> languages = headers.getAcceptableLanguages(); @SuppressWarnings("unused") List<MediaType> mediaTypes = headers.getAcceptableMediaTypes(); return "xml"; } @GET @Produces("text/html") public String getXmlTwo(@Context HttpHeaders headers) { List<Locale> languages = headers.getAcceptableLanguages(); Assertions.assertEquals(1, languages.size(), "Wrong number of accepted languages"); Assertions.assertEquals(new Locale("en", "us"), languages.get(0), "Wrong accepted language"); Assertions.assertEquals(MediaType.valueOf("text/html"), headers.getAcceptableMediaTypes().get(0), "Wrong accepted language"); return "html"; } @GET @Path("/stuff.old") @Produces("text/plain") public String getJson(@Context HttpHeaders headers) { List<Locale> languages = headers.getAcceptableLanguages(); Assertions.assertEquals(1, languages.size(), "Wrong number of accepted languages"); Assertions.assertEquals(new Locale("en", "us"), languages.get(0), "Wrong accepted language"); Assertions.assertEquals(MediaType.valueOf("text/plain"), headers.getAcceptableMediaTypes().get(0), "Wrong accepted language"); return "plain"; } }
ExtensionResource
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/AppAttemptInfo.java
{ "start": 1870, "end": 5307 }
class ____ { protected int id; protected long startTime; protected long finishedTime; protected String containerId; protected String nodeHttpAddress; protected String nodeId; protected String logsLink; protected String blacklistedNodes; private String nodesBlacklistedBySystem; protected String appAttemptId; private String exportPorts; private RMAppAttemptState appAttemptState; public AppAttemptInfo() { } public AppAttemptInfo(ResourceManager rm, RMAppAttempt attempt, Boolean hasAccess, String user, String schemePrefix) { this.startTime = 0; this.containerId = ""; this.nodeHttpAddress = ""; this.nodeId = ""; this.logsLink = ""; this.blacklistedNodes = ""; this.exportPorts = ""; if (attempt != null) { this.id = attempt.getAppAttemptId().getAttemptId(); this.startTime = attempt.getStartTime(); this.finishedTime = attempt.getFinishTime(); this.appAttemptState = attempt.getAppAttemptState(); this.appAttemptId = attempt.getAppAttemptId().toString(); Container masterContainer = attempt.getMasterContainer(); if (masterContainer != null && hasAccess) { this.containerId = masterContainer.getId().toString(); this.nodeHttpAddress = masterContainer.getNodeHttpAddress(); this.nodeId = masterContainer.getNodeId().toString(); Configuration conf = rm.getRMContext().getYarnConfiguration(); String logServerUrl = conf.get(YarnConfiguration.YARN_LOG_SERVER_URL); if ((this.appAttemptState == RMAppAttemptState.FAILED || this.appAttemptState == RMAppAttemptState.FINISHED || this.appAttemptState == RMAppAttemptState.KILLED) && logServerUrl != null) { this.logsLink = PATH_JOINER.join(logServerUrl, masterContainer.getNodeId().toString(), masterContainer.getId().toString(), masterContainer.getId().toString(), user); } else { this.logsLink = WebAppUtils.getRunningLogURL(schemePrefix + masterContainer.getNodeHttpAddress(), masterContainer.getId().toString(), user); } Gson gson = new Gson(); this.exportPorts = gson.toJson(masterContainer.getExposedPorts()); nodesBlacklistedBySystem = StringUtils.join(attempt.getAMBlacklistManager() .getBlacklistUpdates().getBlacklistAdditions(), ", "); if (rm.getResourceScheduler() instanceof AbstractYarnScheduler) { AbstractYarnScheduler ayScheduler = (AbstractYarnScheduler) rm.getResourceScheduler(); SchedulerApplicationAttempt sattempt = ayScheduler.getApplicationAttempt(attempt.getAppAttemptId()); if (sattempt != null) { blacklistedNodes = StringUtils.join(sattempt.getBlacklistedNodes(), ", "); } } } } } public int getAttemptId() { return this.id; } public long getStartTime() { return this.startTime; } public long getFinishedTime() { return this.finishedTime; } public String getNodeHttpAddress() { return this.nodeHttpAddress; } public String getLogsLink() { return this.logsLink; } public String getAppAttemptId() { return this.appAttemptId; } public RMAppAttemptState getAppAttemptState() { return this.appAttemptState; } }
AppAttemptInfo
java
elastic__elasticsearch
x-pack/plugin/esql-core/src/main/java/org/elasticsearch/xpack/esql/core/util/Queries.java
{ "start": 623, "end": 2501 }
enum ____ { FILTER(BoolQueryBuilder::filter), MUST(BoolQueryBuilder::must), MUST_NOT(BoolQueryBuilder::mustNot), SHOULD(BoolQueryBuilder::should); final Function<BoolQueryBuilder, List<QueryBuilder>> innerQueries; Clause(Function<BoolQueryBuilder, List<QueryBuilder>> innerQueries) { this.innerQueries = innerQueries; } } /** * Combines the given queries while attempting to NOT create a new bool query and avoid * unnecessary nested queries. * The method tries to detect if the first query is a bool query - if that is the case it will * reuse that for adding the rest of the clauses. */ public static QueryBuilder combine(Clause clause, List<QueryBuilder> queries) { QueryBuilder firstQuery = null; BoolQueryBuilder bool = null; for (QueryBuilder query : queries) { if (query == null) { continue; } if (firstQuery == null) { firstQuery = query; if (firstQuery instanceof BoolQueryBuilder bqb) { bool = bqb.shallowCopy(); } } // at least two entries, start copying else { // lazy init the root bool if (bool == null) { bool = combine(clause, boolQuery(), firstQuery); } // keep adding queries to it bool = combine(clause, bool, query); } } return bool == null ? firstQuery : bool; } private static BoolQueryBuilder combine(Clause clause, BoolQueryBuilder bool, QueryBuilder query) { var list = clause.innerQueries.apply(bool); if (list.contains(query) == false) { list.add(query); } return bool; } }
Clause
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/PrinterEndpointBuilderFactory.java
{ "start": 13736, "end": 14058 }
class ____ extends AbstractEndpointBuilder implements PrinterEndpointBuilder, AdvancedPrinterEndpointBuilder { public PrinterEndpointBuilderImpl(String path) { super(componentName, path); } } return new PrinterEndpointBuilderImpl(path); } }
PrinterEndpointBuilderImpl
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/buildextension/stereotypes/AdditionalStereotypesTest.java
{ "start": 1394, "end": 2372 }
class ____ { @RegisterExtension public ArcTestContainer container = ArcTestContainer.builder() .beanClasses(ToBeStereotype.class, SimpleBinding.class, SimpleInterceptor.class, SomeBean.class) .stereotypeRegistrars(new MyStereotypeRegistrar()) .annotationTransformations(new MyAnnotationTrasnformer()) .build(); @Test public void test() { InstanceHandle<SomeBean> bean = Arc.container().select(SomeBean.class).getHandle(); assertEquals(ApplicationScoped.class, bean.getBean().getScope()); assertEquals("someBean", bean.getBean().getName()); assertTrue(bean.getBean().isAlternative()); assertEquals(11, bean.getBean().getPriority()); SomeBean instance = bean.get(); assertNotNull(instance); assertEquals("intercepted: hello", instance.hello()); } @Target({ TYPE, METHOD, FIELD, PARAMETER }) @Retention(RUNTIME) @
AdditionalStereotypesTest
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableToFutureTest.java
{ "start": 1048, "end": 5094 }
class ____ extends RxJavaTest { @Test public void success() throws Exception { @SuppressWarnings("unchecked") Future<Object> future = mock(Future.class); Object value = new Object(); when(future.get()).thenReturn(value); Observer<Object> o = TestHelper.mockObserver(); TestObserver<Object> to = new TestObserver<>(o); Observable.fromFuture(future).subscribe(to); to.dispose(); verify(o, times(1)).onNext(value); verify(o, times(1)).onComplete(); verify(o, never()).onError(any(Throwable.class)); verify(future, never()).cancel(true); } @Test public void successOperatesOnSuppliedScheduler() throws Exception { @SuppressWarnings("unchecked") Future<Object> future = mock(Future.class); Object value = new Object(); when(future.get()).thenReturn(value); Observer<Object> o = TestHelper.mockObserver(); TestScheduler scheduler = new TestScheduler(); TestObserver<Object> to = new TestObserver<>(o); Observable.fromFuture(future).subscribeOn(scheduler).subscribe(to); verify(o, never()).onNext(value); scheduler.triggerActions(); verify(o, times(1)).onNext(value); } @Test public void failure() throws Exception { @SuppressWarnings("unchecked") Future<Object> future = mock(Future.class); RuntimeException e = new RuntimeException(); when(future.get()).thenThrow(e); Observer<Object> o = TestHelper.mockObserver(); TestObserver<Object> to = new TestObserver<>(o); Observable.fromFuture(future).subscribe(to); to.dispose(); verify(o, never()).onNext(null); verify(o, never()).onComplete(); verify(o, times(1)).onError(e); verify(future, never()).cancel(true); } @Test public void cancelledBeforeSubscribe() throws Exception { @SuppressWarnings("unchecked") Future<Object> future = mock(Future.class); CancellationException e = new CancellationException("unit test synthetic cancellation"); when(future.get()).thenThrow(e); Observer<Object> o = TestHelper.mockObserver(); TestObserver<Object> to = new TestObserver<>(o); to.dispose(); Observable.fromFuture(future).subscribe(to); to.assertNoErrors(); to.assertNotComplete(); } @Test public void cancellationDuringFutureGet() throws Exception { Future<Object> future = new Future<Object>() { private AtomicBoolean isCancelled = new AtomicBoolean(false); private AtomicBoolean isDone = new AtomicBoolean(false); @Override public boolean cancel(boolean mayInterruptIfRunning) { isCancelled.compareAndSet(false, true); return true; } @Override public boolean isCancelled() { return isCancelled.get(); } @Override public boolean isDone() { return isCancelled() || isDone.get(); } @Override public Object get() throws InterruptedException, ExecutionException { Thread.sleep(500); isDone.compareAndSet(false, true); return "foo"; } @Override public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return get(); } }; Observer<Object> o = TestHelper.mockObserver(); TestObserver<Object> to = new TestObserver<>(o); Observable<Object> futureObservable = Observable.fromFuture(future); futureObservable.subscribeOn(Schedulers.computation()).subscribe(to); Thread.sleep(100); to.dispose(); to.assertNoErrors(); to.assertNoValues(); to.assertNotComplete(); } }
ObservableToFutureTest
java
google__guava
android/guava/src/com/google/common/base/internal/Finalizer.java
{ "start": 8255, "end": 9518 }
class ____ * would be resurrected by virtue of us having a strong reference to it), we should pretty * much just shut down and make sure we don't keep it alive any longer than necessary. */ return null; } try { return finalizableReferenceClass.getMethod("finalizeReferent"); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } private static @Nullable Field getInheritableThreadLocalsField() { try { Field inheritableThreadLocals = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocals.setAccessible(true); return inheritableThreadLocals; } catch (Throwable t) { logger.log( Level.INFO, "Couldn't access Thread.inheritableThreadLocals. Reference finalizer threads will " + "inherit thread local values."); return null; } } private static @Nullable Constructor<Thread> getBigThreadConstructor() { try { return Thread.class.getConstructor( ThreadGroup.class, Runnable.class, String.class, long.class, boolean.class); } catch (Throwable t) { // Probably pre Java 9. We'll fall back to Thread.inheritableThreadLocals. return null; } } }
loader
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggesterTest.java
{ "start": 6389, "end": 6882 }
class ____ { @CanIgnoreReturnValue public static StringBuilder append(StringBuilder input, String name) { input.append(name); return input; } } """) .doTest(); } @Test public void returnInputParams_moreComplex() { helper .addInputLines( "ReturnInputParam.java", """ package com.google.frobber; public final
ReturnInputParam
java
spring-projects__spring-boot
configuration-metadata/spring-boot-configuration-processor/src/test/java/org/springframework/boot/configurationsample/lombok/LombokDefaultValueProperties.java
{ "start": 959, "end": 1048 }
class ____ { private String description = "my description"; }
LombokDefaultValueProperties
java
apache__camel
components/camel-graphql/src/main/java/org/apache/camel/component/graphql/GraphqlEndpoint.java
{ "start": 2592, "end": 10604 }
class ____ extends DefaultEndpoint implements EndpointServiceLocation { @UriPath @Metadata(required = true) private URI httpUri; @UriParam private String proxyHost; @UriParam(label = "security", secret = true) private String accessToken; @UriParam(label = "security", secret = true) private String username; @UriParam(label = "security", secret = true) private String password; @UriParam(label = "security", defaultValue = "Bearer") private String jwtAuthorizationType; @UriParam private String query; @UriParam private String queryFile; @UriParam private String operationName; @UriParam private JsonObject variables; @UriParam private String variablesHeader; @UriParam private String queryHeader; @UriParam(label = "advanced") private HttpClient httpClient; @UriParam(label = "producer", defaultValue = "true", description = "Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code.") private boolean throwExceptionOnFailure = true; @UriParam(label = "common,advanced", description = "To use a custom HeaderFilterStrategy to filter header to and from Camel message.") private HeaderFilterStrategy headerFilterStrategy; public GraphqlEndpoint(String uri, Component component) { super(uri, component); } @Override public String getServiceUrl() { if (httpUri != null) { return httpUri.toString(); } return null; } @Override public Map<String, String> getServiceMetadata() { if (username != null) { return Map.of("username", username); } return null; } @Override protected void doStart() throws Exception { super.doStart(); if (headerFilterStrategy == null) { headerFilterStrategy = new HttpHeaderFilterStrategy(); } } @Override public String getServiceProtocol() { return "rest"; } @Override public Producer createProducer() throws Exception { return new GraphqlProducer(this); } @Override public Consumer createConsumer(Processor processor) throws Exception { throw new UnsupportedOperationException("You cannot receive messages at this endpoint: " + getEndpointUri()); } CloseableHttpClient createHttpClient() { HttpClientBuilder httpClientBuilder = HttpClients.custom(); if (proxyHost != null) { String[] parts = proxyHost.split(":"); String hostname = parts[0]; int port = Integer.parseInt(parts[1]); httpClientBuilder.setProxy(new HttpHost(hostname, port)); } if (accessToken != null) { String authType = "Bearer"; if (this.jwtAuthorizationType != null) { authType = this.jwtAuthorizationType; } httpClientBuilder.setDefaultHeaders( Arrays.asList(new BasicHeader(HttpHeaders.AUTHORIZATION, authType + " " + accessToken))); } if (username != null && password != null) { CredentialsStore credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(null, -1), new UsernamePasswordCredentials(username, password.toCharArray())); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } return httpClientBuilder.build(); } public URI getHttpUri() { return httpUri; } /** * The GraphQL server URI. */ public void setHttpUri(URI httpUri) { this.httpUri = httpUri; } public String getProxyHost() { return proxyHost; } /** * The proxy host in the format "hostname:port". */ public void setProxyHost(String proxyHost) { this.proxyHost = proxyHost; } public String getAccessToken() { return accessToken; } /** * The access token sent in the Authorization header. */ public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public String getUsername() { return username; } /** * The username for Basic authentication. */ public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } /** * The password for Basic authentication. */ public void setPassword(String password) { this.password = password; } public String getQuery() { if (query == null && queryFile != null) { InputStream is = null; try { is = ResourceHelper.resolveResourceAsInputStream(getCamelContext(), queryFile); query = IOHelper.loadText(is); } catch (IOException e) { throw new RuntimeCamelException("Failed to read query file: " + queryFile, e); } finally { IOHelper.close(is); } } return query; } /** * The JWT Authorization type. Default is Bearer. */ public void setJwtAuthorizationType(String jwtAuthorizationType) { this.jwtAuthorizationType = jwtAuthorizationType; } public String getJwtAuthorizationType() { return this.jwtAuthorizationType; } /** * The query text. */ public void setQuery(String query) { this.query = query; } public String getQueryFile() { return queryFile; } /** * The query file name located in the classpath (or use file: to load from file system). */ public void setQueryFile(String queryFile) { this.queryFile = queryFile; } public String getOperationName() { return operationName; } /** * The query or mutation name. */ public void setOperationName(String operationName) { this.operationName = operationName; } public JsonObject getVariables() { return variables; } /** * The JsonObject instance containing the operation variables. */ public void setVariables(JsonObject variables) { this.variables = variables; } public String getVariablesHeader() { return variablesHeader; } /** * The name of a header containing a JsonObject instance containing the operation variables. */ public void setVariablesHeader(String variablesHeader) { this.variablesHeader = variablesHeader; } public String getQueryHeader() { return queryHeader; } /** * The name of a header containing the GraphQL query. */ public void setQueryHeader(String queryHeader) { this.queryHeader = queryHeader; } public HttpClient getHttpClient() { return httpClient; } /** * To use a custom pre-existing Http Client. Beware that when using this, then other configurations such as proxy, * access token, is not applied and all this must be pre-configured on the Http Client. */ public void setHttpClient(HttpClient httpClient) { this.httpClient = httpClient; } public boolean isThrowExceptionOnFailure() { return throwExceptionOnFailure; } public void setThrowExceptionOnFailure(boolean throwExceptionOnFailure) { this.throwExceptionOnFailure = throwExceptionOnFailure; } public HeaderFilterStrategy getHeaderFilterStrategy() { return headerFilterStrategy; } public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) { this.headerFilterStrategy = headerFilterStrategy; } @Override public boolean isLenientProperties() { return true; } }
GraphqlEndpoint
java
apache__camel
components/camel-csv/src/main/java/org/apache/camel/dataformat/csv/CsvRecordConverters.java
{ "start": 1494, "end": 2286 }
class ____ implements CsvRecordConverter<List<String>> { private static final ListCsvRecordConverter SINGLETON = new ListCsvRecordConverter(); @Override public List<String> convertRecord(CSVRecord csvRecord) { List<String> answer = new ArrayList<>(csvRecord.size()); for (int i = 0; i < csvRecord.size(); i++) { answer.add(csvRecord.get(i)); } return answer; } } /** * Returns a converter that transforms the CSV record into a map. * * @return converter that transforms the CSV record into a map */ public static CsvRecordConverter<Map<String, String>> mapConverter() { return MapCsvRecordConverter.SINGLETON; } private static
ListCsvRecordConverter
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/event/InlineDispatcher.java
{ "start": 1092, "end": 1677 }
class ____ implements EventHandler { @Override public void handle(Event event) { dispatch(event); } } @Override protected void dispatch(Event event) { LOG.info("Dispatching the event " + event.getClass().getName() + "." + event.toString()); Class<? extends Enum> type = event.getType().getDeclaringClass(); if (eventDispatchers.get(type) != null) { eventDispatchers.get(type).handle(event); } } @Override public EventHandler<Event> getEventHandler() { return new TestEventHandler(); } public static
TestEventHandler
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/aggregate/OracleAggregateSupport.java
{ "start": 26922, "end": 30116 }
class ____ implements JsonWriteExpression { private final boolean colonSyntax; private final LinkedHashMap<String, JsonWriteExpression> subExpressions = new LinkedHashMap<>(); protected final EmbeddableMappingType embeddableMappingType; protected final String ddlTypeName; public AggregateJsonWriteExpression(SelectableMapping selectableMapping, OracleAggregateSupport aggregateSupport) { this.colonSyntax = aggregateSupport.jsonSupport == JsonSupport.OSON || aggregateSupport.jsonSupport == JsonSupport.MERGEPATCH; this.embeddableMappingType = ( (AggregateJdbcType) selectableMapping.getJdbcMapping().getJdbcType() ) .getEmbeddableMappingType(); this.ddlTypeName = aggregateSupport.determineJsonTypeName( selectableMapping ); } protected void initializeSubExpressions( SelectableMapping[] columns, OracleAggregateSupport aggregateSupport, TypeConfiguration typeConfiguration) { for ( SelectableMapping column : columns ) { final SelectablePath selectablePath = column.getSelectablePath(); final SelectablePath[] parts = selectablePath.getParts(); AggregateJsonWriteExpression currentAggregate = this; EmbeddableMappingType currentMappingType = embeddableMappingType; for ( int i = 1; i < parts.length - 1; i++ ) { final SelectableMapping selectableMapping = currentMappingType.getJdbcValueSelectable( currentMappingType.getSelectableIndex( parts[i].getSelectableName() ) ); currentAggregate = (AggregateJsonWriteExpression) currentAggregate.subExpressions.computeIfAbsent( parts[i].getSelectableName(), k -> new AggregateJsonWriteExpression( selectableMapping, aggregateSupport ) ); currentMappingType = currentAggregate.embeddableMappingType; } final String customWriteExpression = column.getWriteExpression(); currentAggregate.subExpressions.put( parts[parts.length - 1].getSelectableName(), new BasicJsonWriteExpression( column, aggregateSupport.jsonCustomWriteExpression( customWriteExpression, column.getJdbcMapping(), column, typeConfiguration ), colonSyntax ) ); } } @Override public void append( SqlAppender sb, String path, SqlAstTranslator<?> translator, AggregateColumnWriteExpression expression) { sb.append( "json_object" ); char separator = '('; for ( Map.Entry<String, JsonWriteExpression> entry : subExpressions.entrySet() ) { final String column = entry.getKey(); final JsonWriteExpression value = entry.getValue(); final String subPath = path + "->'" + column + "'"; sb.append( separator ); if ( value instanceof AggregateJsonWriteExpression ) { sb.append( '\'' ); sb.append( column ); if ( colonSyntax ) { sb.append( "':" ); } else { sb.append( "' value " ); } value.append( sb, subPath, translator, expression ); } else { value.append( sb, subPath, translator, expression ); } separator = ','; } sb.append( " returning " ); sb.append( ddlTypeName ); sb.append( ')' ); } } private static
AggregateJsonWriteExpression
java
spring-projects__spring-framework
spring-core-test/src/test/java/org/springframework/core/test/tools/CompiledTests.java
{ "start": 1010, "end": 1115 }
class ____ { private static final String HELLO_WORLD = """ package com.example; public
CompiledTests
java
quarkusio__quarkus
integration-tests/virtual-threads/virtual-threads-disabled/src/main/java/io/quarkus/virtual/disabled/MyResourceWithVTOnClass.java
{ "start": 386, "end": 1303 }
class ____ { private final Counter counter; MyResourceWithVTOnClass(Counter counter) { this.counter = counter; } @GET public String testGet() { VirtualThreadsAssertions.assertWorkerOrEventLoopThread(); return "hello-" + counter.increment(); } @POST public String testPost(String body) { VirtualThreadsAssertions.assertWorkerOrEventLoopThread(); return body + "-" + counter.increment(); } @GET @Path("/uni") @Blocking // Mandatory, because it's really a weird case public Uni<String> testUni() { return Uni.createFrom().item("ok"); } @GET @Path("/multi") @Blocking // Mandatory, because it's really a weird case public Multi<String> testMulti() { VirtualThreadsAssertions.assertWorkerOrEventLoopThread(); return Multi.createFrom().items("o", "k"); } }
MyResourceWithVTOnClass
java
apache__hadoop
hadoop-tools/hadoop-gcp/src/test/java/org/apache/hadoop/fs/gs/contract/ITestGoogleContractGetFileStatus.java
{ "start": 1032, "end": 1238 }
class ____ extends AbstractContractGetFileStatusTest { @Override protected AbstractFSContract createContract(Configuration conf) { return new GoogleContract(conf); } }
ITestGoogleContractGetFileStatus
java
apache__camel
components/camel-soap/src/main/java/org/apache/camel/dataformat/soap/name/MethodInfo.java
{ "start": 1134, "end": 2847 }
class ____ { private String name; private String soapAction; private TypeInfo[] in; private TypeInfo out; // map of type name to qname private Map<String, TypeInfo> inTypeMap; /** * Initialize * * @param name method name * @param soapAction * @param in input parameters * @param out return types */ public MethodInfo(String name, String soapAction, TypeInfo[] in, TypeInfo out) { this.name = name; this.soapAction = soapAction; this.in = in; this.out = out; this.inTypeMap = new HashMap<>(); for (TypeInfo typeInfo : in) { if (inTypeMap.containsKey(typeInfo.getTypeName()) && !typeInfo.getTypeName().equals("jakarta.xml.ws.Holder") && !inTypeMap.get(typeInfo.getTypeName()).getElName().equals(typeInfo.getElName())) { throw new RuntimeCamelException( "Ambiguous QName mapping. The type [ " + typeInfo.getTypeName() + " ] is already mapped to a QName in this method." + " This is not supported."); } inTypeMap.put(typeInfo.getTypeName(), typeInfo); } } public String getName() { return name; } public String getSoapAction() { return soapAction; } public TypeInfo[] getIn() { return in; } public TypeInfo getOut() { return out; } public TypeInfo getIn(String typeName) { return this.inTypeMap.get(typeName); } }
MethodInfo
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/test/java/org/apache/hadoop/mapreduce/TestTaskID.java
{ "start": 1531, "end": 1972 }
class ____. */ @Test public void testGetJobID() { JobID jobId = new JobID("1234", 0); TaskID taskId = new TaskID(jobId, TaskType.MAP, 0); assertSame(jobId, taskId.getJobID(), "TaskID did not store the JobID correctly"); taskId = new TaskID(); assertEquals("", taskId.getJobID().getJtIdentifier(), "Job ID was set unexpectedly in default constructor"); } /** * Test of isMap method, of
TaskID
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/cluster/snapshots/get/SnapshotNamePredicate.java
{ "start": 1109, "end": 4965 }
interface ____ { /** * @return Whether a snapshot with the given name should be selected. */ boolean test(String snapshotName, boolean isCurrentSnapshot); /** * @return the snapshot names that must be present in a repository. If one of these snapshots is missing then this repository should * yield a {@link SnapshotMissingException} rather than any snapshots. */ Collection<String> requiredNames(); /** * A {@link SnapshotNamePredicate} which matches all snapshots (and requires no specific names). */ SnapshotNamePredicate MATCH_ALL = new SnapshotNamePredicate() { @Override public boolean test(String snapshotName, boolean isCurrentSnapshot) { return true; } @Override public Collection<String> requiredNames() { return Collections.emptyList(); } }; /** * A {@link SnapshotNamePredicate} which matches all currently-executing snapshots (and requires no specific names). */ SnapshotNamePredicate MATCH_CURRENT_ONLY = new SnapshotNamePredicate() { @Override public boolean test(String snapshotName, boolean isCurrentSnapshot) { return isCurrentSnapshot; } @Override public Collection<String> requiredNames() { return Collections.emptyList(); } }; /** * @return a {@link SnapshotNamePredicate} from the given {@link GetSnapshotsRequest} parameters. */ static SnapshotNamePredicate forSnapshots(boolean ignoreUnavailable, String[] snapshots) { if (ResolvedRepositories.isMatchAll(snapshots)) { return MATCH_ALL; } if (snapshots.length == 1 && GetSnapshotsRequest.CURRENT_SNAPSHOT.equalsIgnoreCase(snapshots[0])) { return MATCH_CURRENT_ONLY; } final List<String> includesBuilder = new ArrayList<>(snapshots.length); final List<String> excludesBuilder = new ArrayList<>(snapshots.length); final Set<String> requiredNamesBuilder = ignoreUnavailable ? null : Sets.newHashSetWithExpectedSize(snapshots.length); boolean seenCurrent = false; boolean seenWildcard = false; for (final var snapshot : snapshots) { if (seenWildcard && snapshot.length() > 1 && snapshot.startsWith("-")) { excludesBuilder.add(snapshot.substring(1)); } else { if (Regex.isSimpleMatchPattern(snapshot)) { seenWildcard = true; includesBuilder.add(snapshot); } else if (GetSnapshotsRequest.CURRENT_SNAPSHOT.equalsIgnoreCase(snapshot)) { seenCurrent = true; seenWildcard = true; } else { if (ignoreUnavailable == false) { requiredNamesBuilder.add(snapshot); } includesBuilder.add(snapshot); } } } final boolean includeCurrent = seenCurrent; final String[] includes = includesBuilder.toArray(Strings.EMPTY_ARRAY); final String[] excludes = excludesBuilder.toArray(Strings.EMPTY_ARRAY); final Set<String> requiredNames = requiredNamesBuilder == null ? Set.of() : Set.copyOf(requiredNamesBuilder); return new SnapshotNamePredicate() { @Override public boolean test(String snapshotName, boolean isCurrentSnapshot) { return ((includeCurrent && isCurrentSnapshot) || Regex.simpleMatch(includes, snapshotName)) && (Regex.simpleMatch(excludes, snapshotName) == false); } @Override public Collection<String> requiredNames() { return requiredNames; } }; } }
SnapshotNamePredicate
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java
{ "start": 6819, "end": 6962 }
class ____; {@code false} otherwise */ static boolean isConfigurationCandidate(AnnotationMetadata metadata) { // Do not consider an
processing
java
apache__camel
components/camel-lucene/src/main/java/org/apache/camel/component/lucene/LuceneConfiguration.java
{ "start": 5190, "end": 5663 }
class ____ extends the abstract class * org.apache.lucene.analysis.Analyzer. Lucene also offers a rich set of analyzers out of the box */ public void setAnalyzer(Analyzer analyzer) { this.analyzer = analyzer; } public int getMaxHits() { return maxHits; } /** * An integer value that limits the result set of the search operation */ public void setMaxHits(int maxHits) { this.maxHits = maxHits; } }
that
java
mockito__mockito
mockito-integration-tests/programmatic-tests/src/test/java/org/mockito/ProgrammaticMockMakerTest.java
{ "start": 7153, "end": 7474 }
class ____ { final String finalMethod() { return "ORIGINAL"; } final String finalMethodCallingNonFinal() { nonFinal(); return "ORIGINAL"; } String nonFinal() { return "ORIGINAL"; } } private static
ClassWithFinalMethod
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/protocol/AddMountTableEntriesRequest.java
{ "start": 1268, "end": 1879 }
class ____ { public static AddMountTableEntriesRequest newInstance() { return StateStoreSerializer.newRecord(AddMountTableEntriesRequest.class); } public static AddMountTableEntriesRequest newInstance(List<MountTable> newEntry) { AddMountTableEntriesRequest request = newInstance(); request.setEntries(newEntry); return request; } @InterfaceAudience.Public @InterfaceStability.Unstable public abstract List<MountTable> getEntries(); @InterfaceAudience.Public @InterfaceStability.Unstable public abstract void setEntries(List<MountTable> mount); }
AddMountTableEntriesRequest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idclass/IdClassWithSuperclassTest.java
{ "start": 730, "end": 1159 }
class ____ { @Test public void testSaveAndGet(SessionFactoryScope scope) { scope.inTransaction( session -> { MyEntity myEntity = new MyEntity( 1, 2 ); session.persist( myEntity ); } ); scope.inTransaction( session -> { MyEntity myEntity = session.get( MyEntity.class, new ChildPrimaryKey( 1, 2 ) ); assertThat( myEntity ).isNotNull(); } ); } public static
IdClassWithSuperclassTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/vector/VectorSimilarityFunction.java
{ "start": 10425, "end": 10648 }
interface ____ extends Releasable { void eval(Page page); float[] getVector(int position); int getDimensions(); void finish(); long baseRamBytesUsed(); }
VectorValueProvider
java
grpc__grpc-java
xds/src/generated/thirdparty/grpc/io/envoyproxy/envoy/service/rate_limit_quota/v3/RateLimitQuotaServiceGrpc.java
{ "start": 13594, "end": 13785 }
class ____ extends RateLimitQuotaServiceBaseDescriptorSupplier { RateLimitQuotaServiceFileDescriptorSupplier() {} } private static final
RateLimitQuotaServiceFileDescriptorSupplier
java
google__guice
extensions/servlet/test/com/google/inject/servlet/ContextPathTest.java
{ "start": 9527, "end": 9910 }
class ____ implements FilterChain { private boolean triggered = false; @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { triggered = true; } public boolean isTriggered() { return triggered; } public void clear() { triggered = false; } } }
TestFilterChain
java
apache__spark
common/kvstore/src/main/java/org/apache/spark/util/kvstore/InMemoryStore.java
{ "start": 15752, "end": 16594 }
class ____<T> implements KVStoreIterator<T> { private final Iterator<T> iter; InMemoryIterator(Iterator<T> iter) { this.iter = iter; } @Override public boolean hasNext() { return iter.hasNext(); } @Override public T next() { return iter.next(); } @Override public List<T> next(int max) { List<T> list = new ArrayList<>(max); while (hasNext() && list.size() < max) { list.add(next()); } return list; } @Override public boolean skip(long n) { long skipped = 0; while (skipped < n) { if (hasNext()) { next(); skipped++; } else { return false; } } return hasNext(); } @Override public void close() { // no op. } } }
InMemoryIterator
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/TestContextAnnotationUtilsTests.java
{ "start": 2348, "end": 3428 }
class ____ { @BeforeEach @AfterEach void clearCaches() { TestContextAnnotationUtils.clearCaches(); } @AfterEach void clearGlobalFlag() { setGlobalFlag(null); } @Test void standardDefaultMode() { assertThat(searchEnclosingClass(OuterTestCase.class)).isFalse(); assertThat(searchEnclosingClass(OuterTestCase.NestedTestCase.class)).isTrue(); assertThat(searchEnclosingClass(OuterTestCase.NestedTestCase.DoubleNestedTestCase.class)).isTrue(); } @Test void overriddenDefaultMode() { setGlobalFlag("\t" + OVERRIDE.name().toLowerCase() + " "); assertThat(searchEnclosingClass(OuterTestCase.class)).isFalse(); assertThat(searchEnclosingClass(OuterTestCase.NestedTestCase.class)).isFalse(); assertThat(searchEnclosingClass(OuterTestCase.NestedTestCase.DoubleNestedTestCase.class)).isFalse(); } private void setGlobalFlag(String flag) { SpringProperties.setProperty(NestedTestConfiguration.ENCLOSING_CONFIGURATION_PROPERTY_NAME, flag); } } @Nested @DisplayName("findAnnotationDescriptor() tests")
SearchEnclosingClassTests
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProvider.java
{ "start": 7007, "end": 13246 }
class ____ the JDBC URL for ( var database: Database.values() ) { if ( database.matchesUrl( url ) ) { final String databaseDriverClassName = database.getDriverClassName( url ); if ( databaseDriverClassName != null ) { try { return loadDriverIfPossible( databaseDriverClassName, serviceRegistry ); } catch (Exception e) { // swallow it, since this was not an explicit setting by the user } } } } return null; } } private static void logAvailableDrivers() { CONNECTION_INFO_LOGGER.jdbcDriverNotSpecified(); final var list = new StringBuilder(); DriverManager.drivers() .forEach( driver -> { if ( !list.isEmpty() ) { list.append( ", " ); } list.append( driver.getClass().getName() ); } ); CONNECTION_INFO_LOGGER.availableJdbcDrivers( list.toString() ); } private static String jdbcUrl(Map<String, Object> configuration) { final String url = (String) configuration.get( URL ); if ( url == null ) { throw new ConnectionProviderConfigurationException( "No JDBC URL specified by property '" + JAKARTA_JDBC_URL + "'" ); } return url; } private static ConnectionCreatorFactory getConnectionCreatorFactory( Map<String, Object> configuration, ServiceRegistry serviceRegistry) { final Object connectionCreatorFactory = configuration.get( CONNECTION_CREATOR_FACTORY ); final ConnectionCreatorFactory factory; if ( connectionCreatorFactory instanceof ConnectionCreatorFactory instance ) { factory = instance; } else if ( connectionCreatorFactory != null ) { factory = loadConnectionCreatorFactory( connectionCreatorFactory.toString(), serviceRegistry ); } else { factory = null; } return factory == null ? ConnectionCreatorFactoryImpl.INSTANCE : factory; } private static Driver loadDriverIfPossible(String driverClassName, ServiceRegistry serviceRegistry) { if ( driverClassName == null ) { CONNECTION_INFO_LOGGER.noDriverClassSpecified(); return null; } else if ( serviceRegistry != null ) { final Class<Driver> driverClass = serviceRegistry.requireService( ClassLoaderService.class ) .classForName( driverClassName ); try { return driverClass.newInstance(); } catch ( Exception e ) { throw new ServiceException( "Specified JDBC Driver " + driverClassName + " could not be loaded", e ); } } else { try { return (Driver) Class.forName( driverClassName ).newInstance(); } catch (Exception e1) { throw new ServiceException( "Specified JDBC Driver " + driverClassName + " could not be loaded", e1 ); } } } private static ConnectionCreatorFactory loadConnectionCreatorFactory( String connectionCreatorFactoryClassName, ServiceRegistry serviceRegistry) { if ( connectionCreatorFactoryClassName == null ) { CONNECTION_INFO_LOGGER.noConnectionCreatorFactoryClassSpecified(); return null; } else if ( serviceRegistry != null ) { final Class<ConnectionCreatorFactory> factoryClass = serviceRegistry.requireService( ClassLoaderService.class ) .classForName( connectionCreatorFactoryClassName ); try { return factoryClass.newInstance(); } catch ( Exception e ) { throw new ServiceException( "Specified ConnectionCreatorFactory " + connectionCreatorFactoryClassName + " could not be loaded", e ); } } else { try { return (ConnectionCreatorFactory) Class.forName( connectionCreatorFactoryClassName ).newInstance(); } catch (Exception e1) { throw new ServiceException( "Specified ConnectionCreatorFactory " + connectionCreatorFactoryClassName + " could not be loaded", e1 ); } } } // use the pool ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override public Connection getConnection() throws SQLException { if ( state == null ) { throw new IllegalStateException( "Cannot get a connection as the driver manager is not properly initialized" ); } return state.getConnection(); } @Override public void closeConnection(Connection connection) throws SQLException { if ( state == null ) { throw new IllegalStateException( "Cannot close a connection as the driver manager is not properly initialized" ); } state.closeConnection( connection ); } @Override public boolean supportsAggressiveRelease() { return false; } @Override public DatabaseConnectionInfo getDatabaseConnectionInfo(Dialect dialect) { return new DatabaseConnectionInfoImpl( DriverManagerConnectionProvider.class, dbInfo.getJdbcUrl(), dbInfo.getJdbcDriver(), dialect.getClass(), dialect.getVersion(), dbInfo.hasSchema(), dbInfo.hasCatalog(), dbInfo.getSchema(), dbInfo.getCatalog(), dbInfo.getAutoCommitMode(), dbInfo.getIsolationLevel(), dbInfo.getPoolMinSize(), dbInfo.getPoolMaxSize(), dbInfo.getJdbcFetchSize() ); } @Override public boolean isUnwrappableAs(Class<?> unwrapType) { return unwrapType.isAssignableFrom( DriverManagerConnectionProvider.class ); } @Override @SuppressWarnings( {"unchecked"}) public <T> T unwrap(Class<T> unwrapType) { if ( unwrapType.isAssignableFrom( DriverManagerConnectionProvider.class ) ) { return (T) this; } else { throw new UnknownUnwrapTypeException( unwrapType ); } } protected int getOpenConnections() { return state.getPool().getOpenConnectionCount(); } protected void validateConnectionsReturned() { final int allocationCount = getOpenConnections(); if ( allocationCount != 0 ) { CONNECTION_INFO_LOGGER.connectionLeakDetected( allocationCount ); } } protected void validateConnections(ConnectionValidator validator) { state.validateConnections( validator ); } // destroy the pool ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override public void stop() { if ( state != null ) { state.stop(); validateConnectionsReturned(); } } @Override protected void finalize() throws Throwable { if ( state != null ) { state.stop(); } super.finalize(); } @Override public boolean isValid(Connection connection) throws SQLException { return true; } }
from
java
google__auto
value/src/test/java/com/google/auto/value/processor/ExtensionTest.java
{ "start": 34735, "end": 36001 }
class ____ extends AutoValueExtension { @Override public boolean applicable(Context context) { return true; } @Override public boolean mustBeFinal(Context context) { return false; } @Override public String generateClass( Context context, String className, String classToExtend, boolean isFinal) { String sideClassName = "Side_" + context.autoValueClass().getSimpleName(); String sideClass = "" // + "package " + context.packageName() + ";\n" + "class " + sideClassName + " {}\n"; Filer filer = context.processingEnvironment().getFiler(); try { String sideClassFqName = context.packageName() + "." + sideClassName; JavaFileObject sourceFile = filer.createSourceFile(sideClassFqName, context.autoValueClass()); try (Writer sourceWriter = sourceFile.openWriter()) { sourceWriter.write(sideClass); } } catch (IOException e) { context .processingEnvironment() .getMessager() .printMessage(Diagnostic.Kind.ERROR, e.toString()); } return null; } } private static
SideFileExtension
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/internal/util/beans/BeanInfoHelper.java
{ "start": 417, "end": 518 }
interface ____ { void processBeanInfo(BeanInfo beanInfo) throws Exception; } public
BeanInfoDelegate
java
apache__logging-log4j2
log4j-fuzz-test/src/main/java/org/apache/logging/log4j/fuzz/EncodingAppender.java
{ "start": 1692, "end": 2623 }
class ____ extends AbstractAppender { public static final String PLUGIN_NAME = "EncodingAppender"; private EncodingAppender(final String name, final Layout<? extends Serializable> layout) { super(name, null, layout, true, null); // Guard `PLUGIN_NAME` against copy-paste mistakes assertThat(PLUGIN_NAME).isEqualTo(getClass().getSimpleName()); } @PluginFactory public static EncodingAppender createAppender( final @PluginAttribute("name") String name, final @PluginElement("layout") Layout<?> layout) { return new EncodingAppender(name, layout); } @Override public void append(final LogEvent event) { try { getLayout().toByteArray(event); } catch (final Exception ignored) { // We are inspecting unexpected access. // Hence, event encoding failures are not of interest. } } }
EncodingAppender
java
elastic__elasticsearch
x-pack/plugin/eql/src/test/java/org/elasticsearch/xpack/eql/expression/function/scalar/string/SubstringFunctionPipeTests.java
{ "start": 1149, "end": 6093 }
class ____ extends AbstractNodeTestCase<SubstringFunctionPipe, Pipe> { @Override protected SubstringFunctionPipe randomInstance() { return randomSubstringFunctionPipe(); } private Expression randomSubstringFunctionExpression() { return randomSubstringFunctionPipe().expression(); } public static SubstringFunctionPipe randomSubstringFunctionPipe() { return (SubstringFunctionPipe) (new Substring( randomSource(), randomStringLiteral(), randomIntLiteral(), randomFrom(true, false) ? randomIntLiteral() : null ).makePipe()); } @Override public void testTransform() { // test transforming only the properties (source, expression), // skipping the children (input, start, end) which are tested separately SubstringFunctionPipe b1 = randomInstance(); Expression newExpression = randomValueOtherThan(b1.expression(), () -> randomSubstringFunctionExpression()); SubstringFunctionPipe newB = new SubstringFunctionPipe(b1.source(), newExpression, b1.input(), b1.start(), b1.end()); assertEquals(newB, b1.transformPropertiesOnly(Expression.class, v -> Objects.equals(v, b1.expression()) ? newExpression : v)); SubstringFunctionPipe b2 = randomInstance(); Source newLoc = randomValueOtherThan(b2.source(), () -> randomSource()); newB = new SubstringFunctionPipe(newLoc, b2.expression(), b2.input(), b2.start(), b2.end()); assertEquals(newB, b2.transformPropertiesOnly(Source.class, v -> Objects.equals(v, b2.source()) ? newLoc : v)); } @Override public void testReplaceChildren() { SubstringFunctionPipe b = randomInstance(); Pipe newInput = randomValueOtherThan(b.input(), () -> pipe(randomStringLiteral())); Pipe newStart = randomValueOtherThan(b.start(), () -> pipe(randomIntLiteral())); Pipe newEnd = b.end() == null ? null : randomValueOtherThan(b.end(), () -> pipe(randomIntLiteral())); SubstringFunctionPipe newB = new SubstringFunctionPipe(b.source(), b.expression(), b.input(), b.start(), b.end()); SubstringFunctionPipe transformed = null; // generate all the combinations of possible children modifications and test all of them for (int i = 1; i < 4; i++) { for (BitSet comb : new Combinations(3, i)) { Pipe tempNewEnd = b.end() == null ? b.end() : (comb.get(2) ? newEnd : b.end()); transformed = newB.replaceChildren(comb.get(0) ? newInput : b.input(), comb.get(1) ? newStart : b.start(), tempNewEnd); assertEquals(transformed.input(), comb.get(0) ? newInput : b.input()); assertEquals(transformed.start(), comb.get(1) ? newStart : b.start()); assertEquals(transformed.end(), tempNewEnd); assertEquals(transformed.expression(), b.expression()); assertEquals(transformed.source(), b.source()); } } } @Override protected SubstringFunctionPipe mutate(SubstringFunctionPipe instance) { List<Function<SubstringFunctionPipe, SubstringFunctionPipe>> randoms = new ArrayList<>(); if (instance.end() == null) { for (int i = 1; i < 3; i++) { for (BitSet comb : new Combinations(2, i)) { randoms.add( f -> new SubstringFunctionPipe( f.source(), f.expression(), comb.get(0) ? randomValueOtherThan(f.input(), () -> pipe(randomStringLiteral())) : f.input(), comb.get(1) ? randomValueOtherThan(f.start(), () -> pipe(randomIntLiteral())) : f.start(), null ) ); } } } else { for (int i = 1; i < 4; i++) { for (BitSet comb : new Combinations(3, i)) { randoms.add( f -> new SubstringFunctionPipe( f.source(), f.expression(), comb.get(0) ? randomValueOtherThan(f.input(), () -> pipe(randomStringLiteral())) : f.input(), comb.get(1) ? randomValueOtherThan(f.start(), () -> pipe(randomIntLiteral())) : f.start(), comb.get(2) ? randomValueOtherThan(f.end(), () -> pipe(randomIntLiteral())) : f.end() ) ); } } } return randomFrom(randoms).apply(instance); } @Override protected SubstringFunctionPipe copy(SubstringFunctionPipe instance) { return new SubstringFunctionPipe(instance.source(), instance.expression(), instance.input(), instance.start(), instance.end()); } }
SubstringFunctionPipeTests
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TestInstanceFactoryTests.java
{ "start": 22839, "end": 23052 }
class ____ { @Test void innerTest2() { callSequence.add("innerTest2"); } } } } @SuppressWarnings("JUnitMalformedDeclaration") @ExtendWith(FooInstanceFactory.class) static
InnerInnerTestCase
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/core/Completable.java
{ "start": 1950, "end": 2772 }
interface ____ the default consumer * type it interacts with is the {@link CompletableObserver} via the {@link #subscribe(CompletableObserver)} method. * The {@code Completable} operates with the following sequential protocol: * <pre><code> * onSubscribe (onError | onComplete)? * </code></pre> * <p> * Note that as with the {@code Observable} protocol, {@code onError} and {@code onComplete} are mutually exclusive events. * <p> * Like {@code Observable}, a running {@code Completable} can be stopped through the {@link Disposable} instance * provided to consumers through {@link CompletableObserver#onSubscribe}. * <p> * Like an {@code Observable}, a {@code Completable} is lazy, can be either "hot" or "cold", synchronous or * asynchronous. {@code Completable} instances returned by the methods of this
and
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/idmanytoone/IdManyToOneTest.java
{ "start": 1732, "end": 4127 }
class ____ implements SettingProvider.Provider<ImplicitNamingStrategy> { @Override public ImplicitNamingStrategy getSetting() { return ImplicitNamingStrategyJpaCompliantImpl.INSTANCE; } } @Test public void testFkCreationOrdering(SessionFactoryScope scope) { //no real test case, the sessionFactory building is tested scope.inTransaction( session -> { } ); } @Test public void testIdClassManyToOne(SessionFactoryScope scope) { scope.inTransaction( s -> { Store store = new Store(); Customer customer = new Customer(); s.persist( store ); s.persist( customer ); StoreCustomer sc = new StoreCustomer( store, customer ); s.persist( sc ); s.flush(); s.clear(); store = s.find( Store.class, store.id ); assertThat( store.customers.size() ).isEqualTo( 1 ); assertThat( store.customers.iterator().next().customer.id ).isEqualTo( customer.id ); } ); //TODO test Customers / ShoppingBaskets / BasketItems testIdClassManyToOneWithReferenceColumn } @Test @JiraKey(value = "HHH-7767") public void testCriteriaRestrictionOnIdManyToOne(SessionFactoryScope scope) { scope.inTransaction( s -> { s.createQuery( "from Course c join c.students cs join cs.student s where s.name = 'Foo'", Object[].class ) .list(); CriteriaBuilder criteriaBuilder = s.getCriteriaBuilder(); CriteriaQuery<Course> criteria = criteriaBuilder.createQuery( Course.class ); Root<Course> root = criteria.from( Course.class ); Join<Object, Object> students = root.join( "students", JoinType.INNER ); Join<Object, Object> student = students.join( "student", JoinType.INNER ); criteria.where( criteriaBuilder.equal( student.get( "name" ), "Foo" ) ); s.createQuery( criteria ).list(); // Criteria criteria = s.createCriteria( Course.class ); // criteria.createCriteria( "students" ).createCriteria( "student" ).add( Restrictions.eq( "name", "Foo" ) ); // criteria.list(); // CriteriaQuery<Course> criteria2 = criteriaBuilder.createQuery( Course.class ); // Criteria criteria2 = s.createCriteria( Course.class ); // criteria2.createAlias( "students", "cs" ); // criteria2.add( Restrictions.eq( "cs.value", "Bar" ) ); // criteria2.createAlias( "cs.student", "s" ); // criteria2.add( Restrictions.eq( "s.name", "Foo" ) ); // criteria2.list(); } ); } }
ImplicitNameSettingProvider
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DisruptorVmComponentBuilderFactory.java
{ "start": 1396, "end": 1898 }
interface ____ { /** * Disruptor VM (camel-disruptor) * Provides asynchronous SEDA behavior using LMAX Disruptor. * * Category: messaging * Since: 2.12 * Maven coordinates: org.apache.camel:camel-disruptor * * @return the dsl builder */ static DisruptorVmComponentBuilder disruptorVm() { return new DisruptorVmComponentBuilderImpl(); } /** * Builder for the Disruptor VM component. */
DisruptorVmComponentBuilderFactory
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/scripting/LanguageDriver.java
{ "start": 2780, "end": 3457 }
class ____ an xml file. * * @param configuration * The MyBatis configuration * @param script * The content of the annotation * @param parameterType * input parameter type got from a mapper method or specified in the parameterType xml attribute. Can be * null. * * @return the sql source */ SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType); default SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType, ParamNameResolver paramNameResolver) { return createSqlSource(configuration, script, parameterType); } }
or
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableDebounceTest.java
{ "start": 1603, "end": 22459 }
class ____ extends RxJavaTest { private TestScheduler scheduler; private Observer<String> observer; private Scheduler.Worker innerScheduler; @Before public void before() { scheduler = new TestScheduler(); observer = TestHelper.mockObserver(); innerScheduler = scheduler.createWorker(); } @Test public void debounceWithOnDroppedCallbackWithEx() throws Throwable { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposable.empty()); publishNext(observer, 100, "one"); // Should be skipped since "two" will arrive before the timeout expires. publishNext(observer, 400, "two"); // Should be published since "three" will arrive after the timeout expires. publishNext(observer, 900, "three"); // Should be skipped since onComplete will arrive before the timeout expires. publishNext(observer, 999, "four"); // Should be skipped since onComplete will arrive before the timeout expires. publishCompleted(observer, 1000); // Should be published as soon as the timeout expires. } }); Action whenDisposed = mock(Action.class); Observable<String> sampled = source .doOnDispose(whenDisposed) .debounce(400, TimeUnit.MILLISECONDS, scheduler, e -> { if ("three".equals(e)) { throw new TestException("forced"); } }); sampled.subscribe(observer); scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); InOrder inOrder = inOrder(observer); // must go to 800 since it must be 400 after when two is sent, which is at 400 scheduler.advanceTimeTo(800, TimeUnit.MILLISECONDS); inOrder.verify(observer, times(1)).onNext("two"); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); inOrder.verify(observer, times(1)).onError(any(TestException.class)); inOrder.verify(observer, never()).onNext("three"); inOrder.verify(observer, never()).onNext("four"); inOrder.verify(observer, never()).onComplete(); inOrder.verifyNoMoreInteractions(); verify(whenDisposed).run(); } @Test public void debounceWithOnDroppedCallback() { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposable.empty()); publishNext(observer, 100, "one"); // Should be skipped since "two" will arrive before the timeout expires. publishNext(observer, 400, "two"); // Should be published since "three" will arrive after the timeout expires. publishNext(observer, 900, "three"); // Should be skipped since onComplete will arrive before the timeout expires. publishNext(observer, 999, "four"); // Should be skipped since onComplete will arrive before the timeout expires. publishCompleted(observer, 1000); // Should be published as soon as the timeout expires. } }); Observer<Object> drops = TestHelper.mockObserver(); InOrder inOrderDrops = inOrder(drops); Observable<String> sampled = source.debounce(400, TimeUnit.MILLISECONDS, scheduler, drops::onNext); sampled.subscribe(observer); scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); InOrder inOrder = inOrder(observer); // must go to 800 since it must be 400 after when two is sent, which is at 400 scheduler.advanceTimeTo(800, TimeUnit.MILLISECONDS); inOrderDrops.verify(drops, times(1)).onNext("one"); inOrder.verify(observer, times(1)).onNext("two"); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); inOrderDrops.verify(drops, times(1)).onNext("three"); inOrder.verify(observer, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); inOrderDrops.verifyNoMoreInteractions(); } @Test public void debounceWithCompleted() { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposable.empty()); publishNext(observer, 100, "one"); // Should be skipped since "two" will arrive before the timeout expires. publishNext(observer, 400, "two"); // Should be published since "three" will arrive after the timeout expires. publishNext(observer, 900, "three"); // Should be skipped since onComplete will arrive before the timeout expires. publishCompleted(observer, 1000); // Should be published as soon as the timeout expires. } }); Observable<String> sampled = source.debounce(400, TimeUnit.MILLISECONDS, scheduler); sampled.subscribe(observer); scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); InOrder inOrder = inOrder(observer); // must go to 800 since it must be 400 after when two is sent, which is at 400 scheduler.advanceTimeTo(800, TimeUnit.MILLISECONDS); inOrder.verify(observer, times(1)).onNext("two"); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); inOrder.verify(observer, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void debounceNeverEmits() { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposable.empty()); // all should be skipped since they are happening faster than the 200ms timeout publishNext(observer, 100, "a"); // Should be skipped publishNext(observer, 200, "b"); // Should be skipped publishNext(observer, 300, "c"); // Should be skipped publishNext(observer, 400, "d"); // Should be skipped publishNext(observer, 500, "e"); // Should be skipped publishNext(observer, 600, "f"); // Should be skipped publishNext(observer, 700, "g"); // Should be skipped publishNext(observer, 800, "h"); // Should be skipped publishCompleted(observer, 900); // Should be published as soon as the timeout expires. } }); Observable<String> sampled = source.debounce(200, TimeUnit.MILLISECONDS, scheduler); sampled.subscribe(observer); scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(0)).onNext(anyString()); scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); inOrder.verify(observer, times(1)).onComplete(); inOrder.verifyNoMoreInteractions(); } @Test public void debounceWithError() { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposable.empty()); Exception error = new TestException(); publishNext(observer, 100, "one"); // Should be published since "two" will arrive after the timeout expires. publishNext(observer, 600, "two"); // Should be skipped since onError will arrive before the timeout expires. publishError(observer, 700, error); // Should be published as soon as the timeout expires. } }); Observable<String> sampled = source.debounce(400, TimeUnit.MILLISECONDS, scheduler); sampled.subscribe(observer); scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); InOrder inOrder = inOrder(observer); // 100 + 400 means it triggers at 500 scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS); inOrder.verify(observer).onNext("one"); scheduler.advanceTimeTo(701, TimeUnit.MILLISECONDS); inOrder.verify(observer).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); } private <T> void publishCompleted(final Observer<T> observer, long delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { observer.onComplete(); } }, delay, TimeUnit.MILLISECONDS); } private <T> void publishError(final Observer<T> observer, long delay, final Exception error) { innerScheduler.schedule(new Runnable() { @Override public void run() { observer.onError(error); } }, delay, TimeUnit.MILLISECONDS); } private <T> void publishNext(final Observer<T> observer, final long delay, final T value) { innerScheduler.schedule(new Runnable() { @Override public void run() { observer.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } @Test public void debounceSelectorNormal1() { PublishSubject<Integer> source = PublishSubject.create(); final PublishSubject<Integer> debouncer = PublishSubject.create(); Function<Integer, Observable<Integer>> debounceSel = new Function<Integer, Observable<Integer>>() { @Override public Observable<Integer> apply(Integer t1) { return debouncer; } }; Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); source.debounce(debounceSel).subscribe(o); source.onNext(1); debouncer.onNext(1); source.onNext(2); source.onNext(3); source.onNext(4); debouncer.onNext(2); source.onNext(5); source.onComplete(); inOrder.verify(o).onNext(1); inOrder.verify(o).onNext(4); inOrder.verify(o).onNext(5); inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void debounceSelectorFuncThrows() { PublishSubject<Integer> source = PublishSubject.create(); Function<Integer, Observable<Integer>> debounceSel = new Function<Integer, Observable<Integer>>() { @Override public Observable<Integer> apply(Integer t1) { throw new TestException(); } }; Observer<Object> o = TestHelper.mockObserver(); source.debounce(debounceSel).subscribe(o); source.onNext(1); verify(o, never()).onNext(any()); verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } @Test public void debounceSelectorObservableThrows() { PublishSubject<Integer> source = PublishSubject.create(); Function<Integer, Observable<Integer>> debounceSel = new Function<Integer, Observable<Integer>>() { @Override public Observable<Integer> apply(Integer t1) { return Observable.error(new TestException()); } }; Observer<Object> o = TestHelper.mockObserver(); source.debounce(debounceSel).subscribe(o); source.onNext(1); verify(o, never()).onNext(any()); verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } @Test public void debounceTimedLastIsNotLost() { PublishSubject<Integer> source = PublishSubject.create(); Observer<Object> o = TestHelper.mockObserver(); source.debounce(100, TimeUnit.MILLISECONDS, scheduler).subscribe(o); source.onNext(1); source.onComplete(); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); verify(o).onNext(1); verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void debounceSelectorLastIsNotLost() { PublishSubject<Integer> source = PublishSubject.create(); final PublishSubject<Integer> debouncer = PublishSubject.create(); Function<Integer, Observable<Integer>> debounceSel = new Function<Integer, Observable<Integer>>() { @Override public Observable<Integer> apply(Integer t1) { return debouncer; } }; Observer<Object> o = TestHelper.mockObserver(); source.debounce(debounceSel).subscribe(o); source.onNext(1); source.onComplete(); debouncer.onComplete(); verify(o).onNext(1); verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void debounceWithTimeBackpressure() throws InterruptedException { TestScheduler scheduler = new TestScheduler(); TestObserverEx<Integer> observer = new TestObserverEx<>(); Observable.merge( Observable.just(1), Observable.just(2).delay(10, TimeUnit.MILLISECONDS, scheduler) ).debounce(20, TimeUnit.MILLISECONDS, scheduler).take(1).subscribe(observer); scheduler.advanceTimeBy(30, TimeUnit.MILLISECONDS); observer.assertValue(2); observer.assertTerminated(); observer.assertNoErrors(); } @Test public void debounceDefault() throws Exception { Observable.just(1).debounce(1, TimeUnit.SECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(1); } @Test public void dispose() { TestHelper.checkDisposed(PublishSubject.create().debounce(1, TimeUnit.SECONDS, new TestScheduler())); TestHelper.checkDisposed(PublishSubject.create().debounce(Functions.justFunction(Observable.never()))); Disposable d = new ObservableDebounceTimed.DebounceEmitter<>(1, 1, null); assertFalse(d.isDisposed()); d.dispose(); assertTrue(d.isDisposed()); } @Test public void badSource() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { new Observable<Integer>() { @Override protected void subscribeActual(Observer<? super Integer> observer) { observer.onSubscribe(Disposable.empty()); observer.onComplete(); observer.onNext(1); observer.onError(new TestException()); observer.onComplete(); } } .debounce(1, TimeUnit.SECONDS, new TestScheduler()) .test() .assertResult(); TestHelper.assertUndeliverable(errors, 0, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void badSourceSelector() { TestHelper.checkBadSourceObservable(new Function<Observable<Integer>, Object>() { @Override public Object apply(Observable<Integer> o) throws Exception { return o.debounce(new Function<Integer, ObservableSource<Long>>() { @Override public ObservableSource<Long> apply(Integer v) throws Exception { return Observable.timer(1, TimeUnit.SECONDS); } }); } }, false, 1, 1, 1); TestHelper.checkBadSourceObservable(new Function<Observable<Integer>, Object>() { @Override public Object apply(final Observable<Integer> o) throws Exception { return Observable.just(1).debounce(new Function<Integer, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(Integer v) throws Exception { return o; } }); } }, false, 1, 1, 1); } @Test public void debounceWithEmpty() { Observable.just(1).debounce(Functions.justFunction(Observable.empty())) .test() .assertResult(1); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<Object>>() { @Override public Observable<Object> apply(Observable<Object> o) throws Exception { return o.debounce(Functions.justFunction(Observable.never())); } }); } @Test public void disposeInOnNext() { final TestObserver<Integer> to = new TestObserver<>(); BehaviorSubject.createDefault(1) .debounce(new Function<Integer, ObservableSource<Object>>() { @Override public ObservableSource<Object> apply(Integer o) throws Exception { to.dispose(); return Observable.never(); } }) .subscribeWith(to) .assertEmpty(); assertTrue(to.isDisposed()); } @Test public void disposedInOnComplete() { final TestObserver<Integer> to = new TestObserver<>(); new Observable<Integer>() { @Override protected void subscribeActual(Observer<? super Integer> observer) { observer.onSubscribe(Disposable.empty()); to.dispose(); observer.onComplete(); } } .debounce(Functions.justFunction(Observable.never())) .subscribeWith(to) .assertEmpty(); } @Test public void emitLate() { final AtomicReference<Observer<? super Integer>> ref = new AtomicReference<>(); TestObserver<Integer> to = Observable.range(1, 2) .debounce(new Function<Integer, ObservableSource<Integer>>() { @Override public ObservableSource<Integer> apply(Integer o) throws Exception { if (o != 1) { return Observable.never(); } return new Observable<Integer>() { @Override protected void subscribeActual(Observer<? super Integer> observer) { observer.onSubscribe(Disposable.empty()); ref.set(observer); } }; } }) .test(); ref.get().onNext(1); to .assertResult(2); } @Test public void timedDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<Object>>() { @Override public Publisher<Object> apply(Flowable<Object> f) throws Exception { return f.debounce(1, TimeUnit.SECONDS); } }); } @Test public void timedDisposedIgnoredBySource() { final TestObserver<Integer> to = new TestObserver<>(); new Observable<Integer>() { @Override protected void subscribeActual( Observer<? super Integer> observer) { observer.onSubscribe(Disposable.empty()); to.dispose(); observer.onNext(1); observer.onComplete(); } } .debounce(1, TimeUnit.SECONDS) .subscribe(to); } @Test public void timedLateEmit() { TestObserver<Integer> to = new TestObserver<>(); DebounceTimedObserver<Integer> sub = new DebounceTimedObserver<>( to, 1, TimeUnit.SECONDS, new TestScheduler().createWorker(), null); sub.onSubscribe(Disposable.empty()); DebounceEmitter<Integer> de = new DebounceEmitter<>(1, 50, sub); de.run(); de.run(); to.assertEmpty(); } @Test public void timedError() { Observable.error(new TestException()) .debounce(1, TimeUnit.SECONDS) .test() .assertFailure(TestException.class); } @Test public void debounceOnEmpty() { Observable.empty().debounce(new Function<Object, ObservableSource<Object>>() { @Override public ObservableSource<Object> apply(Object o) { return Observable.just(new Object()); } }).subscribe(); } @Test public void doubleOnSubscribeTime() { TestHelper.checkDoubleOnSubscribeObservable(o -> o.debounce(1, TimeUnit.SECONDS)); } }
ObservableDebounceTest
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/authentication/logout/Saml2LogoutRequest.java
{ "start": 6006, "end": 9901 }
class ____ { private final RelyingPartyRegistration registration; private String location; private Saml2MessageBinding binding; private Map<String, String> parameters = new LinkedHashMap<>(); private Function<Map<String, String>, String> encoder = DEFAULT_ENCODER; private String id; private Builder(RelyingPartyRegistration registration) { this.registration = registration; this.location = registration.getAssertingPartyMetadata().getSingleLogoutServiceLocation(); this.binding = registration.getAssertingPartyMetadata().getSingleLogoutServiceBinding(); } /** * Use this signed and serialized and Base64-encoded &lt;saml2:LogoutRequest&gt; * * Note that if using the Redirect binding, the value should be * {@link java.util.zip.DeflaterOutputStream deflated} and then Base64-encoded. * * It should not be URL-encoded as this will be done when the request is sent * @param samlRequest the &lt;saml2:LogoutRequest&gt; to use * @return the {@link Builder} for further configurations * @see Saml2LogoutRequestResolver */ public Builder samlRequest(String samlRequest) { this.parameters.put(Saml2ParameterNames.SAML_REQUEST, samlRequest); return this; } /** * Use this SAML 2.0 Message Binding * * By default, the asserting party's configured binding is used * @param binding the SAML 2.0 Message Binding to use * @return the {@link Builder} for further configurations */ public Builder binding(Saml2MessageBinding binding) { this.binding = binding; return this; } /** * Use this location for the SAML 2.0 logout endpoint * * By default, the asserting party's endpoint is used * @param location the SAML 2.0 location to use * @return the {@link Builder} for further configurations */ public Builder location(String location) { this.location = location; return this; } /** * Use this value for the relay state when sending the Logout Request to the * asserting party * * It should not be URL-encoded as this will be done when the request is sent * @param relayState the relay state * @return the {@link Builder} for further configurations */ public Builder relayState(String relayState) { this.parameters.put(Saml2ParameterNames.RELAY_STATE, relayState); return this; } /** * This is the unique id used in the {@link #samlRequest} * @param id the Logout Request id * @return the {@link Builder} for further configurations */ public Builder id(String id) { this.id = id; return this; } /** * Use this {@link Consumer} to modify the set of query parameters * * No parameter should be URL-encoded as this will be done when the request is * sent * @param parametersConsumer the {@link Consumer} * @return the {@link Builder} for further configurations */ public Builder parameters(Consumer<Map<String, String>> parametersConsumer) { parametersConsumer.accept(this.parameters); return this; } /** * Use this strategy for converting parameters into an encoded query string. The * resulting query does not contain a leading question mark. * * In the event that you already have an encoded version that you want to use, you * can call this by doing {@code parameterEncoder((params) -> encodedValue)}. * @param encoder the strategy to use * @return the {@link Builder} for further configurations * @since 5.8 */ public Builder parametersQuery(Function<Map<String, String>, String> encoder) { this.encoder = encoder; return this; } /** * Build the {@link Saml2LogoutRequest} * @return a constructed {@link Saml2LogoutRequest} */ public Saml2LogoutRequest build() { return new Saml2LogoutRequest(this.location, this.binding, this.parameters, this.id, this.registration.getRegistrationId(), this.encoder); } } }
Builder
java
elastic__elasticsearch
x-pack/plugin/enrich/src/main/java/org/elasticsearch/xpack/enrich/rest/RestGetEnrichPolicyAction.java
{ "start": 936, "end": 1800 }
class ____ extends BaseRestHandler { @Override public List<Route> routes() { return List.of(new Route(GET, "/_enrich/policy/{name}"), new Route(GET, "/_enrich/policy")); } @Override public String getName() { return "get_enrich_policy"; } @Override protected RestChannelConsumer prepareRequest(final RestRequest restRequest, final NodeClient client) { final var request = new GetEnrichPolicyAction.Request( RestUtils.getMasterNodeTimeout(restRequest), Strings.splitStringByCommaToArray(restRequest.param("name")) ); return channel -> new RestCancellableNodeClient(client, restRequest.getHttpChannel()).execute( GetEnrichPolicyAction.INSTANCE, request, new RestToXContentListener<>(channel) ); } }
RestGetEnrichPolicyAction
java
spring-projects__spring-security
crypto/src/main/java/org/springframework/security/crypto/password/Pbkdf2PasswordEncoder.java
{ "start": 1859, "end": 5092 }
class ____ extends AbstractValidatingPasswordEncoder { private static final int DEFAULT_SALT_LENGTH = 16; private static final SecretKeyFactoryAlgorithm DEFAULT_ALGORITHM = SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA256; private static final int DEFAULT_HASH_WIDTH = 256; // SHA-256 private static final int DEFAULT_ITERATIONS = 310000; private final BytesKeyGenerator saltGenerator; private final byte[] secret; private final int iterations; private String algorithm = DEFAULT_ALGORITHM.name(); private int hashWidth = DEFAULT_HASH_WIDTH; // @formatter:off /* The length of the hash should be derived from the hashing algorithm. For example: SHA-1 - 160 bits (20 bytes) SHA-256 - 256 bits (32 bytes) SHA-512 - 512 bits (64 bytes) However, the original configuration for PBKDF2 was hashWidth=256 and algorithm=SHA-1, which is incorrect. The default configuration has been updated to hashWidth=256 and algorithm=SHA-256 (see gh-10506). In order to preserve backwards compatibility, the variable 'overrideHashWidth' has been introduced to indicate usage of the deprecated constructor that honors the hashWidth parameter. */ // @formatter:on private boolean overrideHashWidth = true; private boolean encodeHashAsBase64; /** * Constructs a PBKDF2 password encoder with a secret value as well as salt length, * iterations and hash width. * @param secret the secret * @param saltLength the salt length (in bytes) * @param iterations the number of iterations. Users should aim for taking about .5 * seconds on their own system. * @param hashWidth the size of the hash (in bits) * @since 5.5 * @deprecated Use * {@link #Pbkdf2PasswordEncoder(CharSequence, int, int, SecretKeyFactoryAlgorithm)} * instead */ @Deprecated public Pbkdf2PasswordEncoder(CharSequence secret, int saltLength, int iterations, int hashWidth) { this.secret = Utf8.encode(secret); this.saltGenerator = KeyGenerators.secureRandom(saltLength); this.iterations = iterations; this.hashWidth = hashWidth; this.algorithm = SecretKeyFactoryAlgorithm.PBKDF2WithHmacSHA1.name(); this.overrideHashWidth = false; // Honor 'hashWidth' to preserve backwards // compatibility } /** * Constructs a PBKDF2 password encoder with a secret value as well as salt length, * iterations and algorithm. * @param secret the secret * @param saltLength the salt length (in bytes) * @param iterations the number of iterations. Users should aim for taking about .5 * seconds on their own system. * @param secretKeyFactoryAlgorithm the algorithm to use * @since 5.8 */ public Pbkdf2PasswordEncoder(CharSequence secret, int saltLength, int iterations, SecretKeyFactoryAlgorithm secretKeyFactoryAlgorithm) { this.secret = Utf8.encode(secret); this.saltGenerator = KeyGenerators.secureRandom(saltLength); this.iterations = iterations; setAlgorithm(secretKeyFactoryAlgorithm); } /** * Constructs a PBKDF2 password encoder with no additional secret value. There will be * a salt length of 8 bytes, 185,000 iterations, SHA-1 algorithm and a hash length of * 256 bits. The default is based upon aiming for .5 seconds to validate the password * when this
Pbkdf2PasswordEncoder
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java
{ "start": 22071, "end": 23031 }
class ____ { public Object setFoo(int p) { return new Object(); } public Object setFoo(String p) { return new Object(); } } BeanInfo bi = Introspector.getBeanInfo(C.class); assertThat(hasReadMethodForProperty(bi, "foo")).isFalse(); assertThat(hasWriteMethodForProperty(bi, "foo")).isFalse(); BeanInfo ebi = new ExtendedBeanInfo(bi); assertThat(hasReadMethodForProperty(ebi, "foo")).isFalse(); assertThat(hasWriteMethodForProperty(ebi, "foo")).isTrue(); for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) { if (pd.getName().equals("foo")) { assertThat(pd.getWriteMethod()).isEqualTo(C.class.getMethod("setFoo", String.class)); return; } } throw new AssertionError("never matched write method"); } /** * Corners the bug revealed by SPR-8522, in which an (apparently) indexed write method * without a corresponding indexed read method would fail to be processed correctly by * ExtendedBeanInfo. The local
C
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/transport/ForkingResponseHandlerRunnable.java
{ "start": 1087, "end": 3844 }
class ____ extends AbstractRunnable { private static final Logger logger = LogManager.getLogger(ForkingResponseHandlerRunnable.class); private final TransportResponseHandler<?> handler; @Nullable private final TransportException transportException; ForkingResponseHandlerRunnable(TransportResponseHandler<?> handler, @Nullable TransportException transportException) { this(handler, transportException, handler.executor()); } ForkingResponseHandlerRunnable( TransportResponseHandler<?> handler, @Nullable TransportException transportException, Executor executorUsed ) { assert executorUsed != EsExecutors.DIRECT_EXECUTOR_SERVICE : "forking handler required, but got " + handler; this.handler = handler; this.transportException = transportException; } @Override protected abstract void doRun(); // no 'throws Exception' here @Override public boolean isForceExecution() { // we must complete every pending listener return true; } @Override public void onRejection(Exception e) { // force-executed tasks are only rejected on shutdown, but we should have enqueued the completion of every handler before shutting // down any thread pools so this indicates a bug assert false : e; // we must complete every pending listener, and we can't fork to the target threadpool because we're shutting down, so just complete // it on this thread. final TransportException exceptionToDeliver; if (transportException == null) { exceptionToDeliver = new RemoteTransportException(e.getMessage(), e); } else { exceptionToDeliver = transportException; exceptionToDeliver.addSuppressed(e); } try { handler.handleException(exceptionToDeliver); } catch (Exception e2) { exceptionToDeliver.addSuppressed(e2); logger.error( () -> format( "%s [%s]", transportException == null ? "failed to handle rejection of response" : "failed to handle rejection of error response", handler ), exceptionToDeliver ); } } @Override public void onFailure(Exception e) { assert false : e; // delivering the response shouldn't throw anything logger.error( () -> format( "%s [%s]", transportException == null ? "failed to handle rejection of response" : "failed to handle rejection of error response", handler ), e ); } }
ForkingResponseHandlerRunnable
java
netty__netty
buffer/src/test/java/io/netty/buffer/PooledBigEndianDirectByteBufTest.java
{ "start": 808, "end": 1137 }
class ____ extends AbstractPooledByteBufTest { @Override protected ByteBuf alloc(int length, int maxCapacity) { ByteBuf buffer = PooledByteBufAllocator.DEFAULT.directBuffer(length, maxCapacity); assertSame(ByteOrder.BIG_ENDIAN, buffer.order()); return buffer; } }
PooledBigEndianDirectByteBufTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/joinable/ManyToOneJoinTableTest.java
{ "start": 4856, "end": 5159 }
class ____ implements Resource { private static final String ENTITY_NAME = "TestResource"; @EmbeddedId Identifier identifier; public Identifier getIdentifier() { return identifier; } public void setIdentifier(Identifier identifier) { this.identifier = identifier; } } }
ResourceImpl
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/main/java/io/quarkus/rest/client/reactive/deployment/devservices/VertxHttpProxyDevServicesRestClientProxyProvider.java
{ "start": 4524, "end": 4667 }
class ____ the Host HTTP Header in order to avoid having services being blocked * for presenting a wrong value */ private static
sets
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/records/impl/pb/OpportunisticContainersStatusPBImpl.java
{ "start": 1092, "end": 4752 }
class ____ extends OpportunisticContainersStatus { private YarnServerCommonProtos.OpportunisticContainersStatusProto proto = YarnServerCommonProtos.OpportunisticContainersStatusProto .getDefaultInstance(); private YarnServerCommonProtos.OpportunisticContainersStatusProto.Builder builder = null; private boolean viaProto = false; public OpportunisticContainersStatusPBImpl() { builder = YarnServerCommonProtos.OpportunisticContainersStatusProto.newBuilder(); } public OpportunisticContainersStatusPBImpl(YarnServerCommonProtos .OpportunisticContainersStatusProto proto) { this.proto = proto; viaProto = true; } public YarnServerCommonProtos.OpportunisticContainersStatusProto getProto() { proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = YarnServerCommonProtos.OpportunisticContainersStatusProto .newBuilder(proto); } viaProto = false; } @Override public int getRunningOpportContainers() { YarnServerCommonProtos.OpportunisticContainersStatusProtoOrBuilder p = viaProto ? proto : builder; return p.getRunningOpportContainers(); } @Override public void setRunningOpportContainers(int runningOpportContainers) { maybeInitBuilder(); builder.setRunningOpportContainers(runningOpportContainers); } @Override public long getOpportMemoryUsed() { YarnServerCommonProtos.OpportunisticContainersStatusProtoOrBuilder p = viaProto ? proto : builder; return p.getOpportMemoryUsed(); } @Override public void setOpportMemoryUsed(long opportMemoryUsed) { maybeInitBuilder(); builder.setOpportMemoryUsed(opportMemoryUsed); } @Override public int getOpportCoresUsed() { YarnServerCommonProtos.OpportunisticContainersStatusProtoOrBuilder p = viaProto ? proto : builder; return p.getOpportCoresUsed(); } @Override public void setOpportCoresUsed(int opportCoresUsed) { maybeInitBuilder(); builder.setOpportCoresUsed(opportCoresUsed); } @Override public int getQueuedOpportContainers() { YarnServerCommonProtos.OpportunisticContainersStatusProtoOrBuilder p = viaProto ? proto : builder; return p.getQueuedOpportContainers(); } @Override public void setQueuedOpportContainers(int queuedOpportContainers) { maybeInitBuilder(); builder.setQueuedOpportContainers(queuedOpportContainers); } @Override public int getWaitQueueLength() { YarnServerCommonProtos.OpportunisticContainersStatusProtoOrBuilder p = viaProto ? proto : builder; return p.getWaitQueueLength(); } @Override public void setWaitQueueLength(int waitQueueLength) { maybeInitBuilder(); builder.setWaitQueueLength(waitQueueLength); } @Override public int getEstimatedQueueWaitTime() { YarnServerCommonProtos.OpportunisticContainersStatusProtoOrBuilder p = viaProto ? proto : builder; return p.getEstimatedQueueWaitTime(); } @Override public void setEstimatedQueueWaitTime(int queueWaitTime) { maybeInitBuilder(); builder.setEstimatedQueueWaitTime(queueWaitTime); } @Override public int getOpportQueueCapacity() { YarnServerCommonProtos.OpportunisticContainersStatusProtoOrBuilder p = viaProto ? proto : builder; return p.getOpportQueueCapacity(); } @Override public void setOpportQueueCapacity(int maxOpportQueueLength) { maybeInitBuilder(); builder.setOpportQueueCapacity(maxOpportQueueLength); } }
OpportunisticContainersStatusPBImpl
java
alibaba__druid
core/src/main/java/com/alibaba/druid/support/jakarta/StatViewFilter.java
{ "start": 1130, "end": 4970 }
class ____ implements Filter { public static final String PARAM_NAME_PATH = "path"; private static final Log LOG = LogFactory.getLog(StatViewFilter.class); private String servletPath = "/druid"; private String resourcePath = "support/http/resources"; private ResourceHandler handler; private DruidStatService statService = DruidStatService.getInstance(); @Override public void init(FilterConfig config) throws ServletException { if (config == null) { return; } String path = config.getInitParameter(PARAM_NAME_PATH); if (path != null && !path.isEmpty()) { this.servletPath = path; } handler = new ResourceHandler(resourcePath); String paramUserName = config.getInitParameter(PARAM_NAME_USERNAME); if (!StringUtils.isEmpty(paramUserName)) { handler.username = paramUserName; } String paramPassword = config.getInitParameter(PARAM_NAME_PASSWORD); if (!StringUtils.isEmpty(paramPassword)) { handler.password = paramPassword; } String paramRemoteAddressHeader = config.getInitParameter(PARAM_REMOTE_ADDR); if (!StringUtils.isEmpty(paramRemoteAddressHeader)) { handler.remoteAddressHeader = paramRemoteAddressHeader; } try { String param = config.getInitParameter(PARAM_NAME_ALLOW); if (param != null && param.trim().length() != 0) { param = param.trim(); String[] items = param.split(","); for (String item : items) { if (item == null || item.length() == 0) { continue; } IPRange ipRange = new IPRange(item); handler.allowList.add(ipRange); } } } catch (Exception e) { String msg = "initParameter config error, allow : " + config.getInitParameter(PARAM_NAME_ALLOW); LOG.error(msg, e); } try { String param = config.getInitParameter(PARAM_NAME_DENY); if (param != null && param.trim().length() != 0) { param = param.trim(); String[] items = param.split(","); for (String item : items) { if (item == null || item.length() == 0) { continue; } IPRange ipRange = new IPRange(item); handler.denyList.add(ipRange); } } } catch (Exception e) { String msg = "initParameter config error, deny : " + config.getInitParameter(PARAM_NAME_DENY); LOG.error(msg, e); } } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpResp = (HttpServletResponse) response; String contextPath = ((HttpServletRequest) request).getContextPath(); String requestURI = httpReq.getRequestURI(); if (!contextPath.equals("")) { requestURI = requestURI.substring(((HttpServletRequest) request).getContextPath().length()); } if (requestURI.equals(servletPath)) { httpResp.sendRedirect(httpReq.getRequestURI() + '/'); return; } handler.service(httpReq, httpResp, servletPath, new ProcessCallback() { @Override public String process(String url) { return statService.service(url); } }); } @Override public void destroy() { } }
StatViewFilter
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/util/Preconditions_checkNotNullOrEmpty_String_String_Test.java
{ "start": 1028, "end": 1897 }
class ____ { private final static String CUSTOM_MESSAGE = "Wow, that's an error dude .."; @Test void should_throw_illegalargumentexception_if_string_is_empty() { assertThatIllegalArgumentException().isThrownBy(() -> { String string = ""; Preconditions.checkNotNullOrEmpty(string, CUSTOM_MESSAGE); }).withMessage(CUSTOM_MESSAGE); } @Test void should_throw_nullpointerexception_if_string_is_null() { assertThatNullPointerException().isThrownBy(() -> { String string = null; Preconditions.checkNotNullOrEmpty(string, CUSTOM_MESSAGE); }); } @Test void should_return_string_if_it_is_not_null_nor_empty() { String string = "a"; CharSequence result = Preconditions.checkNotNullOrEmpty(string, CUSTOM_MESSAGE); assertThat(result).isEqualTo(string); } }
Preconditions_checkNotNullOrEmpty_String_String_Test
java
netty__netty
microbench/src/main/java/io/netty/handler/codec/http2/Http2FrameWriterDataBenchmark.java
{ "start": 4330, "end": 8425 }
class ____ implements Http2DataWriter { private static final ByteBuf ZERO_BUFFER = unreleasableBuffer(directBuffer(MAX_UNSIGNED_BYTE).writeZero(MAX_UNSIGNED_BYTE)).asReadOnly(); private final int maxFrameSize = DEFAULT_MAX_FRAME_SIZE; @Override public ChannelFuture writeData(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endStream, ChannelPromise promise) { final Http2CodecUtil.SimpleChannelPromiseAggregator promiseAggregator = new Http2CodecUtil.SimpleChannelPromiseAggregator(promise, ctx.channel(), ctx.executor()); final DataFrameHeader header = new DataFrameHeader(ctx, streamId); boolean needToReleaseHeaders = true; boolean needToReleaseData = true; try { checkPositive(streamId, "streamId"); verifyPadding(padding); boolean lastFrame; int remainingData = data.readableBytes(); do { // Determine how much data and padding to write in this frame. Put all padding at the end. int frameDataBytes = min(remainingData, maxFrameSize); int framePaddingBytes = min(padding, max(0, (maxFrameSize - 1) - frameDataBytes)); // Decrement the remaining counters. padding -= framePaddingBytes; remainingData -= frameDataBytes; // Determine whether or not this is the last frame to be sent. lastFrame = remainingData == 0 && padding == 0; // Only the last frame is not retained. Until then, the outer finally must release. ByteBuf frameHeader = header.slice(frameDataBytes, framePaddingBytes, lastFrame && endStream); needToReleaseHeaders = !lastFrame; ctx.write(lastFrame ? frameHeader : frameHeader.retain(), promiseAggregator.newPromise()); // Write the frame data. ByteBuf frameData = data.readSlice(frameDataBytes); // Only the last frame is not retained. Until then, the outer finally must release. needToReleaseData = !lastFrame; ctx.write(lastFrame ? frameData : frameData.retain(), promiseAggregator.newPromise()); // Write the frame padding. if (paddingBytes(framePaddingBytes) > 0) { ctx.write(ZERO_BUFFER.slice(0, paddingBytes(framePaddingBytes)), promiseAggregator.newPromise()); } } while (!lastFrame); } catch (Throwable t) { try { if (needToReleaseHeaders) { header.release(); } if (needToReleaseData) { data.release(); } } finally { promiseAggregator.setFailure(t); promiseAggregator.doneAllocatingPromises(); } return promiseAggregator; } return promiseAggregator.doneAllocatingPromises(); } private static int paddingBytes(int padding) { // The padding parameter contains the 1 byte pad length field as well as the trailing padding bytes. // Subtract 1, so to only get the number of padding bytes that need to be appended to the end of a frame. return padding - 1; } private static void writePaddingLength(ByteBuf buf, int padding) { if (padding > 0) { // It is assumed that the padding length has been bounds checked before this // Minus 1, as the pad length field is included in the padding parameter and is 1 byte wide. buf.writeByte(padding - 1); } } /** * Utility
OldDefaultHttp2FrameWriter
java
apache__dubbo
dubbo-registry/dubbo-registry-api/src/test/java/org/apache/dubbo/registry/client/metadata/store/ExcludedParamsFilter2.java
{ "start": 1060, "end": 1591 }
class ____ implements MetadataParamsFilter { @Override public String[] serviceParamsIncluded() { return new String[0]; } @Override public String[] serviceParamsExcluded() { return new String[0]; } /** * Not included in this test */ @Override public String[] instanceParamsIncluded() { return new String[0]; } @Override public String[] instanceParamsExcluded() { return new String[] {GROUP_KEY, "params-filter"}; } }
ExcludedParamsFilter2
java
playframework__playframework
cache/play-cache/src/main/java/play/cache/CachedAction.java
{ "start": 367, "end": 776 }
class ____ extends Action<Cached> { private AsyncCacheApi cacheApi; @Inject public CachedAction(AsyncCacheApi cacheApi) { this.cacheApi = cacheApi; } public CompletionStage<Result> call(Request req) { final String key = configuration.key(); final Integer duration = configuration.duration(); return cacheApi.getOrElseUpdate(key, () -> delegate.call(req), duration); } }
CachedAction