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__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/assignment/LegacyStickyTaskAssignor.java
{ "start": 2258, "end": 14254 }
class ____ implements LegacyTaskAssignor { private static final Logger log = LoggerFactory.getLogger(LegacyStickyTaskAssignor.class); // For stateful tasks, by default we want to maintain stickiness. So we have higher non_overlap_cost private static final int DEFAULT_STATEFUL_TRAFFIC_COST = 1; private static final int DEFAULT_STATEFUL_NON_OVERLAP_COST = 10; private Map<ProcessId, ClientState> clients; private Set<TaskId> allTaskIds; private Set<TaskId> statefulTaskIds; private final Map<TaskId, ProcessId> previousActiveTaskAssignment = new HashMap<>(); private final Map<TaskId, Set<ProcessId>> previousStandbyTaskAssignment = new HashMap<>(); private RackAwareTaskAssignor rackAwareTaskAssignor; // nullable if passed from FallbackPriorTaskAssignor private AssignmentConfigs configs; private TaskPairs taskPairs; private final boolean mustPreserveActiveTaskAssignment; public LegacyStickyTaskAssignor() { this(false); } LegacyStickyTaskAssignor(final boolean mustPreserveActiveTaskAssignment) { this.mustPreserveActiveTaskAssignment = mustPreserveActiveTaskAssignment; } @Override public boolean assign(final Map<ProcessId, ClientState> clients, final Set<TaskId> allTaskIds, final Set<TaskId> statefulTaskIds, final RackAwareTaskAssignor rackAwareTaskAssignor, final AssignmentConfigs configs) { this.clients = clients; this.allTaskIds = allTaskIds; this.statefulTaskIds = statefulTaskIds; this.rackAwareTaskAssignor = rackAwareTaskAssignor; this.configs = configs; final int maxPairs = allTaskIds.size() * (allTaskIds.size() - 1) / 2; taskPairs = new TaskPairs(maxPairs); mapPreviousTaskAssignment(clients); assignActive(); optimizeActive(); assignStandby(configs.numStandbyReplicas()); optimizeStandby(); return false; } private void optimizeStandby() { if (configs.numStandbyReplicas() > 0 && rackAwareTaskAssignor != null && rackAwareTaskAssignor.canEnableRackAwareAssignor()) { final int trafficCost = configs.rackAwareTrafficCost().orElse(DEFAULT_STATEFUL_TRAFFIC_COST); final int nonOverlapCost = configs.rackAwareNonOverlapCost().orElse(DEFAULT_STATEFUL_NON_OVERLAP_COST); final TreeMap<ProcessId, ClientState> clientStates = new TreeMap<>(clients); rackAwareTaskAssignor.optimizeStandbyTasks(clientStates, trafficCost, nonOverlapCost, (s, d, t, c) -> true); } } private void optimizeActive() { if (rackAwareTaskAssignor != null && rackAwareTaskAssignor.canEnableRackAwareAssignor()) { final int trafficCost = configs.rackAwareTrafficCost().orElse(DEFAULT_STATEFUL_TRAFFIC_COST); final int nonOverlapCost = configs.rackAwareNonOverlapCost().orElse(DEFAULT_STATEFUL_NON_OVERLAP_COST); final SortedSet<TaskId> statefulTasks = new TreeSet<>(statefulTaskIds); final TreeMap<ProcessId, ClientState> clientStates = new TreeMap<>(clients); rackAwareTaskAssignor.optimizeActiveTasks(statefulTasks, clientStates, trafficCost, nonOverlapCost); final TreeSet<TaskId> statelessTasks = (TreeSet<TaskId>) diff(TreeSet::new, allTaskIds, statefulTasks); // No-op if statelessTasks is empty rackAwareTaskAssignor.optimizeActiveTasks(statelessTasks, clientStates, STATELESS_TRAFFIC_COST, STATELESS_NON_OVERLAP_COST); } } private void assignStandby(final int numStandbyReplicas) { for (final TaskId taskId : statefulTaskIds) { for (int i = 0; i < numStandbyReplicas; i++) { final Set<ProcessId> ids = findClientsWithoutAssignedTask(taskId); if (ids.isEmpty()) { log.warn("Unable to assign {} of {} standby tasks for task [{}]. " + "There is not enough available capacity. You should " + "increase the number of threads and/or application instances " + "to maintain the requested number of standby replicas.", numStandbyReplicas - i, numStandbyReplicas, taskId); break; } allocateTaskWithClientCandidates(taskId, ids, false); } } } private void assignActive() { final int totalCapacity = sumCapacity(clients.values()); if (totalCapacity == 0) { throw new IllegalStateException("`totalCapacity` should never be zero."); } final int tasksPerThread = allTaskIds.size() / totalCapacity; final Set<TaskId> assigned = new HashSet<>(); // first try and re-assign existing active tasks to clients that previously had // the same active task for (final Map.Entry<TaskId, ProcessId> entry : previousActiveTaskAssignment.entrySet()) { final TaskId taskId = entry.getKey(); if (allTaskIds.contains(taskId)) { final ClientState client = clients.get(entry.getValue()); if (mustPreserveActiveTaskAssignment || client.hasUnfulfilledQuota(tasksPerThread)) { assignTaskToClient(assigned, taskId, client); } } } final Set<TaskId> unassigned = new HashSet<>(allTaskIds); unassigned.removeAll(assigned); // try and assign any remaining unassigned tasks to clients that previously // have seen the task. for (final Iterator<TaskId> iterator = unassigned.iterator(); iterator.hasNext(); ) { final TaskId taskId = iterator.next(); final Set<ProcessId> clientIds = previousStandbyTaskAssignment.get(taskId); if (clientIds != null) { for (final ProcessId clientId : clientIds) { final ClientState client = clients.get(clientId); if (client.hasUnfulfilledQuota(tasksPerThread)) { assignTaskToClient(assigned, taskId, client); iterator.remove(); break; } } } } // assign any remaining unassigned tasks final List<TaskId> sortedTasks = new ArrayList<>(unassigned); Collections.sort(sortedTasks); for (final TaskId taskId : sortedTasks) { allocateTaskWithClientCandidates(taskId, clients.keySet(), true); } } private void allocateTaskWithClientCandidates(final TaskId taskId, final Set<ProcessId> clientsWithin, final boolean active) { final ClientState client = findClient(taskId, clientsWithin); taskPairs.addPairs(taskId, client.assignedTasks()); if (active) { client.assignActive(taskId); } else { client.assignStandby(taskId); } } private void assignTaskToClient(final Set<TaskId> assigned, final TaskId taskId, final ClientState client) { taskPairs.addPairs(taskId, client.assignedTasks()); client.assignActive(taskId); assigned.add(taskId); } private Set<ProcessId> findClientsWithoutAssignedTask(final TaskId taskId) { final Set<ProcessId> clientIds = new HashSet<>(); for (final Map.Entry<ProcessId, ClientState> client : clients.entrySet()) { if (!client.getValue().hasAssignedTask(taskId)) { clientIds.add(client.getKey()); } } return clientIds; } private ClientState findClient(final TaskId taskId, final Set<ProcessId> clientsWithin) { // optimize the case where there is only 1 id to search within. if (clientsWithin.size() == 1) { return clients.get(clientsWithin.iterator().next()); } final ClientState previous = findClientsWithPreviousAssignedTask(taskId, clientsWithin); if (previous == null) { return leastLoaded(taskId, clientsWithin); } if (shouldBalanceLoad(previous)) { final ClientState standby = findLeastLoadedClientWithPreviousStandByTask(taskId, clientsWithin); if (standby == null || shouldBalanceLoad(standby)) { return leastLoaded(taskId, clientsWithin); } return standby; } return previous; } private boolean shouldBalanceLoad(final ClientState client) { return client.reachedCapacity() && hasClientsWithMoreAvailableCapacity(client); } private boolean hasClientsWithMoreAvailableCapacity(final ClientState client) { for (final ClientState clientState : clients.values()) { if (clientState.hasMoreAvailableCapacityThan(client)) { return true; } } return false; } private ClientState findClientsWithPreviousAssignedTask(final TaskId taskId, final Set<ProcessId> clientsWithin) { final ProcessId previous = previousActiveTaskAssignment.get(taskId); if (previous != null && clientsWithin.contains(previous)) { return clients.get(previous); } return findLeastLoadedClientWithPreviousStandByTask(taskId, clientsWithin); } private ClientState findLeastLoadedClientWithPreviousStandByTask(final TaskId taskId, final Set<ProcessId> clientsWithin) { final Set<ProcessId> ids = previousStandbyTaskAssignment.get(taskId); if (ids == null) { return null; } final HashSet<ProcessId> constrainTo = new HashSet<>(ids); constrainTo.retainAll(clientsWithin); return leastLoaded(taskId, constrainTo); } private ClientState leastLoaded(final TaskId taskId, final Set<ProcessId> clientIds) { final ClientState leastLoaded = findLeastLoaded(taskId, clientIds, true); if (leastLoaded == null) { return findLeastLoaded(taskId, clientIds, false); } return leastLoaded; } private ClientState findLeastLoaded(final TaskId taskId, final Set<ProcessId> clientIds, final boolean checkTaskPairs) { ClientState leastLoaded = null; for (final ProcessId id : clientIds) { final ClientState client = clients.get(id); if (client.assignedTaskCount() == 0) { return client; } if (leastLoaded == null || client.hasMoreAvailableCapacityThan(leastLoaded)) { if (!checkTaskPairs) { leastLoaded = client; } else if (taskPairs.hasNewPair(taskId, client.assignedTasks())) { leastLoaded = client; } } } return leastLoaded; } private void mapPreviousTaskAssignment(final Map<ProcessId, ClientState> clients) { for (final Map.Entry<ProcessId, ClientState> clientState : clients.entrySet()) { for (final TaskId activeTask : clientState.getValue().prevActiveTasks()) { previousActiveTaskAssignment.put(activeTask, clientState.getKey()); } for (final TaskId prevAssignedTask : clientState.getValue().prevStandbyTasks()) { previousStandbyTaskAssignment.computeIfAbsent(prevAssignedTask, t -> new HashSet<>()); previousStandbyTaskAssignment.get(prevAssignedTask).add(clientState.getKey()); } } } private int sumCapacity(final Collection<ClientState> values) { int capacity = 0; for (final ClientState client : values) { capacity += client.capacity(); } return capacity; } private static
LegacyStickyTaskAssignor
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/LazyOutputFormat.java
{ "start": 1422, "end": 2881 }
class ____<K, V> extends FilterOutputFormat<K, V> { /** * Set the underlying output format for LazyOutputFormat. * @param job the {@link JobConf} to modify * @param theClass the underlying class */ @SuppressWarnings("unchecked") public static void setOutputFormatClass(JobConf job, Class<? extends OutputFormat> theClass) { job.setOutputFormat(LazyOutputFormat.class); job.setClass("mapreduce.output.lazyoutputformat.outputformat", theClass, OutputFormat.class); } @Override public RecordWriter<K, V> getRecordWriter(FileSystem ignored, JobConf job, String name, Progressable progress) throws IOException { if (baseOut == null) { getBaseOutputFormat(job); } return new LazyRecordWriter<K, V>(job, baseOut, name, progress); } @Override public void checkOutputSpecs(FileSystem ignored, JobConf job) throws IOException { if (baseOut == null) { getBaseOutputFormat(job); } super.checkOutputSpecs(ignored, job); } @SuppressWarnings("unchecked") private void getBaseOutputFormat(JobConf job) throws IOException { baseOut = ReflectionUtils.newInstance( job.getClass("mapreduce.output.lazyoutputformat.outputformat", null, OutputFormat.class), job); if (baseOut == null) { throw new IOException("Ouput format not set for LazyOutputFormat"); } } /** * <code>LazyRecordWriter</code> is a convenience *
LazyOutputFormat
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/Gh32489Tests.java
{ "start": 6270, "end": 6310 }
interface ____<T, ID> {} static
Repository
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/ExecNodeBase.java
{ "start": 2823, "end": 2985 }
class ____ {@link ExecNode}. * * @param <T> The type of the elements that result from this node. */ @JsonIgnoreProperties(ignoreUnknown = true) public abstract
for
java
google__guava
android/guava/src/com/google/common/util/concurrent/SequentialExecutor.java
{ "start": 7147, "end": 10837 }
class ____ implements Runnable { @Nullable Runnable task; @Override public void run() { try { workOnQueue(); } catch (Error e) { synchronized (queue) { workerRunningState = IDLE; } throw e; // The execution of a task has ended abnormally. // We could have tasks left in the queue, so should perhaps try to restart a worker, // but then the Error will get delayed if we are using a direct (same thread) executor. } } /** * Continues executing tasks from {@link #queue} until it is empty. * * <p>The thread's interrupt bit is cleared before execution of each task. * * <p>If the Thread in use is interrupted before or during execution of the tasks in {@link * #queue}, the Executor will complete its tasks, and then restore the interruption. This means * that once the Thread returns to the Executor that this Executor composes, the interruption * will still be present. If the composed Executor is an ExecutorService, it can respond to * shutdown() by returning tasks queued on that Thread after {@link #worker} drains the queue. */ @SuppressWarnings("CatchingUnchecked") // sneaky checked exception private void workOnQueue() { boolean interruptedDuringTask = false; boolean hasSetRunning = false; try { while (true) { synchronized (queue) { // Choose whether this thread will run or not after acquiring the lock on the first // iteration if (!hasSetRunning) { if (workerRunningState == RUNNING) { // Don't want to have two workers pulling from the queue. return; } else { // Increment the run counter to avoid the ABA problem of a submitter marking the // thread as QUEUED after it already ran and exhausted the queue before returning // from execute(). workerRunCount++; workerRunningState = RUNNING; hasSetRunning = true; } } task = queue.poll(); if (task == null) { workerRunningState = IDLE; return; } } // Remove the interrupt bit before each task. The interrupt is for the "current task" when // it is sent, so subsequent tasks in the queue should not be caused to be interrupted // by a previous one in the queue being interrupted. interruptedDuringTask |= Thread.interrupted(); try { task.run(); } catch (Exception e) { // sneaky checked exception log.get().log(Level.SEVERE, "Exception while executing runnable " + task, e); } finally { task = null; } } } finally { // Ensure that if the thread was interrupted at all while processing the task queue, it // is returned to the delegate Executor interrupted so that it may handle the // interruption if it likes. if (interruptedDuringTask) { Thread.currentThread().interrupt(); } } } @SuppressWarnings("GuardedBy") @Override public String toString() { Runnable currentlyRunning = task; if (currentlyRunning != null) { return "SequentialExecutorWorker{running=" + currentlyRunning + "}"; } return "SequentialExecutorWorker{state=" + workerRunningState + "}"; } } @Override public String toString() { return "SequentialExecutor@" + identityHashCode(this) + "{" + executor + "}"; } }
QueueWorker
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/support/ArgumentConvertingMethodInvoker.java
{ "start": 5422, "end": 6835 }
class ____"); Method[] candidates = ReflectionUtils.getAllDeclaredMethods(targetClass); int minTypeDiffWeight = Integer.MAX_VALUE; @Nullable Object[] argumentsToUse = null; for (Method candidate : candidates) { if (candidate.getName().equals(targetMethod)) { // Check if the inspected method has the correct number of parameters. int parameterCount = candidate.getParameterCount(); if (parameterCount == argCount) { Class<?>[] paramTypes = candidate.getParameterTypes(); @Nullable Object[] convertedArguments = new Object[argCount]; boolean match = true; for (int j = 0; j < argCount && match; j++) { // Verify that the supplied argument is assignable to the method parameter. try { convertedArguments[j] = converter.convertIfNecessary(arguments[j], paramTypes[j]); } catch (TypeMismatchException ex) { // Ignore -> simply doesn't match. match = false; } } if (match) { int typeDiffWeight = getTypeDifferenceWeight(paramTypes, convertedArguments); if (typeDiffWeight < minTypeDiffWeight) { minTypeDiffWeight = typeDiffWeight; matchingMethod = candidate; argumentsToUse = convertedArguments; } } } } } if (matchingMethod != null) { setArguments(argumentsToUse); return matchingMethod; } } return null; } }
set
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/pagination/hhh9965/HHH9965Test.java
{ "start": 1008, "end": 1401 }
class ____ { @Test public void testHHH9965(SessionFactoryScope scope) { assertThrows( HibernateException.class, () -> scope.inTransaction( session -> { session.createSelectionQuery( "SELECT s FROM Shop s join fetch s.products", Shop.class ) .setMaxResults( 3 ) .list(); fail( "Pagination over collection fetch failure was expected" ); } ) ); } }
HHH9965Test
java
spring-projects__spring-boot
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/exchanges/HttpExchange.java
{ "start": 9827, "end": 11284 }
class ____ { private final int status; private final Map<String, List<String>> headers; private Response(RecordableHttpResponse request, Set<Include> includes) { this.status = request.getStatus(); this.headers = Collections.unmodifiableMap(filterHeaders(request.getHeaders(), includes)); } /** * Creates a fully-configured {@code Response} instance. Primarily for use by * {@link HttpExchangeRepository} implementations when recreating a response from * a persistent store. * @param status the status of the response * @param headers the response headers */ public Response(int status, Map<String, List<String>> headers) { this.status = status; this.headers = Collections.unmodifiableMap(new LinkedHashMap<>(headers)); } private Map<String, List<String>> filterHeaders(Map<String, List<String>> headers, Set<Include> includes) { HeadersFilter filter = new HeadersFilter(includes, Include.RESPONSE_HEADERS); filter.excludeUnless(HttpHeaders.SET_COOKIE, Include.COOKIE_HEADERS); return filter.apply(headers); } /** * Return the status code of the response. * @return the response status code */ public int getStatus() { return this.status; } /** * Return the response headers. * @return the headers */ public Map<String, List<String>> getHeaders() { return this.headers; } } /** * The session associated with the exchange. */ public static final
Response
java
google__guice
extensions/throwingproviders/test/com/google/inject/throwingproviders/CheckedProviderTest.java
{ "start": 27151, "end": 27997 }
class ____ implements Foo { static Exception nextToThrow; static String nextToReturn; @ThrowingInject AnotherMockFoo() throws RemoteException, BindException { if (nextToThrow instanceof RemoteException) { throw (RemoteException) nextToThrow; } else if (nextToThrow instanceof BindException) { throw (BindException) nextToThrow; } else if (nextToThrow instanceof RuntimeException) { throw (RuntimeException) nextToThrow; } else if (nextToThrow == null) { // Do nothing, return this. } else { throw new AssertionError("nextToThrow must be a runtime or remote exception"); } } @Override public String s() { return nextToReturn; } @Override public String toString() { return nextToReturn; } } static
AnotherMockFoo
java
spring-projects__spring-security
core/src/main/java/org/springframework/security/core/session/AbstractSessionEvent.java
{ "start": 871, "end": 1074 }
class ____ extends ApplicationEvent { @Serial private static final long serialVersionUID = -6878881229287231479L; public AbstractSessionEvent(Object source) { super(source); } }
AbstractSessionEvent
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/ids/DateIdTestEntity.java
{ "start": 346, "end": 1385 }
class ____ { @Id private Date id; @Audited private String str1; public DateIdTestEntity() { } public DateIdTestEntity(String str1) { this.str1 = str1; } public DateIdTestEntity(Date id, String str1) { this.id = id; this.str1 = str1; } public Date getId() { return id; } public void setId(Date id) { this.id = id; } public String getStr1() { return str1; } public void setStr1(String str1) { this.str1 = str1; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } DateIdTestEntity that = (DateIdTestEntity) o; if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; } if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { return false; } return true; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (str1 != null ? str1.hashCode() : 0); return result; } }
DateIdTestEntity
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/convert/UpdateViaObjectReaderTest.java
{ "start": 1467, "end": 1564 }
class ____ { public DataA da = new DataA(); public int k = 3; } static
DataB
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ImmutableAnnotationCheckerTest.java
{ "start": 10716, "end": 11325 }
class ____ implements Annotation { // BUG: Diagnostic contains: not annotated with @com.google.errorprone.annotations.Immutable final Lib l = new Lib(); public Class<? extends Annotation> annotationType() { return Deprecated.class; } } """) .doTest(); } @Test public void generated() { compilationHelper .addSourceLines( "Test.java", """ import java.lang.annotation.Annotation; import javax.annotation.processing.Generated; @Generated("com.google.auto.value.processor.AutoAnnotationProcessor")
MyAnno
java
google__error-prone
check_api/src/main/java/com/google/errorprone/VisitorState.java
{ "start": 16693, "end": 16837 }
class ____: %s", classname); int lastPeriod = classname.lastIndexOf('.'); if (lastPeriod == -1) { return classname; // top level
name
java
playframework__playframework
web/play-java-forms/src/main/java/play/data/format/Formats.java
{ "start": 5862, "end": 5984 }
interface ____ {} /** Annotation formatter, triggered by the <code>@NonEmpty</code> annotation. */ public static
NonEmpty
java
apache__camel
components/camel-dynamic-router/src/test/java/org/apache/camel/component/dynamicrouter/control/DynamicRouterControlProducerTest.java
{ "start": 3285, "end": 18647 }
class ____ { @RegisterExtension static CamelContextExtension contextExtension = new DefaultCamelContextExtension(); @Mock DynamicRouterControlService controlService; @Mock DynamicRouterControlConfiguration configuration; @Mock DynamicRouterControlEndpoint endpoint; @Mock Exchange exchange; @Mock Message message; @Mock AsyncCallback callback; CamelContext context; DynamicRouterControlProducer producer; @BeforeEach void setup() { context = contextExtension.getContext(); producer = new DynamicRouterControlProducer(endpoint, controlService, configuration); producer.setCamelContext(context); } @Test void performSubscribeAction() { String subscribeChannel = "testChannel"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_SUBSCRIBE, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel, CONTROL_SUBSCRIPTION_ID, "testId", CONTROL_DESTINATION_URI, "mock://test", CONTROL_PREDICATE, "true", CONTROL_EXPRESSION_LANGUAGE, "simple", CONTROL_PRIORITY, 10); when(message.getHeaders()).thenReturn(headers); Mockito.doNothing().when(callback).done(false); producer.performSubscribe(message, callback); Mockito.verify(controlService, Mockito.times(1)).subscribeWithPredicateExpression( subscribeChannel, "testId", "mock://test", 10, "true", "simple", false); } @Test void performSubscribeActionWithEmptyExpressionLanguage() { String subscribeChannel = "testChannel"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_SUBSCRIBE, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel, CONTROL_SUBSCRIPTION_ID, "testId", CONTROL_DESTINATION_URI, "mock://test", CONTROL_PREDICATE, "true", CONTROL_EXPRESSION_LANGUAGE, "", CONTROL_PRIORITY, 10); when(message.getHeaders()).thenReturn(headers); Mockito.doNothing().when(callback).done(false); producer.performSubscribe(message, callback); Mockito.verify(controlService, Mockito.times(1)).subscribeWithPredicateInstance( subscribeChannel, "testId", "mock://test", 10, null, false); } @Test void performUnsubscribeActionWithControlMessage() { String subscriptionId = "testId"; String subscribeChannel = "testChannel"; DynamicRouterControlMessage unsubscribeMsg = DynamicRouterControlMessage.Builder.newBuilder() .subscriptionId(subscriptionId) .subscribeChannel(subscribeChannel) .build(); when(message.getBody()).thenReturn(unsubscribeMsg); when(message.getBody(DynamicRouterControlMessage.class)).thenReturn(unsubscribeMsg); Mockito.doNothing().when(callback).done(false); producer.performUnsubscribe(message, callback); Mockito.verify(controlService, Mockito.times(1)) .removeSubscription(subscribeChannel, subscriptionId); } @Test void performUnsubscribeActionWithHeaders() { String subscriptionId = "testId"; String subscribeChannel = "testChannel"; when(message.getHeader(CONTROL_SUBSCRIPTION_ID, configuration.getSubscriptionId(), String.class)) .thenReturn(subscriptionId); when(message.getHeader(CONTROL_SUBSCRIBE_CHANNEL, configuration.getSubscribeChannel(), String.class)) .thenReturn(subscribeChannel); Mockito.doNothing().when(callback).done(false); producer.performUnsubscribe(message, callback); Mockito.verify(controlService, Mockito.times(1)) .removeSubscription(subscribeChannel, subscriptionId); } @Test void performUpdateAction() { // First, perform initial subscription String subscribeChannel = "testChannel"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_SUBSCRIBE, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel, CONTROL_SUBSCRIPTION_ID, "testId", CONTROL_DESTINATION_URI, "mock://test", CONTROL_PREDICATE, "true", CONTROL_EXPRESSION_LANGUAGE, "simple", CONTROL_PRIORITY, 10); when(message.getHeaders()).thenReturn(headers); Mockito.doNothing().when(callback).done(false); producer.performSubscribe(message, callback); Mockito.verify(controlService, Mockito.times(1)) .subscribeWithPredicateExpression( subscribeChannel, "testId", "mock://test", 10, "true", "simple", false); // Then, perform update headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_UPDATE, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel, CONTROL_SUBSCRIPTION_ID, "testId", CONTROL_DESTINATION_URI, "mock://testUpdate", CONTROL_PREDICATE, "true", CONTROL_EXPRESSION_LANGUAGE, "simple", CONTROL_PRIORITY, 100); when(message.getHeaders()).thenReturn(headers); Mockito.doNothing().when(callback).done(false); producer.performUpdate(message, callback); Mockito.verify(controlService, Mockito.times(1)) .subscribeWithPredicateExpression( subscribeChannel, "testId", "mock://testUpdate", 100, "true", "simple", true); } @Test void performSubscribeActionWithPredicateInBody() { String subscribeChannel = "testChannel"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_SUBSCRIBE, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel, CONTROL_SUBSCRIPTION_ID, "testId", CONTROL_DESTINATION_URI, "mock://test", CONTROL_PRIORITY, 10); Language language = context.resolveLanguage("simple"); Predicate predicate = language.createPredicate("true"); when(message.getBody()).thenReturn(predicate); when(message.getHeaders()).thenReturn(headers); Mockito.doNothing().when(callback).done(false); producer.performSubscribe(message, callback); Mockito.verify(controlService, Mockito.times(1)) .subscribeWithPredicateInstance( subscribeChannel, "testId", "mock://test", 10, predicate, false); } @Test void performSubscribeActionWithPredicateBean() { String subscribeChannel = "testChannel"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_SUBSCRIBE, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel, CONTROL_SUBSCRIPTION_ID, "testId", CONTROL_DESTINATION_URI, "mock://test", CONTROL_PRIORITY, 10, CONTROL_PREDICATE_BEAN, "testPredicate"); when(message.getHeaders()).thenReturn(headers); Mockito.doNothing().when(callback).done(false); producer.performSubscribe(message, callback); Mockito.verify(controlService, Mockito.times(1)) .subscribeWithPredicateBean( subscribeChannel, "testId", "mock://test", 10, "testPredicate", false); } @Test void performSubscribeActionWithMessageInBody() { String subscribeChannel = "testChannel"; DynamicRouterControlMessage subMsg = DynamicRouterControlMessage.Builder.newBuilder() .subscribeChannel(subscribeChannel) .subscriptionId("testId") .destinationUri("mock://test") .priority(10) .predicate("true") .expressionLanguage("simple") .build(); when(message.getBody()).thenReturn(subMsg); when(message.getBody(DynamicRouterControlMessage.class)).thenReturn(subMsg); Mockito.doNothing().when(callback).done(false); producer.performSubscribe(message, callback); Mockito.verify(controlService, Mockito.times(1)) .subscribeWithPredicateExpression( subscribeChannel, "testId", "mock://test", 10, "true", "simple", false); } @Test void performSubscribeActionWithMessageInBodyWithEmptyExpressionLanguage() { String subscribeChannel = "testChannel"; DynamicRouterControlMessage subMsg = DynamicRouterControlMessage.Builder.newBuilder() .subscribeChannel(subscribeChannel) .subscriptionId("testId") .destinationUri("mock://test") .priority(10) .predicate("true") .expressionLanguage("") .build(); when(message.getBody()).thenReturn(subMsg); when(message.getBody(DynamicRouterControlMessage.class)).thenReturn(subMsg); Exception ex = assertThrows(IllegalStateException.class, () -> producer.performSubscribe(message, callback)); assertEquals("Predicate bean could not be found", ex.getMessage()); } @Test void performSubscribeActionWithMessageInBodyWithEmptyExpression() { String subscribeChannel = "testChannel"; DynamicRouterControlMessage subMsg = DynamicRouterControlMessage.Builder.newBuilder() .subscribeChannel(subscribeChannel) .subscriptionId("testId") .destinationUri("mock://test") .priority(10) .predicate("") .expressionLanguage("simple") .build(); when(message.getBody()).thenReturn(subMsg); when(message.getBody(DynamicRouterControlMessage.class)).thenReturn(subMsg); Exception ex = assertThrows(IllegalStateException.class, () -> producer.performSubscribe(message, callback)); assertEquals("Predicate bean could not be found", ex.getMessage()); } @Test void performSubscribeActionWithMessageInBodyAndPredicateBean() { String subscribeChannel = "testChannel"; DynamicRouterControlMessage subMsg = DynamicRouterControlMessage.Builder.newBuilder() .subscribeChannel(subscribeChannel) .subscriptionId("testId") .destinationUri("mock://test") .priority(10) .predicateBean("testPredicate") .build(); when(message.getBody()).thenReturn(subMsg); when(message.getBody(DynamicRouterControlMessage.class)).thenReturn(subMsg); Mockito.doNothing().when(callback).done(false); producer.performSubscribe(message, callback); Mockito.verify(controlService, Mockito.times(1)) .subscribeWithPredicateBean( subscribeChannel, "testId", "mock://test", 10, "testPredicate", false); } @Test void performUpdateActionWithMessageInBody() { String subscribeChannel = "testChannel"; DynamicRouterControlMessage subMsg = DynamicRouterControlMessage.Builder.newBuilder() .subscribeChannel(subscribeChannel) .subscriptionId("testId") .destinationUri("mock://test") .priority(10) .predicate("true") .expressionLanguage("simple") .build(); when(message.getBody()).thenReturn(subMsg); when(message.getBody(DynamicRouterControlMessage.class)).thenReturn(subMsg); Mockito.doNothing().when(callback).done(false); producer.performUpdate(message, callback); Mockito.verify(controlService, Mockito.times(1)) .subscribeWithPredicateExpression( subscribeChannel, "testId", "mock://test", 10, "true", "simple", true); } @Test void testPerformListAction() { String subscribeChannel = "testChannel"; String filterString = "PrioritizedFilterProcessor [id: test, priority: 1, predicate: test, endpoint: test]"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_LIST, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel); when(exchange.getMessage()).thenReturn(message); when(message.getHeaders()).thenReturn(headers); when(controlService.getSubscriptionsForChannel(subscribeChannel)).thenReturn("[" + filterString + "]"); Mockito.doNothing().when(callback).done(false); producer.performList(exchange, callback); Mockito.verify(message, Mockito.times(1)).setBody("[" + filterString + "]", String.class); } @Test void testPerformListActionWithException() { String subscribeChannel = "testChannel"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_LIST, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel); when(exchange.getMessage()).thenReturn(message); when(message.getHeaders()).thenReturn(headers); Mockito.doNothing().when(callback).done(false); Exception ex = new IllegalArgumentException("test exception"); Mockito.doThrow(ex).when(controlService).getSubscriptionsForChannel(subscribeChannel); producer.performList(exchange, callback); Mockito.verify(exchange, Mockito.times(1)).setException(ex); } @Test void testPerformStatsAction() { String subscribeChannel = "testChannel"; String statString = "PrioritizedFilterStatistics [id: testId, count: 1, first:12345, last: 23456]"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_STATS, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel); when(exchange.getMessage()).thenReturn(message); when(message.getHeaders()).thenReturn(headers); when(controlService.getStatisticsForChannel(subscribeChannel)).thenReturn("[" + statString + "]"); Mockito.doNothing().when(callback).done(false); producer.performStats(exchange, callback); Mockito.verify(message, Mockito.times(1)).setBody("[" + statString + "]", String.class); } @Test void testPerformStatsActionWithException() { String subscribeChannel = "testChannel"; Map<String, Object> headers = Map.of( CONTROL_ACTION_HEADER, CONTROL_ACTION_STATS, CONTROL_SUBSCRIBE_CHANNEL, subscribeChannel); when(exchange.getMessage()).thenReturn(message); when(message.getHeaders()).thenReturn(headers); Exception ex = new IllegalArgumentException("test exception"); Mockito.doThrow(ex).when(controlService).getStatisticsForChannel(subscribeChannel); Mockito.doNothing().when(callback).done(false); producer.performStats(exchange, callback); Mockito.verify(exchange, Mockito.times(1)).setException(ex); } @Test void testGetInstance() { DynamicRouterControlProducer instance = new DynamicRouterControlProducerFactory() .getInstance(endpoint, controlService, configuration); Assertions.assertNotNull(instance); } }
DynamicRouterControlProducerTest
java
apache__flink
flink-core-api/src/main/java/org/apache/flink/api/java/tuple/Tuple11.java
{ "start": 1892, "end": 2522 }
class ____ extends Tuple11", then don't use * instances of Foo in a DataStream&lt;Tuple11&gt; / DataSet&lt;Tuple11&gt;, but declare it as * DataStream&lt;Foo&gt; / DataSet&lt;Foo&gt;.) * </ul> * * @see Tuple * @param <T0> The type of field 0 * @param <T1> The type of field 1 * @param <T2> The type of field 2 * @param <T3> The type of field 3 * @param <T4> The type of field 4 * @param <T5> The type of field 5 * @param <T6> The type of field 6 * @param <T7> The type of field 7 * @param <T8> The type of field 8 * @param <T9> The type of field 9 * @param <T10> The type of field 10 */ @Public public
Foo
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/DefaultExtJSONParser_parseArray.java
{ "start": 553, "end": 10723 }
class ____ extends TestCase { public void test_0() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,,,3]"); List list = new ArrayList(); parser.parseArray(int.class, list); Assert.assertEquals("[1, 2, 3]", list.toString()); } public void test_1() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,3]"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(int.class, list); Assert.assertEquals("[1, 2, 3]", list.toString()); } public void test_2() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("['1','2','3']"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(String.class, list); Assert.assertEquals("[1, 2, 3]", list.toString()); Assert.assertEquals("1", list.get(0)); } public void test_3() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,3]"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(BigDecimal.class, list); Assert.assertEquals("[1, 2, 3]", list.toString()); Assert.assertEquals(new BigDecimal("1"), list.get(0)); } public void test_4() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,3,null]"); parser.config(Feature.AllowArbitraryCommas, true); List list = new ArrayList(); parser.parseArray(BigDecimal.class, list); Assert.assertEquals("[1, 2, 3, null]", list.toString()); Assert.assertEquals(new BigDecimal("1"), list.get(0)); } public void test_5() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,3,null]"); Object[] array = parser.parseArray(new Type[] { Integer.class, BigDecimal.class, Long.class, String.class }); Assert.assertEquals(new Integer(1), array[0]); Assert.assertEquals(new BigDecimal("2"), array[1]); Assert.assertEquals(new Long(3), array[2]); Assert.assertEquals(null, array[3]); } public void test_error() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{}"); Exception error = null; try { parser.parseArray(new ArrayList()); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_6() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1.2]"); parser.config(Feature.UseBigDecimal, false); ArrayList list = new ArrayList(); parser.parseArray(list); Assert.assertEquals(Double.valueOf(1.2), list.get(0)); } public void test_7() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); DefaultJSONParser parser = new DefaultJSONParser("[\"2011-01-09T13:49:53.254\", \"xxx\", true, false, null, {}]"); parser.config(Feature.AllowISO8601DateFormat, true); ArrayList list = new ArrayList(); parser.parseArray(list); Assert.assertEquals(new Date(1294552193254L), list.get(0)); Assert.assertEquals("xxx", list.get(1)); Assert.assertEquals(Boolean.TRUE, list.get(2)); Assert.assertEquals(Boolean.FALSE, list.get(3)); Assert.assertEquals(null, list.get(4)); Assert.assertEquals(new JSONObject(), list.get(5)); } public void test_8() throws Exception { JSON.defaultTimeZone = TimeZone.getTimeZone("Asia/Shanghai"); DefaultJSONParser parser = new DefaultJSONParser("\"2011-01-09T13:49:53.254\""); parser.config(Feature.AllowISO8601DateFormat, true); Object value = parser.parse(); Assert.assertEquals(new Date(1294552193254L), value); } public void test_9() throws Exception { DefaultJSONParser parser = new DefaultJSONParser(""); parser.config(Feature.AllowISO8601DateFormat, true); Object value = parser.parse(); Assert.assertEquals(null, value); } public void test_error_2() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{}"); Exception error = null; try { parser.accept(JSONToken.NULL); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_10() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,3]"); Object[] array = parser.parseArray(new Type[] { Integer[].class }); Integer[] values = (Integer[]) array[0]; Assert.assertEquals(new Integer(1), values[0]); Assert.assertEquals(new Integer(2), values[1]); Assert.assertEquals(new Integer(3), values[2]); } public void test_11() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1]"); Object[] array = parser.parseArray(new Type[] { String.class }); Assert.assertEquals("1", array[0]); } public void test_12() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("['1']"); Object[] array = parser.parseArray(new Type[] { int.class }); Assert.assertEquals(new Integer(1), array[0]); } public void test_13() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("['1']"); Object[] array = parser.parseArray(new Type[] { Integer.class }); Assert.assertEquals(new Integer(1), array[0]); } public void test_14() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[]"); Object[] array = parser.parseArray(new Type[] {}); Assert.assertEquals(0, array.length); } public void test_15() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,null]"); ArrayList list = new ArrayList(); parser.config(Feature.AllowISO8601DateFormat, false); parser.parseArray(String.class, list); Assert.assertEquals("1", list.get(0)); Assert.assertEquals(null, list.get(1)); } public void test_16() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[[1]]"); parser.config(Feature.AllowISO8601DateFormat, false); Object[] array = parser.parseArray(new Type[] { new TypeReference<List<Integer>>() { }.getType() }); Assert.assertEquals(new Integer(1), ((List<Integer>) (array[0])).get(0)); } public void test_17() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[]"); Object[] array = parser.parseArray(new Type[] { Integer[].class }); Integer[] values = (Integer[]) array[0]; Assert.assertEquals(0, values.length); } public void test_18() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("null"); parser.config(Feature.AllowISO8601DateFormat, false); List<Integer> list = (List<Integer>) parser.parseArrayWithType(new TypeReference<List<Integer>>() { }.getType()); Assert.assertEquals(null, list); } public void test_error_var() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,null }"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { Object[] array = parser.parseArray(new Type[] { Integer[].class }); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_3() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,null }"); ArrayList list = new ArrayList(); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(String.class, list); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_4() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,null }"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(new Type[] { String.class }); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_5() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,null }"); ArrayList list = new ArrayList(); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(String.class, list); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_6() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{1,null }"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(new Type[] { String.class }); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_7() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("{1}"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(new Type[] {}); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } public void test_error_8() throws Exception { DefaultJSONParser parser = new DefaultJSONParser("[1,2,3 4]"); parser.config(Feature.AllowISO8601DateFormat, false); Exception error = null; try { parser.parseArray(new Type[] { Integer.class }); } catch (Exception ex) { error = ex; } Assert.assertNotNull(error); } }
DefaultExtJSONParser_parseArray
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/exec/spi/Callback.java
{ "start": 591, "end": 959 }
interface ____ { /** * Register a callback action */ void registerAfterLoadAction(AfterLoadAction afterLoadAction); /** * Invoke all {@linkplain #registerAfterLoadAction registered} actions */ void invokeAfterLoadActions(Object entity, EntityMappingType entityMappingType, SharedSessionContractImplementor session); boolean hasAfterLoadActions(); }
Callback
java
alibaba__druid
core/src/main/java/com/alibaba/druid/support/monitor/entity/MonitorInstance.java
{ "start": 698, "end": 2038 }
class ____ { private long id; private String domain; private String app; private String cluster; private String host; private String ip; private Date lastActiveTime; private Long lastPID; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getCluster() { return cluster; } public void setCluster(String cluster) { this.cluster = cluster; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Date getLastActiveTime() { return lastActiveTime; } public void setLastActiveTime(Date lastActiveTime) { this.lastActiveTime = lastActiveTime; } public Long getLastPID() { return lastPID; } public void setLastPID(Long lastPID) { this.lastPID = lastPID; } }
MonitorInstance
java
apache__camel
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java
{ "start": 408762, "end": 411377 }
class ____ extends YamlDeserializerBase<GlobalOptionsDefinition> { public GlobalOptionsDefinitionDeserializer() { super(GlobalOptionsDefinition.class); } @Override protected GlobalOptionsDefinition newInstance() { return new GlobalOptionsDefinition(); } @Override protected boolean setProperty(GlobalOptionsDefinition target, String propertyKey, String propertyName, Node node) { propertyKey = org.apache.camel.util.StringHelper.dashToCamelCase(propertyKey); switch(propertyKey) { case "globalOption": { java.util.List<org.apache.camel.model.GlobalOptionDefinition> val = asFlatList(node, org.apache.camel.model.GlobalOptionDefinition.class); target.setGlobalOptions(val); break; } default: { return false; } } return true; } } @YamlType( nodes = "grok", types = org.apache.camel.model.dataformat.GrokDataFormat.class, order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1, displayName = "Grok", description = "Unmarshal unstructured data to objects using Logstash based Grok patterns.", deprecated = false, properties = { @YamlProperty(name = "allowMultipleMatchesPerLine", type = "boolean", defaultValue = "true", description = "If false, every line of input is matched for pattern only once. Otherwise the line can be scanned multiple times when non-terminal pattern is used.", displayName = "Allow Multiple Matches Per Line"), @YamlProperty(name = "flattened", type = "boolean", defaultValue = "false", description = "Turns on flattened mode. In flattened mode the exception is thrown when there are multiple pattern matches with same key.", displayName = "Flattened"), @YamlProperty(name = "id", type = "string", description = "The id of this node", displayName = "Id"), @YamlProperty(name = "namedOnly", type = "boolean", defaultValue = "false", description = "Whether to capture named expressions only or not (i.e. %{IP:ip} but not ${IP})", displayName = "Named Only"), @YamlProperty(name = "pattern", type = "string", required = true, description = "The grok pattern to match lines of input", displayName = "Pattern") } ) public static
GlobalOptionsDefinitionDeserializer
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plan/logical/show/ShowInfo.java
{ "start": 1002, "end": 2534 }
class ____ extends LeafPlan implements TelemetryAware { private final List<Attribute> attributes; public ShowInfo(Source source) { super(source); attributes = new ArrayList<>(); for (var name : List.of("version", "date", "hash")) { attributes.add(new ReferenceAttribute(Source.EMPTY, null, name, KEYWORD)); } } @Override public void writeTo(StreamOutput out) { throw new UnsupportedOperationException("not serialized"); } @Override public String getWriteableName() { throw new UnsupportedOperationException("not serialized"); } @Override public List<Attribute> output() { return attributes; } public List<List<Object>> values() { List<Object> row = new ArrayList<>(attributes.size()); row.add(new BytesRef(Build.current().version())); row.add(new BytesRef(Build.current().date())); row.add(new BytesRef(Build.current().hash())); return List.of(row); } @Override public String telemetryLabel() { return "SHOW"; } @Override public boolean expressionsResolved() { return true; } @Override protected NodeInfo<? extends LogicalPlan> info() { return NodeInfo.create(this); } @Override public int hashCode() { return getClass().hashCode(); } @Override public boolean equals(Object obj) { return this == obj || obj != null && getClass() == obj.getClass(); } }
ShowInfo
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/QueryUtilsUnitTests.java
{ "start": 1803, "end": 36829 }
class ____ { private static final String QUERY = "select u from User u"; private static final String FQ_QUERY = "select u from org.acme.domain.User$Foo_Bar u"; private static final String SIMPLE_QUERY = "from User u"; private static final String COUNT_QUERY = "select count(u) from User u"; private static final String QUERY_WITH_AS = "select u from User as u where u.username = ?"; private static final Pattern MULTI_WHITESPACE = Pattern.compile("\\s+"); @Test void createsCountQueryCorrectly() { assertCountQuery(QUERY, COUNT_QUERY); } @Test void createsCountQueriesCorrectlyForCapitalLetterJPQL() { assertCountQuery("FROM User u WHERE u.foo.bar = ?", "select count(u) FROM User u WHERE u.foo.bar = ?"); assertCountQuery("SELECT u FROM User u where u.foo.bar = ?", "select count(u) FROM User u where u.foo.bar = ?"); } @Test void createsCountQueryForDistinctQueries() { assertCountQuery("select distinct u from User u where u.foo = ?", "select count(distinct u) from User u where u.foo = ?"); } @Test void createsCountQueryForConstructorQueries() { assertCountQuery("select distinct new User(u.name) from User u where u.foo = ?", "select count(distinct u) from User u where u.foo = ?"); } @Test void createsCountQueryForJoins() { assertCountQuery("select distinct new User(u.name) from User u left outer join u.roles r WHERE r = ?", "select count(distinct u) from User u left outer join u.roles r WHERE r = ?"); } @Test void createsCountQueryForQueriesWithSubSelects() { assertCountQuery("select u from User u left outer join u.roles r where r in (select r from Role)", "select count(u) from User u left outer join u.roles r where r in (select r from Role)"); } @Test void createsCountQueryForAliasesCorrectly() { assertCountQuery("select u from User as u", "select count(u) from User as u"); } @Test void allowsShortJpaSyntax() { assertCountQuery(SIMPLE_QUERY, COUNT_QUERY); } @Test // GH-2260 void detectsAliasCorrectly() { assertThat(detectAlias(QUERY)).isEqualTo("u"); assertThat(detectAlias(SIMPLE_QUERY)).isEqualTo("u"); assertThat(detectAlias(COUNT_QUERY)).isEqualTo("u"); assertThat(detectAlias(QUERY_WITH_AS)).isEqualTo("u"); assertThat(detectAlias("SELECT FROM USER U")).isEqualTo("U"); assertThat(detectAlias("select u from User u")).isEqualTo("u"); assertThat(detectAlias("select u from com.acme.User u")).isEqualTo("u"); assertThat(detectAlias("select u from T05User u")).isEqualTo("u"); assertThat(detectAlias("select u from User u where not exists (from User u2)")).isEqualTo("u"); assertThat(detectAlias("(select u from User u where not exists (from User u2))")).isEqualTo("u"); assertThat(detectAlias("(select u from User u where not exists ((from User u2 where not exists (from User u3))))")) .isEqualTo("u"); assertThat(detectAlias( "from Foo f left join f.bar b with type(b) = BarChild where (f.id = (select max(f.id) from Foo f2 where type(f2) = FooChild) or 1 <> 1) and 1=1")) .isEqualTo("f"); assertThat(detectAlias( "(from Foo f max(f) ((((select * from Foo f2 (from Foo f3) max(*)) (from Foo f4)) max(f5)) (f6)) (from Foo f7))")) .isEqualTo("f"); assertThat(detectAlias( "SELECT e FROM DbEvent e WHERE (CAST(:modifiedFrom AS date) IS NULL OR e.modificationDate >= :modifiedFrom)")) .isEqualTo("e"); assertThat(detectAlias("from User u where (cast(:effective as date) is null) OR :effective >= u.createdAt")) .isEqualTo("u"); assertThat(detectAlias("from User u where (cast(:effectiveDate as date) is null) OR :effectiveDate >= u.createdAt")) .isEqualTo("u"); assertThat(detectAlias("from User u where (cast(:effectiveFrom as date) is null) OR :effectiveFrom >= u.createdAt")) .isEqualTo("u"); assertThat( detectAlias("from User u where (cast(:e1f2f3ectiveFrom as date) is null) OR :effectiveFrom >= u.createdAt")) .isEqualTo("u"); } @Test // GH-2260 void testRemoveSubqueries() throws Exception { // boundary conditions assertThat(removeSubqueries(null)).isNull(); assertThat(removeSubqueries("")).isEmpty(); assertThat(removeSubqueries(" ")).isEqualTo(" "); assertThat(removeSubqueries("(")).isEqualTo("("); assertThat(removeSubqueries(")")).isEqualTo(")"); assertThat(removeSubqueries("(()")).isEqualTo("(()"); assertThat(removeSubqueries("())")).isEqualTo("())"); // realistic conditions assertThat(removeSubqueries(QUERY)).isEqualTo(QUERY); assertThat(removeSubqueries(SIMPLE_QUERY)).isEqualTo(SIMPLE_QUERY); assertThat(removeSubqueries(COUNT_QUERY)).isEqualTo(COUNT_QUERY); assertThat(removeSubqueries(QUERY_WITH_AS)).isEqualTo(QUERY_WITH_AS); assertThat(removeSubqueries("SELECT FROM USER U")).isEqualTo("SELECT FROM USER U"); assertThat(removeSubqueries("select u from User u")).isEqualTo("select u from User u"); assertThat(removeSubqueries("select u from com.acme.User u")).isEqualTo("select u from com.acme.User u"); assertThat(removeSubqueries("select u from T05User u")).isEqualTo("select u from T05User u"); assertThat(normalizeWhitespace(removeSubqueries("select u from User u where not exists (from User u2)"))) .isEqualTo("select u from User u where not exists"); assertThat(normalizeWhitespace(removeSubqueries("(select u from User u where not exists (from User u2))"))) .isEqualTo("(select u from User u where not exists )"); assertThat(normalizeWhitespace( removeSubqueries("select u from User u where not exists (from User u2 where not exists (from User u3))"))) .isEqualTo("select u from User u where not exists"); assertThat(normalizeWhitespace( removeSubqueries("select u from User u where not exists ((from User u2 where not exists (from User u3)))"))) .isEqualTo("select u from User u where not exists ( )"); assertThat(normalizeWhitespace( removeSubqueries("(select u from User u where not exists ((from User u2 where not exists (from User u3))))"))) .isEqualTo("(select u from User u where not exists ( ))"); } @Test // GH-2581 void testRemoveMultilineSubqueries() { assertThat(normalizeWhitespace(removeSubqueries(""" select u from User u where not exists ( from User u2 )"""))).isEqualTo("select u from User u where not exists"); assertThat(normalizeWhitespace(removeSubqueries(""" ( select u from User u\s where not exists ( from User u2 ) )"""))).isEqualTo("( select u from User u where not exists )"); assertThat(normalizeWhitespace(removeSubqueries(""" select u from User u\s where not exists ( from User u2\s where not exists ( from User u3 ) )"""))).isEqualTo("select u from User u where not exists"); assertThat(normalizeWhitespace(removeSubqueries(""" select u from User u\s where not exists ( ( from User u2\s where not exists ( from User u3 ) ) )"""))).isEqualTo("select u from User u where not exists ( )"); assertThat(normalizeWhitespace(removeSubqueries(""" ( select u from User u\s where not exists ( ( from User u2\s where not exists ( from User u3 ) ) ) )"""))).isEqualTo("( select u from User u where not exists ( ) )"); } @Test // GH-2557 void applySortingAccountsForNewlinesInSubselect() { Sort sort = Sort.by(Order.desc("age")); assertThat(QueryUtils.applySorting(""" select u from user u where exists (select u2 from user u2 ) """, sort)).isEqualTo(""" select u from user u where exists (select u2 from user u2 ) order by u.age desc"""); } @Test // GH-2563 void aliasDetectionProperlyHandlesNewlinesInSubselects() { assertThat(detectAlias(""" SELECT o FROM Order o AND EXISTS(SELECT 1 FROM Vehicle vehicle WHERE vehicle.vehicleOrderId = o.id AND LOWER(COALESCE(vehicle.make, '')) LIKE :query)""")).isEqualTo("o"); } private String normalizeWhitespace(String s) { Matcher matcher = MULTI_WHITESPACE.matcher(s); if (matcher.find()) { return matcher.replaceAll(" ").trim(); } return s.strip(); } @Test void allowsFullyQualifiedEntityNamesInQuery() { assertThat(detectAlias(FQ_QUERY)).isEqualTo("u"); assertCountQuery(FQ_QUERY, "select count(u) from org.acme.domain.User$Foo_Bar u"); } @Test // DATAJPA-252 void detectsJoinAliasesCorrectly() { Set<String> aliases = getOuterJoinAliases("select p from Person p left outer join x.foo b2_$ar where …"); assertThat(aliases).hasSize(1); assertThat(aliases).contains("b2_$ar"); aliases = getOuterJoinAliases("select p from Person p left join x.foo b2_$ar where …"); assertThat(aliases).hasSize(1); assertThat(aliases).contains("b2_$ar"); aliases = getOuterJoinAliases( "select p from Person p left outer join x.foo as b2_$ar, left join x.bar as foo where …"); assertThat(aliases).hasSize(2); assertThat(aliases).contains("b2_$ar", "foo"); aliases = getOuterJoinAliases( "select p from Person p left join x.foo as b2_$ar, left outer join x.bar foo where …"); assertThat(aliases).hasSize(2); assertThat(aliases).contains("b2_$ar", "foo"); } @Test // DATAJPA-252 void doesNotPrefixOrderReferenceIfOuterJoinAliasDetected() { String query = "select p from Person p left join p.address address"; assertThat(applySorting(query, Sort.by("address.city"))).endsWith("order by address.city asc"); assertThat(applySorting(query, Sort.by("address.city", "lastname"), "p")) .endsWith("order by address.city asc, p.lastname asc"); } @Test // DATAJPA-252 void extendsExistingOrderByClausesCorrectly() { String query = "select p from Person p order by p.lastname asc"; assertThat(applySorting(query, Sort.by("firstname"), "p")).endsWith("order by p.lastname asc, p.firstname asc"); } @Test // DATAJPA-296 void appliesIgnoreCaseOrderingCorrectly() { Sort sort = Sort.by(Order.by("firstname").ignoreCase()); String query = "select p from Person p"; assertThat(applySorting(query, sort, "p")).endsWith("order by lower(p.firstname) asc"); } @Test // DATAJPA-296 void appendsIgnoreCaseOrderingCorrectly() { Sort sort = Sort.by(Order.by("firstname").ignoreCase()); String query = "select p from Person p order by p.lastname asc"; assertThat(applySorting(query, sort, "p")).endsWith("order by p.lastname asc, lower(p.firstname) asc"); } @Test // DATAJPA-342 void usesReturnedVariableInCountProjectionIfSet() { assertCountQuery("select distinct m.genre from Media m where m.user = ?1 order by m.genre asc", "select count(distinct m.genre) from Media m where m.user = ?1"); } @Test // DATAJPA-343 void projectsCountQueriesForQueriesWithSubselects() { assertCountQuery("select o from Foo o where cb.id in (select b from Bar b)", "select count(o) from Foo o where cb.id in (select b from Bar b)"); } @Test // DATAJPA-148 void doesNotPrefixSortsIfFunction() { Sort sort = Sort.by("sum(foo)"); assertThatExceptionOfType(InvalidDataAccessApiUsageException.class) .isThrownBy(() -> applySorting("select p from Person p", sort, "p")); } @Test // DATAJPA-377 void removesOrderByInGeneratedCountQueryFromOriginalQueryIfPresent() { assertCountQuery("select distinct m.genre from Media m where m.user = ?1 OrDer By m.genre ASC", "select count(distinct m.genre) from Media m where m.user = ?1"); } @Test // DATAJPA-375 void findsExistingOrderByIndependentOfCase() { Sort sort = Sort.by("lastname"); String query = applySorting("select p from Person p ORDER BY p.firstname", sort, "p"); assertThat(query).endsWith("ORDER BY p.firstname, p.lastname asc"); } @Test // DATAJPA-409 void createsCountQueryForNestedReferenceCorrectly() { assertCountQuery("select a.b from A a", "select count(a.b) from A a"); } @Test // DATAJPA-420 void createsCountQueryForScalarSelects() { assertCountQuery("select p.lastname,p.firstname from Person p", "select count(p) from Person p"); } @Test // DATAJPA-456 void createCountQueryFromTheGivenCountProjection() { assertThat(createCountQueryFor("select p.lastname,p.firstname from Person p", "p.lastname")) .isEqualTo("select count(p.lastname) from Person p"); } @Test // DATAJPA-726 void detectsAliasesInPlainJoins() { String query = "select p from Customer c join c.productOrder p where p.delayed = true"; Sort sort = Sort.by("p.lineItems"); assertThat(applySorting(query, sort, "c")).endsWith("order by p.lineItems asc"); } @Test // DATAJPA-736 void supportsNonAsciiCharactersInEntityNames() { assertThat(createCountQueryFor("select u from Usèr u")).isEqualTo("select count(u) from Usèr u"); } @Test // DATAJPA-798 void detectsAliasInQueryContainingLineBreaks() { assertThat(detectAlias("select \n u \n from \n User \nu")).isEqualTo("u"); } @Test // DATAJPA-815 void doesPrefixPropertyWith() { String query = "from Cat c join Dog d"; Sort sort = Sort.by("dPropertyStartingWithJoinAlias"); assertThat(applySorting(query, sort, "c")).endsWith("order by c.dPropertyStartingWithJoinAlias asc"); } @Test // DATAJPA-938 void detectsConstructorExpressionInDistinctQuery() { assertThat(hasConstructorExpression("select distinct new Foo() from Bar b")).isTrue(); } @Test // DATAJPA-938 void detectsComplexConstructorExpression() { assertThat(hasConstructorExpression("select new foo.bar.Foo(ip.id, ip.name, sum(lp.amount)) " // + "from Bar lp join lp.investmentProduct ip " // + "where (lp.toDate is null and lp.fromDate <= :now and lp.fromDate is not null) and lp.accountId = :accountId " // + "group by ip.id, ip.name, lp.accountId " // + "order by ip.name ASC")).isTrue(); } @Test // DATAJPA-938 void detectsConstructorExpressionWithLineBreaks() { assertThat(hasConstructorExpression("select new foo.bar.FooBar(\na.id) from DtoA a ")).isTrue(); } @Test // DATAJPA-960 void doesNotQualifySortIfNoAliasDetected() { assertThat(applySorting("from mytable where ?1 is null", Sort.by("firstname"))).endsWith("order by firstname asc"); } @Test // DATAJPA-965, DATAJPA-970 void doesNotAllowWhitespaceInSort() { Sort sort = Sort.by("case when foo then bar"); assertThatExceptionOfType(InvalidDataAccessApiUsageException.class) .isThrownBy(() -> applySorting("select p from Person p", sort, "p")); } @Test // DATAJPA-965, DATAJPA-970 void doesNotPrefixUnsafeJpaSortFunctionCalls() { JpaSort sort = JpaSort.unsafe("sum(foo)"); assertThat(applySorting("select p from Person p", sort, "p")).endsWith("order by sum(foo) asc"); } @Test // DATAJPA-965, DATAJPA-970 void doesNotPrefixMultipleAliasedFunctionCalls() { String query = "SELECT AVG(m.price) AS avgPrice, SUM(m.stocks) AS sumStocks FROM Magazine m"; Sort sort = Sort.by("avgPrice", "sumStocks"); assertThat(applySorting(query, sort, "m")).endsWith("order by avgPrice asc, sumStocks asc"); } @Test // DATAJPA-965, DATAJPA-970 void doesNotPrefixSingleAliasedFunctionCalls() { String query = "SELECT AVG(m.price) AS avgPrice FROM Magazine m"; Sort sort = Sort.by("avgPrice"); assertThat(applySorting(query, sort, "m")).endsWith("order by avgPrice asc"); } @Test // DATAJPA-965, DATAJPA-970 void prefixesSingleNonAliasedFunctionCallRelatedSortProperty() { String query = "SELECT AVG(m.price) AS avgPrice FROM Magazine m"; Sort sort = Sort.by("someOtherProperty"); assertThat(applySorting(query, sort, "m")).endsWith("order by m.someOtherProperty asc"); } @Test // DATAJPA-965, DATAJPA-970 void prefixesNonAliasedFunctionCallRelatedSortPropertyWhenSelectClauseContainsAliasedFunctionForDifferentProperty() { String query = "SELECT m.name, AVG(m.price) AS avgPrice FROM Magazine m"; Sort sort = Sort.by("name", "avgPrice"); assertThat(applySorting(query, sort, "m")).endsWith("order by m.name asc, avgPrice asc"); } @Test // DATAJPA-965, DATAJPA-970 void doesNotPrefixAliasedFunctionCallNameWithMultipleNumericParameters() { String query = "SELECT SUBSTRING(m.name, 2, 5) AS trimmedName FROM Magazine m"; Sort sort = Sort.by("trimmedName"); assertThat(applySorting(query, sort, "m")).endsWith("order by trimmedName asc"); } @Test // DATAJPA-965, DATAJPA-970 void doesNotPrefixAliasedFunctionCallNameWithMultipleStringParameters() { String query = "SELECT CONCAT(m.name, 'foo') AS extendedName FROM Magazine m"; Sort sort = Sort.by("extendedName"); assertThat(applySorting(query, sort, "m")).endsWith("order by extendedName asc"); } @Test // DATAJPA-965, DATAJPA-970 void doesNotPrefixAliasedFunctionCallNameWithUnderscores() { String query = "SELECT AVG(m.price) AS avg_price FROM Magazine m"; Sort sort = Sort.by("avg_price"); assertThat(applySorting(query, sort, "m")).endsWith("order by avg_price asc"); } @Test // DATAJPA-965, DATAJPA-970 void doesNotPrefixAliasedFunctionCallNameWithDots() { String query = "SELECT AVG(m.price) AS m.avg FROM Magazine m"; Sort sort = Sort.by("m.avg"); assertThat(applySorting(query, sort, "m")).endsWith("order by m.avg asc"); } @Test // DATAJPA-965, DATAJPA-970 void doesNotPrefixAliasedFunctionCallNameWhenQueryStringContainsMultipleWhiteSpaces() { String query = "SELECT AVG( m.price ) AS avgPrice FROM Magazine m"; Sort sort = Sort.by("avgPrice"); assertThat(applySorting(query, sort, "m")).endsWith("order by avgPrice asc"); } @Test // GH-3911 void discoversFunctionAliasesCorrectly() { assertThat(getFunctionAliases("SELECT COUNT(1) a alias1,2 s alias2")).isEmpty(); assertThat(getFunctionAliases("SELECT COUNT(1) as alias1,2 as alias2")).containsExactly("alias1"); assertThat(getFunctionAliases("SELECT COUNT(1) as alias1,COUNT(2) as alias2")).contains("alias1", "alias2"); assertThat(getFunctionAliases("SELECT COUNT(1) as alias1, 2 as alias2")).containsExactly("alias1"); assertThat(getFunctionAliases("SELECT COUNT(1) as alias1, COUNT(2) as alias2")).contains("alias1", "alias2"); assertThat(getFunctionAliases("COUNT(1) as alias1,COUNT(2) as alias2")).contains("alias1", "alias2"); assertThat(getFunctionAliases("COUNT(1) as alias1,COUNT(2) as alias2")).contains("alias1", "alias2"); assertThat(getFunctionAliases("1 as alias1, COUNT(2) as alias2")).containsExactly("alias2"); assertThat(getFunctionAliases("1 as alias1, COUNT(2) as alias2")).containsExactly("alias2"); assertThat(getFunctionAliases("COUNT(1) as alias1,2 as alias2")).containsExactly("alias1"); assertThat(getFunctionAliases("COUNT(1) as alias1, 2 as alias2")).containsExactly("alias1"); } @Test // GH-3911 void discoversFieldAliasesCorrectly() { assertThat(getFieldAliases("SELECT 1 a alias1,2 s alias2")).isEmpty(); assertThat(getFieldAliases("SELECT 1 as alias1,2 as alias2")).contains("alias1", "alias2"); assertThat(getFieldAliases("SELECT 1 as alias1,2 as alias2")).contains("alias1", "alias2"); assertThat(getFieldAliases("1 as alias1,2 as alias2")).contains("alias1", "alias2"); assertThat(getFieldAliases("1 as alias1, 2 as alias2")).contains("alias1", "alias2"); } @Test // DATAJPA-1000 void discoversCorrectAliasForJoinFetch() { Set<String> aliases = QueryUtils .getOuterJoinAliases("SELECT DISTINCT user FROM User user LEFT JOIN FETCH user.authorities AS authority"); assertThat(aliases).containsExactly("authority"); } @Test // DATAJPA-1171 void doesNotContainStaticClauseInExistsQuery() { assertThat(QueryUtils.getExistsQueryString("entity", "x", Collections.singleton("id"))) // .endsWith("WHERE x.id = :id"); } @Test // DATAJPA-1363 void discoversAliasWithComplexFunction() { assertThat( QueryUtils.getFunctionAliases("select new MyDto(sum(case when myEntity.prop3=0 then 1 else 0 end) as myAlias")) // .contains("myAlias"); } @Test // DATAJPA-1506 void detectsAliasWithGroupAndOrderBy() { assertThat(detectAlias("select * from User group by name")).isNull(); assertThat(detectAlias("select * from User order by name")).isNull(); assertThat(detectAlias("select * from User u group by name")).isEqualTo("u"); assertThat(detectAlias("select * from User u order by name")).isEqualTo("u"); } @Test // DATAJPA-1500 void createCountQuerySupportsWhitespaceCharacters() { assertThat(createCountQueryFor(""" select * from User user where user.age = 18 order by user.name \s""")).isEqualTo(""" select count(user) from User user where user.age = 18"""); } @Test // GH-3329 void createCountQuerySupportsNewLineCharacters() { assertThat(createCountQueryFor(""" select * from User user where user.age = 18 order by user.name, user.age DESC \s""")).isEqualTo(""" select count(user) from User user where user.age = 18"""); } @Test // GH-2341 void createCountQueryStarCharacterConverted() { assertThat(createCountQueryFor("select * from User user")).isEqualTo("select count(user) from User user"); } @Test void createCountQuerySupportsLineBreaksInSelectClause() { assertThat(createCountQueryFor(""" select user.age, user.name from User user where user.age = 18 order by user.name \s""")).isEqualTo(""" select count(user) from User user where user.age = 18"""); } @Test // DATAJPA-1061 void appliesSortCorrectlyForFieldAliases() { String query = "SELECT m.price, lower(m.title) AS title, a.name as authorName FROM Magazine m INNER JOIN m.author a"; Sort sort = Sort.by("authorName"); String fullQuery = applySorting(query, sort); assertThat(fullQuery).endsWith("order by authorName asc"); } @Test // GH-2280 void appliesOrderingCorrectlyForFieldAliasWithIgnoreCase() { String query = "SELECT customer.id as id, customer.name as name FROM CustomerEntity customer"; Sort sort = Sort.by(Order.by("name").ignoreCase()); String fullQuery = applySorting(query, sort); assertThat(fullQuery).isEqualTo( "SELECT customer.id as id, customer.name as name FROM CustomerEntity customer order by lower(name) asc"); } @Test // DATAJPA-1061 void appliesSortCorrectlyForFunctionAliases() { String query = "SELECT m.price, lower(m.title) AS title, a.name as authorName FROM Magazine m INNER JOIN m.author a"; Sort sort = Sort.by("title"); String fullQuery = applySorting(query, sort); assertThat(fullQuery).endsWith("order by title asc"); } @Test // DATAJPA-1061 void appliesSortCorrectlyForSimpleField() { String query = "SELECT m.price, lower(m.title) AS title, a.name as authorName FROM Magazine m INNER JOIN m.author a"; Sort sort = Sort.by("price"); String fullQuery = applySorting(query, sort); assertThat(fullQuery).endsWith("order by m.price asc"); } @Test void createCountQuerySupportsLineBreakRightAfterDistinct() { assertThat(createCountQueryFor(""" select distinct user.age, user.name from User user""")).isEqualTo(createCountQueryFor(""" select distinct user.age, user.name from User user""")); } @Test void detectsAliasWithGroupAndOrderByWithLineBreaks() { assertThat(detectAlias("select * from User group\nby name")).isNull(); assertThat(detectAlias("select * from User order\nby name")).isNull(); assertThat(detectAlias("select * from User u group\nby name")).isEqualTo("u"); assertThat(detectAlias("select * from User u order\nby name")).isEqualTo("u"); assertThat(detectAlias("select * from User\nu\norder \n by name")).isEqualTo("u"); } @Test // DATAJPA-1679 void findProjectionClauseWithDistinct() { SoftAssertions.assertSoftly(sofly -> { sofly.assertThat(QueryUtils.getProjection("select * from x")).isEqualTo("*"); sofly.assertThat(QueryUtils.getProjection("select a, b, c from x")).isEqualTo("a, b, c"); sofly.assertThat(QueryUtils.getProjection("select distinct a, b, c from x")).isEqualTo("a, b, c"); sofly.assertThat(QueryUtils.getProjection("select DISTINCT a, b, c from x")).isEqualTo("a, b, c"); }); } @Test // DATAJPA-1696 void findProjectionClauseWithSubselect() { // This is not a required behavior, in fact the opposite is, // but it documents a current limitation. // to fix this without breaking findProjectionClauseWithIncludedFrom we need a more sophisticated parser. assertThat(QueryUtils.getProjection("select * from (select x from y)")).isNotEqualTo("*"); } @Test // DATAJPA-1696 void findProjectionClauseWithIncludedFrom() { assertThat(QueryUtils.getProjection("select x, frommage, y from t")).isEqualTo("x, frommage, y"); } @Test // GH-2341 void countProjectionDistrinctQueryIncludesNewLineAfterFromAndBeforeJoin() { String originalQuery = "SELECT DISTINCT entity1\nFROM Entity1 entity1\nLEFT JOIN Entity2 entity2 ON entity1.key = entity2.key"; assertCountQuery(originalQuery, "select count(DISTINCT entity1) FROM Entity1 entity1\nLEFT JOIN Entity2 entity2 ON entity1.key = entity2.key"); } @Test // GH-2341 void countProjectionDistinctQueryIncludesNewLineAfterEntity() { String originalQuery = "SELECT DISTINCT entity1\nFROM Entity1 entity1 LEFT JOIN Entity2 entity2 ON entity1.key = entity2.key"; assertCountQuery(originalQuery, "select count(DISTINCT entity1) FROM Entity1 entity1 LEFT JOIN Entity2 entity2 ON entity1.key = entity2.key"); } @Test // GH-2341 void countProjectionDistinctQueryIncludesNewLineAfterEntityAndBeforeWhere() { String originalQuery = "SELECT DISTINCT entity1\nFROM Entity1 entity1 LEFT JOIN Entity2 entity2 ON entity1.key = entity2.key\nwhere entity1.id = 1799"; assertCountQuery(originalQuery, "select count(DISTINCT entity1) FROM Entity1 entity1 LEFT JOIN Entity2 entity2 ON entity1.key = entity2.key\nwhere entity1.id = 1799"); } @Test // GH-2393 void createCountQueryStartsWithWhitespace() { assertThat(createCountQueryFor(" \nselect * from User u where u.age > :age")) .isEqualTo("select count(u) from User u where u.age > :age"); assertThat(createCountQueryFor(" \nselect u from User u where u.age > :age")) .isEqualTo("select count(u) from User u where u.age > :age"); } private static void assertCountQuery(String originalQuery, String countQuery) { assertThat(createCountQueryFor(originalQuery)).isEqualTo(countQuery); } @Test // GH-2260 void applySortingAccountsForNativeWindowFunction() { Sort sort = Sort.by(Order.desc("age")); // order by absent assertThat(QueryUtils.applySorting("select * from user u", sort)) .isEqualTo("select * from user u order by u.age desc"); // order by present assertThat(QueryUtils.applySorting("select * from user u order by u.lastname", sort)) .isEqualTo("select * from user u order by u.lastname, u.age desc"); // partition by assertThat(QueryUtils.applySorting("select dense_rank() over (partition by age) from user u", sort)) .isEqualTo("select dense_rank() over (partition by age) from user u order by u.age desc"); // order by in over clause assertThat(QueryUtils.applySorting("select dense_rank() over (order by lastname) from user u", sort)) .isEqualTo("select dense_rank() over (order by lastname) from user u order by u.age desc"); // order by in over clause (additional spaces) assertThat(QueryUtils.applySorting("select dense_rank() over ( order by lastname ) from user u", sort)) .isEqualTo("select dense_rank() over ( order by lastname ) from user u order by u.age desc"); // order by in over clause + at the end assertThat( QueryUtils.applySorting("select dense_rank() over (order by lastname) from user u order by u.lastname", sort)) .isEqualTo("select dense_rank() over (order by lastname) from user u order by u.lastname, u.age desc"); // partition by + order by in over clause assertThat(QueryUtils .applySorting("select dense_rank() over (partition by active, age order by lastname) from user u", sort)) .isEqualTo( "select dense_rank() over (partition by active, age order by lastname) from user u order by u.age desc"); // partition by + order by in over clause + order by at the end assertThat(QueryUtils.applySorting( "select dense_rank() over (partition by active, age order by lastname) from user u order by active", sort)) .isEqualTo( "select dense_rank() over (partition by active, age order by lastname) from user u order by active, u.age desc"); // partition by + order by in over clause + frame clause assertThat(QueryUtils.applySorting( "select dense_rank() over ( partition by active, age order by username rows between current row and unbounded following ) from user u", sort)).isEqualTo( "select dense_rank() over ( partition by active, age order by username rows between current row and unbounded following ) from user u order by u.age desc"); // partition by + order by in over clause + frame clause + order by at the end assertThat(QueryUtils.applySorting( "select dense_rank() over ( partition by active, age order by username rows between current row and unbounded following ) from user u order by active", sort)).isEqualTo( "select dense_rank() over ( partition by active, age order by username rows between current row and unbounded following ) from user u order by active, u.age desc"); // order by in subselect (select expression) assertThat( QueryUtils.applySorting("select lastname, (select i.id from item i order by i.id limit 1) from user u", sort)) .isEqualTo("select lastname, (select i.id from item i order by i.id limit 1) from user u order by u.age desc"); // order by in subselect (select expression) + at the end assertThat(QueryUtils.applySorting( "select lastname, (select i.id from item i order by 1 limit 1) from user u order by active", sort)).isEqualTo( "select lastname, (select i.id from item i order by 1 limit 1) from user u order by active, u.age desc"); // order by in subselect (from expression) assertThat(QueryUtils.applySorting("select * from (select * from user order by age desc limit 10) u", sort)) .isEqualTo("select * from (select * from user order by age desc limit 10) u order by age desc"); // order by in subselect (from expression) + at the end assertThat(QueryUtils.applySorting( "select * from (select * from user order by 1, 2, 3 desc limit 10) u order by u.active asc", sort)).isEqualTo( "select * from (select * from user order by 1, 2, 3 desc limit 10) u order by u.active asc, age desc"); } @Test // GH-2511 void countQueryUsesCorrectVariable() { String countQueryFor = createCountQueryFor("SELECT * FROM User WHERE created_at > $1"); assertThat(countQueryFor).isEqualTo("select count(*) FROM User WHERE created_at > $1"); countQueryFor = createCountQueryFor( "SELECT * FROM mytable WHERE nr = :number AND kon = :kon AND datum >= '2019-01-01'"); assertThat(countQueryFor) .isEqualTo("select count(*) FROM mytable WHERE nr = :number AND kon = :kon AND datum >= '2019-01-01'"); countQueryFor = createCountQueryFor("SELECT * FROM context ORDER BY time"); assertThat(countQueryFor).isEqualTo("select count(*) FROM context"); countQueryFor = createCountQueryFor("select * FROM users_statuses WHERE (user_created_at BETWEEN $1 AND $2)"); assertThat(countQueryFor) .isEqualTo("select count(*) FROM users_statuses WHERE (user_created_at BETWEEN $1 AND $2)"); countQueryFor = createCountQueryFor( "SELECT * FROM users_statuses us WHERE (user_created_at BETWEEN :fromDate AND :toDate)"); assertThat(countQueryFor) .isEqualTo("select count(us) FROM users_statuses us WHERE (user_created_at BETWEEN :fromDate AND :toDate)"); } @Test // GH-2496, GH-2522, GH-2537, GH-2045 void orderByShouldWorkWithSubSelectStatements() { Sort sort = Sort.by(Order.desc("age")); assertThat(QueryUtils.applySorting( """ SELECT foo_bar.* FROM foo foo INNER JOIN foo_bar_dnrmv foo_bar ON foo_bar.foo_id = foo.foo_id INNER JOIN ( SELECT foo_bar_action.*, RANK() OVER (PARTITION BY "foo_bar_action".attributes->>'baz' ORDER BY "foo_bar_action".attributes->>'qux' DESC) AS ranking FROM foo_bar_action WHERE foo_bar_action.deleted_ts IS NULL) foo_bar_action ON foo_bar.foo_bar_id = foo_bar_action.foo_bar_id AND ranking = 1 INNER JOIN bar bar ON foo_bar.bar_id = bar.bar_id INNER JOIN bar_metadata bar_metadata ON bar.bar_metadata_key = bar_metadata.bar_metadata_key WHERE foo.tenant_id =:tenantId AND (foo.attributes ->> :serialNum IN (:serialNumValue))""", sort)).endsWith("order by foo.age desc"); assertThat(QueryUtils.applySorting("select r " // + "From DataRecord r " // + "where " // + " ( " // + " r.adusrId = :userId " // + " or EXISTS( select 1 FROM DataRecordDvsRight dr WHERE dr.adusrId = :userId AND dr.dataRecord = r ) " // + ")", sort)).endsWith("order by r.age desc"); assertThat(QueryUtils.applySorting("select distinct u " // + "from FooBar u " // + "where [REDACTED] " // + "and (" // + " not exists (" // + " from FooBarGroup group " // + " where group in :excludedGroups " // + " and group in elements(u.groups)" // + " )" // + ")", sort)).endsWith("order by u.age desc"); assertThat(QueryUtils.applySorting("SELECT i " // + "FROM Item i " // + "FETCH ALL PROPERTIES \" " // + "+ \"WHERE i.id IN (\" " // + "+ \"SELECT max(i2.id) FROM Item i2 \" " // + "+ \"WHERE i2.field.id = :fieldId \" " // + "+ \"GROUP BY i2.field.id, i2.version)", sort)).endsWith("order by i.age desc"); assertThat(QueryUtils.applySorting(""" select\s f.id, ( select timestamp from bar where date(bar.timestamp) > '2022-05-21' and bar.foo_id = f.id\s order by date(bar.timestamp) desc limit 1 ) as timestamp from foo f""", sort)).endsWith("order by f.age desc"); } @ParameterizedTest // GH-2884 @ValueSource(strings = { ",", ";" }) void functionAliasShouldSupportArgumentsWithCommasOrArgumentsWithSemiColons(String arg) { assertThat(QueryUtils.getFunctionAliases(String.format(""" select s.id as id, s.name as name, gp.points from specialist s left join ( select q.specialist_id, listagg(q.points, '%s') as points from qualification q group by q.specialist_id ) gp on gp.specialist_id = s.id where name like :name """, arg))).containsExactly("points"); } @Test // GH-3324 void createCountQueryForSimpleQuery() { assertCountQuery("select * from User", "select count(*) from User"); assertCountQuery("select * from User u", "select count(u) from User u"); } }
QueryUtilsUnitTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/NestedStructEmbeddableTest.java
{ "start": 28043, "end": 28973 }
class ____ { private Integer integerField; private DoubleNested doubleNested; public SimpleEmbeddable() { } public SimpleEmbeddable(Integer integerField, String leaf) { this.integerField = integerField; this.doubleNested = new DoubleNested( leaf ); } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } SimpleEmbeddable that = (SimpleEmbeddable) o; if ( !Objects.equals( integerField, that.integerField ) ) { return false; } return Objects.equals( doubleNested, that.doubleNested ); } @Override public int hashCode() { int result = integerField != null ? integerField.hashCode() : 0; result = 31 * result + ( doubleNested != null ? doubleNested.hashCode() : 0 ); return result; } } @Embeddable @Struct( name = "double_nested") public static
SimpleEmbeddable
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/GetGroupsForTesting.java
{ "start": 1314, "end": 2717 }
class ____ extends GetGroupsBase { public GetGroupsForTesting(Configuration conf) { super(conf); } public GetGroupsForTesting(Configuration conf, PrintStream out) { super(conf, out); } @Override protected InetSocketAddress getProtocolAddress(Configuration conf) throws IOException { return conf.getSocketAddr(YarnConfiguration.RM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_ADMIN_PORT); } @Override public void setConf(Configuration conf) { conf = new YarnConfiguration(conf); super.setConf(conf); } @Override protected GetUserMappingsProtocol getUgmProtocol() throws IOException { Configuration conf = getConf(); final InetSocketAddress addr = conf.getSocketAddr( YarnConfiguration.RM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_ADMIN_ADDRESS, YarnConfiguration.DEFAULT_RM_ADMIN_PORT); final YarnRPC rpc = YarnRPC.create(conf); ResourceManagerAdministrationProtocol adminProtocol = (ResourceManagerAdministrationProtocol) rpc.getProxy( ResourceManagerAdministrationProtocol.class, addr, getConf()); return adminProtocol; } public static void main(String[] argv) throws Exception { int res = ToolRunner.run(new GetGroupsForTesting(new YarnConfiguration()), argv); System.exit(res); } }
GetGroupsForTesting
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/index/mapper/MapperTestCase.java
{ "start": 52400, "end": 81202 }
interface ____ { /** * @return True if synthetic source support is implemented to exactly store the source * without modifications. */ default boolean preservesExactSource() { return false; } default boolean ignoreAbove() { return false; } /** * Examples that should work when source is generated from doc values. */ SyntheticSourceExample example(int maxValues) throws IOException; /** * Examples of mappings that should be rejected when source is configured to * be loaded from doc values. */ List<SyntheticSourceInvalidExample> invalidExample() throws IOException; } protected abstract SyntheticSourceSupport syntheticSourceSupport(boolean ignoreMalformed); protected SyntheticSourceSupport syntheticSourceSupport(boolean ignoreMalformed, boolean columnReader) { return syntheticSourceSupport(ignoreMalformed); } public final void testSyntheticSource() throws IOException { assertSyntheticSource(syntheticSourceSupport(shouldUseIgnoreMalformed()).example(5)); } public final void testSyntheticSourceWithTranslogSnapshot() throws IOException { assertSyntheticSourceWithTranslogSnapshot(syntheticSourceSupport(shouldUseIgnoreMalformed()), true); assertSyntheticSourceWithTranslogSnapshot(syntheticSourceSupport(shouldUseIgnoreMalformed()), false); } public void testSyntheticSourceIgnoreMalformedExamples() throws IOException { assumeTrue("type doesn't support ignore_malformed", supportsIgnoreMalformed()); // We need to call this in order to hit the assumption inside so that // it tells us when field supports ignore_malformed but doesn't support it together with synthetic source. // E.g. `assumeFalse(ignoreMalformed)` syntheticSourceSupport(true); for (ExampleMalformedValue v : exampleMalformedValues()) { CheckedConsumer<XContentBuilder, IOException> mapping = b -> { v.mapping.accept(b); b.field("ignore_malformed", true); }; assertSyntheticSource(new SyntheticSourceExample(v.value, v.value, mapping)); } } private void assertSyntheticSource(SyntheticSourceExample example) throws IOException { DocumentMapper mapper = createSytheticSourceMapperService(mapping(b -> { b.startObject("field"); example.mapping().accept(b); b.endObject(); })).documentMapper(); assertThat(syntheticSource(mapper, example::buildInput), equalTo(example.expected())); assertThat( syntheticSource(mapper, new SourceFilter(new String[] { "field" }, null), example::buildInput), equalTo(example.expected()) ); assertThat(syntheticSource(mapper, new SourceFilter(null, new String[] { "field" }), example::buildInput), equalTo("{}")); } private void assertSyntheticSourceWithTranslogSnapshot(SyntheticSourceSupport support, boolean doIndexSort) throws IOException { var firstExample = support.example(1); int maxDocs = randomIntBetween(20, 50); var settings = Settings.builder() .put(IndexSettings.INDEX_MAPPER_SOURCE_MODE_SETTING.getKey(), SourceFieldMapper.Mode.SYNTHETIC) .put(IndexSettings.RECOVERY_USE_SYNTHETIC_SOURCE_SETTING.getKey(), true) .build(); var mapperService = createMapperService(getVersion(), settings, () -> true, mapping(b -> { b.startObject("field"); firstExample.mapping().accept(b); b.endObject(); })); var docMapper = mapperService.documentMapper(); try (var directory = newDirectory()) { List<SyntheticSourceExample> examples = new ArrayList<>(); IndexWriterConfig config = newIndexWriterConfig(random(), new StandardAnalyzer()); config.setIndexSort(new Sort(new SortField("sort", SortField.Type.LONG))); try (var iw = new RandomIndexWriter(random(), directory, config)) { for (int seqNo = 0; seqNo < maxDocs; seqNo++) { var example = support.example(randomIntBetween(1, 5)); examples.add(example); var doc = docMapper.parse(source(example::buildInput)); assertNull(doc.dynamicMappingsUpdate()); doc.updateSeqID(seqNo, 1); doc.version().setLongValue(0); if (doIndexSort) { doc.rootDoc().add(new NumericDocValuesField("sort", randomLong())); } iw.addDocuments(doc.docs()); if (frequently()) { iw.flush(); } } } try (var indexReader = wrapInMockESDirectoryReader(DirectoryReader.open(directory))) { int start = randomBoolean() ? 0 : randomIntBetween(1, maxDocs - 10); var snapshot = new LuceneSyntheticSourceChangesSnapshot( mapperService, new Engine.Searcher( "recovery", indexReader, new BM25Similarity(), null, new UsageTrackingQueryCachingPolicy(), () -> {} ), randomIntBetween(1, maxDocs), randomLongBetween(0, ByteSizeValue.ofBytes(Integer.MAX_VALUE).getBytes()), start, maxDocs, true, randomBoolean(), IndexVersion.current() ); for (int i = start; i < maxDocs; i++) { var example = examples.get(i); var op = snapshot.next(); if (op instanceof Translog.Index opIndex) { assertThat(opIndex.source().utf8ToString(), equalTo(example.expected())); } } } } } protected boolean supportsEmptyInputArray() { return true; } public final void testSupportsParsingObject() throws IOException { DocumentMapper mapper = createMapperService(fieldMapping(this::minimalMapping)).documentMapper(); FieldMapper fieldMapper = (FieldMapper) mapper.mappers().getMapper("field"); if (fieldMapper.supportsParsingObject()) { Object sampleValueForDocument = getSampleObjectForDocument(); assertThat(sampleValueForDocument, instanceOf(Map.class)); SourceToParse source = source(builder -> { builder.field("field"); builder.value(sampleValueForDocument); }); ParsedDocument doc = mapper.parse(source); assertNotNull(doc); } else { expectThrows(Exception.class, () -> mapper.parse(source(b -> { b.startObject("field"); b.endObject(); }))); } assertParseMinimalWarnings(); } public final void testSyntheticSourceMany() throws IOException { boolean ignoreMalformed = shouldUseIgnoreMalformed(); int maxValues = randomBoolean() ? 1 : 5; SyntheticSourceSupport support = syntheticSourceSupport(ignoreMalformed); DocumentMapper mapper = createSytheticSourceMapperService(mapping(b -> { b.startObject("field"); support.example(maxValues).mapping().accept(b); b.endObject(); })).documentMapper(); int count = between(2, 1000); String[] expected = new String[count]; try (Directory directory = newDirectory()) { try ( RandomIndexWriter iw = new RandomIndexWriter( random(), directory, LuceneTestCase.newIndexWriterConfig(random(), new MockAnalyzer(random())).setMergePolicy(NoMergePolicy.INSTANCE) ) ) { for (int i = 0; i < count; i++) { if (rarely() && supportsEmptyInputArray()) { expected[i] = support.preservesExactSource() ? "{\"field\":[]}" : "{}"; iw.addDocument(mapper.parse(source(b -> b.startArray("field").endArray())).rootDoc()); continue; } SyntheticSourceExample example = support.example(maxValues); expected[i] = example.expected(); iw.addDocument(mapper.parse(source(example::buildInput)).rootDoc()); } } try (DirectoryReader reader = DirectoryReader.open(directory)) { int i = 0; SourceLoader loader = mapper.mappers().newSourceLoader(null, SourceFieldMetrics.NOOP); StoredFieldLoader storedFieldLoader = loader.requiredStoredFields().isEmpty() ? StoredFieldLoader.empty() : StoredFieldLoader.create(false, loader.requiredStoredFields()); for (LeafReaderContext leaf : reader.leaves()) { int[] docIds = IntStream.range(0, leaf.reader().maxDoc()).toArray(); SourceLoader.Leaf sourceLoaderLeaf = loader.leaf(leaf.reader(), docIds); LeafStoredFieldLoader storedLeaf = storedFieldLoader.getLoader(leaf, docIds); for (int docId : docIds) { storedLeaf.advanceTo(docId); String source = sourceLoaderLeaf.source(storedLeaf, docId).internalSourceRef().utf8ToString(); assertThat("doc " + docId, source, equalTo(expected[i++])); } } } } } public final void testNoSyntheticSourceForScript() throws IOException { // Fetch the ingest script support to eagerly assumeFalse if the mapper doesn't support ingest scripts ingestScriptSupport(); DocumentMapper mapper = createSytheticSourceMapperService(mapping(b -> { b.startObject("field"); minimalMapping(b); b.field("script", randomBoolean() ? "empty" : "non-empty"); b.endObject(); })).documentMapper(); assertThat(syntheticSource(mapper, b -> {}), equalTo("{}")); } public final void testSyntheticSourceInObject() throws IOException { boolean ignoreMalformed = shouldUseIgnoreMalformed(); SyntheticSourceExample syntheticSourceExample = syntheticSourceSupport(ignoreMalformed).example(5); DocumentMapper mapper = createSytheticSourceMapperService(mapping(b -> { b.startObject("obj").startObject("properties").startObject("field"); syntheticSourceExample.mapping().accept(b); b.endObject().endObject().endObject(); })).documentMapper(); assertThat(syntheticSource(mapper, b -> { b.startObject("obj"); syntheticSourceExample.buildInput(b); b.endObject(); }), equalTo("{\"obj\":" + syntheticSourceExample.expected() + "}")); assertThat(syntheticSource(mapper, new SourceFilter(new String[] { "obj.field" }, null), b -> { b.startObject("obj"); syntheticSourceExample.buildInput(b); b.endObject(); }), equalTo("{\"obj\":" + syntheticSourceExample.expected() + "}")); assertThat(syntheticSource(mapper, new SourceFilter(null, new String[] { "obj.field" }), b -> { b.startObject("obj"); syntheticSourceExample.buildInput(b); b.endObject(); }), equalTo("{}")); } public final void testSyntheticEmptyList() throws IOException { assumeTrue("Field does not support [] as input", supportsEmptyInputArray()); boolean ignoreMalformed = shouldUseIgnoreMalformed(); SyntheticSourceSupport support = syntheticSourceSupport(ignoreMalformed); SyntheticSourceExample syntheticSourceExample = support.example(5); DocumentMapper mapper = createSytheticSourceMapperService(mapping(b -> { b.startObject("field"); syntheticSourceExample.mapping().accept(b); b.endObject(); })).documentMapper(); var expected = support.preservesExactSource() ? "{\"field\":[]}" : "{}"; assertThat(syntheticSource(mapper, b -> b.startArray("field").endArray()), equalTo(expected)); } protected boolean shouldUseIgnoreMalformed() { // 5% of test runs use ignore_malformed return supportsIgnoreMalformed() && randomDouble() <= 0.05; } public final void testSyntheticEmptyListNoDocValuesLoader() throws IOException { assumeTrue("Field does not support [] as input", supportsEmptyInputArray()); assertNoDocValueLoader(b -> b.startArray("field").endArray()); } public final void testEmptyDocumentNoDocValueLoader() throws IOException { assumeFalse("Field will add values even if no fields are supplied", addsValueWhenNotSupplied()); assertNoDocValueLoader(b -> {}); } protected boolean addsValueWhenNotSupplied() { return false; } private void assertNoDocValueLoader(CheckedConsumer<XContentBuilder, IOException> doc) throws IOException { boolean ignoreMalformed = supportsIgnoreMalformed() ? rarely() : false; SyntheticSourceExample syntheticSourceExample = syntheticSourceSupport(ignoreMalformed).example(5); DocumentMapper mapper = createSytheticSourceMapperService(mapping(b -> { b.startObject("field"); syntheticSourceExample.mapping().accept(b); b.endObject(); })).documentMapper(); try (Directory directory = newDirectory()) { RandomIndexWriter iw = new RandomIndexWriter(random(), directory); iw.addDocument(mapper.parse(source(doc)).rootDoc()); iw.close(); try (DirectoryReader reader = DirectoryReader.open(directory)) { LeafReader leafReader = getOnlyLeafReader(reader); SourceLoader.SyntheticFieldLoader fieldLoader = ((FieldMapper) mapper.mapping().getRoot().getMapper("field")) .syntheticFieldLoader(); /* * null means "there are no values for this field, don't call me". * Empty fields are common enough that we need to make sure this * optimization kicks in. */ assertThat(fieldLoader.docValuesLoader(leafReader, new int[] { 0 }), nullValue()); } } } public final void testSyntheticSourceInvalid() throws IOException { boolean ignoreMalformed = shouldUseIgnoreMalformed(); List<SyntheticSourceInvalidExample> examples = new ArrayList<>(syntheticSourceSupport(ignoreMalformed).invalidExample()); for (SyntheticSourceInvalidExample example : examples) { Exception e = expectThrows( IllegalArgumentException.class, example.toString(), () -> createSytheticSourceMapperService(mapping(b -> { b.startObject("field"); example.mapping.accept(b); b.endObject(); })) ); assertThat(e.getMessage(), example.error); } } public final void testSyntheticSourceInNestedObject() throws IOException { boolean ignoreMalformed = shouldUseIgnoreMalformed(); SyntheticSourceExample syntheticSourceExample = syntheticSourceSupport(ignoreMalformed).example(5); DocumentMapper mapper = createSytheticSourceMapperService(mapping(b -> { b.startObject("obj").field("type", "nested").startObject("properties").startObject("field"); syntheticSourceExample.mapping().accept(b); b.endObject().endObject().endObject(); })).documentMapper(); assertThat(syntheticSource(mapper, b -> { b.startObject("obj"); syntheticSourceExample.buildInput(b); b.endObject(); }), equalTo("{\"obj\":" + syntheticSourceExample.expected() + "}")); assertThat(syntheticSource(mapper, new SourceFilter(new String[] { "obj.field" }, null), b -> { b.startObject("obj"); syntheticSourceExample.buildInput(b); b.endObject(); }), equalTo("{\"obj\":" + syntheticSourceExample.expected() + "}")); assertThat(syntheticSource(mapper, new SourceFilter(null, new String[] { "obj.field" }), b -> { b.startObject("obj"); syntheticSourceExample.buildInput(b); b.endObject(); }), equalTo("{\"obj\":{}}")); assertThat(syntheticSource(mapper, new SourceFilter(null, new String[] { "obj" }), b -> { b.startObject("obj"); syntheticSourceExample.buildInput(b); b.endObject(); }), equalTo("{}")); } protected SyntheticSourceSupport syntheticSourceSupportForKeepTests(boolean ignoreMalformed, Mapper.SourceKeepMode keepMode) { return syntheticSourceSupport(ignoreMalformed); } public void testSyntheticSourceKeepNone() throws IOException { SyntheticSourceExample example = syntheticSourceSupportForKeepTests(shouldUseIgnoreMalformed(), Mapper.SourceKeepMode.NONE).example( 1 ); DocumentMapper mapper = createSytheticSourceMapperService(mapping(b -> { b.startObject("field"); b.field("synthetic_source_keep", "none"); example.mapping().accept(b); b.endObject(); })).documentMapper(); assertThat(syntheticSource(mapper, example::buildInput), equalTo(example.expected())); } public void testSyntheticSourceKeepAll() throws IOException { SyntheticSourceExample example = syntheticSourceSupportForKeepTests(shouldUseIgnoreMalformed(), Mapper.SourceKeepMode.ALL).example( 1 ); DocumentMapper mapperAll = createSytheticSourceMapperService(mapping(b -> { b.startObject("field"); b.field("synthetic_source_keep", "all"); example.mapping().accept(b); b.endObject(); })).documentMapper(); var builder = XContentFactory.jsonBuilder(); builder.startObject(); example.buildInput(builder); builder.endObject(); String expected = Strings.toString(builder); assertThat(syntheticSource(mapperAll, example::buildInput), equalTo(expected)); } public void testSyntheticSourceKeepArrays() throws IOException { SyntheticSourceExample example = syntheticSourceSupportForKeepTests(shouldUseIgnoreMalformed(), Mapper.SourceKeepMode.ARRAYS) .example(1); DocumentMapper mapperAll = createSytheticSourceMapperService(mapping(b -> { b.startObject("field"); b.field("synthetic_source_keep", randomSyntheticSourceKeep()); example.mapping().accept(b); b.endObject(); })).documentMapper(); int elementCount = randomIntBetween(2, 5); CheckedConsumer<XContentBuilder, IOException> buildInput = (XContentBuilder builder) -> { example.buildInputArray(builder, elementCount); }; var builder = XContentFactory.jsonBuilder(); builder.startObject(); buildInput.accept(builder); builder.endObject(); String expected = Strings.toString(builder); String actual = syntheticSource(mapperAll, buildInput); assertThat(actual, equalTo(expected)); } protected boolean supportsBulkLongBlockReading() { return false; } protected boolean supportsBulkIntBlockReading() { return false; } protected boolean supportsBulkDoubleBlockReading() { return false; } protected Object[] getThreeSampleValues() { return new Object[] { 1L, 2L, 3L }; } protected Object[] getThreeEncodedSampleValues() { return getThreeSampleValues(); } public void testSingletonIntBulkBlockReading() throws IOException { assumeTrue("field type supports bulk singleton int reading", supportsBulkIntBlockReading()); testSingletonBulkBlockReading(columnAtATimeReader -> (AbstractIntsFromDocValuesBlockLoader.Singleton) columnAtATimeReader); } public void testSingletonLongBulkBlockReading() throws IOException { assumeTrue("field type supports bulk singleton long reading", supportsBulkLongBlockReading()); testSingletonBulkBlockReading(columnAtATimeReader -> (LongsBlockLoader.Singleton) columnAtATimeReader); } public void testSingletonDoubleBulkBlockReading() throws IOException { assumeTrue("field type supports bulk singleton double reading", supportsBulkDoubleBlockReading()); testSingletonBulkBlockReading(columnAtATimeReader -> (DoublesBlockLoader.Singleton) columnAtATimeReader); } private void testSingletonBulkBlockReading(Function<BlockLoader.ColumnAtATimeReader, BlockDocValuesReader> readerCast) throws IOException { assumeTrue("field type supports bulk singleton long reading", supportsBulkLongBlockReading()); var settings = indexSettings(IndexVersion.current(), 1, 1).put("index.mode", "logsdb").build(); var mapperService = createMapperService(settings, fieldMapping(this::minimalMapping)); var mapper = mapperService.documentMapper(); var mockBlockContext = mock(MappedFieldType.BlockLoaderContext.class); when(mockBlockContext.fieldExtractPreference()).thenReturn(MappedFieldType.FieldExtractPreference.DOC_VALUES); IndexMetadata indexMetadata = new IndexMetadata.Builder("index").settings(settings).build(); IndexSettings indexSettings = new IndexSettings(indexMetadata, settings); when(mockBlockContext.indexSettings()).thenReturn(indexSettings); var sampleValuesForIndexing = getThreeSampleValues(); var expectedSampleValues = getThreeEncodedSampleValues(); { // Dense CheckedConsumer<RandomIndexWriter, IOException> builder = iw -> { for (int i = 0; i < 3; i++) { var value = sampleValuesForIndexing[i]; var doc = mapper.parse(source(b -> b.field("@timestamp", 1L).field("field", "" + value))).rootDoc(); iw.addDocument(doc); } }; CheckedConsumer<DirectoryReader, IOException> test = reader -> { assertThat(reader.leaves(), hasSize(1)); assertThat(reader.numDocs(), equalTo(3)); LeafReaderContext context = reader.leaves().get(0); var blockLoader = mapperService.fieldType("field").blockLoader(mockBlockContext); BlockDocValuesReader columnReader = readerCast.apply(blockLoader.columnAtATimeReader(context)); assertThat( ((BlockDocValuesReader.NumericDocValuesAccessor) columnReader).numericDocValues(), instanceOf(BlockLoader.OptionalColumnAtATimeReader.class) ); var docBlock = TestBlock.docs(IntStream.range(0, 3).toArray()); var block = (TestBlock) columnReader.read(TestBlock.factory(), docBlock, 0, randomBoolean()); for (int i = 0; i < block.size(); i++) { assertThat(block.get(i), equalTo(expectedSampleValues[i])); } }; withLuceneIndex(mapperService, builder, test); } { // Sparse CheckedConsumer<RandomIndexWriter, IOException> builder = iw -> { var doc = mapper.parse(source(b -> b.field("@timestamp", 1L).field("field", "" + sampleValuesForIndexing[0]))).rootDoc(); iw.addDocument(doc); doc = mapper.parse(source(b -> b.field("@timestamp", 1L))).rootDoc(); iw.addDocument(doc); doc = mapper.parse(source(b -> b.field("@timestamp", 1L).field("field", "" + sampleValuesForIndexing[2]))).rootDoc(); iw.addDocument(doc); }; CheckedConsumer<DirectoryReader, IOException> test = reader -> { assertThat(reader.leaves(), hasSize(1)); assertThat(reader.numDocs(), equalTo(3)); LeafReaderContext context = reader.leaves().get(0); var blockLoader = mapperService.fieldType("field").blockLoader(mockBlockContext); BlockDocValuesReader columnReader = readerCast.apply(blockLoader.columnAtATimeReader(context)); var docBlock = TestBlock.docs(IntStream.range(0, 3).toArray()); var block = (TestBlock) columnReader.read(TestBlock.factory(), docBlock, 0, false); assertThat(block.get(0), equalTo(expectedSampleValues[0])); assertThat(block.get(1), nullValue()); assertThat(block.get(2), equalTo(expectedSampleValues[2])); docBlock = TestBlock.docs(0, 2); columnReader = readerCast.apply(blockLoader.columnAtATimeReader(context)); var numeric = ((BlockDocValuesReader.NumericDocValuesAccessor) columnReader).numericDocValues(); assertThat(numeric, instanceOf(BlockLoader.OptionalColumnAtATimeReader.class)); var directReader = (BlockLoader.OptionalColumnAtATimeReader) numeric; boolean toInt = supportsBulkIntBlockReading(); assertNull(directReader.tryRead(TestBlock.factory(), docBlock, 0, false, null, toInt)); block = (TestBlock) directReader.tryRead(TestBlock.factory(), docBlock, 0, true, null, toInt); assertNotNull(block); assertThat(block.get(0), equalTo(expectedSampleValues[0])); assertThat(block.get(1), equalTo(expectedSampleValues[2])); }; withLuceneIndex(mapperService, builder, test); } { // Multi-value CheckedConsumer<RandomIndexWriter, IOException> builder = iw -> { var doc = mapper.parse(source(b -> b.field("@timestamp", 1L).field("field", "" + sampleValuesForIndexing[0]))).rootDoc(); iw.addDocument(doc); doc = mapper.parse( source( b -> b.field("@timestamp", 1L) .field("field", List.of("" + sampleValuesForIndexing[0], "" + sampleValuesForIndexing[1])) ) ).rootDoc(); iw.addDocument(doc); doc = mapper.parse(source(b -> b.field("@timestamp", 1L).field("field", "" + sampleValuesForIndexing[2]))).rootDoc(); iw.addDocument(doc); }; CheckedConsumer<DirectoryReader, IOException> test = reader -> { assertThat(reader.leaves(), hasSize(1)); assertThat(reader.numDocs(), equalTo(3)); LeafReaderContext context = reader.leaves().get(0); var blockLoader = mapperService.fieldType("field").blockLoader(mockBlockContext); var columnReader = blockLoader.columnAtATimeReader(context); assertThat( columnReader, anyOf( instanceOf(LongsBlockLoader.Sorted.class), instanceOf(DoublesBlockLoader.Sorted.class), instanceOf(AbstractIntsFromDocValuesBlockLoader.Singleton.class) ) ); var docBlock = TestBlock.docs(IntStream.range(0, 3).toArray()); var block = (TestBlock) columnReader.read(TestBlock.factory(), docBlock, 0, false); assertThat(block.get(0), equalTo(expectedSampleValues[0])); assertThat(block.get(1), equalTo(List.of(expectedSampleValues[0], expectedSampleValues[1]))); assertThat(block.get(2), equalTo(expectedSampleValues[2])); }; withLuceneIndex(mapperService, builder, test); } } protected String randomSyntheticSourceKeep() { return randomFrom("all", "arrays"); } @Override protected final <T> T compileScript(Script script, ScriptContext<T> context) { return ingestScriptSupport().compileScript(script, context); } protected abstract IngestScriptSupport ingestScriptSupport(); protected abstract
SyntheticSourceSupport
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/jpa/internal/util/PersistenceUnitTransactionTypeHelper.java
{ "start": 460, "end": 1931 }
class ____ { private PersistenceUnitTransactionTypeHelper() { } public static PersistenceUnitTransactionType interpretTransactionType(Object value) { if ( value == null ) { return null; } else if ( value instanceof PersistenceUnitTransactionType transactionType ) { return transactionType; } else { final String stringValue = value.toString().trim(); if ( stringValue.isEmpty() ) { return null; } else if ( JTA.name().equalsIgnoreCase( stringValue ) ) { return JTA; } else if ( RESOURCE_LOCAL.name().equalsIgnoreCase( stringValue ) ) { return RESOURCE_LOCAL; } else { throw new PersistenceException( "Unknown TransactionType: '" + stringValue + "'" ); } } } @SuppressWarnings("removal") public static jakarta.persistence.spi.PersistenceUnitTransactionType toDeprecatedForm(PersistenceUnitTransactionType type) { return type == null ? null : switch (type) { case JTA -> jakarta.persistence.spi.PersistenceUnitTransactionType.JTA; case RESOURCE_LOCAL -> jakarta.persistence.spi.PersistenceUnitTransactionType.RESOURCE_LOCAL; }; } @SuppressWarnings("removal") public static PersistenceUnitTransactionType toNewForm(jakarta.persistence.spi.PersistenceUnitTransactionType type) { return type == null ? null : switch (type) { case JTA -> PersistenceUnitTransactionType.JTA; case RESOURCE_LOCAL -> PersistenceUnitTransactionType.RESOURCE_LOCAL; }; } }
PersistenceUnitTransactionTypeHelper
java
apache__flink
flink-state-backends/flink-statebackend-rocksdb/src/test/java/org/apache/flink/state/rocksdb/RocksDBStateBackendConfigTest.java
{ "start": 48480, "end": 49510 }
class ____ implements ConfigurableRocksDBOptionsFactory { public static final ConfigOption<Integer> BACKGROUND_JOBS_OPTION = ConfigOptions.key("my.custom.rocksdb.backgroundJobs").intType().defaultValue(2); private int backgroundJobs = BACKGROUND_JOBS_OPTION.defaultValue(); @Override public DBOptions createDBOptions( DBOptions currentOptions, Collection<AutoCloseable> handlesToClose) { return currentOptions.setMaxBackgroundJobs(backgroundJobs); } @Override public ColumnFamilyOptions createColumnOptions( ColumnFamilyOptions currentOptions, Collection<AutoCloseable> handlesToClose) { return currentOptions.setCompactionStyle(CompactionStyle.UNIVERSAL); } @Override public RocksDBOptionsFactory configure(ReadableConfig configuration) { this.backgroundJobs = configuration.get(BACKGROUND_JOBS_OPTION); return this; } } }
TestOptionsFactory
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/language/JavaScriptExpression.java
{ "start": 1295, "end": 1994 }
class ____ extends TypedExpressionDefinition { public JavaScriptExpression() { } protected JavaScriptExpression(JavaScriptExpression source) { super(source); } public JavaScriptExpression(String expression) { super(expression); } private JavaScriptExpression(Builder builder) { super(builder); } @Override public JavaScriptExpression copyDefinition() { return new JavaScriptExpression(this); } @Override public String getLanguage() { return "js"; } /** * {@code Builder} is a specific builder for {@link JavaScriptExpression}. */ @XmlTransient public static
JavaScriptExpression
java
netty__netty
transport/src/main/java/io/netty/channel/group/ChannelGroup.java
{ "start": 3440, "end": 3764 }
class ____ extends {@link ChannelInboundHandlerAdapter} { * {@code @Override} * public void channelActive({@link ChannelHandlerContext} ctx) { * // closed on shutdown. * <strong>allChannels.add(ctx.channel());</strong> * super.channelActive(ctx); * } * } * </pre> */ public
MyHandler
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringSetPropertyNameDynamicTest.java
{ "start": 1299, "end": 2083 }
class ____ { public static final String EXCHANGE_PROP_TX_FAILED = "ExchangePropTxFailed"; } @Test public void testSetPropertyNameWithExpression() throws Exception { MockEndpoint resultEndpoint = getMockEndpoint("mock:end"); resultEndpoint.expectedMessageCount(1); sendBody("direct:start", "Hello"); resultEndpoint.assertIsSatisfied(); Exchange exchange = resultEndpoint.getExchanges().get(0); assertEquals(Boolean.TRUE, exchange.getProperty(TestConstans.EXCHANGE_PROP_TX_FAILED, Boolean.class)); } @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/setPropertyNameDynamic.xml"); } }
TestConstans
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/JsonFunctionsITCase.java
{ "start": 81896, "end": 82209 }
class ____ extends ScalarFunction { @DataTypeHint("ROW<f0 STRING, f1 INT>") public RowData eval(String name, Integer age) { return GenericRowData.of(StringData.fromString(name), age); } } /** Helper POJO for testing structured types. */ public static
CreateInternalRow
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/refresh/RefreshAndInheritanceTest.java
{ "start": 3464, "end": 3798 }
class ____ { @Id @GeneratedValue private long id; @ManyToOne @JoinColumn(name = "OWNER_ID", foreignKey = @ForeignKey()) protected Company owner = null; public void setOwner(Company owner) { this.owner = owner; } } @Entity(name = "ManufacturerComputerSystem") @DiscriminatorValue("2") public static
ComputerSystem
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/SessionFactory.java
{ "start": 7273, "end": 18677 }
interface ____ extends EntityManagerFactory, Referenceable, Serializable { /** * The JNDI name, used to bind the {@code SessionFactory} to JNDI. */ String getJndiName(); /** * Obtain a {@linkplain org.hibernate.SessionBuilder session builder} * for creating new instances of {@link org.hibernate.Session} with * certain customized options. * * @return The session builder */ SessionBuilder withOptions(); /** * Open a {@link Session}. * <p> * Any JDBC {@link Connection connection} will be obtained lazily from the * {@link org.hibernate.engine.jdbc.connections.spi.ConnectionProvider} * as needed to perform requested work. * * @return The created session. * * @apiNote This operation is very similar to {@link #createEntityManager()} * * @throws HibernateException Indicates a problem opening the session; pretty rare here. */ Session openSession() throws HibernateException; /** * Obtains the <em>current session</em>, an instance of {@link Session} * implicitly associated with some context or scope. For example, the * session might be associated with the current thread, or with the * current JTA transaction. * <p> * The context used for scoping the current session (that is, the * definition of what precisely "current" means here) is determined * by an implementation of * {@link org.hibernate.context.spi.CurrentSessionContext}. An * implementation may be selected using the configuration property * {@value org.hibernate.cfg.AvailableSettings#CURRENT_SESSION_CONTEXT_CLASS}. * <p> * If no {@link org.hibernate.context.spi.CurrentSessionContext} is * explicitly configured, but JTA support is enabled, then * {@link org.hibernate.context.internal.JTASessionContext} is used, * and the current session is scoped to the active JTA transaction. * * @return The current session. * * @throws HibernateException Indicates an issue locating a suitable current session. * * @see org.hibernate.context.spi.CurrentSessionContext * @see org.hibernate.cfg.AvailableSettings#CURRENT_SESSION_CONTEXT_CLASS */ Session getCurrentSession() throws HibernateException; /** * Obtain a {@link StatelessSession} builder. * * @return The stateless session builder */ StatelessSessionBuilder withStatelessOptions(); /** * Open a new stateless session. * * @return The new stateless session. */ StatelessSession openStatelessSession(); /** * Open a new stateless session, utilizing the specified JDBC * {@link Connection}. * * @param connection Connection provided by the application. * * @return The new stateless session. */ StatelessSession openStatelessSession(Connection connection); /** * Open a {@link Session} and use it to perform the given action. * * @apiNote This method does not begin a transaction, and so * the session is not automatically flushed before the method * returns unless either: * <ul> * <li>the given action calls {@link Session#flush() flush()} * explicitly, or * <li>a transaction is initiated by the given action, using * {@link Session#inTransaction}, for example. * </ul> * * @see #inTransaction(Consumer) */ default void inSession(Consumer<? super Session> action) { try ( Session session = openSession() ) { action.accept( session ); } } /** * Open a {@link StatelessSession} and use it to perform the * given action. * * @apiNote This method does not begin a transaction, and so * the session is not automatically flushed before the method * returns unless either: * <ul> * <li>the given action calls {@link Session#flush() flush()} * explicitly, or * <li>a transaction is initiated by the given action, using * {@link Session#inTransaction}, for example. * </ul> * * @see #inStatelessTransaction(Consumer) * * @since 6.3 */ default void inStatelessSession(Consumer<? super StatelessSession> action) { try ( StatelessSession session = openStatelessSession() ) { action.accept( session ); } } /** * Open a {@link Session} and use it to perform the given action * within the bounds of a transaction. * * @apiNote This method competes with the JPA-defined method * {@link #runInTransaction} */ default void inTransaction(Consumer<? super Session> action) { inSession( session -> manageTransaction( session, session.beginTransaction(), action ) ); } /** * Open a {@link StatelessSession} and use it to perform an action * within the bounds of a transaction. * * @since 6.3 */ default void inStatelessTransaction(Consumer<? super StatelessSession> action) { inStatelessSession( session -> manageTransaction( session, session.beginTransaction(), action ) ); } /** * Open a {@link Session} and use it to obtain a value. * * @apiNote This method does not begin a transaction, and so * the session is not automatically flushed before the method * returns unless either: * <ul> * <li>the given action calls {@link Session#flush() flush()} * explicitly, or * <li>a transaction is initiated by the given action, using * {@link Session#inTransaction}, for example. * </ul> * * @see #fromTransaction(Function) */ default <R> R fromSession(Function<? super Session,R> action) { try ( Session session = openSession() ) { return action.apply( session ); } } /** * Open a {@link StatelessSession} and use it to obtain a value. * * @apiNote This method does not begin a transaction, and so * the session is not automatically flushed before the method * returns unless either: * <ul> * <li>the given action calls {@link Session#flush() flush()} * explicitly, or * <li>a transaction is initiated by the given action, using * {@link Session#inTransaction}, for example. * </ul> * * @see #fromStatelessTransaction(Function) * * @since 6.3 */ default <R> R fromStatelessSession(Function<? super StatelessSession,R> action) { try ( StatelessSession session = openStatelessSession() ) { return action.apply( session ); } } /** * Open a {@link Session} and use it to obtain a value * within the bounds of a transaction. * * @apiNote This method competes with the JPA-defined method * {@link #callInTransaction} */ default <R> R fromTransaction(Function<? super Session,R> action) { return fromSession( session -> manageTransaction( session, session.beginTransaction(), action ) ); } /** * Open a {@link StatelessSession} and use it to obtain a value * within the bounds of a transaction. * * @since 6.3 */ default <R> R fromStatelessTransaction(Function<? super StatelessSession,R> action) { return fromStatelessSession( session -> manageTransaction( session, session.beginTransaction(), action ) ); } /** * Create a new {@link Session}. */ @Override Session createEntityManager(); /** * Create a new {@link Session}, with the given * {@linkplain EntityManager#getProperties properties}. */ @Override Session createEntityManager(Map<?, ?> map); /** * Create a new {@link Session}, with the given * {@linkplain SynchronizationType synchronization type}. * * @throws IllegalStateException if the persistence unit has * {@linkplain jakarta.persistence.PersistenceUnitTransactionType#RESOURCE_LOCAL * resource-local} transaction management */ @Override Session createEntityManager(SynchronizationType synchronizationType); /** * Create a new {@link Session}, with the given * {@linkplain SynchronizationType synchronization type} and * {@linkplain EntityManager#getProperties properties}. * * @throws IllegalStateException if the persistence unit has * {@linkplain jakarta.persistence.PersistenceUnitTransactionType#RESOURCE_LOCAL * resource-local} transaction management */ @Override Session createEntityManager(SynchronizationType synchronizationType, Map<?, ?> map); /** * Retrieve the {@linkplain Statistics statistics} for this factory. * * @return The statistics. */ Statistics getStatistics(); /** * A {@link SchemaManager} with the same default catalog and schema as * pooled connections belonging to this factory. Intended mostly as a * convenience for writing tests. * * @since 6.2 */ @Override SchemaManager getSchemaManager(); /** * Obtain a {@link HibernateCriteriaBuilder} which may be used to * {@linkplain HibernateCriteriaBuilder#createQuery(Class) construct} * {@linkplain org.hibernate.query.criteria.JpaCriteriaQuery criteria * queries}. * * @see SharedSessionContract#getCriteriaBuilder() */ @Override HibernateCriteriaBuilder getCriteriaBuilder(); /** * Destroy this {@code SessionFactory} and release all its resources, * including caches and connection pools. * <p> * It is the responsibility of the application to ensure that there are * no open {@linkplain Session sessions} before calling this method as * the impact on those {@linkplain Session sessions} is indeterminate. * <p> * No-ops if already {@linkplain #isClosed() closed}. * * @throws HibernateException Indicates an issue closing the factory. */ @Override void close() throws HibernateException; /** * Is this factory already closed? * * @return True if this factory is already closed; false otherwise. */ boolean isClosed(); /** * Obtain direct access to the underlying cache regions. * * @return The direct cache access API. */ @Override Cache getCache(); /** * Return all {@link EntityGraph}s registered for the given entity type. * * @see #addNamedEntityGraph */ <T> List<EntityGraph<? super T>> findEntityGraphsByType(Class<T> entityClass); /** * Return the root {@link EntityGraph} with the given name, or {@code null} * if there is no graph with the given name. * * @param name the name given to some {@link jakarta.persistence.NamedEntityGraph} * @return an instance of {@link RootGraph} * * @see #addNamedEntityGraph */ RootGraph<?> findEntityGraphByName(String name); /** * * Create an {@link EntityGraph} for the given entity type. * * @param entityType The entity type for the graph * * @see #createGraphForDynamicEntity(String) * * @since 7.0 */ default <T> RootGraph<T> createEntityGraph(Class<T> entityType) { return new RootGraphImpl<>( null, (EntityDomainType<T>) getMetamodel().entity( entityType ) ); } /** * Create an {@link EntityGraph} which may be used from loading a * {@linkplain org.hibernate.metamodel.RepresentationMode#MAP dynamic} * entity with {@link Session#find(EntityGraph, Object, FindOption...)}. * <p> * This allows a dynamic entity to be loaded without the need for a cast. * <pre> * var MyDynamicEntity_ = factory.createGraphForDynamicEntity("MyDynamicEntity"); * Map&lt;String,?&gt; myDynamicEntity = session.find(MyDynamicEntity_, id); * </pre> * * @apiNote Dynamic entities are normally defined using XML mappings. * * @param entityName The name of the dynamic entity * * @since 7.0 * * @see Session#find(EntityGraph, Object, FindOption...) * @see #createEntityGraph(Class) */ RootGraph<Map<String,?>> createGraphForDynamicEntity(String entityName); /** * Creates a {@link RootGraph} for the given {@code rootEntityClass} and parses the * graph text into it. * * @param rootEntityClass The entity
SessionFactory
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderUncompressedTest.java
{ "start": 1417, "end": 2874 }
class ____ { private static final String CONFIG = "log4j-rolling4.xml"; private static final String DIR = "target/rolling4"; private final Logger logger = LogManager.getLogger(RollingAppenderUncompressedTest.class.getName()); @ClassRule public static CleanFolders rule = new CleanFolders(CONFIG); @BeforeClass public static void setupClass() { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG); } @AfterClass public static void cleanupClass() { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); final LoggerContext ctx = LoggerContext.getContext(); ctx.reconfigure(); StatusLogger.getLogger().reset(); } @Test public void testAppender() { for (int i = 0; i < 100; ++i) { logger.debug("This is test message number " + i); } final File dir = new File(DIR); assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0); final File[] files = dir.listFiles(); assertNotNull(files); boolean found = false; for (final File file : files) { final String name = file.getName(); if (name.startsWith("test1") && name.endsWith(".log")) { found = true; break; } } assertTrue("No archived files found", found); } }
RollingAppenderUncompressedTest
java
elastic__elasticsearch
x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/ssl/SSLTrustRestrictionsTests.java
{ "start": 12070, "end": 12681 }
class ____ { private final PrivateKey key; private final Path keyPath; private final X509Certificate certificate; private final Path certPath; private CertificateInfo(PrivateKey key, Path keyPath, X509Certificate certificate, Path certPath) { this.key = key; this.keyPath = keyPath; this.certificate = certificate; this.certPath = certPath; } private Path getKeyPath() { return keyPath; } private Path getCertPath() { return certPath; } } }
CertificateInfo
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/event/spi/DirtyCheckEventListener.java
{ "start": 282, "end": 495 }
interface ____ { /** Handle the given dirty-check event. * * @param event The dirty-check event to be handled. */ void onDirtyCheck(DirtyCheckEvent event) throws HibernateException; }
DirtyCheckEventListener
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuilderMetadata.java
{ "start": 7998, "end": 8250 }
interface ____ { /** * Return the name of the creator. * @return the creator name */ String getName(); /** * Return the version of the creator. * @return the creator version */ String getVersion(); } /** * Update
CreatedBy
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/example/SpringExpressionTrimTest.java
{ "start": 1149, "end": 2047 }
class ____ extends SpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/spring/example/expressionTrim.xml"); } @Test public void testDefault() throws Exception { String out = template.requestBody("direct:a", "World", String.class); assertEquals("Hello World", out); } @Test public void testTrim() throws Exception { String out = template.requestBody("direct:b", "World", String.class); assertEquals("Hello World", out); } @Test public void testNoTrim() throws Exception { String out = template.requestBody("direct:c", "World", String.class); // the xml has whitespace noise which is not trimmed assertEquals("\n Hello World\n ", out); } }
SpringExpressionTrimTest
java
mapstruct__mapstruct
processor/src/test/resources/fixtures/21/org/mapstruct/ap/test/bugs/_3591/ContainerBeanMapperImpl.java
{ "start": 522, "end": 3163 }
class ____ implements ContainerBeanMapper { @Override public ContainerBeanDto mapWithMapMapping(ContainerBean containerBean, ContainerBeanDto containerBeanDto) { if ( containerBean == null ) { return containerBeanDto; } if ( containerBeanDto.getBeanMap() != null ) { Map<String, ContainerBeanDto> map = stringContainerBeanMapToStringContainerBeanDtoMap( containerBean.getBeanMap() ); if ( map != null ) { containerBeanDto.getBeanMap().clear(); containerBeanDto.getBeanMap().putAll( map ); } else { containerBeanDto.setBeanMap( null ); } } else { Map<String, ContainerBeanDto> map = stringContainerBeanMapToStringContainerBeanDtoMap( containerBean.getBeanMap() ); if ( map != null ) { containerBeanDto.setBeanMap( map ); } } containerBeanDto.setBeanStream( containerBeanStreamToContainerBeanDtoStream( containerBean.getBeanStream() ) ); containerBeanDto.setValue( containerBean.getValue() ); return containerBeanDto; } protected Stream<ContainerBeanDto> containerBeanStreamToContainerBeanDtoStream(Stream<ContainerBean> stream) { if ( stream == null ) { return null; } return stream.map( containerBean -> containerBeanToContainerBeanDto( containerBean ) ); } protected ContainerBeanDto containerBeanToContainerBeanDto(ContainerBean containerBean) { if ( containerBean == null ) { return null; } ContainerBeanDto containerBeanDto = new ContainerBeanDto(); containerBeanDto.setBeanMap( stringContainerBeanMapToStringContainerBeanDtoMap( containerBean.getBeanMap() ) ); containerBeanDto.setBeanStream( containerBeanStreamToContainerBeanDtoStream( containerBean.getBeanStream() ) ); containerBeanDto.setValue( containerBean.getValue() ); return containerBeanDto; } protected Map<String, ContainerBeanDto> stringContainerBeanMapToStringContainerBeanDtoMap(Map<String, ContainerBean> map) { if ( map == null ) { return null; } Map<String, ContainerBeanDto> map1 = LinkedHashMap.newLinkedHashMap( map.size() ); for ( java.util.Map.Entry<String, ContainerBean> entry : map.entrySet() ) { String key = entry.getKey(); ContainerBeanDto value = containerBeanToContainerBeanDto( entry.getValue() ); map1.put( key, value ); } return map1; } }
ContainerBeanMapperImpl
java
apache__camel
test-infra/camel-test-infra-opensearch/src/main/java/org/apache/camel/test/infra/opensearch/services/RemoteOpenSearchInfraService.java
{ "start": 945, "end": 1953 }
class ____ implements OpenSearchInfraService { private static final int OPEN_SEARCH_PORT = 9200; @Override public int getPort() { String strPort = System.getProperty(OpenSearchProperties.OPEN_SEARCH_PORT); if (strPort != null) { return Integer.parseInt(strPort); } return OPEN_SEARCH_PORT; } @Override public String getOpenSearchHost() { return System.getProperty(OpenSearchProperties.OPEN_SEARCH_HOST); } @Override public void registerProperties() { // NO-OP } @Override public void initialize() { registerProperties(); } @Override public void shutdown() { // NO-OP } @Override public String getUsername() { return System.getProperty(OpenSearchProperties.OPEN_SEARCH_USERNAME); } @Override public String getPassword() { return System.getProperty(OpenSearchProperties.OPEN_SEARCH_PASSWORD); } }
RemoteOpenSearchInfraService
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/serialization/EntityProxySerializationTest.java
{ "start": 6432, "end": 7096 }
class ____ implements Serializable { private Long id; private String name; Set<ChildEntity> children = new HashSet<>(); @Id public Long getId() { return id; } public void setId(final Long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } @OneToMany(targetEntity = ChildEntity.class, mappedBy = "parent") @Fetch(FetchMode.SELECT) public Set<ChildEntity> getChildren() { return children; } public void setChildren(final Set<ChildEntity> children) { this.children = children; } } @Entity(name = "ChildEntity") static
SimpleEntity
java
dropwizard__dropwizard
dropwizard-json-logging/src/main/java/io/dropwizard/logging/json/layout/TimestampFormatter.java
{ "start": 427, "end": 2185 }
class ____ { private static final Map<String, DateTimeFormatter> FORMATTERS = Map.ofEntries( entry("ISO_LOCAL_DATE", DateTimeFormatter.ISO_LOCAL_DATE), entry("ISO_OFFSET_DATE", DateTimeFormatter.ISO_OFFSET_DATE), entry("ISO_DATE", DateTimeFormatter.ISO_DATE), entry("ISO_LOCAL_TIME", DateTimeFormatter.ISO_LOCAL_TIME), entry("ISO_OFFSET_TIME", DateTimeFormatter.ISO_OFFSET_TIME), entry("ISO_TIME", DateTimeFormatter.ISO_TIME), entry("ISO_LOCAL_DATE_TIME", DateTimeFormatter.ISO_LOCAL_DATE_TIME), entry("ISO_OFFSET_DATE_TIME", DateTimeFormatter.ISO_OFFSET_DATE_TIME), entry("ISO_ZONED_DATE_TIME", DateTimeFormatter.ISO_ZONED_DATE_TIME), entry("ISO_DATE_TIME", DateTimeFormatter.ISO_DATE_TIME), entry("ISO_ORDINAL_DATE", DateTimeFormatter.ISO_ORDINAL_DATE), entry("ISO_WEEK_DATE", DateTimeFormatter.ISO_WEEK_DATE), entry("ISO_INSTANT", DateTimeFormatter.ISO_INSTANT), entry("BASIC_ISO_DATE", DateTimeFormatter.BASIC_ISO_DATE), entry("RFC_1123_DATE_TIME", DateTimeFormatter.RFC_1123_DATE_TIME)); @Nullable private final DateTimeFormatter dateTimeFormatter; public TimestampFormatter(@Nullable String timestampFormat, ZoneId zoneId) { if (timestampFormat != null) { dateTimeFormatter = Optional.ofNullable(FORMATTERS.get(timestampFormat)) .orElseGet(() -> DateTimeFormatter.ofPattern(timestampFormat)) .withZone(zoneId); } else { dateTimeFormatter = null; } } public Object format(long timestamp) { return dateTimeFormatter == null ? timestamp : dateTimeFormatter.format(Instant.ofEpochMilli(timestamp)); } }
TimestampFormatter
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/SqmWindow.java
{ "start": 1572, "end": 10249 }
class ____ extends AbstractSqmNode implements JpaWindow, SqmVisitableNode { private final List<SqmExpression<?>> partitions; private final List<SqmSortSpecification> orderList; private FrameMode mode; private FrameKind startKind; private @Nullable SqmExpression<?> startExpression; private FrameKind endKind; private @Nullable SqmExpression<?> endExpression; private FrameExclusion exclusion; public SqmWindow(NodeBuilder nodeBuilder) { this( nodeBuilder, new ArrayList<>(), new ArrayList<>(), RANGE, UNBOUNDED_PRECEDING, null, CURRENT_ROW, null, NO_OTHERS ); } public SqmWindow( NodeBuilder nodeBuilder, List<SqmExpression<?>> partitions, List<SqmSortSpecification> orderList, FrameMode mode, FrameKind startKind, @Nullable SqmExpression<?> startExpression, FrameKind endKind, @Nullable SqmExpression<?> endExpression, FrameExclusion exclusion) { super( nodeBuilder ); this.partitions = partitions; this.orderList = orderList; this.mode = mode; this.startKind = startKind; this.startExpression = startExpression; this.endKind = endKind; this.endExpression = endExpression; this.exclusion = exclusion; } public List<SqmExpression<?>> getPartitions() { return partitions; } public List<SqmSortSpecification> getOrderList() { return orderList; } public @Nullable SqmExpression<?> getStartExpression() { return startExpression; } public @Nullable SqmExpression<?> getEndExpression() { return endExpression; } public FrameMode getMode() { return mode; } public FrameKind getStartKind() { return startKind; } public FrameKind getEndKind() { return endKind; } public FrameExclusion getExclusion() { return exclusion; } @Override public JpaWindow frameRows(JpaWindowFrame startFrame, JpaWindowFrame endFrame) { return this.setFrames( ROWS, startFrame, endFrame ); } @Override public JpaWindow frameRange(JpaWindowFrame startFrame, JpaWindowFrame endFrame) { return this.setFrames( RANGE, startFrame, endFrame ); } @Override public JpaWindow frameGroups(JpaWindowFrame startFrame, JpaWindowFrame endFrame) { return this.setFrames( GROUPS, startFrame, endFrame ); } private SqmWindow setFrames(FrameMode frameMode, JpaWindowFrame startFrame, JpaWindowFrame endFrame) { this.mode = frameMode; if ( startFrame != null ) { this.startKind = startFrame.getKind(); this.startExpression = (SqmExpression<?>) startFrame.getExpression(); } if ( endFrame != null ) { this.endKind = endFrame.getKind(); this.endExpression = (SqmExpression<?>) endFrame.getExpression(); } return this; } @Override public JpaWindow frameExclude(FrameExclusion frameExclusion) { this.exclusion = frameExclusion; return this; } @Override public JpaWindow partitionBy(Expression<?>... expressions) { for ( Expression<?> expression : expressions ) { this.partitions.add( (SqmExpression<?>) expression ); } return this; } @Override public JpaWindow orderBy(Order... orders) { for ( Order order : orders ) { this.orderList.add( (SqmSortSpecification) order ); } return this; } public SqmWindow copy(SqmCopyContext context) { final SqmWindow existing = context.getCopy( this ); if ( existing != null ) { return existing; } final List<SqmExpression<?>> partitionsCopy = new ArrayList<>( partitions.size() ); for ( SqmExpression<?> partition : partitions ) { partitionsCopy.add( partition.copy( context ) ); } final List<SqmSortSpecification> orderListCopy = new ArrayList<>( orderList.size() ); for ( SqmSortSpecification sortSpecification : orderList ) { orderListCopy.add( sortSpecification.copy( context ) ); } return context.registerCopy( this, new SqmWindow( nodeBuilder(), partitionsCopy, orderListCopy, mode, startKind, startExpression == null ? null : startExpression.copy( context ), endKind, endExpression == null ? null : endExpression.copy( context ), exclusion ) ); } @Override public <X> X accept(SemanticQueryWalker<X> walker) { return walker.visitWindow( this ); } @Override public void appendHqlString(StringBuilder hql, SqmRenderContext context) { boolean needsWhitespace = false; if ( !this.partitions.isEmpty() ) { needsWhitespace = true; hql.append( "partition by " ); this.partitions.get( 0 ).appendHqlString( hql, context ); for ( int i = 1; i < this.partitions.size(); i++ ) { hql.append( ',' ); this.partitions.get( i ).appendHqlString( hql, context ); } } if ( !orderList.isEmpty() ) { if ( needsWhitespace ) { hql.append( ' ' ); } needsWhitespace = true; hql.append( "order by " ); orderList.get( 0 ).appendHqlString( hql, context ); for ( int i = 1; i < orderList.size(); i++ ) { hql.append( ',' ); orderList.get( i ).appendHqlString( hql, context ); } } if ( mode == RANGE && startKind == UNBOUNDED_PRECEDING && endKind == CURRENT_ROW && exclusion == NO_OTHERS ) { // This is the default, so we don't need to render anything } else { if ( needsWhitespace ) { hql.append( ' ' ); } switch ( mode ) { case GROUPS: hql.append( "groups " ); break; case RANGE: hql.append( "range " ); break; case ROWS: hql.append( "rows " ); break; } if ( endKind == CURRENT_ROW ) { renderFrameKind( hql, startKind, startExpression, context ); } else { hql.append( "between " ); renderFrameKind( hql, startKind, startExpression, context ); hql.append( " and " ); renderFrameKind( hql, endKind, endExpression, context ); } switch ( exclusion ) { case TIES: hql.append( " exclude ties" ); break; case CURRENT_ROW: hql.append( " exclude current row" ); break; case GROUP: hql.append( " exclude group" ); break; } } } private static void renderFrameKind(StringBuilder sb, FrameKind kind, @Nullable SqmExpression<?> expression, SqmRenderContext context) { switch ( kind ) { case CURRENT_ROW: sb.append( "current row" ); break; case UNBOUNDED_PRECEDING: sb.append( "unbounded preceding" ); break; case UNBOUNDED_FOLLOWING: sb.append( "unbounded following" ); break; case OFFSET_PRECEDING: castNonNull( expression ).appendHqlString( sb, context ); sb.append( " preceding" ); break; case OFFSET_FOLLOWING: castNonNull( expression ).appendHqlString( sb, context ); sb.append( " following" ); break; default: throw new UnsupportedOperationException( "Unsupported frame kind: " + kind ); } } @Override public boolean equals(@Nullable Object object) { return object instanceof SqmWindow sqmWindow && Objects.equals( partitions, sqmWindow.partitions ) && Objects.equals( orderList, sqmWindow.orderList ) && mode == sqmWindow.mode && startKind == sqmWindow.startKind && Objects.equals( startExpression, sqmWindow.startExpression ) && endKind == sqmWindow.endKind && Objects.equals( endExpression, sqmWindow.endExpression ) && exclusion == sqmWindow.exclusion; } @Override public int hashCode() { int result = Objects.hashCode( partitions ); result = 31 * result + Objects.hashCode( orderList ); result = 31 * result + mode.hashCode(); result = 31 * result + startKind.hashCode(); result = 31 * result + Objects.hashCode( startExpression ); result = 31 * result + endKind.hashCode(); result = 31 * result + Objects.hashCode( endExpression ); result = 31 * result + exclusion.hashCode(); return result; } @Override public boolean isCompatible(Object object) { return object instanceof SqmWindow sqmWindow && SqmCacheable.areCompatible( partitions, sqmWindow.partitions ) && SqmCacheable.areCompatible( orderList, sqmWindow.orderList ) && mode == sqmWindow.mode && startKind == sqmWindow.startKind && SqmCacheable.areCompatible( startExpression, sqmWindow.startExpression ) && endKind == sqmWindow.endKind && SqmCacheable.areCompatible( endExpression, sqmWindow.endExpression ) && exclusion == sqmWindow.exclusion; } @Override public int cacheHashCode() { int result = SqmCacheable.cacheHashCode( partitions ); result = 31 * result + SqmCacheable.cacheHashCode( orderList ); result = 31 * result + mode.hashCode(); result = 31 * result + startKind.hashCode(); result = 31 * result + SqmCacheable.cacheHashCode( startExpression ); result = 31 * result + endKind.hashCode(); result = 31 * result + SqmCacheable.cacheHashCode( endExpression ); result = 31 * result + exclusion.hashCode(); return result; } }
SqmWindow
java
google__guava
android/guava/src/com/google/common/io/CountingInputStream.java
{ "start": 1057, "end": 2399 }
class ____ extends FilterInputStream { private long count; private long mark = -1; /** * Wraps another input stream, counting the number of bytes read. * * @param in the input stream to be wrapped */ public CountingInputStream(InputStream in) { super(checkNotNull(in)); } /** Returns the number of bytes read. */ public long getCount() { return count; } @Override public int read() throws IOException { int result = in.read(); if (result != -1) { count++; } return result; } @Override public int read(byte[] b, int off, int len) throws IOException { int result = in.read(b, off, len); if (result != -1) { count += result; } return result; } @Override public long skip(long n) throws IOException { long result = in.skip(n); count += result; return result; } @Override public synchronized void mark(int readlimit) { in.mark(readlimit); mark = count; // it's okay to mark even if mark isn't supported, as reset won't work } @Override public synchronized void reset() throws IOException { if (!in.markSupported()) { throw new IOException("Mark not supported"); } if (mark == -1) { throw new IOException("Mark not set"); } in.reset(); count = mark; } }
CountingInputStream
java
spring-projects__spring-security
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/BaseOpenSamlAuthenticationRequestResolver.java
{ "start": 10517, "end": 11336 }
class ____ implements RequestMatcher { private final RequestMatcher matcher; PathPatternQueryRequestMatcher(String path, String... params) { List<RequestMatcher> matchers = new ArrayList<>(); matchers.add(pathPattern(path)); for (String param : params) { String[] parts = param.split("="); if (parts.length == 1) { matchers.add(new ParameterRequestMatcher(parts[0])); } else { matchers.add(new ParameterRequestMatcher(parts[0], parts[1])); } } this.matcher = new AndRequestMatcher(matchers); } @Override public boolean matches(HttpServletRequest request) { return matcher(request).isMatch(); } @Override public MatchResult matcher(HttpServletRequest request) { return this.matcher.matcher(request); } } static final
PathPatternQueryRequestMatcher
java
quarkusio__quarkus
extensions/schema-registry/confluent/common/deployment/src/main/java/io/quarkus/confluent/registry/common/ConfluentRegistryClientProcessor.java
{ "start": 4092, "end": 5269 }
class ____ only reachable when kafka-schema-registry-client v [5.2,7) is in the classpath reflectiveClass .produce(ReflectiveClassBuildItem.weakClass(true, true, false, "io.confluent.kafka.schemaregistry.client.rest.entities.requests.ModeGetResponse")); serviceProviders .produce(new ServiceProviderBuildItem( "io.confluent.kafka.schemaregistry.client.security.basicauth.BasicAuthCredentialProvider", "io.confluent.kafka.schemaregistry.client.security.basicauth.SaslBasicAuthCredentialProvider", "io.confluent.kafka.schemaregistry.client.security.basicauth.UrlBasicAuthCredentialProvider", "io.confluent.kafka.schemaregistry.client.security.basicauth.UserInfoCredentialProvider")); } } @BuildStep(onlyIf = NativeImageFutureDefault.RunTimeInitializeSecurityProvider.class) RuntimeInitializedPackageBuildItem runtimeInitializedClasses() { return new RuntimeInitializedPackageBuildItem("io.confluent.kafka.schemaregistry.client.security"); } }
is
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/SpringMDCTest.java
{ "start": 2412, "end": 2700 }
class ____ implements Processor { @Override public void process(Exchange exchange) throws Exception { assertEquals("route-b", MDC.get("camel.routeId")); assertEquals(exchange.getExchangeId(), MDC.get("camel.exchangeId")); } } }
ProcessorB
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/event/spi/AbstractCollectionEvent.java
{ "start": 4637, "end": 4739 }
class ____ */ public String getAffectedOwnerEntityName() { return affectedOwnerEntityName; } }
name
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/upgrade/HttpUpgradeCheckHeaderMergingTest.java
{ "start": 2464, "end": 2739 }
class ____ implements HttpUpgradeCheck { @Override public Uni<CheckResult> perform(HttpUpgradeContext context) { return CheckResult.permitUpgrade(Map.of("k", List.of("val1"))); } } @Dependent public static
Header1HttpUpgradeCheck
java
quarkusio__quarkus
integration-tests/oidc-code-flow/src/main/java/io/quarkus/it/keycloak/TenantLogout.java
{ "start": 423, "end": 1862 }
class ____ { @Context HttpHeaders headers; @Inject RoutingContext context; @Authenticated @GET public String getTenantLogout() { return "Tenant Logout, refreshed: " + (context.get("refresh_token_grant_response") != null); } // It is needed for the proactive-auth=false to work: /tenant-logout/logout should match a user initiated logout request // which must be handled by `CodeAuthenticationMechanism`. // Adding `@Authenticated` gives control to `CodeAuthenticationMechanism` instead of RestEasy. @GET @Authenticated @Path("logout") public String getTenantLogoutPath() { throw new InternalServerErrorException(); } @GET @Path("post-logout") public String postLogout(@QueryParam("state") String postLogoutState) { Cookie cookie = headers.getCookies().get("q_post_logout_tenant-logout"); if (cookie == null) { throw new InternalServerErrorException("q_post_logout cookie is not available"); } if (postLogoutState == null) { throw new InternalServerErrorException("'state' query parameter is not available"); } if (!postLogoutState.equals(cookie.getValue())) { throw new InternalServerErrorException("'state' query parameter is not equal to the q_post_logout cookie value"); } return "You were logged out, please login again"; } }
TenantLogout
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_interface.java
{ "start": 1441, "end": 1510 }
class ____ extends X<Integer> { } public static
X_I
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/DebeziumMysqlComponentBuilderFactory.java
{ "start": 1904, "end": 5210 }
interface ____ extends ComponentBuilder<DebeziumMySqlComponent> { /** * Additional properties for debezium components in case they can't be * set directly on the camel configurations (e.g: setting Kafka Connect * properties needed by Debezium engine, for example setting * KafkaOffsetBackingStore), the properties have to be prefixed with * additionalProperties.. E.g: * additionalProperties.transactional.id=12345&amp;additionalProperties.schema.registry.url=http://localhost:8811/avro. This is a multi-value option with prefix: additionalProperties. * * The option is a: &lt;code&gt;java.util.Map&amp;lt;java.lang.String, * java.lang.Object&amp;gt;&lt;/code&gt; type. * * Group: common * * @param additionalProperties the value to set * @return the dsl builder */ default DebeziumMysqlComponentBuilder additionalProperties(java.util.Map<java.lang.String, java.lang.Object> additionalProperties) { doSetProperty("additionalProperties", additionalProperties); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: consumer * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default DebeziumMysqlComponentBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allow pre-configured Configurations to be set. * * The option is a: * &lt;code&gt;org.apache.camel.component.debezium.mysql.configuration.MySqlConnectorEmbeddedDebeziumConfiguration&lt;/code&gt; type. * * Group: consumer * * @param configuration the value to set * @return the dsl builder */ default DebeziumMysqlComponentBuilder configuration(org.apache.camel.component.debezium.mysql.configuration.MySqlConnectorEmbeddedDebeziumConfiguration configuration) { doSetProperty("configuration", configuration); return this; } /** * The Converter
DebeziumMysqlComponentBuilder
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/support/DelegatingSmartContextLoader.java
{ "start": 1368, "end": 2819 }
class ____ extends AbstractDelegatingSmartContextLoader { private static final String GROOVY_XML_CONTEXT_LOADER_CLASS_NAME = "org.springframework.test.context.support.GenericGroovyXmlContextLoader"; private static final boolean GROOVY_PRESENT = ClassUtils.isPresent("groovy.lang.Closure", DelegatingSmartContextLoader.class.getClassLoader()) && ClassUtils.isPresent(GROOVY_XML_CONTEXT_LOADER_CLASS_NAME, DelegatingSmartContextLoader.class.getClassLoader()); private final SmartContextLoader xmlLoader; private final SmartContextLoader annotationConfigLoader; public DelegatingSmartContextLoader() { if (GROOVY_PRESENT) { try { Class<?> loaderClass = ClassUtils.forName(GROOVY_XML_CONTEXT_LOADER_CLASS_NAME, DelegatingSmartContextLoader.class.getClassLoader()); this.xmlLoader = (SmartContextLoader) BeanUtils.instantiateClass(loaderClass); } catch (Throwable ex) { throw new IllegalStateException("Failed to enable support for Groovy scripts; " + "could not load class: " + GROOVY_XML_CONTEXT_LOADER_CLASS_NAME, ex); } } else { this.xmlLoader = new GenericXmlContextLoader(); } this.annotationConfigLoader = new AnnotationConfigContextLoader(); } @Override protected SmartContextLoader getXmlLoader() { return this.xmlLoader; } @Override protected SmartContextLoader getAnnotationConfigLoader() { return this.annotationConfigLoader; } }
DelegatingSmartContextLoader
java
google__error-prone
check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java
{ "start": 18777, "end": 18914 }
interface ____ extends Suppressible { Description matchNewArray(NewArrayTree tree, VisitorState state); } public
NewArrayTreeMatcher
java
apache__camel
core/camel-core-languages/src/main/java/org/apache/camel/language/simple/ast/SimpleFunctionStart.java
{ "start": 1265, "end": 10313 }
class ____ extends BaseSimpleNode implements BlockStart { // use caches to avoid re-parsing the same expressions over and over again private final Map<String, Expression> cacheExpression; private final CompositeNodes block; private final boolean skipFileFunctions; public SimpleFunctionStart(SimpleToken token, Map<String, Expression> cacheExpression, boolean skipFileFunctions) { super(token); this.block = new CompositeNodes(token); this.cacheExpression = cacheExpression; this.skipFileFunctions = skipFileFunctions; } public CompositeNodes getBlock() { return block; } public boolean lazyEval(SimpleNode child) { String text = child.toString(); // don't lazy evaluate nested type references as they are static return !text.startsWith("${type:"); } @Override public String toString() { // output a nice toString, so it makes debugging easier, so we can see the entire block return "${" + block + "}"; } @Override public Expression createExpression(CamelContext camelContext, String expression) { // a function can either be a simple literal function, or contain nested functions if (block.getChildren().size() == 1 && block.getChildren().get(0) instanceof LiteralNode) { return doCreateLiteralExpression(camelContext, expression); } else { return doCreateCompositeExpression(camelContext, expression); } } private Expression doCreateLiteralExpression(CamelContext camelContext, String expression) { SimpleFunctionExpression function = new SimpleFunctionExpression(this.getToken(), cacheExpression, skipFileFunctions); LiteralNode literal = (LiteralNode) block.getChildren().get(0); function.addText(literal.getText()); return function.createExpression(camelContext, expression); } private Expression doCreateCompositeExpression(CamelContext camelContext, String expression) { final SimpleToken token = getToken(); return new Expression() { @Override public <T> T evaluate(Exchange exchange, Class<T> type) { StringBuilder sb = new StringBuilder(256); boolean quoteEmbeddedFunctions = false; // we need to concat the block so we have the expression for (SimpleNode child : block.getChildren()) { // whether a nested function should be lazy evaluated or not boolean lazy = true; if (child instanceof SimpleFunctionStart simpleFunctionStart) { lazy = simpleFunctionStart.lazyEval(child); } if (child instanceof LiteralNode literal) { String text = literal.getText(); sb.append(text); quoteEmbeddedFunctions |= literal.quoteEmbeddedNodes(); // if its quoted literal then embed that as text } else if (!lazy || child instanceof SingleQuoteStart || child instanceof DoubleQuoteStart) { try { // pass in null when we evaluate the nested expressions Expression nested = child.createExpression(camelContext, null); String text = nested.evaluate(exchange, String.class); if (text != null) { if (quoteEmbeddedFunctions && !StringHelper.isQuoted(text)) { sb.append("'").append(text).append("'"); } else { sb.append(text); } } } catch (SimpleParserException e) { // must rethrow parser exception as illegal syntax with details about the location throw new SimpleIllegalSyntaxException(expression, e.getIndex(), e.getMessage(), e); } // if its an inlined function then embed that function as text so it can be evaluated lazy } else if (child instanceof SimpleFunctionStart) { sb.append(child); } } // we have now concat the block as a String which contains the function expression // which we then need to evaluate as a function String exp = sb.toString(); SimpleFunctionExpression function = new SimpleFunctionExpression(token, cacheExpression, skipFileFunctions); function.addText(exp); try { return function.createExpression(camelContext, exp).evaluate(exchange, type); } catch (SimpleParserException e) { // must rethrow parser exception as illegal syntax with details about the location throw new SimpleIllegalSyntaxException(expression, e.getIndex(), e.getMessage(), e); } } @Override public String toString() { return expression; } }; } @Override public boolean acceptAndAddNode(SimpleNode node) { // only accept literals, quotes or embedded functions if (node instanceof LiteralNode || node instanceof SimpleFunctionStart || node instanceof SingleQuoteStart || node instanceof DoubleQuoteStart) { block.addChild(node); return true; } else { return false; } } @Override public String createCode(CamelContext camelContext, String expression) throws SimpleParserException { String answer; // a function can either be a simple literal function or contain nested functions if (block.getChildren().size() == 1 && block.getChildren().get(0) instanceof LiteralNode) { answer = doCreateLiteralCode(camelContext, expression); } else { answer = doCreateCompositeCode(camelContext, expression); } return answer; } private String doCreateLiteralCode(CamelContext camelContext, String expression) { SimpleFunctionExpression function = new SimpleFunctionExpression(this.getToken(), cacheExpression, skipFileFunctions); LiteralNode literal = (LiteralNode) block.getChildren().get(0); function.addText(literal.getText()); return function.createCode(camelContext, expression); } private String doCreateCompositeCode(CamelContext camelContext, String expression) { StringBuilder sb = new StringBuilder(256); boolean quoteEmbeddedFunctions = false; // we need to concat the block, so we have the expression for (SimpleNode child : block.getChildren()) { if (child instanceof LiteralNode literal) { String text = literal.getText(); sb.append(text); quoteEmbeddedFunctions |= literal.quoteEmbeddedNodes(); // if its quoted literal then embed that as text } else if (child instanceof SingleQuoteStart || child instanceof DoubleQuoteStart) { try { // pass in null when we evaluate the nested expressions String text = child.createCode(camelContext, null); if (text != null) { if (quoteEmbeddedFunctions && !StringHelper.isQuoted(text)) { sb.append("'").append(text).append("'"); } else { sb.append(text); } } } catch (SimpleParserException e) { // must rethrow parser exception as illegal syntax with details about the location throw new SimpleIllegalSyntaxException(expression, e.getIndex(), e.getMessage(), e); } } else if (child instanceof SimpleFunctionStart) { // inlined function String inlined = child.createCode(camelContext, expression); sb.append(inlined); } } // we have now concat the block as a String which contains inlined functions parsed // so now we should reparse as a single function String exp = sb.toString(); SimpleFunctionExpression function = new SimpleFunctionExpression(token, cacheExpression, skipFileFunctions); function.addText(exp); try { return function.createCode(camelContext, exp); } catch (SimpleParserException e) { // must rethrow parser exception as illegal syntax with details about the location throw new SimpleIllegalSyntaxException(expression, e.getIndex(), e.getMessage(), e); } } }
SimpleFunctionStart
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/LuceneEndpointBuilderFactory.java
{ "start": 1451, "end": 1574 }
interface ____ { /** * Builder for endpoint for the Lucene component. */ public
LuceneEndpointBuilderFactory
java
elastic__elasticsearch
x-pack/plugin/rank-rrf/src/test/java/org/elasticsearch/xpack/rank/rrf/RRFRankDocTests.java
{ "start": 670, "end": 3971 }
class ____ extends AbstractRankDocWireSerializingTestCase<RRFRankDoc> { static RRFRankDoc createTestRRFRankDoc(int queryCount) { RRFRankDoc instance = new RRFRankDoc( randomNonNegativeInt(), randomBoolean() ? -1 : randomNonNegativeInt(), queryCount, randomIntBetween(1, 100) ); instance.score = randomFloat(); instance.rank = randomBoolean() ? NO_RANK : randomIntBetween(1, 10000); for (int qi = 0; qi < queryCount; ++qi) { if (randomBoolean()) { instance.positions[qi] = randomIntBetween(1, 10000); instance.scores[qi] = randomFloat(); } } return instance; } @Override protected List<NamedWriteableRegistry.Entry> getAdditionalNamedWriteables() { try (RRFRankPlugin rrfRankPlugin = new RRFRankPlugin()) { return rrfRankPlugin.getNamedWriteables(); } catch (IOException ex) { throw new AssertionError("Failed to create RRFRankPlugin", ex); } } @Override protected Reader<RRFRankDoc> instanceReader() { return RRFRankDoc::new; } @Override protected RRFRankDoc createTestRankDoc() { int queryCount = randomIntBetween(2, 20); return createTestRRFRankDoc(queryCount); } @Override protected RRFRankDoc mutateInstance(RRFRankDoc instance) throws IOException { int doc = instance.doc; int shardIndex = instance.shardIndex; float score = instance.score; int rankConstant = instance.rankConstant; int rank = instance.rank; int queries = instance.positions.length; int[] positions = new int[queries]; float[] scores = new float[queries]; switch (randomInt(6)) { case 0: doc = randomValueOtherThan(doc, ESTestCase::randomNonNegativeInt); break; case 1: shardIndex = shardIndex == -1 ? randomNonNegativeInt() : -1; break; case 2: score = randomValueOtherThan(score, ESTestCase::randomFloat); break; case 3: rankConstant = randomValueOtherThan(rankConstant, () -> randomIntBetween(1, 100)); break; case 4: rank = rank == NO_RANK ? randomIntBetween(1, 10000) : NO_RANK; break; case 5: for (int i = 0; i < queries; i++) { positions[i] = instance.positions[i] == NO_RANK ? randomIntBetween(1, 10000) : NO_RANK; } break; case 6: for (int i = 0; i < queries; i++) { scores[i] = randomValueOtherThan(scores[i], ESTestCase::randomFloat); } break; default: throw new AssertionError(); } RRFRankDoc mutated = new RRFRankDoc(doc, shardIndex, queries, rankConstant); System.arraycopy(positions, 0, mutated.positions, 0, instance.positions.length); System.arraycopy(scores, 0, mutated.scores, 0, instance.scores.length); mutated.rank = rank; mutated.score = score; return mutated; } }
RRFRankDocTests
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/validation/beanvalidation/MethodValidationAdapterPropertyPathTests.java
{ "start": 1860, "end": 6146 }
class ____ { @Test void fieldOfObjectPropertyOfBean() { Method method = getMethod("addCourse"); Object[] args = {new Course("CS 101", invalidPerson, Collections.emptyList())}; MethodValidationResult result = validationAdapter.validateArguments(new MyService(), method, null, args, HINTS); assertThat(result.getAllErrors()).hasSize(1); ParameterErrors errors = result.getBeanResults().get(0); assertSingleFieldError(errors, 1, null, null, null, "professor.name", invalidPerson.name()); } @Test void fieldOfObjectPropertyOfListElement() { Method method = getMethod("addCourseList"); List<Course> courses = List.of(new Course("CS 101", invalidPerson, Collections.emptyList())); MethodValidationResult result = validationAdapter.validateArguments( new MyService(), method, null, new Object[] {courses}, HINTS); assertThat(result.getAllErrors()).hasSize(1); ParameterErrors errors = result.getBeanResults().get(0); assertSingleFieldError(errors, 1, courses, 0, null, "professor.name", invalidPerson.name()); } @Test void fieldOfObjectPropertyOfListElements() { Method method = getMethod("addCourseList"); List<Course> courses = List.of( new Course("CS 101", invalidPerson, Collections.emptyList()), new Course("CS 102", invalidPerson, Collections.emptyList())); MethodValidationResult result = validationAdapter.validateArguments( new MyService(), method, null, new Object[] {courses}, HINTS); assertThat(result.getAllErrors()).hasSize(2); for (int i = 0; i < 2; i++) { ParameterErrors errors = result.getBeanResults().get(i); assertThat(errors.getContainerIndex()).isEqualTo(i); assertThat(errors.getFieldError().getField()).isEqualTo("professor.name"); } } @Test void fieldOfObjectPropertyUnderListPropertyOfListElement() { Method method = getMethod("addCourseList"); Course cs101 = new Course("CS 101", invalidPerson, Collections.emptyList()); Course cs201 = new Course("CS 201", validPerson, List.of(cs101)); Course cs301 = new Course("CS 301", validPerson, List.of(cs201)); List<Course> courses = List.of(cs301); Object[] args = {courses}; MethodValidationResult result = validationAdapter.validateArguments(new MyService(), method, null, args, HINTS); assertThat(result.getAllErrors()).hasSize(1); ParameterErrors errors = result.getBeanResults().get(0); assertSingleFieldError(errors, 1, courses, 0, null, "requiredCourses[0].requiredCourses[0].professor.name", invalidPerson.name()); } @Test void fieldOfObjectPropertyOfArrayElement() { Method method = getMethod("addCourseArray"); Course[] courses = new Course[] {new Course("CS 101", invalidPerson, Collections.emptyList())}; MethodValidationResult result = validationAdapter.validateArguments( new MyService(), method, null, new Object[] {courses}, HINTS); assertThat(result.getAllErrors()).hasSize(1); ParameterErrors errors = result.getBeanResults().get(0); assertSingleFieldError(errors, 1, courses, 0, null, "professor.name", invalidPerson.name()); } @Test void fieldOfObjectPropertyOfMapValue() { Method method = getMethod("addCourseMap"); Map<String, Course> courses = Map.of("CS 101", new Course("CS 101", invalidPerson, Collections.emptyList())); MethodValidationResult result = validationAdapter.validateArguments( new MyService(), method, null, new Object[] {courses}, HINTS); assertThat(result.getAllErrors()).hasSize(1); ParameterErrors errors = result.getBeanResults().get(0); assertSingleFieldError(errors, 1, courses, null, "CS 101", "professor.name", invalidPerson.name()); } @Test void fieldOfObjectPropertyOfOptionalBean() { Method method = getMethod("addOptionalCourse"); Optional<Course> optional = Optional.of(new Course("CS 101", invalidPerson, Collections.emptyList())); Object[] args = {optional}; MethodValidationResult result = validationAdapter.validateArguments(new MyService(), method, null, args, HINTS); assertThat(result.getAllErrors()).hasSize(1); ParameterErrors errors = result.getBeanResults().get(0); assertSingleFieldError(errors, 1, optional, null, null, "professor.name", invalidPerson.name()); } } @Nested
ArgumentTests
java
greenrobot__greendao
tests/DaoTestPerformance/src/androidTest/java/org/greenrobot/greendao/performance/Benchmark.java
{ "start": 1276, "end": 6662 }
class ____ { public static final String TAG = "Benchmark"; private final List<Pair<String, String>> fixedColumns = new ArrayList<>(); private final List<Pair<String, String>> values = new ArrayList<>(); private final File file; private final SimpleDateFormat dateFormat; private final char separator = '\t'; private String[] headers; private boolean storeThreadTime; private boolean started; private long threadTimeMillis; private long timeMillis; private String name; private int runs; private int warmUpRuns; public Benchmark(File file) { this.file = file; dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); checkForLastHeader(file); } private void checkForLastHeader(File file) { String contents = null; try { contents = FileUtils.readUtf8(file); } catch (FileNotFoundException e) { // OK } catch (IOException e) { throw new RuntimeException(e); } if (contents == null) { return; } String[] lines = StringUtils.split(contents, '\n'); for (int i = lines.length - 1; i >= 0; i--) { String[] columnValues = StringUtils.split(lines[i], separator); if (columnValues.length > 1) { boolean longValueFound = false; for (String value : columnValues) { try { Long.parseLong(value); longValueFound = true; break; } catch (NumberFormatException e) { // OK, header candidate } } if (!longValueFound) { headers = columnValues; break; } } } } public Benchmark warmUpRuns(int warmUpRuns) { this.warmUpRuns = warmUpRuns; return this; } public Benchmark enableThreadTime() { this.storeThreadTime = true; return this; } public Benchmark disableThreadTime() { this.storeThreadTime = false; return this; } public Benchmark addFixedColumn(String key, String value) { fixedColumns.add(new Pair<String, String>(key, value)); return this; } public Benchmark addFixedColumnDevice() { addFixedColumn("device", Build.MODEL); return this; } public void start(String name) { if (started) { throw new RuntimeException("Already started"); } started = true; prepareForNextRun(); if (values.isEmpty()) { values.addAll(fixedColumns); String startTime = dateFormat.format(new Date()); values.add(new Pair<>("time", startTime)); } this.name = name; threadTimeMillis = SystemClock.currentThreadTimeMillis(); timeMillis = SystemClock.elapsedRealtime(); } /** * Try to give GC some time to settle down. */ public void prepareForNextRun() { for (int i = 0; i < 5; i++) { System.gc(); try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } } } public void stop() { long time = SystemClock.elapsedRealtime() - timeMillis; long timeThread = SystemClock.currentThreadTimeMillis() - threadTimeMillis; if (!started) { throw new RuntimeException("Not started"); } started = false; Log.d(TAG, name + ": " + time + " ms (thread: " + timeThread + " ms)"); values.add(new Pair<>(name, Long.toString(time))); if (storeThreadTime) { values.add(new Pair<>(name + "-thread", Long.toString(timeThread))); } name = null; } public void commit() { runs++; if (runs > warmUpRuns) { Log.d(TAG, "Writing results for run " + runs); String[] collectedHeaders = getAllFirsts(values); if (!Arrays.equals(collectedHeaders, headers)) { headers = collectedHeaders; String line = StringUtils.join(headers, "" + separator) + '\n'; try { FileUtils.appendUtf8(file, line); } catch (IOException e) { throw new RuntimeException("Could not write header in benchmark file", e); } } StringBuilder line = new StringBuilder(); for (Pair<String, String> pair : values) { line.append(pair.second).append(separator); } line.append('\n'); try { FileUtils.appendUtf8(file, line); } catch (IOException e) { throw new RuntimeException("Could not write header in benchmark file", e); } } else { Log.d(TAG, "Ignoring results for run " + runs + " (warm up)"); } values.clear(); } private String[] getAllFirsts(List<Pair<String, String>> columns) { String[] firsts = new String[columns.size()]; for (int i = 0; i < firsts.length; i++) { firsts[i] = columns.get(i).first; } return firsts; } }
Benchmark
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/bind/ValueObjectBinderTests.java
{ "start": 25987, "end": 26227 }
class ____ { private final Foo foo; NestedConstructorBeanWithEmptyDefaultValueForEnumTypes(@DefaultValue Foo foo) { this.foo = foo; } Foo getFoo() { return this.foo; }
NestedConstructorBeanWithEmptyDefaultValueForEnumTypes
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/observers/DisposableObserver.java
{ "start": 1524, "end": 2698 }
class ____> multiple times."}. * * <p>Implementation of {@link #onStart()}, {@link #onNext(Object)}, {@link #onError(Throwable)} * and {@link #onComplete()} are not allowed to throw any unchecked exceptions. * If for some reason this can't be avoided, use {@link io.reactivex.rxjava3.core.Observable#safeSubscribe(io.reactivex.rxjava3.core.Observer)} * instead of the standard {@code subscribe()} method. * * <p>Example<pre><code> * Disposable d = * Observable.range(1, 5) * .subscribeWith(new DisposableObserver&lt;Integer&gt;() { * &#64;Override public void onStart() { * System.out.println("Start!"); * } * &#64;Override public void onNext(Integer t) { * if (t == 3) { * dispose(); * } * System.out.println(t); * } * &#64;Override public void onError(Throwable t) { * t.printStackTrace(); * } * &#64;Override public void onComplete() { * System.out.println("Done!"); * } * }); * // ... * d.dispose(); * </code></pre> * * @param <T> the received value type */ public abstract
name
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-common/src/main/java/org/apache/hadoop/mapreduce/v2/api/MRClientProtocol.java
{ "start": 3251, "end": 5249 }
interface ____ { /** * Address to which the client is connected * @return InetSocketAddress */ public InetSocketAddress getConnectAddress(); public GetJobReportResponse getJobReport(GetJobReportRequest request) throws IOException; public GetTaskReportResponse getTaskReport(GetTaskReportRequest request) throws IOException; public GetTaskAttemptReportResponse getTaskAttemptReport(GetTaskAttemptReportRequest request) throws IOException; public GetCountersResponse getCounters(GetCountersRequest request) throws IOException; public GetTaskAttemptCompletionEventsResponse getTaskAttemptCompletionEvents(GetTaskAttemptCompletionEventsRequest request) throws IOException; public GetTaskReportsResponse getTaskReports(GetTaskReportsRequest request) throws IOException; public GetDiagnosticsResponse getDiagnostics(GetDiagnosticsRequest request) throws IOException; public KillJobResponse killJob(KillJobRequest request) throws IOException; public KillTaskResponse killTask(KillTaskRequest request) throws IOException; public KillTaskAttemptResponse killTaskAttempt(KillTaskAttemptRequest request) throws IOException; public FailTaskAttemptResponse failTaskAttempt(FailTaskAttemptRequest request) throws IOException; public GetDelegationTokenResponse getDelegationToken(GetDelegationTokenRequest request) throws IOException; /** * Renew an existing delegation token. * * @param request the delegation token to be renewed. * @return the new expiry time for the delegation token. * @throws IOException */ public RenewDelegationTokenResponse renewDelegationToken( RenewDelegationTokenRequest request) throws IOException; /** * Cancel an existing delegation token. * * @param request the delegation token to be cancelled. * @return an empty response. * @throws IOException */ public CancelDelegationTokenResponse cancelDelegationToken( CancelDelegationTokenRequest request) throws IOException; }
MRClientProtocol
java
google__dagger
hilt-compiler/main/java/dagger/hilt/processor/internal/root/KspRootProcessor.java
{ "start": 1543, "end": 1775 }
class ____ implements SymbolProcessorProvider { @Override public SymbolProcessor create(SymbolProcessorEnvironment symbolProcessorEnvironment) { return new KspRootProcessor(symbolProcessorEnvironment); } } }
Provider
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/highavailability/JobResultEntry.java
{ "start": 1178, "end": 1508 }
class ____ { private final JobResult jobResult; public JobResultEntry(JobResult jobResult) { this.jobResult = Preconditions.checkNotNull(jobResult); } public JobResult getJobResult() { return jobResult; } public JobID getJobId() { return jobResult.getJobId(); } }
JobResultEntry
java
redisson__redisson
redisson/src/main/java/org/redisson/remote/RxRemoteProxy.java
{ "start": 1136, "end": 2499 }
class ____ extends AsyncRemoteProxy { public RxRemoteProxy(CommandAsyncExecutor commandExecutor, String name, String responseQueueName, Codec codec, String executorId, String cancelRequestMapName, BaseRemoteService remoteService) { super(convert(commandExecutor), name, responseQueueName, codec, executorId, cancelRequestMapName, remoteService); } private static CommandAsyncExecutor convert(CommandAsyncExecutor commandExecutor) { if (commandExecutor instanceof CommandRxExecutor) { return commandExecutor; } return CommandRxExecutor.create(commandExecutor.getConnectionManager(), commandExecutor.getObjectBuilder()); } @Override protected List<Class<?>> permittedClasses() { return Arrays.asList(Completable.class, Single.class, Maybe.class); } @Override protected Object convertResult(RemotePromise<Object> result, Class<?> returnType) { Flowable<Object> flowable = ((CommandRxExecutor) commandExecutor).flowable(() -> new CompletableFutureWrapper<>(result)); if (returnType == Completable.class) { return flowable.ignoreElements(); } if (returnType == Single.class) { return flowable.singleOrError(); } return flowable.singleElement(); } }
RxRemoteProxy
java
apache__hadoop
hadoop-tools/hadoop-gcp/src/main/java/org/apache/hadoop/fs/gs/CreateFileOptions.java
{ "start": 3512, "end": 4735 }
class ____ { private Map<String, byte[]> attributes = ImmutableMap.of(); private String contentType = "application/octet-stream"; private long overwriteGenerationId = StorageResourceId.UNKNOWN_GENERATION_ID; private WriteMode writeMode = WriteMode.CREATE_NEW; private boolean ensureNoDirectoryConflict = true; CreateOperationOptionsBuilder setWriteMode(WriteMode mode) { this.writeMode = mode; return this; } CreateOperationOptionsBuilder setEnsureNoDirectoryConflict(boolean ensure) { this.ensureNoDirectoryConflict = ensure; return this; } CreateFileOptions build() { CreateFileOptions options = new CreateFileOptions(this); checkArgument(!options.getAttributes().containsKey("Content-Type"), "The Content-Type attribute must be set via the contentType option"); if (options.getWriteMode() != WriteMode.OVERWRITE) { checkArgument(options.getOverwriteGenerationId() == StorageResourceId.UNKNOWN_GENERATION_ID, "overwriteGenerationId is set to %s but it can be set only in OVERWRITE mode", options.getOverwriteGenerationId()); } return options; } } }
CreateOperationOptionsBuilder
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/intarrays/IntArrays_assertDoesNotContain_Test.java
{ "start": 1919, "end": 6159 }
class ____ extends IntArraysBaseTest { @Test void should_pass_if_actual_does_not_contain_given_values() { arrays.assertDoesNotContain(someInfo(), actual, arrayOf(12)); } @Test void should_pass_if_actual_does_not_contain_given_values_even_if_duplicated() { arrays.assertDoesNotContain(someInfo(), actual, arrayOf(12, 12, 20)); } @Test void should_throw_error_if_array_of_values_to_look_for_is_empty() { assertThatIllegalArgumentException().isThrownBy(() -> arrays.assertDoesNotContain(someInfo(), actual, emptyArray())) .withMessage(valuesToLookForIsEmpty()); } @Test void should_throw_error_if_array_of_values_to_look_for_is_null() { assertThatNullPointerException().isThrownBy(() -> arrays.assertDoesNotContain(someInfo(), actual, null)) .withMessage(valuesToLookForIsNull()); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertDoesNotContain(someInfo(), null, arrayOf(8))) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_contains_given_values() { AssertionInfo info = someInfo(); int[] expected = { 6, 8, 20 }; Throwable error = catchThrowable(() -> arrays.assertDoesNotContain(info, actual, expected)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldNotContain(actual, expected, newLinkedHashSet(6, 8))); } @Test void should_pass_if_actual_does_not_contain_given_values_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertDoesNotContain(someInfo(), actual, arrayOf(12)); } @Test void should_pass_if_actual_does_not_contain_given_values_even_if_duplicated_according_to_custom_comparison_strategy() { arraysWithCustomComparisonStrategy.assertDoesNotContain(someInfo(), actual, arrayOf(12, 12, 20)); } @Test void should_throw_error_if_array_of_values_to_look_for_is_empty_whatever_custom_comparison_strategy_is() { assertThatIllegalArgumentException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertDoesNotContain(someInfo(), actual, emptyArray())) .withMessage(valuesToLookForIsEmpty()); } @Test void should_throw_error_if_array_of_values_to_look_for_is_null_whatever_custom_comparison_strategy_is() { assertThatNullPointerException().isThrownBy(() -> arraysWithCustomComparisonStrategy.assertDoesNotContain(someInfo(), actual, null)) .withMessage(valuesToLookForIsNull()); } @Test void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertDoesNotContain(someInfo(), null, arrayOf(-8))) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_contains_given_values_according_to_custom_comparison_strategy() { AssertionInfo info = someInfo(); int[] expected = { 6, -8, 20 }; Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertDoesNotContain(info, actual, expected)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldNotContain(actual, expected, newLinkedHashSet(6, -8), absValueComparisonStrategy)); } }
IntArrays_assertDoesNotContain_Test
java
apache__camel
components/camel-reactive-streams/src/test/java/org/apache/camel/component/reactive/streams/BackpressureStrategyTest.java
{ "start": 1417, "end": 7749 }
class ____ extends BaseReactiveTest { @Test public void testBackpressureBufferStrategy() throws Exception { new RouteBuilder() { @Override public void configure() { from("timer:gen?period=20&repeatCount=20&includeMetadata=true") .setBody().header(Exchange.TIMER_COUNTER) .to("reactive-streams:integers"); } }.addRoutesToCamelContext(context); Flowable<Integer> integers = Flowable.fromPublisher(CamelReactiveStreams.get(context).fromStream("integers", Integer.class)); ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>(); CountDownLatch latch = new CountDownLatch(1); Flowable.interval(0, 50, TimeUnit.MILLISECONDS) .zipWith(integers, (l, i) -> i) .timeout(2000, TimeUnit.MILLISECONDS, Flowable.empty()) .doOnComplete(latch::countDown) .subscribe(queue::add); context().start(); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertEquals(20, queue.size()); int num = 1; for (int i : queue) { assertEquals(num++, i); } } @Test public void testBackpressureDropStrategy() throws Exception { ReactiveStreamsComponent comp = (ReactiveStreamsComponent) context().getComponent("reactive-streams"); comp.setBackpressureStrategy(ReactiveStreamsBackpressureStrategy.OLDEST); new RouteBuilder() { @Override public void configure() { from("timer:gen?period=20&repeatCount=20&includeMetadata=true") .setBody().header(Exchange.TIMER_COUNTER) .to("reactive-streams:integers"); } }.addRoutesToCamelContext(context); ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>(); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(2); TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>() { @Override public void onNext(Integer o) { queue.add(o); latch.countDown(); latch2.countDown(); } }; subscriber.setInitiallyRequested(1); CamelReactiveStreams.get(context).fromStream("integers", Integer.class).subscribe(subscriber); context().start(); assertTrue(latch.await(5, TimeUnit.SECONDS)); Thread.sleep(1000); // wait for all numbers to be generated subscriber.request(19); assertTrue(latch2.await(1, TimeUnit.SECONDS)); Thread.sleep(200); // add other time to ensure no other items arrive assertEquals(2, queue.size()); int sum = queue.stream().reduce((i, j) -> i + j).get(); assertEquals(3, sum); // 1 + 2 = 3 subscriber.cancel(); } @Test public void testBackpressureLatestStrategy() throws Exception { ReactiveStreamsComponent comp = (ReactiveStreamsComponent) context().getComponent("reactive-streams"); comp.setBackpressureStrategy(ReactiveStreamsBackpressureStrategy.LATEST); new RouteBuilder() { @Override public void configure() { from("timer:gen?period=20&repeatCount=20&includeMetadata=true") .setBody().header(Exchange.TIMER_COUNTER) .to("reactive-streams:integers"); } }.addRoutesToCamelContext(context); ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>(); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(2); TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>() { @Override public void onNext(Integer o) { queue.add(o); latch.countDown(); latch2.countDown(); } }; subscriber.setInitiallyRequested(1); CamelReactiveStreams.get(context).fromStream("integers", Integer.class).subscribe(subscriber); context().start(); assertTrue(latch.await(5, TimeUnit.SECONDS)); Thread.sleep(1000); // wait for all numbers to be generated subscriber.request(19); assertTrue(latch2.await(1, TimeUnit.SECONDS)); Thread.sleep(200); // add other time to ensure no other items arrive assertEquals(2, queue.size()); int sum = queue.stream().reduce((i, j) -> i + j).get(); assertEquals(21, sum); // 1 + 20 = 21 subscriber.cancel(); } @Test public void testBackpressureDropStrategyInEndpoint() throws Exception { new RouteBuilder() { @Override public void configure() { from("timer:gen?period=20&repeatCount=20&includeMetadata=true") .setBody().header(Exchange.TIMER_COUNTER) .to("reactive-streams:integers?backpressureStrategy=OLDEST"); } }.addRoutesToCamelContext(context); ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>(); final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(2); TestSubscriber<Integer> subscriber = new TestSubscriber<Integer>() { @Override public void onNext(Integer o) { queue.add(o); latch.countDown(); latch2.countDown(); } }; subscriber.setInitiallyRequested(1); CamelReactiveStreams.get(context).fromStream("integers", Integer.class).subscribe(subscriber); context().start(); assertTrue(latch.await(5, TimeUnit.SECONDS)); Thread.sleep(1000); // wait for all numbers to be generated subscriber.request(19); assertTrue(latch2.await(1, TimeUnit.SECONDS)); Thread.sleep(200); // add other time to ensure no other items arrive assertEquals(2, queue.size()); int sum = queue.stream().reduce((i, j) -> i + j).get(); assertEquals(3, sum); // 1 + 2 = 3 subscriber.cancel(); } }
BackpressureStrategyTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/join/ReloadMultipleCollectionElementsTest.java
{ "start": 6282, "end": 6976 }
class ____ { private Long id; private String name; private Set<Flight> flights = new HashSet<Flight>(); public Company() { } @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "comp_id") public Long getId() { return id; } public String getName() { return name; } public void setId(Long newId) { id = newId; } public void setName(String string) { name = string; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "company") @Column(name = "flight_id") public Set<Flight> getFlights() { return flights; } public void setFlights(Set<Flight> flights) { this.flights = flights; } } }
Company
java
apache__avro
lang/java/avro/src/test/java/org/apache/avro/util/CaseFinder.java
{ "start": 5519, "end": 8927 }
class ____ { /** * Scan test-case file <code>in</code> looking for test subcases marked with * <code>caseLabel</code>. Any such cases are appended (in order) to the "cases" * parameter. If <code>caseLabel</code> equals the string <code>"INPUT"</code>, * then returns the list of &lt;<i>input</i>, <code>null</code>&gt; pairs for * <i>input</i> equal to all heredoc's named INPUT's found in the input stream. */ public static List<Object[]> find(BufferedReader in, String label, List<Object[]> cases) throws IOException { if (!Pattern.matches(LABEL_REGEX, label)) throw new IllegalArgumentException("Bad case subcase label: " + label); final String subcaseMarker = "<<" + label; for (String line = in.readLine();;) { // Find next new case while (line != null && !line.startsWith(NEW_CASE_MARKER)) line = in.readLine(); if (line == null) break; String input; input = processHereDoc(in, line); if (label.equals(NEW_CASE_NAME)) { cases.add(new Object[] { input, null }); line = in.readLine(); continue; } // Check to see if there's a subcase named "label" for that case do { line = in.readLine(); } while (line != null && (!line.startsWith(NEW_CASE_MARKER) && !line.startsWith(subcaseMarker))); if (line == null || line.startsWith(NEW_CASE_MARKER)) continue; String expectedOutput = processHereDoc(in, line); cases.add(new Object[] { input, expectedOutput }); } in.close(); return cases; } private static final String NEW_CASE_NAME = "INPUT"; private static final String NEW_CASE_MARKER = "<<" + NEW_CASE_NAME; private static final String LABEL_REGEX = "[a-zA-Z][_a-zA-Z0-9]*"; private static final Pattern START_LINE_PATTERN = Pattern.compile("^<<(" + LABEL_REGEX + ")(.*)$"); /** * Reads and returns content of a heredoc. Assumes we just read a * start-of-here-doc marker for a here-doc labeled "docMarker." Replaces * arbitrary newlines with system newlines, but strips newline from final line * of heredoc. Throws IOException if EOF is reached before heredoc is terminate. */ private static String processHereDoc(BufferedReader in, String docStart) throws IOException { Matcher m = START_LINE_PATTERN.matcher(docStart); if (!m.matches()) throw new IllegalArgumentException("Wasn't given the start of a heredoc (\"" + docStart + "\")"); String docName = m.group(1); // Determine if this is a single-line heredoc, and process if it is String singleLineText = m.group(2); if (singleLineText.length() != 0) { if (!singleLineText.startsWith(" ")) throw new IOException("Single-line heredoc missing initial space (\"" + docStart + "\")"); return singleLineText.substring(1); } // Process multi-line heredocs StringBuilder result = new StringBuilder(); String line = in.readLine(); String prevLine = ""; boolean firstTime = true; while (line != null && !line.equals(docName)) { if (!firstTime) result.append(prevLine).append('\n'); else firstTime = false; prevLine = line; line = in.readLine(); } if (line == null) throw new IOException("Here document (" + docName + ") terminated by end-of-file."); return result.append(prevLine).toString(); } }
CaseFinder
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/spi/NoOpThreadContextMap.java
{ "start": 1222, "end": 2042 }
class ____ implements ThreadContextMap { /** * @since 2.24.0 */ public static final ThreadContextMap INSTANCE = new NoOpThreadContextMap(); @Override public void clear() {} @Override public boolean containsKey(final String key) { return false; } @Override public @Nullable String get(final String key) { return null; } @Override public Map<String, String> getCopy() { return new HashMap<>(); } @Override public @Nullable Map<String, String> getImmutableMapOrNull() { return null; } @Override public boolean isEmpty() { return true; } @Override public void put(final String key, final String value) {} @Override public void remove(final String key) {} }
NoOpThreadContextMap
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ZippedElementsShouldSatisfy.java
{ "start": 2358, "end": 3205 }
class ____ { public final Object actualElement; public final Object otherElement; public final String error; public ZipSatisfyError(Object actualElement, Object otherElement, String error) { this.actualElement = actualElement; this.otherElement = otherElement; this.error = error; } public static String describe(AssertionInfo info, ZipSatisfyError satisfyError) { return "(%s, %s)%nerror: %s".formatted(info.representation().toStringOf(satisfyError.actualElement), info.representation().toStringOf(satisfyError.otherElement), satisfyError.error); } @Override public String toString() { return "(%s, %s)%nerror: %s".formatted(actualElement, otherElement, error); } } }
ZipSatisfyError
java
apache__camel
core/camel-core-languages/src/main/java/org/apache/camel/language/simple/SimpleLanguage.java
{ "start": 8413, "end": 9025 }
class ____ implements Predicate { private final String text; public SimplePredicate(String text) { this.text = text; } @Override public boolean matches(Exchange exchange) { String r = ScriptHelper.resolveOptionalExternalScript(getCamelContext(), exchange, text); Predicate pred = SimpleLanguage.this.createPredicate(r); pred.init(getCamelContext()); return pred.matches(exchange); } @Override public String toString() { return text; } } private
SimplePredicate
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/PqcComponentBuilderFactory.java
{ "start": 1385, "end": 1852 }
interface ____ { /** * PQC Algorithms (camel-pqc) * Post Quantum Cryptography Signature and Verification component. * * Category: security * Since: 4.12 * Maven coordinates: org.apache.camel:camel-pqc * * @return the dsl builder */ static PqcComponentBuilder pqc() { return new PqcComponentBuilderImpl(); } /** * Builder for the PQC Algorithms component. */
PqcComponentBuilderFactory
java
spring-projects__spring-security
core/src/test/java/org/springframework/security/authorization/method/AuthorizationMethodPointcutsTests.java
{ "start": 2961, "end": 3067 }
class ____ { String methodOne(String paramOne) { return "value"; } } public static
ClassController
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/script/field/vectors/DenseVectorDocValuesField.java
{ "start": 990, "end": 2297 }
class ____ extends AbstractScriptFieldFactory<DenseVector> implements Field<DenseVector>, DocValuesScriptFieldFactory, DenseVectorScriptDocValues.DenseVectorSupplier { protected final String name; protected final ElementType elementType; public DenseVectorDocValuesField(String name, ElementType elementType) { this.name = name; this.elementType = elementType; } @Override public String getName() { return name; } public ElementType getElementType() { return elementType; } public Element getElement() { return Element.getElement(elementType); } @Override public int size() { return isEmpty() ? 0 : 1; } /** * Get the DenseVector for a document if one exists, DenseVector.EMPTY otherwise */ public abstract DenseVector get(); public abstract DenseVector get(DenseVector defaultValue); public abstract DenseVectorScriptDocValues toScriptDocValues(); // DenseVector fields are single valued, so Iterable does not make sense. @Override public Iterator<DenseVector> iterator() { throw new UnsupportedOperationException("Cannot iterate over single valued dense_vector field, use get() instead"); } }
DenseVectorDocValuesField
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/internal/SubSearchContext.java
{ "start": 1361, "end": 8782 }
class ____ extends FilteredSearchContext { // By default return 3 hits per bucket. A higher default would make the response really large by default, since // the top hits are returned per bucket. private static final int DEFAULT_SIZE = 3; private int from; private int size = DEFAULT_SIZE; private SortAndFormats sort; private ParsedQuery parsedQuery; private Query query; private final FetchSearchResult fetchSearchResult; private final QuerySearchResult querySearchResult; private StoredFieldsContext storedFields; private ScriptFieldsContext scriptFields; private FetchSourceContext fetchSourceContext; private FetchDocValuesContext docValuesContext; private FetchFieldsContext fetchFieldsContext; private SearchHighlightContext highlight; private boolean explain; private boolean trackScores; private boolean version; private boolean seqNoAndPrimaryTerm; @SuppressWarnings("this-escape") public SubSearchContext(SearchContext context) { super(context); context.addReleasable(this); this.fetchSearchResult = new FetchSearchResult(); addReleasable(fetchSearchResult::decRef); this.querySearchResult = new QuerySearchResult(); } public SubSearchContext(SubSearchContext subSearchContext) { this((SearchContext) subSearchContext); this.from = subSearchContext.from; this.size = subSearchContext.size; this.sort = subSearchContext.sort; this.parsedQuery = subSearchContext.parsedQuery; this.query = subSearchContext.query; this.storedFields = subSearchContext.storedFields; this.scriptFields = subSearchContext.scriptFields; this.fetchSourceContext = subSearchContext.fetchSourceContext; this.docValuesContext = subSearchContext.docValuesContext; this.fetchFieldsContext = subSearchContext.fetchFieldsContext; this.highlight = subSearchContext.highlight; this.explain = subSearchContext.explain; this.trackScores = subSearchContext.trackScores; this.version = subSearchContext.version; this.seqNoAndPrimaryTerm = subSearchContext.seqNoAndPrimaryTerm; } @Override public void preProcess() {} @Override public Query buildFilteredQuery(Query query) { throw new UnsupportedOperationException("this context should be read only"); } @Override public SearchContext aggregations(SearchContextAggregations aggregations) { throw new UnsupportedOperationException("Not supported"); } @Override public SearchHighlightContext highlight() { return highlight; } @Override public void highlight(SearchHighlightContext highlight) { this.highlight = highlight; } @Override public boolean hasScriptFields() { return scriptFields != null && scriptFields.fields().isEmpty() == false; } @Override public ScriptFieldsContext scriptFields() { if (scriptFields == null) { scriptFields = new ScriptFieldsContext(); } return this.scriptFields; } @Override public boolean sourceRequested() { return fetchSourceContext != null && fetchSourceContext.fetchSource(); } @Override public FetchSourceContext fetchSourceContext() { return fetchSourceContext; } @Override public SearchContext fetchSourceContext(FetchSourceContext fetchSourceContext) { this.fetchSourceContext = fetchSourceContext; return this; } @Override public FetchDocValuesContext docValuesContext() { return docValuesContext; } @Override public SearchContext docValuesContext(FetchDocValuesContext docValuesContext) { this.docValuesContext = docValuesContext; return this; } @Override public FetchFieldsContext fetchFieldsContext() { return fetchFieldsContext; } @Override public SubSearchContext fetchFieldsContext(FetchFieldsContext fetchFieldsContext) { this.fetchFieldsContext = fetchFieldsContext; return this; } @Override public void terminateAfter(int terminateAfter) { throw new UnsupportedOperationException("Not supported"); } @Override public SearchContext minimumScore(float minimumScore) { throw new UnsupportedOperationException("Not supported"); } @Override public SearchContext sort(SortAndFormats sort) { this.sort = sort; return this; } @Override public SortAndFormats sort() { return sort; } @Override public SubSearchContext parsedQuery(ParsedQuery parsedQuery) { this.parsedQuery = parsedQuery; if (parsedQuery != null) { this.query = parsedQuery.query(); } return this; } @Override public ParsedQuery parsedQuery() { return parsedQuery; } @Override public Query query() { return query; } @Override public SearchContext trackScores(boolean trackScores) { this.trackScores = trackScores; return this; } @Override public boolean trackScores() { return trackScores; } @Override public SearchContext parsedPostFilter(ParsedQuery postFilter) { throw new UnsupportedOperationException("Not supported"); } @Override public int from() { return from; } @Override public SearchContext from(int from) { this.from = from; return this; } @Override public int size() { return size; } @Override public SearchContext size(int size) { this.size = size; return this; } @Override public boolean hasStoredFields() { return storedFields != null && storedFields.fieldNames() != null; } @Override public StoredFieldsContext storedFieldsContext() { return storedFields; } @Override public SearchContext storedFieldsContext(StoredFieldsContext storedFieldsContext) { this.storedFields = storedFieldsContext; return this; } @Override public boolean explain() { return explain; } @Override public void explain(boolean explain) { this.explain = explain; } @Override public boolean version() { return version; } @Override public void version(boolean version) { this.version = version; } @Override public boolean seqNoAndPrimaryTerm() { return seqNoAndPrimaryTerm; } @Override public void seqNoAndPrimaryTerm(boolean seqNoAndPrimaryTerm) { this.seqNoAndPrimaryTerm = seqNoAndPrimaryTerm; } @Override public CollapseContext collapse() { return null; } @Override public QuerySearchResult queryResult() { return querySearchResult; } @Override public FetchSearchResult fetchResult() { return fetchSearchResult; } @Override public long getRelativeTimeInMillis() { throw new UnsupportedOperationException("Not supported"); } @Override public TotalHits getTotalHits() { return querySearchResult.getTotalHits(); } @Override public float getMaxScore() { return querySearchResult.getMaxScore(); } }
SubSearchContext
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/DeSelectFields.java
{ "start": 1290, "end": 1415 }
enum ____ a string literals * <br> 2. write your logical based on * the return of method contains(DeSelectType) */ public
with
java
google__dagger
javatests/dagger/hilt/android/InjectionTest.java
{ "start": 21376, "end": 22001 }
class ____ extends Hilt_InjectionTest_DoubleInjectService { @Inject Long counter; @Override public void onCreate() { inject(); super.onCreate(); } @Override public IBinder onBind(Intent intent) { return null; } } @Test public void testServiceDoesNotInjectTwice() throws Exception { DoubleInjectService testService = Robolectric.setupService(DoubleInjectService.class); assertThat(testService.counter).isEqualTo(1L); } /** Hilt BroadcastReceiver that manually calls inject(). */ @AndroidEntryPoint(BroadcastReceiver.class) public static final
DoubleInjectService
java
apache__spark
common/network-common/src/test/java/org/apache/spark/network/TransportRequestHandlerSuite.java
{ "start": 1659, "end": 7438 }
class ____ { @Test public void handleStreamRequest() throws Exception { RpcHandler rpcHandler = new NoOpRpcHandler(); OneForOneStreamManager streamManager = (OneForOneStreamManager) (rpcHandler.getStreamManager()); Channel channel = mock(Channel.class); List<Pair<Object, ExtendedChannelPromise>> responseAndPromisePairs = new ArrayList<>(); when(channel.writeAndFlush(any())) .thenAnswer(invocationOnMock0 -> { Object response = invocationOnMock0.getArguments()[0]; ExtendedChannelPromise channelFuture = new ExtendedChannelPromise(channel); responseAndPromisePairs.add(Pair.of(response, channelFuture)); return channelFuture; }); // Prepare the stream. List<ManagedBuffer> managedBuffers = new ArrayList<>(); managedBuffers.add(new TestManagedBuffer(10)); managedBuffers.add(new TestManagedBuffer(20)); managedBuffers.add(null); managedBuffers.add(new TestManagedBuffer(30)); managedBuffers.add(new TestManagedBuffer(40)); long streamId = streamManager.registerStream("test-app", managedBuffers.iterator(), channel); Assertions.assertEquals(1, streamManager.numStreamStates()); TransportClient reverseClient = mock(TransportClient.class); TransportRequestHandler requestHandler = new TransportRequestHandler(channel, reverseClient, rpcHandler, 2L, null); RequestMessage request0 = new StreamRequest(String.format("%d_%d", streamId, 0)); requestHandler.handle(request0); Assertions.assertEquals(1, responseAndPromisePairs.size()); Assertions.assertTrue(responseAndPromisePairs.get(0).getLeft() instanceof StreamResponse); Assertions.assertEquals(managedBuffers.get(0), ((StreamResponse) (responseAndPromisePairs.get(0).getLeft())).body()); RequestMessage request1 = new StreamRequest(String.format("%d_%d", streamId, 1)); requestHandler.handle(request1); Assertions.assertEquals(2, responseAndPromisePairs.size()); Assertions.assertTrue(responseAndPromisePairs.get(1).getLeft() instanceof StreamResponse); Assertions.assertEquals(managedBuffers.get(1), ((StreamResponse) (responseAndPromisePairs.get(1).getLeft())).body()); // Finish flushing the response for request0. responseAndPromisePairs.get(0).getRight().finish(true); StreamRequest request2 = new StreamRequest(String.format("%d_%d", streamId, 2)); requestHandler.handle(request2); Assertions.assertEquals(3, responseAndPromisePairs.size()); Assertions.assertTrue(responseAndPromisePairs.get(2).getLeft() instanceof StreamFailure); Assertions.assertEquals(String.format("Stream '%s' was not found.", request2.streamId), ((StreamFailure) (responseAndPromisePairs.get(2).getLeft())).error); RequestMessage request3 = new StreamRequest(String.format("%d_%d", streamId, 3)); requestHandler.handle(request3); Assertions.assertEquals(4, responseAndPromisePairs.size()); Assertions.assertTrue(responseAndPromisePairs.get(3).getLeft() instanceof StreamResponse); Assertions.assertEquals(managedBuffers.get(3), ((StreamResponse) (responseAndPromisePairs.get(3).getLeft())).body()); // Request4 will trigger the close of channel, because the number of max chunks being // transferred is 2; RequestMessage request4 = new StreamRequest(String.format("%d_%d", streamId, 4)); requestHandler.handle(request4); verify(channel, times(1)).close(); Assertions.assertEquals(4, responseAndPromisePairs.size()); streamManager.connectionTerminated(channel); Assertions.assertEquals(0, streamManager.numStreamStates()); } @Test public void handleMergedBlockMetaRequest() throws Exception { RpcHandler.MergedBlockMetaReqHandler metaHandler = (client, request, callback) -> { if (request.shuffleId != -1 && request.reduceId != -1) { callback.onSuccess(2, mock(ManagedBuffer.class)); } else { callback.onFailure(new RuntimeException("empty block")); } }; RpcHandler rpcHandler = new RpcHandler() { @Override public void receive( TransportClient client, ByteBuffer message, RpcResponseCallback callback) {} @Override public StreamManager getStreamManager() { return null; } @Override public MergedBlockMetaReqHandler getMergedBlockMetaReqHandler() { return metaHandler; } }; Channel channel = mock(Channel.class); List<Pair<Object, ExtendedChannelPromise>> responseAndPromisePairs = new ArrayList<>(); when(channel.writeAndFlush(any())).thenAnswer(invocationOnMock0 -> { Object response = invocationOnMock0.getArguments()[0]; ExtendedChannelPromise channelFuture = new ExtendedChannelPromise(channel); responseAndPromisePairs.add(Pair.of(response, channelFuture)); return channelFuture; }); TransportClient reverseClient = mock(TransportClient.class); TransportRequestHandler requestHandler = new TransportRequestHandler(channel, reverseClient, rpcHandler, 2L, null); MergedBlockMetaRequest validMetaReq = new MergedBlockMetaRequest(19, "app1", 0, 0, 0); requestHandler.handle(validMetaReq); assertEquals(1, responseAndPromisePairs.size()); assertTrue(responseAndPromisePairs.get(0).getLeft() instanceof MergedBlockMetaSuccess); assertEquals(2, ((MergedBlockMetaSuccess) (responseAndPromisePairs.get(0).getLeft())).getNumChunks()); MergedBlockMetaRequest invalidMetaReq = new MergedBlockMetaRequest(21, "app1", -1, 0, 1); requestHandler.handle(invalidMetaReq); assertEquals(2, responseAndPromisePairs.size()); assertTrue(responseAndPromisePairs.get(1).getLeft() instanceof RpcFailure); } }
TransportRequestHandlerSuite
java
apache__rocketmq
proxy/src/test/java/org/apache/rocketmq/proxy/remoting/channel/RemotingChannelManagerTest.java
{ "start": 1666, "end": 6491 }
class ____ { @Mock private RemotingProxyOutClient remotingProxyOutClient; @Mock private ProxyRelayService proxyRelayService; private final String remoteAddress = "10.152.39.53:9768"; private final String localAddress = "11.193.0.1:1210"; private RemotingChannelManager remotingChannelManager; private final ProxyContext ctx = ProxyContext.createForInner(this.getClass()); @Before public void before() { this.remotingChannelManager = new RemotingChannelManager(this.remotingProxyOutClient, this.proxyRelayService); } @Test public void testCreateChannel() { String group = "group"; String clientId = RandomStringUtils.randomAlphabetic(10); Channel producerChannel = createMockChannel(); RemotingChannel producerRemotingChannel = this.remotingChannelManager.createProducerChannel(ctx, producerChannel, group, clientId); assertNotNull(producerRemotingChannel); assertSame(producerRemotingChannel, this.remotingChannelManager.createProducerChannel(ctx, producerChannel, group, clientId)); Channel consumerChannel = createMockChannel(); RemotingChannel consumerRemotingChannel = this.remotingChannelManager.createConsumerChannel(ctx, consumerChannel, group, clientId, new HashSet<>()); assertSame(consumerRemotingChannel, this.remotingChannelManager.createConsumerChannel(ctx, consumerChannel, group, clientId, new HashSet<>())); assertNotNull(consumerRemotingChannel); assertNotSame(producerRemotingChannel, consumerRemotingChannel); } @Test public void testRemoveProducerChannel() { String group = "group"; String clientId = RandomStringUtils.randomAlphabetic(10); { Channel producerChannel = createMockChannel(); RemotingChannel producerRemotingChannel = this.remotingChannelManager.createProducerChannel(ctx, producerChannel, group, clientId); assertSame(producerRemotingChannel, this.remotingChannelManager.removeProducerChannel(ctx, group, producerRemotingChannel)); assertTrue(this.remotingChannelManager.groupChannelMap.isEmpty()); } { Channel producerChannel = createMockChannel(); RemotingChannel producerRemotingChannel = this.remotingChannelManager.createProducerChannel(ctx, producerChannel, group, clientId); assertSame(producerRemotingChannel, this.remotingChannelManager.removeProducerChannel(ctx, group, producerChannel)); assertTrue(this.remotingChannelManager.groupChannelMap.isEmpty()); } } @Test public void testRemoveConsumerChannel() { String group = "group"; String clientId = RandomStringUtils.randomAlphabetic(10); { Channel consumerChannel = createMockChannel(); RemotingChannel consumerRemotingChannel = this.remotingChannelManager.createConsumerChannel(ctx, consumerChannel, group, clientId, new HashSet<>()); assertSame(consumerRemotingChannel, this.remotingChannelManager.removeConsumerChannel(ctx, group, consumerRemotingChannel)); assertTrue(this.remotingChannelManager.groupChannelMap.isEmpty()); } { Channel consumerChannel = createMockChannel(); RemotingChannel consumerRemotingChannel = this.remotingChannelManager.createConsumerChannel(ctx, consumerChannel, group, clientId, new HashSet<>()); assertSame(consumerRemotingChannel, this.remotingChannelManager.removeConsumerChannel(ctx, group, consumerChannel)); assertTrue(this.remotingChannelManager.groupChannelMap.isEmpty()); } } @Test public void testRemoveChannel() { String consumerGroup = "consumerGroup"; String producerGroup = "producerGroup"; String clientId = RandomStringUtils.randomAlphabetic(10); Channel consumerChannel = createMockChannel(); RemotingChannel consumerRemotingChannel = this.remotingChannelManager.createConsumerChannel(ctx, consumerChannel, consumerGroup, clientId, new HashSet<>()); Channel producerChannel = createMockChannel(); RemotingChannel producerRemotingChannel = this.remotingChannelManager.createProducerChannel(ctx, producerChannel, producerGroup, clientId); assertSame(consumerRemotingChannel, this.remotingChannelManager.removeChannel(consumerChannel).stream().findFirst().get()); assertSame(producerRemotingChannel, this.remotingChannelManager.removeChannel(producerChannel).stream().findFirst().get()); assertTrue(this.remotingChannelManager.groupChannelMap.isEmpty()); } private Channel createMockChannel() { return new MockChannel(RandomStringUtils.randomAlphabetic(10)); } private
RemotingChannelManagerTest
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/inject/generics/Engine.java
{ "start": 67, "end": 376 }
interface ____<T extends CylinderProvider> { // <1> default int getCylinders() { return getCylinderProvider().getCylinders(); } default String start() { return "Starting " + getCylinderProvider().getClass().getSimpleName(); } T getCylinderProvider(); } // tag::class[]
Engine
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/AuthConfig.java
{ "start": 285, "end": 1394 }
interface ____ { /** * If basic auth should be enabled. If both basic and form auth is enabled then basic auth will be enabled in silent mode. * <p> * The basic auth is enabled by default if no authentication mechanisms are configured or Quarkus can safely * determine that basic authentication is required. */ Optional<Boolean> basic(); /** * If form authentication is enabled. */ @WithDefault("false") @WithName("form.enabled") boolean form(); /** * If this is true and credentials are present then a user will always be authenticated * before the request progresses. * <p> * If this is false then an attempt will only be made to authenticate the user if a permission * check is performed or the current user is required for some other reason. */ @WithDefault("true") boolean proactive(); /** * Propagate security identity to support its injection in Vert.x route handlers registered directly with the router. */ @WithDefault("false") boolean propagateSecurityIdentity(); }
AuthConfig
java
apache__camel
components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/service/spi/CommentsSPI.java
{ "start": 1711, "end": 3812 }
interface ____ { // @formatter:off @GET @Path("/v{apiVersion}/comments") @Produces(MediaType.APPLICATION_JSON) List<Comment> list( @PathParam("apiVersion") String apiVersion, @QueryParam("context") Context context, @QueryParam("page") Integer page, @QueryParam("per_page") Integer perPage, @QueryParam("search") String search, @QueryParam("after") Date after, @QueryParam("author") List<Integer> author, @QueryParam("author_exclude") List<Integer> authorExclude, @QueryParam("author_email") String authorEmail, @QueryParam("before") Date before, @QueryParam("exclude") List<Integer> exclude, @QueryParam("include") List<Integer> include, @QueryParam("karma") Integer karma, @QueryParam("offset") List<Integer> offset, @QueryParam("order") Order order, @QueryParam("orderby") CommentOrderBy orderBy, @QueryParam("parent") List<Integer> parent, @QueryParam("parent_exclude") List<Integer> parentExclude, @QueryParam("post") List<Integer> post, @QueryParam("status") CommentStatus status, @QueryParam("type") String type); @GET @Path("/v{apiVersion}/comments/{id}") @Produces(MediaType.APPLICATION_JSON) Comment retrieve( @PathParam("apiVersion") String apiVersion, @PathParam("id") Integer id, @QueryParam("context") Context context); // @formatter:on @POST @Path("/v{apiVersion}/comments") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) Comment create(@PathParam("apiVersion") String apiVersion, Comment comment); // @formatter:off @POST @Path("/v{apiVersion}/comments/{id}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) Comment update(@PathParam("apiVersion") String apiVersion, @PathParam("id") int id, Comment post); @DELETE @Path("/v{apiVersion}/comments/{id}") Comment delete(@PathParam("apiVersion") String apiVersion, @PathParam("id") int id, @QueryParam("force") boolean force); }
CommentsSPI
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoValueCompilationTest.java
{ "start": 72189, "end": 72572 }
interface ____ {", " Builder foo(int x);", " Baz build();", " }", "}"); Compilation compilation = javac() .withProcessors(new AutoValueProcessor(), new AutoValueBuilderProcessor()) .compile(javaFileObject); assertThat(compilation) .hadErrorContaining("can only be applied to a
Builder
java
resilience4j__resilience4j
resilience4j-framework-common/src/test/java/io/github/resilience4j/common/utils/SpringConfigUtilsTest.java
{ "start": 1333, "end": 7354 }
class ____ { @Test public void testBulkHeadMergeSpringProperties() { CommonBulkheadConfigurationProperties.InstanceProperties shared = new CommonBulkheadConfigurationProperties.InstanceProperties(); shared.setMaxConcurrentCalls(3); shared.setEventConsumerBufferSize(200); assertThat(shared.getEventConsumerBufferSize()).isEqualTo(200); CommonBulkheadConfigurationProperties.InstanceProperties instanceProperties = new CommonBulkheadConfigurationProperties.InstanceProperties(); instanceProperties.setMaxConcurrentCalls(3); assertThat(instanceProperties.getEventConsumerBufferSize()).isNull(); ConfigUtils.mergePropertiesIfAny(shared, instanceProperties); assertThat(instanceProperties.getEventConsumerBufferSize()).isEqualTo(200); } @Test public void testCircuitBreakerMergeSpringProperties() { CommonCircuitBreakerConfigurationProperties.InstanceProperties sharedProperties = new CommonCircuitBreakerConfigurationProperties.InstanceProperties(); sharedProperties.setSlidingWindowSize(1337); sharedProperties.setPermittedNumberOfCallsInHalfOpenState(1000); sharedProperties.setRegisterHealthIndicator(true); sharedProperties.setAllowHealthIndicatorToFail(true); sharedProperties.setEventConsumerBufferSize(200); CommonCircuitBreakerConfigurationProperties.InstanceProperties backendWithDefaultConfig = new CommonCircuitBreakerConfigurationProperties.InstanceProperties(); backendWithDefaultConfig.setPermittedNumberOfCallsInHalfOpenState(99); assertThat(backendWithDefaultConfig.getEventConsumerBufferSize()).isNull(); assertThat(backendWithDefaultConfig.getAllowHealthIndicatorToFail()).isNull(); ConfigUtils.mergePropertiesIfAny(backendWithDefaultConfig, sharedProperties); assertThat(backendWithDefaultConfig.getEventConsumerBufferSize()).isEqualTo(200); assertThat(backendWithDefaultConfig.getRegisterHealthIndicator()).isTrue(); assertThat(backendWithDefaultConfig.getAllowHealthIndicatorToFail()).isTrue(); } @Test public void testRetrySpringProperties() { CommonRetryConfigurationProperties.InstanceProperties sharedProperties = new CommonRetryConfigurationProperties.InstanceProperties(); sharedProperties.setMaxAttempts(2); sharedProperties.setWaitDuration(Duration.ofMillis(100)); sharedProperties.setEnableRandomizedWait(true); sharedProperties.setExponentialBackoffMultiplier(0.1); sharedProperties.setExponentialMaxWaitDuration(Duration.ofMinutes(2)); sharedProperties.setEnableExponentialBackoff(false); CommonRetryConfigurationProperties.InstanceProperties backendWithDefaultConfig = new CommonRetryConfigurationProperties.InstanceProperties(); backendWithDefaultConfig.setBaseConfig("default"); backendWithDefaultConfig.setWaitDuration(Duration.ofMillis(200L)); assertThat(backendWithDefaultConfig.getEnableExponentialBackoff()).isNull(); assertThat(backendWithDefaultConfig.getExponentialBackoffMultiplier()).isNull(); assertThat(backendWithDefaultConfig.getExponentialMaxWaitDuration()).isNull(); assertThat(backendWithDefaultConfig.getEnableRandomizedWait()).isNull(); ConfigUtils.mergePropertiesIfAny(sharedProperties, backendWithDefaultConfig); assertThat(backendWithDefaultConfig.getEnableExponentialBackoff()).isFalse(); assertThat(backendWithDefaultConfig.getExponentialBackoffMultiplier()).isEqualTo(0.1); assertThat(backendWithDefaultConfig.getExponentialMaxWaitDuration()).isEqualTo(Duration.ofMinutes(2)); assertThat(backendWithDefaultConfig.getEnableRandomizedWait()).isTrue(); } @Test public void testRateLimiterSpringProperties() { CommonRateLimiterConfigurationProperties.InstanceProperties sharedProperties = new CommonRateLimiterConfigurationProperties.InstanceProperties(); sharedProperties.setLimitForPeriod(2); sharedProperties.setLimitRefreshPeriod(Duration.ofMillis(6000000)); sharedProperties.setSubscribeForEvents(true); sharedProperties.setRegisterHealthIndicator(true); sharedProperties.setEventConsumerBufferSize(200); CommonRateLimiterConfigurationProperties.InstanceProperties backendWithDefaultConfig = new CommonRateLimiterConfigurationProperties.InstanceProperties(); backendWithDefaultConfig.setBaseConfig("default"); backendWithDefaultConfig.setLimitForPeriod(200); assertThat(backendWithDefaultConfig.getRegisterHealthIndicator()).isNull(); assertThat(backendWithDefaultConfig.getEventConsumerBufferSize()).isNull(); assertThat(backendWithDefaultConfig.getSubscribeForEvents()).isNull(); ConfigUtils.mergePropertiesIfAny(sharedProperties, backendWithDefaultConfig); assertThat(backendWithDefaultConfig.getRegisterHealthIndicator()).isTrue(); assertThat(backendWithDefaultConfig.getEventConsumerBufferSize()).isEqualTo(200); assertThat(backendWithDefaultConfig.getSubscribeForEvents()).isTrue(); } @Test public void testTimeLimiterSpringProperties() { CommonTimeLimiterConfigurationProperties.InstanceProperties sharedProperties = new CommonTimeLimiterConfigurationProperties.InstanceProperties(); sharedProperties.setTimeoutDuration(Duration.ofSeconds(20)); sharedProperties.setCancelRunningFuture(false); sharedProperties.setEventConsumerBufferSize(200); CommonTimeLimiterConfigurationProperties.InstanceProperties backendWithDefaultConfig = new CommonTimeLimiterConfigurationProperties.InstanceProperties(); sharedProperties.setCancelRunningFuture(true); assertThat(backendWithDefaultConfig.getEventConsumerBufferSize()).isNull(); ConfigUtils.mergePropertiesIfAny(sharedProperties, backendWithDefaultConfig); assertThat(backendWithDefaultConfig.getEventConsumerBufferSize()).isEqualTo(200); } }
SpringConfigUtilsTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/any/annotations/AnyOnExistingColumnsTest.java
{ "start": 4213, "end": 5079 }
class ____ { @Id private Long id; @Column( name = "property_type" ) private String propertyType; @Any @AnyKeyJavaClass( Long.class ) @AnyDiscriminator( DiscriminatorType.STRING ) @AnyDiscriminatorValues( { @AnyDiscriminatorValue( discriminator = "I", entity = IntegerProperty.class ), @AnyDiscriminatorValue( discriminator = "S", entity = StringProperty.class ) } ) @Column( name = "property_type", updatable = false, insertable = false ) @JoinColumn( name = "id", updatable = false, insertable = false ) @Cascade( CascadeType.ALL ) private Property property; public PropertyHolder() { } public PropertyHolder(Long id, String propertyType, Property property) { this.id = id; this.propertyType = propertyType; this.property = property; } public Property getProperty() { return property; } } }
PropertyHolder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/iomanager/RequestQueue.java
{ "start": 1025, "end": 1641 }
class ____<E> extends LinkedBlockingQueue<E> implements Closeable { private static final long serialVersionUID = 3804115535778471680L; /** Flag marking this queue as closed. */ private volatile boolean closed = false; /** * Closes this request queue. * * @see java.io.Closeable#close() */ @Override public void close() { this.closed = true; } /** * Checks whether this request queue is closed. * * @return True, if the queue is closed, false otherwise. */ public boolean isClosed() { return this.closed; } }
RequestQueue
java
alibaba__fastjson
src/main/java/com/alibaba/fastjson/util/IOUtils.java
{ "start": 1214, "end": 29750 }
class ____ { public final static String FASTJSON_PROPERTIES = "fastjson.properties"; public final static String FASTJSON_COMPATIBLEWITHJAVABEAN = "fastjson.compatibleWithJavaBean"; public final static String FASTJSON_COMPATIBLEWITHFIELDNAME = "fastjson.compatibleWithFieldName"; public final static Properties DEFAULT_PROPERTIES = new Properties(); public final static Charset UTF8 = Charset.forName("UTF-8"); public final static char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; public final static boolean[] firstIdentifierFlags = new boolean[256]; public final static boolean[] identifierFlags = new boolean[256]; static { for (char c = 0; c < firstIdentifierFlags.length; ++c) { if (c >= 'A' && c <= 'Z') { firstIdentifierFlags[c] = true; } else if (c >= 'a' && c <= 'z') { firstIdentifierFlags[c] = true; } else if (c == '_' || c == '$') { firstIdentifierFlags[c] = true; } } for (char c = 0; c < identifierFlags.length; ++c) { if (c >= 'A' && c <= 'Z') { identifierFlags[c] = true; } else if (c >= 'a' && c <= 'z') { identifierFlags[c] = true; } else if (c == '_') { identifierFlags[c] = true; } else if (c >= '0' && c <= '9') { identifierFlags[c] = true; } } try { loadPropertiesFromFile(); } catch (Throwable e) { //skip } } public static String getStringProperty(String name) { String prop = null; try { prop = System.getProperty(name); } catch (SecurityException e) { //skip } return (prop == null) ? DEFAULT_PROPERTIES.getProperty(name) : prop; } public static void loadPropertiesFromFile(){ InputStream imputStream = AccessController.doPrivileged(new PrivilegedAction<InputStream>() { public InputStream run() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl != null) { return cl.getResourceAsStream(FASTJSON_PROPERTIES); } else { return ClassLoader.getSystemResourceAsStream(FASTJSON_PROPERTIES); } } }); if (null != imputStream) { try { DEFAULT_PROPERTIES.load(imputStream); imputStream.close(); } catch (java.io.IOException e) { // skip } } } public final static byte[] specicalFlags_doubleQuotes = new byte[161]; public final static byte[] specicalFlags_singleQuotes = new byte[161]; public final static boolean[] specicalFlags_doubleQuotesFlags = new boolean[161]; public final static boolean[] specicalFlags_singleQuotesFlags = new boolean[161]; public final static char[] replaceChars = new char[93]; static { specicalFlags_doubleQuotes['\0'] = 4; specicalFlags_doubleQuotes['\1'] = 4; specicalFlags_doubleQuotes['\2'] = 4; specicalFlags_doubleQuotes['\3'] = 4; specicalFlags_doubleQuotes['\4'] = 4; specicalFlags_doubleQuotes['\5'] = 4; specicalFlags_doubleQuotes['\6'] = 4; specicalFlags_doubleQuotes['\7'] = 4; specicalFlags_doubleQuotes['\b'] = 1; // 8 specicalFlags_doubleQuotes['\t'] = 1; // 9 specicalFlags_doubleQuotes['\n'] = 1; // 10 specicalFlags_doubleQuotes['\u000B'] = 4; // 11 specicalFlags_doubleQuotes['\f'] = 1; // 12 specicalFlags_doubleQuotes['\r'] = 1; // 13 specicalFlags_doubleQuotes['\"'] = 1; // 34 specicalFlags_doubleQuotes['\\'] = 1; // 92 specicalFlags_singleQuotes['\0'] = 4; specicalFlags_singleQuotes['\1'] = 4; specicalFlags_singleQuotes['\2'] = 4; specicalFlags_singleQuotes['\3'] = 4; specicalFlags_singleQuotes['\4'] = 4; specicalFlags_singleQuotes['\5'] = 4; specicalFlags_singleQuotes['\6'] = 4; specicalFlags_singleQuotes['\7'] = 4; specicalFlags_singleQuotes['\b'] = 1; // 8 specicalFlags_singleQuotes['\t'] = 1; // 9 specicalFlags_singleQuotes['\n'] = 1; // 10 specicalFlags_singleQuotes['\u000B'] = 4; // 11 specicalFlags_singleQuotes['\f'] = 1; // 12 specicalFlags_singleQuotes['\r'] = 1; // 13 specicalFlags_singleQuotes['\\'] = 1; // 92 specicalFlags_singleQuotes['\''] = 1; // 39 for (int i = 14; i <= 31; ++i) { specicalFlags_doubleQuotes[i] = 4; specicalFlags_singleQuotes[i] = 4; } for (int i = 127; i < 160; ++i) { specicalFlags_doubleQuotes[i] = 4; specicalFlags_singleQuotes[i] = 4; } for (int i = 0; i < 161; ++i) { specicalFlags_doubleQuotesFlags[i] = specicalFlags_doubleQuotes[i] != 0; specicalFlags_singleQuotesFlags[i] = specicalFlags_singleQuotes[i] != 0; } replaceChars['\0'] = '0'; replaceChars['\1'] = '1'; replaceChars['\2'] = '2'; replaceChars['\3'] = '3'; replaceChars['\4'] = '4'; replaceChars['\5'] = '5'; replaceChars['\6'] = '6'; replaceChars['\7'] = '7'; replaceChars['\b'] = 'b'; // 8 replaceChars['\t'] = 't'; // 9 replaceChars['\n'] = 'n'; // 10 replaceChars['\u000B'] = 'v'; // 11 replaceChars['\f'] = 'f'; // 12 replaceChars['\r'] = 'r'; // 13 replaceChars['\"'] = '"'; // 34 replaceChars['\''] = '\''; // 39 replaceChars['/'] = '/'; // 47 replaceChars['\\'] = '\\'; // 92 } public final static char[] ASCII_CHARS = { '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7', '0', '8', '0', '9', '0', 'A', '0', 'B', '0', 'C', '0', 'D', '0', 'E', '0', 'F', '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '1', 'A', '1', 'B', '1', 'C', '1', 'D', '1', 'E', '1', 'F', '2', '0', '2', '1', '2', '2', '2', '3', '2', '4', '2', '5', '2', '6', '2', '7', '2', '8', '2', '9', '2', 'A', '2', 'B', '2', 'C', '2', 'D', '2', 'E', '2', 'F', }; public static void close(Closeable x) { if (x != null) { try { x.close(); } catch (Exception e) { // skip } } } // Requires positive x public static int stringSize(long x) { long p = 10; for (int i = 1; i < 19; i++) { if (x < p) return i; p = 10 * p; } return 19; } public static void getChars(long i, int index, char[] buf) { long q; int r; int charPos = index; char sign = 0; if (i < 0) { sign = '-'; i = -i; } // Get 2 digits/iteration using longs until quotient fits into an int while (i > Integer.MAX_VALUE) { q = i / 100; // really: r = i - (q * 100); r = (int) (i - ((q << 6) + (q << 5) + (q << 2))); i = q; buf[--charPos] = DigitOnes[r]; buf[--charPos] = DigitTens[r]; } // Get 2 digits/iteration using ints int q2; int i2 = (int) i; while (i2 >= 65536) { q2 = i2 / 100; // really: r = i2 - (q * 100); r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2)); i2 = q2; buf[--charPos] = DigitOnes[r]; buf[--charPos] = DigitTens[r]; } // Fall thru to fast mode for smaller numbers // assert(i2 <= 65536, i2); for (;;) { q2 = (i2 * 52429) >>> (16 + 3); r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ... buf[--charPos] = digits[r]; i2 = q2; if (i2 == 0) break; } if (sign != 0) { buf[--charPos] = sign; } } /** * Places characters representing the integer i into the character array buf. The characters are placed into the * buffer backwards starting with the least significant digit at the specified index (exclusive), and working * backwards from there. Will fail if i == Integer.MIN_VALUE */ public static void getChars(int i, int index, char[] buf) { int q, r, p = index; char sign = 0; if (i < 0) { sign = '-'; i = -i; } while (i >= 65536) { q = i / 100; // really: r = i - (q * 100); r = i - ((q << 6) + (q << 5) + (q << 2)); i = q; buf[--p] = DigitOnes[r]; buf[--p] = DigitTens[r]; } // Fall thru to fast mode for smaller numbers // assert(i <= 65536, i); for (;;) { q = (i * 52429) >>> (16 + 3); r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... buf[--p] = digits[r]; i = q; if (i == 0) break; } if (sign != 0) { buf[--p] = sign; } } public static void getChars(byte b, int index, char[] buf) { int i = b; int q, r; int charPos = index; char sign = 0; if (i < 0) { sign = '-'; i = -i; } // Fall thru to fast mode for smaller numbers // assert(i <= 65536, i); for (;;) { q = (i * 52429) >>> (16 + 3); r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... buf[--charPos] = digits[r]; i = q; if (i == 0) break; } if (sign != 0) { buf[--charPos] = sign; } } /** * All possible chars for representing a number as a String */ final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; final static char[] DigitTens = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', }; final static char[] DigitOnes = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', }; final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE }; // Requires positive x public static int stringSize(int x) { for (int i = 0;; i++) { if (x <= sizeTable[i]) { return i + 1; } } } public static void decode(CharsetDecoder charsetDecoder, ByteBuffer byteBuf, CharBuffer charByte) { try { CoderResult cr = charsetDecoder.decode(byteBuf, charByte, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = charsetDecoder.flush(charByte); if (!cr.isUnderflow()) { cr.throwException(); } } catch (CharacterCodingException x) { // Substitution is always enabled, // so this shouldn't happen throw new JSONException("utf8 decode error, " + x.getMessage(), x); } } public static boolean firstIdentifier(char ch) { return ch < IOUtils.firstIdentifierFlags.length && IOUtils.firstIdentifierFlags[ch]; } public static boolean isIdent(char ch) { return ch < identifierFlags.length && identifierFlags[ch]; } public static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); public static final int[] IA = new int[256]; static { Arrays.fill(IA, -1); for (int i = 0, iS = CA.length; i < iS; i++) IA[CA[i]] = i; IA['='] = 0; } /** * Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as * fast as #decode(char[]). The preconditions are:<br> * + The array must have a line length of 76 chars OR no line separators at all (one line).<br> * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within * the encoded string<br> * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br> * * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11 * @param chars The source array. Length 0 will return an empty array. <code>null</code> will throw an exception. * @return The decoded array of bytes. May be of length 0. */ public static byte[] decodeBase64(char[] chars, int offset, int charsLen) { // Check special case if (charsLen == 0) { return new byte[0]; } int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming. // Trim illegal chars from start while (sIx < eIx && IA[chars[sIx]] < 0) sIx++; // Trim illegal chars from end while (eIx > 0 && IA[chars[eIx]] < 0) eIx--; // get the padding count (=) (0, 1 or 2) int pad = chars[eIx] == '=' ? (chars[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end. int cCnt = eIx - sIx + 1; // Content count including possible separators int sepCnt = charsLen > 76 ? (chars[76] == '\r' ? cCnt / 78 : 0) << 1 : 0; int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes byte[] bytes = new byte[len]; // Preallocate byte[] of exact length // Decode all but the last 0 - 2 bytes. int d = 0; for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { // Assemble three bytes into an int from four "valid" characters. int i = IA[chars[sIx++]] << 18 | IA[chars[sIx++]] << 12 | IA[chars[sIx++]] << 6 | IA[chars[sIx++]]; // Add the bytes bytes[d++] = (byte) (i >> 16); bytes[d++] = (byte) (i >> 8); bytes[d++] = (byte) i; // If line separator, jump over it. if (sepCnt > 0 && ++cc == 19) { sIx += 2; cc = 0; } } if (d < len) { // Decode last 1-3 bytes (incl '=') into 1-3 bytes int i = 0; for (int j = 0; sIx <= eIx - pad; j++) i |= IA[chars[sIx++]] << (18 - j * 6); for (int r = 16; d < len; r -= 8) bytes[d++] = (byte) (i >> r); } return bytes; } /** * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11 */ public static byte[] decodeBase64(String chars, int offset, int charsLen) { // Check special case if (charsLen == 0) { return new byte[0]; } int sIx = offset, eIx = offset + charsLen - 1; // Start and end index after trimming. // Trim illegal chars from start while (sIx < eIx && IA[chars.charAt(sIx)] < 0) sIx++; // Trim illegal chars from end while (eIx > 0 && IA[chars.charAt(eIx)] < 0) eIx--; // get the padding count (=) (0, 1 or 2) int pad = chars.charAt(eIx) == '=' ? (chars.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end. int cCnt = eIx - sIx + 1; // Content count including possible separators int sepCnt = charsLen > 76 ? (chars.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes byte[] bytes = new byte[len]; // Preallocate byte[] of exact length // Decode all but the last 0 - 2 bytes. int d = 0; for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { // Assemble three bytes into an int from four "valid" characters. int i = IA[chars.charAt(sIx++)] << 18 | IA[chars.charAt(sIx++)] << 12 | IA[chars.charAt(sIx++)] << 6 | IA[chars.charAt(sIx++)]; // Add the bytes bytes[d++] = (byte) (i >> 16); bytes[d++] = (byte) (i >> 8); bytes[d++] = (byte) i; // If line separator, jump over it. if (sepCnt > 0 && ++cc == 19) { sIx += 2; cc = 0; } } if (d < len) { // Decode last 1-3 bytes (incl '=') into 1-3 bytes int i = 0; for (int j = 0; sIx <= eIx - pad; j++) i |= IA[chars.charAt(sIx++)] << (18 - j * 6); for (int r = 16; d < len; r -= 8) bytes[d++] = (byte) (i >> r); } return bytes; } /** * Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as fast * as decode(String). The preconditions are:<br> * + The array must have a line length of 76 chars OR no line separators at all (one line).<br> * + Line separator must be "\r\n", as specified in RFC 2045 + The array must not contain illegal characters within * the encoded string<br> * + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br> * * @author Mikael Grev Date: 2004-aug-02 Time: 11:31:11 * @param s The source string. Length 0 will return an empty array. <code>null</code> will throw an exception. * @return The decoded array of bytes. May be of length 0. */ public static byte[] decodeBase64(String s) { // Check special case int sLen = s.length(); if (sLen == 0) { return new byte[0]; } int sIx = 0, eIx = sLen - 1; // Start and end index after trimming. // Trim illegal chars from start while (sIx < eIx && IA[s.charAt(sIx) & 0xff] < 0) sIx++; // Trim illegal chars from end while (eIx > 0 && IA[s.charAt(eIx) & 0xff] < 0) eIx--; // get the padding count (=) (0, 1 or 2) int pad = s.charAt(eIx) == '=' ? (s.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end. int cCnt = eIx - sIx + 1; // Content count including possible separators int sepCnt = sLen > 76 ? (s.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0; int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes byte[] dArr = new byte[len]; // Preallocate byte[] of exact length // Decode all but the last 0 - 2 bytes. int d = 0; for (int cc = 0, eLen = (len / 3) * 3; d < eLen;) { // Assemble three bytes into an int from four "valid" characters. int i = IA[s.charAt(sIx++)] << 18 | IA[s.charAt(sIx++)] << 12 | IA[s.charAt(sIx++)] << 6 | IA[s.charAt(sIx++)]; // Add the bytes dArr[d++] = (byte) (i >> 16); dArr[d++] = (byte) (i >> 8); dArr[d++] = (byte) i; // If line separator, jump over it. if (sepCnt > 0 && ++cc == 19) { sIx += 2; cc = 0; } } if (d < len) { // Decode last 1-3 bytes (incl '=') into 1-3 bytes int i = 0; for (int j = 0; sIx <= eIx - pad; j++) i |= IA[s.charAt(sIx++)] << (18 - j * 6); for (int r = 16; d < len; r -= 8) dArr[d++] = (byte) (i >> r); } return dArr; } public static int encodeUTF8(char[] chars, int offset, int len, byte[] bytes) { int sl = offset + len; int dp = 0; int dlASCII = dp + Math.min(len, bytes.length); // ASCII only optimized loop while (dp < dlASCII && chars[offset] < '\u0080') { bytes[dp++] = (byte) chars[offset++]; } while (offset < sl) { char c = chars[offset++]; if (c < 0x80) { // Have at most seven bits bytes[dp++] = (byte) c; } else if (c < 0x800) { // 2 bytes, 11 bits bytes[dp++] = (byte) (0xc0 | (c >> 6)); bytes[dp++] = (byte) (0x80 | (c & 0x3f)); } else if (c >= '\uD800' && c < ('\uDFFF' + 1)) { //Character.isSurrogate(c) but 1.7 final int uc; int ip = offset - 1; if (c >= '\uD800' && c < ('\uDBFF' + 1)) { // Character.isHighSurrogate(c) if (sl - ip < 2) { uc = -1; } else { char d = chars[ip + 1]; // d >= '\uDC00' && d < ('\uDFFF' + 1) if (d >= '\uDC00' && d < ('\uDFFF' + 1)) { // Character.isLowSurrogate(d) uc = ((c << 10) + d) + (0x010000 - ('\uD800' << 10) - '\uDC00'); // Character.toCodePoint(c, d) } else { // throw new JSONException("encodeUTF8 error", new MalformedInputException(1)); bytes[dp++] = (byte) '?'; continue; } } } else { // if (c >= '\uDC00' && c < ('\uDFFF' + 1)) { // Character.isLowSurrogate(c) bytes[dp++] = (byte) '?'; continue; // throw new JSONException("encodeUTF8 error", new MalformedInputException(1)); } else { uc = c; } } if (uc < 0) { bytes[dp++] = (byte) '?'; } else { bytes[dp++] = (byte) (0xf0 | ((uc >> 18))); bytes[dp++] = (byte) (0x80 | ((uc >> 12) & 0x3f)); bytes[dp++] = (byte) (0x80 | ((uc >> 6) & 0x3f)); bytes[dp++] = (byte) (0x80 | (uc & 0x3f)); offset++; // 2 chars } } else { // 3 bytes, 16 bits bytes[dp++] = (byte) (0xe0 | ((c >> 12))); bytes[dp++] = (byte) (0x80 | ((c >> 6) & 0x3f)); bytes[dp++] = (byte) (0x80 | (c & 0x3f)); } } return dp; } /** * @deprecated */ public static int decodeUTF8(byte[] sa, int sp, int len, char[] da) { final int sl = sp + len; int dp = 0; int dlASCII = Math.min(len, da.length); // ASCII only optimized loop while (dp < dlASCII && sa[sp] >= 0) da[dp++] = (char) sa[sp++]; while (sp < sl) { int b1 = sa[sp++]; if (b1 >= 0) { // 1 byte, 7 bits: 0xxxxxxx da[dp++] = (char) b1; } else if ((b1 >> 5) == -2 && (b1 & 0x1e) != 0) { // 2 bytes, 11 bits: 110xxxxx 10xxxxxx if (sp < sl) { int b2 = sa[sp++]; if ((b2 & 0xc0) != 0x80) { // isNotContinuation(b2) return -1; } else { da[dp++] = (char) (((b1 << 6) ^ b2)^ (((byte) 0xC0 << 6) ^ ((byte) 0x80 << 0))); } continue; } return -1; } else if ((b1 >> 4) == -2) { // 3 bytes, 16 bits: 1110xxxx 10xxxxxx 10xxxxxx if (sp + 1 < sl) { int b2 = sa[sp++]; int b3 = sa[sp++]; if ((b1 == (byte) 0xe0 && (b2 & 0xe0) == 0x80) // || (b2 & 0xc0) != 0x80 // || (b3 & 0xc0) != 0x80) { // isMalformed3(b1, b2, b3) return -1; } else { char c = (char)((b1 << 12) ^ (b2 << 6) ^ (b3 ^ (((byte) 0xE0 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80 << 0)))); boolean isSurrogate = c >= '\uD800' && c < ('\uDFFF' + 1); if (isSurrogate) { return -1; } else { da[dp++] = c; } } continue; } return -1; } else if ((b1 >> 3) == -2) { // 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx if (sp + 2 < sl) { int b2 = sa[sp++]; int b3 = sa[sp++]; int b4 = sa[sp++]; int uc = ((b1 << 18) ^ (b2 << 12) ^ (b3 << 6) ^ (b4 ^ (((byte) 0xF0 << 18) ^ ((byte) 0x80 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80 << 0)))); if (((b2 & 0xc0) != 0x80 || (b3 & 0xc0) != 0x80 || (b4 & 0xc0) != 0x80) // isMalformed4 || // shortest form check !(uc >= 0x010000 && uc < 0X10FFFF + 1) // !Character.isSupplementaryCodePoint(uc) ) { return -1; } else { da[dp++] = (char) ((uc >>> 10) + ('\uD800' - (0x010000 >>> 10))); // Character.highSurrogate(uc); da[dp++] = (char) ((uc & 0x3ff) + '\uDC00'); // Character.lowSurrogate(uc); } continue; } return -1; } else { return -1; } } return dp; } /** * @deprecated */ public static String readAll(Reader reader) { StringBuilder buf = new StringBuilder(); try { char[] chars = new char[2048]; for (;;) { int len = reader.read(chars, 0, chars.length); if (len < 0) { break; } buf.append(chars, 0, len); } } catch(Exception ex) { throw new JSONException("read string from reader error", ex); } return buf.toString(); } public static boolean isValidJsonpQueryParam(String value){ if (value == null || value.length() == 0) { return false; } for (int i = 0, len = value.length(); i < len; ++i) { char ch = value.charAt(i); if(ch != '.' && !IOUtils.isIdent(ch)){ return false; } } return true; } }
IOUtils
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/parallel/ParallelPeek.java
{ "start": 1150, "end": 3269 }
class ____<T> extends ParallelFlowable<T> { final ParallelFlowable<T> source; final Consumer<? super T> onNext; final Consumer<? super T> onAfterNext; final Consumer<? super Throwable> onError; final Action onComplete; final Action onAfterTerminated; final Consumer<? super Subscription> onSubscribe; final LongConsumer onRequest; final Action onCancel; public ParallelPeek(ParallelFlowable<T> source, Consumer<? super T> onNext, Consumer<? super T> onAfterNext, Consumer<? super Throwable> onError, Action onComplete, Action onAfterTerminated, Consumer<? super Subscription> onSubscribe, LongConsumer onRequest, Action onCancel ) { this.source = source; this.onNext = Objects.requireNonNull(onNext, "onNext is null"); this.onAfterNext = Objects.requireNonNull(onAfterNext, "onAfterNext is null"); this.onError = Objects.requireNonNull(onError, "onError is null"); this.onComplete = Objects.requireNonNull(onComplete, "onComplete is null"); this.onAfterTerminated = Objects.requireNonNull(onAfterTerminated, "onAfterTerminated is null"); this.onSubscribe = Objects.requireNonNull(onSubscribe, "onSubscribe is null"); this.onRequest = Objects.requireNonNull(onRequest, "onRequest is null"); this.onCancel = Objects.requireNonNull(onCancel, "onCancel is null"); } @Override public void subscribe(Subscriber<? super T>[] subscribers) { subscribers = RxJavaPlugins.onSubscribe(this, subscribers); if (!validate(subscribers)) { return; } int n = subscribers.length; @SuppressWarnings("unchecked") Subscriber<? super T>[] parents = new Subscriber[n]; for (int i = 0; i < n; i++) { parents[i] = new ParallelPeekSubscriber<>(subscribers[i], this); } source.subscribe(parents); } @Override public int parallelism() { return source.parallelism(); } static final
ParallelPeek
java
spring-projects__spring-boot
loader/spring-boot-loader/src/test/java/org/springframework/boot/loader/net/protocol/jar/OptimizationsTests.java
{ "start": 891, "end": 2207 }
class ____ { @AfterEach void reset() { Optimizations.disable(); } @Test void defaultIsNotEnabled() { assertThat(Optimizations.isEnabled()).isFalse(); assertThat(Optimizations.isEnabled(true)).isFalse(); assertThat(Optimizations.isEnabled(false)).isFalse(); } @Test void enableWithReadContentsEnables() { Optimizations.enable(true); assertThat(Optimizations.isEnabled()).isTrue(); assertThat(Optimizations.isEnabled(true)).isTrue(); assertThat(Optimizations.isEnabled(false)).isFalse(); } @Test void enableWithoutReadContentsEnables() { Optimizations.enable(false); assertThat(Optimizations.isEnabled()).isTrue(); assertThat(Optimizations.isEnabled(true)).isFalse(); assertThat(Optimizations.isEnabled(false)).isTrue(); } @Test void enableIsByThread() throws InterruptedException { Optimizations.enable(true); boolean[] enabled = new boolean[1]; Thread thread = new Thread(() -> enabled[0] = Optimizations.isEnabled()); thread.start(); thread.join(); assertThat(enabled[0]).isFalse(); } @Test void disableDisables() { Optimizations.enable(true); Optimizations.disable(); assertThat(Optimizations.isEnabled()).isFalse(); assertThat(Optimizations.isEnabled(true)).isFalse(); assertThat(Optimizations.isEnabled(false)).isFalse(); } }
OptimizationsTests
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/additionalsupportedoptions/CustomAdditionalSupportedOptionsProvider.java
{ "start": 356, "end": 636 }
class ____ implements AdditionalSupportedOptionsProvider { @Override public Set<String> getAdditionalSupportedOptions() { return Collections.singleton( "myorg.custom.defaultNullEnumConstant" ); } } // end::documentation[]
CustomAdditionalSupportedOptionsProvider
java
google__dagger
dagger-android-support/main/java/dagger/android/support/DaggerApplication.java
{ "start": 1028, "end": 1198 }
class ____ extends dagger.android.DaggerApplication { @Override protected abstract AndroidInjector<? extends DaggerApplication> applicationInjector(); }
DaggerApplication
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/fielddata/fieldcomparator/HalfFloatComparator.java
{ "start": 2515, "end": 3921 }
class ____ extends NumericLeafComparator { public HalfFloatLeafComparator(LeafReaderContext context) throws IOException { super(context); } private float getValueForDoc(int doc) throws IOException { if (docValues.advanceExact(doc)) { return Float.intBitsToFloat((int) docValues.longValue()); } else { return missingValue; } } @Override public void setBottom(int slot) throws IOException { bottom = values[slot]; super.setBottom(slot); } @Override public int compareBottom(int doc) throws IOException { return Float.compare(bottom, getValueForDoc(doc)); } @Override public int compareTop(int doc) throws IOException { return Float.compare(topValue, getValueForDoc(doc)); } @Override public void copy(int slot, int doc) throws IOException { values[slot] = getValueForDoc(doc); super.copy(slot, doc); } @Override protected long bottomAsComparableLong() { return HalfFloatPoint.halfFloatToSortableShort(bottom); } @Override protected long topAsComparableLong() { return HalfFloatPoint.halfFloatToSortableShort(topValue); } } }
HalfFloatLeafComparator
java
apache__flink
flink-core/src/main/java/org/apache/flink/api/common/operators/DualInputSemanticProperties.java
{ "start": 1109, "end": 6038 }
class ____ implements SemanticProperties { private static final long serialVersionUID = 1L; /** * Mapping from fields in the source record(s) in the first input to fields in the destination * record(s). */ private Map<Integer, FieldSet> fieldMapping1; /** * Mapping from fields in the source record(s) in the second input to fields in the destination * record(s). */ private Map<Integer, FieldSet> fieldMapping2; /** Set of fields that are read in the source record(s) from the first input. */ private FieldSet readFields1; /** Set of fields that are read in the source record(s) from the second input. */ private FieldSet readFields2; public DualInputSemanticProperties() { this.fieldMapping1 = new HashMap<Integer, FieldSet>(); this.fieldMapping2 = new HashMap<Integer, FieldSet>(); this.readFields1 = null; this.readFields2 = null; } @Override public FieldSet getForwardingTargetFields(int input, int sourceField) { if (input != 0 && input != 1) { throw new IndexOutOfBoundsException(); } else if (input == 0) { return fieldMapping1.containsKey(sourceField) ? fieldMapping1.get(sourceField) : FieldSet.EMPTY_SET; } else { return fieldMapping2.containsKey(sourceField) ? fieldMapping2.get(sourceField) : FieldSet.EMPTY_SET; } } @Override public int getForwardingSourceField(int input, int targetField) { Map<Integer, FieldSet> fieldMapping; if (input != 0 && input != 1) { throw new IndexOutOfBoundsException(); } else if (input == 0) { fieldMapping = fieldMapping1; } else { fieldMapping = fieldMapping2; } for (Map.Entry<Integer, FieldSet> e : fieldMapping.entrySet()) { if (e.getValue().contains(targetField)) { return e.getKey(); } } return -1; } @Override public FieldSet getReadFields(int input) { if (input != 0 && input != 1) { throw new IndexOutOfBoundsException(); } if (input == 0) { return readFields1; } else { return readFields2; } } /** * Adds, to the existing information, a field that is forwarded directly from the source * record(s) in the first input to the destination record(s). * * @param input the input of the source field * @param sourceField the position in the source record * @param targetField the position in the destination record */ public void addForwardedField(int input, int sourceField, int targetField) { Map<Integer, FieldSet> fieldMapping; if (input != 0 && input != 1) { throw new IndexOutOfBoundsException(); } else if (input == 0) { fieldMapping = this.fieldMapping1; } else { fieldMapping = this.fieldMapping2; } if (isTargetFieldPresent(targetField, fieldMapping)) { throw new InvalidSemanticAnnotationException( "Target field " + targetField + " was added twice to input " + input); } FieldSet targetFields = fieldMapping.get(sourceField); if (targetFields != null) { fieldMapping.put(sourceField, targetFields.addField(targetField)); } else { fieldMapping.put(sourceField, new FieldSet(targetField)); } } private boolean isTargetFieldPresent(int targetField, Map<Integer, FieldSet> fieldMapping) { for (FieldSet targetFields : fieldMapping.values()) { if (targetFields.contains(targetField)) { return true; } } return false; } /** * Adds, to the existing information, field(s) that are read in the source record(s) from the * first input. * * @param input the input of the read fields * @param readFields the position(s) in the source record(s) */ public void addReadFields(int input, FieldSet readFields) { if (input != 0 && input != 1) { throw new IndexOutOfBoundsException(); } else if (input == 0) { this.readFields1 = (this.readFields1 == null) ? readFields.clone() : this.readFields1.addFields(readFields); } else { this.readFields2 = (this.readFields2 == null) ? readFields.clone() : this.readFields2.addFields(readFields); } } @Override public String toString() { return "DISP(" + this.fieldMapping1 + "; " + this.fieldMapping2 + ")"; } }
DualInputSemanticProperties
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/search/geo/SpatialQueryBuilders.java
{ "start": 1028, "end": 1275 }
interface ____ tests to abstract away which exact QueryBuilder is used in the tests. * We have generalized the Geo-specific tests in test.framework to be re-used by Cartesian tests * in the xpack-spatial module. This requires implmenting this
allows
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/support/BeanRegistryAdapterTests.java
{ "start": 10055, "end": 10261 }
class ____ implements BeanRegistrar { @Override public void register(BeanRegistry registry, Environment env) { registry.register(new DefaultBeanRegistrar()); } } private static
ChainedBeanRegistrar
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/fielddata/plain/BinaryIndexFieldData.java
{ "start": 1332, "end": 1429 }
class ____ implements IndexFieldData<BinaryDVLeafFieldData> { public static
BinaryIndexFieldData
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/trait/MiniBatchInterval.java
{ "start": 1214, "end": 3175 }
class ____ { public static final String FIELD_NAME_INTERVAL = "interval"; public static final String FIELD_NAME_MODE = "mode"; /** interval of mini-batch. */ @JsonProperty(FIELD_NAME_INTERVAL) private final long interval; /** The type of mini-batch: rowtime/proctime. */ @JsonProperty(FIELD_NAME_MODE) private final MiniBatchMode mode; /** default none value. */ public static final MiniBatchInterval NONE = new MiniBatchInterval(0L, MiniBatchMode.None); /** * specific for cases when there exists nodes require watermark but mini-batch interval of * watermark is disabled by force, e.g. existing window aggregate. * * <p>The difference between NONE AND NO_MINIBATCH is when merging with other miniBatchInterval, * NONE case yields other miniBatchInterval, while NO_MINIBATCH case yields NO_MINIBATCH. */ public static final MiniBatchInterval NO_MINIBATCH = new MiniBatchInterval(-1L, MiniBatchMode.None); @JsonCreator public MiniBatchInterval( @JsonProperty(FIELD_NAME_INTERVAL) long interval, @JsonProperty(FIELD_NAME_MODE) MiniBatchMode mode) { this.interval = interval; this.mode = checkNotNull(mode); } public long getInterval() { return interval; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MiniBatchInterval that = (MiniBatchInterval) o; return interval == that.interval && mode == that.mode; } @Override public int hashCode() { return Objects.hash(interval, mode); } public MiniBatchMode getMode() { return mode; } @Override public String toString() { return "MiniBatchInterval{" + "interval=" + interval + ", mode=" + mode + '}'; } }
MiniBatchInterval