Dataset Preview
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed because of a cast error
Error code: DatasetGenerationCastError Exception: DatasetGenerationCastError Message: An error occurred while generating the dataset All the data files must have the same columns, but at some point there are 2 new columns ({'X', 'y'}) and 3 missing columns ({'lang', 'code', 'indentifier'}). This happened while the csv dataset builder was generating data using hf://datasets/anshulsc/REID-2.0/eval_test.csv (at revision 53a3169a6edbe2aef2d2261ae85f1d9734ef4c31) Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations) Traceback: Traceback (most recent call last): File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1871, in _prepare_split_single writer.write_table(table) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 623, in write_table pa_table = table_cast(pa_table, self._schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2293, in table_cast return cast_table_to_schema(table, schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2241, in cast_table_to_schema raise CastError( datasets.table.CastError: Couldn't cast X: string y: string -- schema metadata -- pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 465 to {'code': Value(dtype='string', id=None), 'indentifier': Value(dtype='string', id=None), 'lang': Value(dtype='string', id=None)} because column names don't match During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1438, in compute_config_parquet_and_info_response parquet_operations = convert_to_parquet(builder) File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1050, in convert_to_parquet builder.download_and_prepare( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 925, in download_and_prepare self._download_and_prepare( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1001, in _download_and_prepare self._prepare_split(split_generator, **prepare_split_kwargs) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1742, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1873, in _prepare_split_single raise DatasetGenerationCastError.from_cast_error( datasets.exceptions.DatasetGenerationCastError: An error occurred while generating the dataset All the data files must have the same columns, but at some point there are 2 new columns ({'X', 'y'}) and 3 missing columns ({'lang', 'code', 'indentifier'}). This happened while the csv dataset builder was generating data using hf://datasets/anshulsc/REID-2.0/eval_test.csv (at revision 53a3169a6edbe2aef2d2261ae85f1d9734ef4c31) Please either edit the data files to have matching columns, or separate them into different configurations (see docs at https://hf.co/docs/hub/datasets-manual-configuration#multiple-configurations)
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
code
string | indentifier
string | lang
string |
---|---|---|
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.nio.channels.DatagramChannel;
import static org.testng.Assert.assertThrows;
public class SendPortZero {
private InetAddress loopbackAddr, wildcardAddr;
private DatagramSocket datagramSocket, datagramSocketAdaptor;
private DatagramPacket loopbackZeroPkt, wildcardZeroPkt, wildcardValidPkt;
private static final Class<SocketException> SE = SocketException.class;
@BeforeTest
public void setUp() throws IOException {
datagramSocket = new DatagramSocket();
datagramSocketAdaptor = DatagramChannel.open().socket();
byte[] buf = "test".getBytes();
loopbackAddr = InetAddress.getLoopbackAddress();
wildcardAddr = new InetSocketAddress(0).getAddress();
loopbackZeroPkt = new DatagramPacket(buf, 0, buf. [MASK] );
loopbackZeroPkt.setAddress(loopbackAddr);
loopbackZeroPkt.setPort(0);
wildcardZeroPkt = new DatagramPacket(buf, 0, buf. [MASK] );
wildcardZeroPkt.setAddress(wildcardAddr);
wildcardZeroPkt.setPort(0);
wildcardValidPkt = new DatagramPacket(buf, 0, buf. [MASK] );
wildcardValidPkt.setAddress(wildcardAddr);
wildcardValidPkt.setPort(datagramSocket.getLocalPort());
}
@DataProvider(name = "data")
public Object[][] variants() {
return new Object[][]{
{ datagramSocket, loopbackZeroPkt },
{ datagramSocket, wildcardZeroPkt },
{ datagramSocketAdaptor, loopbackZeroPkt },
{ datagramSocketAdaptor, wildcardZeroPkt },
};
}
@Test(dataProvider = "data")
public void testSend(DatagramSocket ds, DatagramPacket pkt) {
assertThrows(SE, () -> ds.send(pkt));
}
@AfterTest
public void tearDown() {
datagramSocket.close();
datagramSocketAdaptor.close();
}
}
| length | java |
package org.apache.kafka.server.share.context;
import org.apache.kafka.common.TopicIdPartition;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.Uuid;
import org.apache.kafka.common.message.ShareFetchResponseData;
import org.apache.kafka.common.message.ShareFetchResponseData.PartitionData;
import org.apache.kafka.common.protocol.Errors;
import org.apache.kafka.common.requests.ShareFetchRequest;
import org.apache.kafka.common.requests.ShareFetchRequest.SharePartitionData;
import org.apache.kafka.common.requests.ShareFetchResponse;
import org.apache.kafka.common.requests.ShareRequestMetadata;
import org.apache.kafka.server.share.CachedSharePartition;
import org.apache.kafka.server.share.ErroneousAndValidPartitionData;
import org.apache.kafka.server.share.session.ShareSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
public class ShareSessionContext extends ShareFetchContext {
private static final Logger log = LoggerFactory.getLogger(ShareSessionContext.class);
private final ShareRequestMetadata reqMetadata;
private final boolean [MASK] ;
private Map<TopicIdPartition, SharePartitionData> shareFetchData;
private ShareSession session;
public ShareSessionContext(ShareRequestMetadata reqMetadata,
Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData) {
this.reqMetadata = reqMetadata;
this.shareFetchData = shareFetchData;
this. [MASK] = false;
}
public ShareSessionContext(ShareRequestMetadata reqMetadata, ShareSession session) {
this.reqMetadata = reqMetadata;
this.session = session;
this. [MASK] = true;
}
public Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> shareFetchData() {
return shareFetchData;
}
public boolean [MASK] () {
return [MASK] ;
}
public ShareSession session() {
return session;
}
@Override
boolean isTraceEnabled() {
return log.isTraceEnabled();
}
@Override
public ShareFetchResponse throttleResponse(int throttleTimeMs) {
if (! [MASK] ) {
return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs,
Collections.emptyIterator(), Collections.emptyList()));
}
int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch());
int sessionEpoch;
synchronized (session) {
sessionEpoch = session.epoch;
}
if (sessionEpoch != expectedEpoch) {
log.debug("Subsequent share session {} expected epoch {}, but got {}. " +
"Possible duplicate request.", session.key(), expectedEpoch, sessionEpoch);
return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH,
throttleTimeMs, Collections.emptyIterator(), Collections.emptyList()));
}
return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.NONE, throttleTimeMs,
Collections.emptyIterator(), Collections.emptyList()));
}
private class PartitionIterator implements Iterator<Entry<TopicIdPartition, PartitionData>> {
private final Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator;
private final boolean updateShareContextAndRemoveUnselected;
private Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> nextElement;
public PartitionIterator(Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> iterator, boolean updateShareContextAndRemoveUnselected) {
this.iterator = iterator;
this.updateShareContextAndRemoveUnselected = updateShareContextAndRemoveUnselected;
}
@Override
public boolean hasNext() {
while ((nextElement == null) && iterator.hasNext()) {
Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = iterator.next();
TopicIdPartition topicPart = element.getKey();
ShareFetchResponseData.PartitionData respData = element.getValue();
synchronized (session) {
CachedSharePartition cachedPart = session.partitionMap().find(new CachedSharePartition(topicPart));
boolean mustRespond = cachedPart.maybeUpdateResponseData(respData, updateShareContextAndRemoveUnselected);
if (mustRespond) {
nextElement = element;
if (updateShareContextAndRemoveUnselected && ShareFetchResponse.recordsSize(respData) > 0) {
session.partitionMap().remove(cachedPart);
session.partitionMap().mustAdd(cachedPart);
}
} else {
if (updateShareContextAndRemoveUnselected) {
iterator.remove();
}
}
}
}
return nextElement != null;
}
@Override
public Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> next() {
if (!hasNext()) throw new NoSuchElementException();
Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData> element = nextElement;
nextElement = null;
return element;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
@Override
public int responseSize(LinkedHashMap<TopicIdPartition, PartitionData> updates, short version) {
if (! [MASK] )
return ShareFetchResponse.sizeOf(version, updates.entrySet().iterator());
synchronized (session) {
int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch());
if (session.epoch != expectedEpoch) {
return ShareFetchResponse.sizeOf(version, Collections.emptyIterator());
}
return ShareFetchResponse.sizeOf(version, new PartitionIterator(updates.entrySet().iterator(), false));
}
}
@Override
public ShareFetchResponse updateAndGenerateResponseData(String groupId, Uuid memberId,
LinkedHashMap<TopicIdPartition, ShareFetchResponseData.PartitionData> updates) {
if (! [MASK] ) {
return new ShareFetchResponse(ShareFetchResponse.toMessage(
Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList()));
} else {
int expectedEpoch = ShareRequestMetadata.nextEpoch(reqMetadata.epoch());
int sessionEpoch;
synchronized (session) {
sessionEpoch = session.epoch;
}
if (sessionEpoch != expectedEpoch) {
log.debug("Subsequent share session {} expected epoch {}, but got {}. Possible duplicate request.",
session.key(), expectedEpoch, sessionEpoch);
return new ShareFetchResponse(ShareFetchResponse.toMessage(Errors.INVALID_SHARE_SESSION_EPOCH,
0, Collections.emptyIterator(), Collections.emptyList()));
}
Iterator<Map.Entry<TopicIdPartition, ShareFetchResponseData.PartitionData>> partitionIterator = new PartitionIterator(
updates.entrySet().iterator(), true);
while (partitionIterator.hasNext()) {
partitionIterator.next();
}
log.debug("Subsequent share session context with session key {} returning {}", session.key(),
partitionsToLogString(updates.keySet()));
return new ShareFetchResponse(ShareFetchResponse.toMessage(
Errors.NONE, 0, updates.entrySet().iterator(), Collections.emptyList()));
}
}
@Override
public ErroneousAndValidPartitionData getErroneousAndValidTopicIdPartitions() {
if (! [MASK] ) {
return new ErroneousAndValidPartitionData(shareFetchData);
}
Map<TopicIdPartition, PartitionData> erroneous = new HashMap<>();
Map<TopicIdPartition, ShareFetchRequest.SharePartitionData> valid = new HashMap<>();
synchronized (session) {
session.partitionMap().forEach(cachedSharePartition -> {
TopicIdPartition topicIdPartition = new TopicIdPartition(cachedSharePartition.topicId(), new
TopicPartition(cachedSharePartition.topic(), cachedSharePartition.partition()));
ShareFetchRequest.SharePartitionData reqData = cachedSharePartition.reqData();
if (topicIdPartition.topic() == null) {
erroneous.put(topicIdPartition, ShareFetchResponse.partitionResponse(topicIdPartition, Errors.UNKNOWN_TOPIC_ID));
} else {
valid.put(topicIdPartition, reqData);
}
});
return new ErroneousAndValidPartitionData(erroneous, valid);
}
}
}
| isSubsequent | java |
package org.apache.flink.runtime.scheduler;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
import org.apache.flink.runtime.clusterframework.types.ResourceProfile;
import org.apache.flink.runtime.clusterframework.types.SlotProfile;
import org.apache.flink.runtime.clusterframework.types.SlotProfileTestingUtils;
import org.apache.flink.runtime.executiongraph.ExecutionAttemptID;
import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup;
import org.apache.flink.runtime.jobmaster.LogicalSlot;
import org.apache.flink.runtime.jobmaster.SlotRequestId;
import org.apache.flink.runtime.jobmaster.TestingPayload;
import org.apache.flink.runtime.jobmaster.slotpool.DummyPayload;
import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequest;
import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulk;
import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequestBulkChecker;
import org.apache.flink.runtime.scheduler.SharedSlotProfileRetriever.SharedSlotProfileRetrieverFactory;
import org.apache.flink.runtime.scheduler.strategy.ExecutionVertexID;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.function.BiConsumerWithException;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createExecutionAttemptId;
import static org.apache.flink.runtime.executiongraph.ExecutionGraphTestUtils.createRandomExecutionVertexId;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class SlotSharingExecutionSlotAllocatorTest {
private static final Duration ALLOCATION_TIMEOUT = Duration.ofMillis(100L);
private static final ResourceProfile RESOURCE_PROFILE = ResourceProfile.fromResources(3, 5);
private static final ExecutionVertexID EV1 = createRandomExecutionVertexId();
private static final ExecutionVertexID EV2 = createRandomExecutionVertexId();
private static final ExecutionVertexID EV3 = createRandomExecutionVertexId();
private static final ExecutionVertexID EV4 = createRandomExecutionVertexId();
@Test
void testSlotProfileRequestAskedBulkAndGroup() {
AllocationContext context = AllocationContext. [MASK] ().addGroup(EV1, EV2).build();
ExecutionSlotSharingGroup executionSlotSharingGroup =
context.getSlotSharingStrategy().getExecutionSlotSharingGroup(EV1);
context.allocateSlotsFor(EV1, EV2);
List<Set<ExecutionVertexID>> askedBulks =
context.getSlotProfileRetrieverFactory().getAskedBulks();
assertThat(askedBulks).hasSize(1);
assertThat(askedBulks.get(0)).containsExactlyInAnyOrder(EV1, EV2);
assertThat(context.getSlotProfileRetrieverFactory().getAskedGroups())
.containsExactly(executionSlotSharingGroup);
}
@Test
void testSlotRequestProfile() {
AllocationContext context = AllocationContext. [MASK] ().addGroup(EV1, EV2, EV3).build();
ResourceProfile physicalsSlotResourceProfile = RESOURCE_PROFILE.multiply(3);
context.allocateSlotsFor(EV1, EV2);
Optional<PhysicalSlotRequest> slotRequest =
context.getSlotProvider().getRequests().values().stream().findFirst();
assertThat(slotRequest).isPresent();
assertThat(slotRequest.get().getSlotProfile().getPhysicalSlotResourceProfile())
.isEqualTo(physicalsSlotResourceProfile);
}
@Test
void testAllocatePhysicalSlotForNewSharedSlot() {
AllocationContext context =
AllocationContext. [MASK] ().addGroup(EV1, EV2).addGroup(EV3, EV4).build();
Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments =
context.allocateSlotsFor(EV1, EV2, EV3, EV4);
Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values());
assertThat(assignIds).containsExactlyInAnyOrder(EV1, EV2, EV3, EV4);
assertThat(context.getSlotProvider().getRequests()).hasSize(2);
}
@Test
void testAllocateLogicalSlotFromAvailableSharedSlot() {
AllocationContext context = AllocationContext. [MASK] ().addGroup(EV1, EV2).build();
context.allocateSlotsFor(EV1);
Map<ExecutionAttemptID, ExecutionSlotAssignment> executionSlotAssignments =
context.allocateSlotsFor(EV2);
Collection<ExecutionVertexID> assignIds = getAssignIds(executionSlotAssignments.values());
assertThat(assignIds).containsExactly(EV2);
assertThat(context.getSlotProvider().getRequests()).hasSize(1);
}
@Test
void testDuplicateAllocationDoesNotRecreateLogicalSlotFuture()
throws ExecutionException, InterruptedException {
AllocationContext context = AllocationContext. [MASK] ().addGroup(EV1).build();
ExecutionSlotAssignment assignment1 =
getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1);
ExecutionSlotAssignment assignment2 =
getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1);
assertThat(assignment1.getLogicalSlotFuture().get())
.isSameAs(assignment2.getLogicalSlotFuture().get());
}
@Test
void testFailedPhysicalSlotRequestFailsLogicalSlotFuturesAndRemovesSharedSlot() {
AllocationContext context =
AllocationContext. [MASK] ()
.addGroup(EV1)
.withPhysicalSlotProvider(
TestingPhysicalSlotProvider
.createWithoutImmediatePhysicalSlotCreation())
.build();
CompletableFuture<LogicalSlot> logicalSlotFuture =
getAssignmentByExecutionVertexId(context.allocateSlotsFor(EV1), EV1)
.getLogicalSlotFuture();
SlotRequestId slotRequestId =
context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId();
assertThat(logicalSlotFuture).isNotDone();
context.getSlotProvider()
.getResponses()
.get(slotRequestId)
.completeExceptionally(new Throwable());
assertThat(logicalSlotFuture).isCompletedExceptionally();
context.allocateSlotsFor(EV1);
assertThat(context.getSlotProvider().getRequests()).hasSize(2);
}
@Test
void testSlotWillBeOccupiedIndefinitelyFalse() throws ExecutionException, InterruptedException {
testSlotWillBeOccupiedIndefinitely(false);
}
@Test
void testSlotWillBeOccupiedIndefinitelyTrue() throws ExecutionException, InterruptedException {
testSlotWillBeOccupiedIndefinitely(true);
}
private static void testSlotWillBeOccupiedIndefinitely(boolean slotWillBeOccupiedIndefinitely)
throws ExecutionException, InterruptedException {
AllocationContext context =
AllocationContext. [MASK] ()
.addGroup(EV1)
.setSlotWillBeOccupiedIndefinitely(slotWillBeOccupiedIndefinitely)
.build();
context.allocateSlotsFor(EV1);
PhysicalSlotRequest slotRequest = context.getSlotProvider().getFirstRequestOrFail();
assertThat(slotRequest.willSlotBeOccupiedIndefinitely())
.isEqualTo(slotWillBeOccupiedIndefinitely);
TestingPhysicalSlot physicalSlot =
context.getSlotProvider().getResponses().get(slotRequest.getSlotRequestId()).get();
assertThat(physicalSlot.getPayload()).isNotNull();
assertThat(physicalSlot.getPayload().willOccupySlotIndefinitely())
.isEqualTo(slotWillBeOccupiedIndefinitely);
}
@Test
void testReturningLogicalSlotsRemovesSharedSlot() throws Exception {
testLogicalSlotRequestCancellationOrRelease(
false,
true,
(context, assignment) -> assignment.getLogicalSlotFuture().get().releaseSlot(null));
}
@Test
void testLogicalSlotCancelsPhysicalSlotRequestAndRemovesSharedSlot() throws Exception {
testLogicalSlotRequestCancellationOrRelease(
true,
true,
(context, assignment) -> {
context.getAllocator().cancel(assignment.getExecutionAttemptId());
assertThatThrownBy(
() -> {
context.getAllocator()
.cancel(assignment.getExecutionAttemptId());
assignment.getLogicalSlotFuture().get();
})
.as("The logical future must finish with the cancellation exception.")
.hasCauseInstanceOf(CancellationException.class);
});
}
@Test
void
testCompletedLogicalSlotCancelationDoesNotCancelPhysicalSlotRequestAndDoesNotRemoveSharedSlot()
throws Exception {
testLogicalSlotRequestCancellationOrRelease(
false,
false,
(context, assignment) -> {
context.getAllocator().cancel(assignment.getExecutionAttemptId());
assignment.getLogicalSlotFuture().get();
});
}
private static void testLogicalSlotRequestCancellationOrRelease(
boolean completePhysicalSlotFutureManually,
boolean cancelsPhysicalSlotRequestAndRemovesSharedSlot,
BiConsumerWithException<AllocationContext, ExecutionSlotAssignment, Exception>
cancelOrReleaseAction)
throws Exception {
AllocationContext.Builder allocationContextBuilder =
AllocationContext. [MASK] ().addGroup(EV1, EV2, EV3);
if (completePhysicalSlotFutureManually) {
allocationContextBuilder.withPhysicalSlotProvider(
TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation());
}
AllocationContext context = allocationContextBuilder.build();
Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments =
context.allocateSlotsFor(EV1, EV2);
assertThat(context.getSlotProvider().getRequests()).hasSize(1);
cancelOrReleaseAction.accept(context, getAssignmentByExecutionVertexId(assignments, EV1));
Map<ExecutionAttemptID, ExecutionSlotAssignment> assignmentsAfterOneCancellation =
context.allocateSlotsFor(EV1, EV2);
assertThat(context.getSlotProvider().getRequests()).hasSize(1);
for (ExecutionSlotAssignment assignment : assignmentsAfterOneCancellation.values()) {
cancelOrReleaseAction.accept(context, assignment);
}
SlotRequestId slotRequestId =
context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId();
assertThat(context.getSlotProvider().getCancellations().containsKey(slotRequestId))
.isEqualTo(cancelsPhysicalSlotRequestAndRemovesSharedSlot);
context.allocateSlotsFor(EV3);
int expectedNumberOfRequests = cancelsPhysicalSlotRequestAndRemovesSharedSlot ? 2 : 1;
assertThat(context.getSlotProvider().getRequests()).hasSize(expectedNumberOfRequests);
}
@Test
void testPhysicalSlotReleaseLogicalSlots() throws ExecutionException, InterruptedException {
AllocationContext context = AllocationContext. [MASK] ().addGroup(EV1, EV2).build();
Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments =
context.allocateSlotsFor(EV1, EV2);
List<TestingPayload> payloads =
assignments.values().stream()
.map(
assignment -> {
TestingPayload payload = new TestingPayload();
assignment
.getLogicalSlotFuture()
.thenAccept(
logicalSlot ->
logicalSlot.tryAssignPayload(payload));
return payload;
})
.collect(Collectors.toList());
SlotRequestId slotRequestId =
context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId();
TestingPhysicalSlot physicalSlot = context.getSlotProvider().getFirstResponseOrFail().get();
assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone()))
.isFalse();
assertThat(physicalSlot.getPayload()).isNotNull();
physicalSlot.getPayload().release(new Throwable());
assertThat(payloads.stream().allMatch(payload -> payload.getTerminalStateFuture().isDone()))
.isTrue();
assertThat(context.getSlotProvider().getCancellations()).containsKey(slotRequestId);
context.allocateSlotsFor(EV1, EV2);
assertThat(context.getSlotProvider().getRequests()).hasSize(2);
}
@Test
void testSchedulePendingRequestBulkTimeoutCheck() {
TestingPhysicalSlotRequestBulkChecker bulkChecker =
new TestingPhysicalSlotRequestBulkChecker();
AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker);
context.allocateSlotsFor(EV1, EV3);
PhysicalSlotRequestBulk bulk = bulkChecker.getBulk();
assertThat(bulk.getPendingRequests()).hasSize(2);
assertThat(bulk.getPendingRequests())
.containsExactlyInAnyOrder(RESOURCE_PROFILE.multiply(2), RESOURCE_PROFILE);
assertThat(bulk.getAllocationIdsOfFulfilledRequests()).isEmpty();
assertThat(bulkChecker.getTimeout()).isEqualTo(ALLOCATION_TIMEOUT);
}
@Test
void testRequestFulfilledInBulk() {
TestingPhysicalSlotRequestBulkChecker bulkChecker =
new TestingPhysicalSlotRequestBulkChecker();
AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker);
context.allocateSlotsFor(EV1, EV3);
AllocationID allocationId = new AllocationID();
ResourceProfile pendingSlotResourceProfile =
fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, allocationId);
PhysicalSlotRequestBulk bulk = bulkChecker.getBulk();
assertThat(bulk.getPendingRequests()).hasSize(1);
assertThat(bulk.getPendingRequests()).containsExactly(pendingSlotResourceProfile);
assertThat(bulk.getAllocationIdsOfFulfilledRequests()).hasSize(1);
assertThat(bulk.getAllocationIdsOfFulfilledRequests()).containsExactly(allocationId);
}
@Test
void testRequestBulkCancel() {
TestingPhysicalSlotRequestBulkChecker bulkChecker =
new TestingPhysicalSlotRequestBulkChecker();
AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker);
Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments1 =
context.allocateSlotsFor(EV1, EV3);
fulfilOneOfTwoSlotRequestsAndGetPendingProfile(context, new AllocationID());
PhysicalSlotRequestBulk bulk1 = bulkChecker.getBulk();
Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments2 =
context.allocateSlotsFor(EV2);
bulk1.cancel(new Throwable());
assertThat(assignments1).hasSize(2);
CompletableFuture<LogicalSlot> ev1slot =
getAssignmentByExecutionVertexId(assignments1, EV1).getLogicalSlotFuture();
boolean ev1failed = ev1slot.isCompletedExceptionally();
CompletableFuture<LogicalSlot> ev3slot =
getAssignmentByExecutionVertexId(assignments1, EV3).getLogicalSlotFuture();
boolean ev3failed = ev3slot.isCompletedExceptionally();
LogicalSlot slot = ev1failed ? ev3slot.join() : ev1slot.join();
releaseLogicalSlot(slot);
context.allocateSlotsFor(EV1, EV3);
assertThat(context.getSlotProvider().getRequests()).hasSize(3);
assertThat(ev1failed).isNotEqualTo(ev3failed);
assertThat(assignments2).hasSize(1);
assertThat(getAssignmentByExecutionVertexId(assignments2, EV2).getLogicalSlotFuture())
.isNotCompletedExceptionally();
}
private static void releaseLogicalSlot(LogicalSlot slot) {
slot.tryAssignPayload(new DummyPayload(CompletableFuture.completedFuture(null)));
slot.releaseSlot(new Throwable());
}
@Test
void testBulkClearIfPhysicalSlotRequestFails() {
TestingPhysicalSlotRequestBulkChecker bulkChecker =
new TestingPhysicalSlotRequestBulkChecker();
AllocationContext context = createBulkCheckerContextWithEv12GroupAndEv3Group(bulkChecker);
context.allocateSlotsFor(EV1, EV3);
SlotRequestId slotRequestId =
context.getSlotProvider().getFirstRequestOrFail().getSlotRequestId();
context.getSlotProvider()
.getResultForRequestId(slotRequestId)
.completeExceptionally(new Throwable());
PhysicalSlotRequestBulk bulk = bulkChecker.getBulk();
assertThat(bulk.getPendingRequests()).isEmpty();
}
@Test
void failLogicalSlotsIfPhysicalSlotIsFailed() {
final TestingPhysicalSlotRequestBulkChecker bulkChecker =
new TestingPhysicalSlotRequestBulkChecker();
AllocationContext context =
AllocationContext. [MASK] ()
.addGroup(EV1, EV2)
.withBulkChecker(bulkChecker)
.withPhysicalSlotProvider(
TestingPhysicalSlotProvider.createWithFailingPhysicalSlotCreation(
new FlinkException("test failure")))
.build();
final Map<ExecutionAttemptID, ExecutionSlotAssignment> allocatedSlots =
context.allocateSlotsFor(EV1, EV2);
for (ExecutionSlotAssignment allocatedSlot : allocatedSlots.values()) {
assertThat(allocatedSlot.getLogicalSlotFuture()).isCompletedExceptionally();
}
assertThat(bulkChecker.getBulk().getPendingRequests()).isEmpty();
final Set<SlotRequestId> requests = context.getSlotProvider().getRequests().keySet();
assertThat(context.getSlotProvider().getCancellations().keySet()).isEqualTo(requests);
}
@Test
void testSlotRequestProfileFromExecutionSlotSharingGroup() {
final ResourceProfile resourceProfile1 = ResourceProfile.fromResources(1, 10);
final ResourceProfile resourceProfile2 = ResourceProfile.fromResources(2, 20);
final AllocationContext context =
AllocationContext. [MASK] ()
.addGroupAndResource(resourceProfile1, EV1, EV3)
.addGroupAndResource(resourceProfile2, EV2, EV4)
.build();
context.allocateSlotsFor(EV1, EV2);
assertThat(context.getSlotProvider().getRequests()).hasSize(2);
assertThat(
context.getSlotProvider().getRequests().values().stream()
.map(PhysicalSlotRequest::getSlotProfile)
.map(SlotProfile::getPhysicalSlotResourceProfile)
.collect(Collectors.toList()))
.containsExactlyInAnyOrder(resourceProfile1, resourceProfile2);
}
@Test
void testSlotProviderBatchSlotRequestTimeoutCheckIsDisabled() {
final AllocationContext context = AllocationContext. [MASK] ().build();
assertThat(context.getSlotProvider().isBatchSlotRequestTimeoutCheckEnabled()).isFalse();
}
private static List<ExecutionVertexID> getAssignIds(
Collection<ExecutionSlotAssignment> assignments) {
return assignments.stream()
.map(ExecutionSlotAssignment::getExecutionAttemptId)
.map(ExecutionAttemptID::getExecutionVertexId)
.collect(Collectors.toList());
}
private static AllocationContext createBulkCheckerContextWithEv12GroupAndEv3Group(
PhysicalSlotRequestBulkChecker bulkChecker) {
return AllocationContext. [MASK] ()
.addGroup(EV1, EV2)
.addGroup(EV3)
.withBulkChecker(bulkChecker)
.withPhysicalSlotProvider(
TestingPhysicalSlotProvider.createWithoutImmediatePhysicalSlotCreation())
.build();
}
private static ResourceProfile fulfilOneOfTwoSlotRequestsAndGetPendingProfile(
AllocationContext context, AllocationID allocationId) {
Map<SlotRequestId, PhysicalSlotRequest> requests = context.getSlotProvider().getRequests();
List<SlotRequestId> slotRequestIds = new ArrayList<>(requests.keySet());
assertThat(slotRequestIds).hasSize(2);
SlotRequestId slotRequestId1 = slotRequestIds.get(0);
SlotRequestId slotRequestId2 = slotRequestIds.get(1);
context.getSlotProvider()
.getResultForRequestId(slotRequestId1)
.complete(TestingPhysicalSlot.builder().withAllocationID(allocationId).build());
return requests.get(slotRequestId2).getSlotProfile().getPhysicalSlotResourceProfile();
}
private static ExecutionSlotAssignment getAssignmentByExecutionVertexId(
Map<ExecutionAttemptID, ExecutionSlotAssignment> assignments,
ExecutionVertexID executionVertexId) {
return assignments.entrySet().stream()
.filter(entry -> entry.getKey().getExecutionVertexId().equals(executionVertexId))
.map(Map.Entry::getValue)
.collect(Collectors.toList())
.get(0);
}
private static class AllocationContext {
private final TestingPhysicalSlotProvider slotProvider;
private final TestingSlotSharingStrategy slotSharingStrategy;
private final SlotSharingExecutionSlotAllocator allocator;
private final TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory;
private AllocationContext(
TestingPhysicalSlotProvider slotProvider,
TestingSlotSharingStrategy slotSharingStrategy,
SlotSharingExecutionSlotAllocator allocator,
TestingSharedSlotProfileRetrieverFactory slotProfileRetrieverFactory) {
this.slotProvider = slotProvider;
this.slotSharingStrategy = slotSharingStrategy;
this.allocator = allocator;
this.slotProfileRetrieverFactory = slotProfileRetrieverFactory;
}
private SlotSharingExecutionSlotAllocator getAllocator() {
return allocator;
}
private Map<ExecutionAttemptID, ExecutionSlotAssignment> allocateSlotsFor(
ExecutionVertexID... ids) {
return allocator.allocateSlotsFor(
Arrays.stream(ids)
.map(
executionVertexId ->
createExecutionAttemptId(executionVertexId, 0))
.collect(Collectors.toList()));
}
private TestingSlotSharingStrategy getSlotSharingStrategy() {
return slotSharingStrategy;
}
private TestingPhysicalSlotProvider getSlotProvider() {
return slotProvider;
}
private TestingSharedSlotProfileRetrieverFactory getSlotProfileRetrieverFactory() {
return slotProfileRetrieverFactory;
}
private static Builder [MASK] () {
return new Builder();
}
private static class Builder {
private final Map<ExecutionVertexID[], ResourceProfile> groups = new HashMap<>();
private boolean slotWillBeOccupiedIndefinitely = false;
private PhysicalSlotRequestBulkChecker bulkChecker =
new TestingPhysicalSlotRequestBulkChecker();
private TestingPhysicalSlotProvider physicalSlotProvider =
TestingPhysicalSlotProvider.createWithInfiniteSlotCreation();
private Builder addGroup(ExecutionVertexID... group) {
groups.put(group, ResourceProfile.UNKNOWN);
return this;
}
private Builder addGroupAndResource(
ResourceProfile resourceProfile, ExecutionVertexID... group) {
groups.put(group, resourceProfile);
return this;
}
private Builder setSlotWillBeOccupiedIndefinitely(
boolean slotWillBeOccupiedIndefinitely) {
this.slotWillBeOccupiedIndefinitely = slotWillBeOccupiedIndefinitely;
return this;
}
private Builder withBulkChecker(PhysicalSlotRequestBulkChecker bulkChecker) {
this.bulkChecker = bulkChecker;
return this;
}
private Builder withPhysicalSlotProvider(
TestingPhysicalSlotProvider physicalSlotProvider) {
this.physicalSlotProvider = physicalSlotProvider;
return this;
}
private AllocationContext build() {
TestingSharedSlotProfileRetrieverFactory sharedSlotProfileRetrieverFactory =
new TestingSharedSlotProfileRetrieverFactory();
TestingSlotSharingStrategy slotSharingStrategy =
TestingSlotSharingStrategy.createWithGroupsAndResources(groups);
SlotSharingExecutionSlotAllocator allocator =
new SlotSharingExecutionSlotAllocator(
physicalSlotProvider,
slotWillBeOccupiedIndefinitely,
slotSharingStrategy,
sharedSlotProfileRetrieverFactory,
bulkChecker,
ALLOCATION_TIMEOUT,
executionVertexID -> RESOURCE_PROFILE);
return new AllocationContext(
physicalSlotProvider,
slotSharingStrategy,
allocator,
sharedSlotProfileRetrieverFactory);
}
}
}
private static class TestingSlotSharingStrategy implements SlotSharingStrategy {
private final Map<ExecutionVertexID, ExecutionSlotSharingGroup> executionSlotSharingGroups;
private TestingSlotSharingStrategy(
Map<ExecutionVertexID, ExecutionSlotSharingGroup> executionSlotSharingGroups) {
this.executionSlotSharingGroups = executionSlotSharingGroups;
}
@Override
public ExecutionSlotSharingGroup getExecutionSlotSharingGroup(
ExecutionVertexID executionVertexId) {
return executionSlotSharingGroups.get(executionVertexId);
}
@Override
public Set<ExecutionSlotSharingGroup> getExecutionSlotSharingGroups() {
return new HashSet<>(executionSlotSharingGroups.values());
}
private static TestingSlotSharingStrategy createWithGroupsAndResources(
Map<ExecutionVertexID[], ResourceProfile> groupAndResources) {
Map<ExecutionVertexID, ExecutionSlotSharingGroup> executionSlotSharingGroups =
new HashMap<>();
for (Map.Entry<ExecutionVertexID[], ResourceProfile> groupAndResource :
groupAndResources.entrySet()) {
SlotSharingGroup slotSharingGroup = new SlotSharingGroup();
slotSharingGroup.setResourceProfile(groupAndResource.getValue());
ExecutionSlotSharingGroup executionSlotSharingGroup =
new ExecutionSlotSharingGroup(slotSharingGroup);
for (ExecutionVertexID executionVertexId : groupAndResource.getKey()) {
executionSlotSharingGroup.addVertex(executionVertexId);
executionSlotSharingGroups.put(executionVertexId, executionSlotSharingGroup);
}
}
return new TestingSlotSharingStrategy(executionSlotSharingGroups);
}
}
private static class TestingSharedSlotProfileRetrieverFactory
implements SharedSlotProfileRetrieverFactory {
private final List<Set<ExecutionVertexID>> askedBulks;
private final List<ExecutionSlotSharingGroup> askedGroups;
private TestingSharedSlotProfileRetrieverFactory() {
this.askedBulks = new ArrayList<>();
this.askedGroups = new ArrayList<>();
}
@Override
public SharedSlotProfileRetriever createFromBulk(Set<ExecutionVertexID> bulk) {
askedBulks.add(bulk);
return (group, resourceProfile) -> {
askedGroups.add(group);
return SlotProfileTestingUtils.noLocality(resourceProfile);
};
}
private List<Set<ExecutionVertexID>> getAskedBulks() {
return Collections.unmodifiableList(askedBulks);
}
private List<ExecutionSlotSharingGroup> getAskedGroups() {
return Collections.unmodifiableList(askedGroups);
}
}
}
| newBuilder | java |
package org.apache.kafka.connect.runtime.rest;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.connect.errors. [MASK] ;
import org.apache.kafka.connect.health.ConnectClusterDetails;
import org.apache.kafka.connect.rest.ConnectRestExtension;
import org.apache.kafka.connect.rest.ConnectRestExtensionContext;
import org.apache.kafka.connect.runtime.Herder;
import org.apache.kafka.connect.runtime.health.ConnectClusterDetailsImpl;
import org.apache.kafka.connect.runtime.health.ConnectClusterStateImpl;
import org.apache.kafka.connect.runtime.rest.errors. [MASK] Mapper;
import org.apache.kafka.connect.runtime.rest.util.SSLUtils;
import com.fasterxml.jackson.jakarta.rs.json.JacksonJsonProvider;
import org.eclipse.jetty.ee10.servlet.FilterHolder;
import org.eclipse.jetty.ee10.servlet.ServletContextHandler;
import org.eclipse.jetty.ee10.servlet.ServletHolder;
import org.eclipse.jetty.ee10.servlets.HeaderFilter;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.CustomRequestLog;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.Slf4jRequestLogWriter;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.server.handler.CrossOriginHandler;
import org.eclipse.jetty.server.handler.StatisticsHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.glassfish.hk2.utilities.Binder;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.servlet.ServletContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jakarta.servlet.DispatcherType;
import jakarta.ws.rs.core.UriBuilder;
public abstract class RestServer {
public static final long DEFAULT_REST_REQUEST_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(90);
public static final long DEFAULT_HEALTH_CHECK_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(10);
private static final Logger log = LoggerFactory.getLogger(RestServer.class);
private static final String ADMIN_SERVER_CONNECTOR_NAME = "Admin";
private static final Pattern LISTENER_PATTERN = Pattern.compile("^(.*):
private static final long GRACEFUL_SHUTDOWN_TIMEOUT_MS = 60 * 1000;
private static final String PROTOCOL_HTTP = "http";
private static final String PROTOCOL_HTTPS = "https";
protected final RestServerConfig config;
private final ContextHandlerCollection handlers;
private final Server jettyServer;
private final RequestTimeout requestTimeout;
private List<ConnectRestExtension> connectRestExtensions = Collections.emptyList();
protected RestServer(RestServerConfig config) {
this.config = config;
List<String> listeners = config.listeners();
List<String> adminListeners = config.adminListeners();
jettyServer = new Server();
handlers = new ContextHandlerCollection();
requestTimeout = new RequestTimeout(DEFAULT_REST_REQUEST_TIMEOUT_MS, DEFAULT_HEALTH_CHECK_TIMEOUT_MS);
createConnectors(listeners, adminListeners);
}
public final void createConnectors(List<String> listeners, List<String> adminListeners) {
List<Connector> connectors = new ArrayList<>();
for (String listener : listeners) {
Connector connector = createConnector(listener);
connectors.add(connector);
log.info("Added connector for {}", listener);
}
jettyServer.setConnectors(connectors.toArray(new Connector[0]));
if (adminListeners != null && !adminListeners.isEmpty()) {
for (String adminListener : adminListeners) {
Connector conn = createConnector(adminListener, true);
jettyServer.addConnector(conn);
log.info("Added admin connector for {}", adminListener);
}
}
}
public final Connector createConnector(String listener) {
return createConnector(listener, false);
}
public final Connector createConnector(String listener, boolean isAdmin) {
Matcher listenerMatcher = LISTENER_PATTERN.matcher(listener);
if (!listenerMatcher.matches())
throw new ConfigException("Listener doesn't have the right format (protocol:
String protocol = listenerMatcher.group(1).toLowerCase(Locale.ENGLISH);
if (!PROTOCOL_HTTP.equals(protocol) && !PROTOCOL_HTTPS.equals(protocol))
throw new ConfigException(String.format("Listener protocol must be either \"%s\" or \"%s\".", PROTOCOL_HTTP, PROTOCOL_HTTPS));
String hostname = listenerMatcher.group(2);
int port = Integer.parseInt(listenerMatcher.group(3));
ServerConnector connector;
if (PROTOCOL_HTTPS.equals(protocol)) {
SslContextFactory.Server ssl;
if (isAdmin) {
ssl = SSLUtils.createServerSideSslContextFactory(config, RestServerConfig.ADMIN_LISTENERS_HTTPS_CONFIGS_PREFIX);
} else {
ssl = SSLUtils.createServerSideSslContextFactory(config);
}
connector = new ServerConnector(jettyServer, ssl);
if (!isAdmin) {
connector.setName(String.format("%s_%s%d", PROTOCOL_HTTPS, hostname, port));
}
} else {
connector = new ServerConnector(jettyServer);
if (!isAdmin) {
connector.setName(String.format("%s_%s%d", PROTOCOL_HTTP, hostname, port));
}
}
if (isAdmin) {
connector.setName(ADMIN_SERVER_CONNECTOR_NAME);
}
if (!hostname.isEmpty())
connector.setHost(hostname);
connector.setPort(port);
connector.setIdleTimeout(requestTimeout.timeoutMs());
return connector;
}
public void initializeServer() {
log.info("Initializing REST server");
Slf4jRequestLogWriter slf4jRequestLogWriter = new Slf4jRequestLogWriter();
slf4jRequestLogWriter.setLoggerName(RestServer.class.getCanonicalName());
CustomRequestLog requestLog = new CustomRequestLog(slf4jRequestLogWriter, CustomRequestLog.EXTENDED_NCSA_FORMAT + " %{ms}T");
jettyServer.setRequestLog(requestLog);
StatisticsHandler statsHandler = new StatisticsHandler();
statsHandler.setHandler(handlers);
jettyServer.setHandler(statsHandler);
jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS);
jettyServer.setStopAtShutdown(true);
try {
jettyServer.start();
} catch (Exception e) {
throw new [MASK] ("Unable to initialize REST server", e);
}
log.info("REST server listening at " + jettyServer.getURI() + ", advertising URL " + advertisedUrl());
URI adminUrl = adminUrl();
if (adminUrl != null)
log.info("REST admin endpoints at " + adminUrl);
}
protected final void initializeResources() {
log.info("Initializing REST resources");
ResourceConfig resourceConfig = newResourceConfig();
Collection<Class<?>> regularResources = regularResources();
regularResources.forEach(resourceConfig::register);
configureRegularResources(resourceConfig);
List<String> adminListeners = config.adminListeners();
ResourceConfig adminResourceConfig;
if (adminListeners != null && adminListeners.isEmpty()) {
log.info("Skipping adding admin resources");
adminResourceConfig = resourceConfig;
} else {
if (adminListeners == null) {
log.info("Adding admin resources to main listener");
adminResourceConfig = resourceConfig;
} else {
log.info("Adding admin resources to admin listener");
adminResourceConfig = newResourceConfig();
}
Collection<Class<?>> adminResources = adminResources();
adminResources.forEach(adminResourceConfig::register);
configureAdminResources(adminResourceConfig);
}
ServletContainer servletContainer = new ServletContainer(resourceConfig);
ServletHolder servletHolder = new ServletHolder(servletContainer);
List<Handler> contextHandlers = new ArrayList<>();
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.addServlet(servletHolder, "
protected abstract Collection<Class<?>> regularResources();
protected abstract Collection<Class<?>> adminResources();
protected void configureRegularResources(ResourceConfig resourceConfig) {
}
protected void configureAdminResources(ResourceConfig adminResourceConfig) {
}
public URI serverUrl() {
return jettyServer.getURI();
}
public void stop() {
log.info("Stopping REST server");
try {
if (handlers.isRunning()) {
for (Handler handler : handlers.getHandlers()) {
if (handler != null) {
Utils.closeQuietly(handler::stop, handler.toString());
}
}
}
for (ConnectRestExtension connectRestExtension : connectRestExtensions) {
try {
connectRestExtension.close();
} catch (IOException e) {
log.warn("Error while invoking close on " + connectRestExtension.getClass(), e);
}
}
jettyServer.stop();
jettyServer.join();
} catch (Exception e) {
throw new [MASK] ("Unable to stop REST server", e);
} finally {
try {
jettyServer.destroy();
} catch (Exception e) {
log.error("Unable to destroy REST server", e);
}
}
log.info("REST server stopped");
}
public URI advertisedUrl() {
UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI());
String advertisedSecurityProtocol = determineAdvertisedProtocol();
ServerConnector serverConnector = findConnector(advertisedSecurityProtocol);
builder.scheme(advertisedSecurityProtocol);
String advertisedHostname = config.advertisedHostName();
if (advertisedHostname != null && !advertisedHostname.isEmpty())
builder.host(advertisedHostname);
else if (serverConnector != null && serverConnector.getHost() != null && !serverConnector.getHost().isEmpty())
builder.host(serverConnector.getHost());
Integer advertisedPort = config.advertisedPort();
if (advertisedPort != null)
builder.port(advertisedPort);
else if (serverConnector != null && serverConnector.getPort() > 0)
builder.port(serverConnector.getPort());
else if (serverConnector != null && serverConnector.getLocalPort() > 0)
builder.port(serverConnector.getLocalPort());
log.info("Advertised URI: {}", builder.build());
return builder.build();
}
public URI adminUrl() {
ServerConnector adminConnector = null;
for (Connector connector : jettyServer.getConnectors()) {
if (ADMIN_SERVER_CONNECTOR_NAME.equals(connector.getName()))
adminConnector = (ServerConnector) connector;
}
if (adminConnector == null) {
List<String> adminListeners = config.adminListeners();
if (adminListeners == null) {
return advertisedUrl();
} else if (adminListeners.isEmpty()) {
return null;
} else {
log.error("No admin connector found for listeners {}", adminListeners);
return null;
}
}
UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI());
builder.port(adminConnector.getLocalPort());
return builder.build();
}
public void requestTimeout(long requestTimeoutMs) {
this.requestTimeout.timeoutMs(requestTimeoutMs);
}
public void healthCheckTimeout(long healthCheckTimeoutMs) {
this.requestTimeout.healthCheckTimeoutMs(healthCheckTimeoutMs);
}
String determineAdvertisedProtocol() {
String advertisedSecurityProtocol = config.advertisedListener();
if (advertisedSecurityProtocol == null) {
String listeners = config.rawListeners();
if (listeners == null)
return PROTOCOL_HTTP;
else
listeners = listeners.toLowerCase(Locale.ENGLISH);
if (listeners.contains(String.format("%s:
return PROTOCOL_HTTP;
else if (listeners.contains(String.format("%s:
return PROTOCOL_HTTPS;
else
return PROTOCOL_HTTP;
} else {
return advertisedSecurityProtocol.toLowerCase(Locale.ENGLISH);
}
}
ServerConnector findConnector(String protocol) {
for (Connector connector : jettyServer.getConnectors()) {
String connectorName = connector.getName();
if (connectorName.startsWith(protocol + "_") && !ADMIN_SERVER_CONNECTOR_NAME.equals(connectorName))
return (ServerConnector) connector;
}
return null;
}
protected final void registerRestExtensions(Herder herder, ResourceConfig resourceConfig) {
connectRestExtensions = herder.plugins().newPlugins(
config.restExtensions(),
config, ConnectRestExtension.class);
long herderRequestTimeoutMs = DEFAULT_REST_REQUEST_TIMEOUT_MS;
Integer rebalanceTimeoutMs = config.rebalanceTimeoutMs();
if (rebalanceTimeoutMs != null) {
herderRequestTimeoutMs = Math.min(herderRequestTimeoutMs, rebalanceTimeoutMs.longValue());
}
ConnectClusterDetails connectClusterDetails = new ConnectClusterDetailsImpl(
herder.kafkaClusterId()
);
ConnectRestExtensionContext connectRestExtensionContext =
new ConnectRestExtensionContextImpl(
new ConnectRestConfigurable(resourceConfig),
new ConnectClusterStateImpl(herderRequestTimeoutMs, connectClusterDetails, herder)
);
for (ConnectRestExtension connectRestExtension : connectRestExtensions) {
connectRestExtension.register(connectRestExtensionContext);
}
}
protected void configureHttpResponseHeaderFilter(ServletContextHandler context, String headerConfig) {
FilterHolder headerFilterHolder = new FilterHolder(HeaderFilter.class);
headerFilterHolder.setInitParameter("headerConfig", headerConfig);
context.addFilter(headerFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
}
private static class RequestTimeout implements RestRequestTimeout {
private final RequestBinder binder;
private volatile long timeoutMs;
private volatile long healthCheckTimeoutMs;
public RequestTimeout(long initialTimeoutMs, long initialHealthCheckTimeoutMs) {
this.timeoutMs = initialTimeoutMs;
this.healthCheckTimeoutMs = initialHealthCheckTimeoutMs;
this.binder = new RequestBinder();
}
@Override
public long timeoutMs() {
return timeoutMs;
}
@Override
public long healthCheckTimeoutMs() {
return healthCheckTimeoutMs;
}
public void timeoutMs(long timeoutMs) {
this.timeoutMs = timeoutMs;
}
public void healthCheckTimeoutMs(long healthCheckTimeoutMs) {
this.healthCheckTimeoutMs = healthCheckTimeoutMs;
}
public Binder binder() {
return binder;
}
private class RequestBinder extends AbstractBinder {
@Override
protected void configure() {
bind(RequestTimeout.this).to(RestRequestTimeout.class);
}
}
}
}
| ConnectException | java |
package jdk.internal.logger;
import java.util. [MASK] ;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.ServiceLoader;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import java.util.function.Supplier;
import java.lang.System.LoggerFinder;
import java.lang.System.Logger;
import java.lang.ref.WeakReference;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import jdk.internal.misc.InnocuousThread;
import jdk.internal.misc.VM;
import sun.util.logging.PlatformLogger;
import jdk.internal.logger.LazyLoggers.LazyLoggerAccessor;
public final class BootstrapLogger implements Logger, PlatformLogger.Bridge,
PlatformLogger.ConfigurableBridge {
private static class BootstrapExecutors implements ThreadFactory {
static final long KEEP_EXECUTOR_ALIVE_SECONDS = 30;
private static class BootstrapMessageLoggerTask implements Runnable {
ExecutorService owner;
Runnable run;
public BootstrapMessageLoggerTask(ExecutorService owner, Runnable r) {
this.owner = owner;
this.run = r;
}
@Override
public void run() {
try {
run.run();
} finally {
owner = null;
}
}
}
private static volatile WeakReference<ExecutorService> executorRef;
private static ExecutorService getExecutor() {
WeakReference<ExecutorService> ref = executorRef;
ExecutorService executor = ref == null ? null : ref.get();
if (executor != null) return executor;
synchronized (BootstrapExecutors.class) {
ref = executorRef;
executor = ref == null ? null : ref.get();
if (executor == null) {
executor = new ThreadPoolExecutor(0, 1,
KEEP_EXECUTOR_ALIVE_SECONDS, TimeUnit.SECONDS,
new LinkedBlockingQueue<>(), new BootstrapExecutors());
}
executorRef = new WeakReference<>(executor);
return executorRef.get();
}
}
@Override
public Thread newThread(Runnable r) {
ExecutorService owner = getExecutor();
Thread thread = InnocuousThread.newThread(new BootstrapMessageLoggerTask(owner, r));
thread.setName("BootstrapMessageLoggerTask-" + thread.getName());
thread.setDaemon(true);
return thread;
}
static void submit(Runnable r) {
getExecutor().execute(r);
}
static void join(Runnable r) {
try {
getExecutor().submit(r).get();
} catch (InterruptedException | ExecutionException ex) {
throw new RuntimeException(ex);
}
}
static void awaitPendingTasks() {
WeakReference<ExecutorService> ref = executorRef;
ExecutorService executor = ref == null ? null : ref.get();
if (ref == null) {
synchronized(BootstrapExecutors.class) {
ref = executorRef;
executor = ref == null ? null : ref.get();
}
}
if (executor != null) {
join(()->{});
}
}
static boolean isAlive() {
WeakReference<ExecutorService> ref = executorRef;
if (ref != null && !ref.refersTo(null)) return true;
synchronized (BootstrapExecutors.class) {
ref = executorRef;
return ref != null && !ref.refersTo(null);
}
}
static LogEvent head, tail;
static void enqueue(LogEvent event) {
if (event.next != null) return;
synchronized (BootstrapExecutors.class) {
if (event.next != null) return;
event.next = event;
if (tail == null) {
head = tail = event;
} else {
tail.next = event;
tail = event;
}
}
}
static void flush() {
LogEvent event;
synchronized(BootstrapExecutors.class) {
event = head;
head = tail = null;
}
while(event != null) {
LogEvent.log(event);
synchronized(BootstrapExecutors.class) {
LogEvent prev = event;
event = (event.next == event ? null : event.next);
prev.next = null;
}
}
}
}
final LazyLoggerAccessor holder;
final BooleanSupplier isLoadingThread;
boolean isLoadingThread() {
return isLoadingThread != null && isLoadingThread.getAsBoolean();
}
BootstrapLogger(LazyLoggerAccessor holder, BooleanSupplier isLoadingThread) {
this.holder = holder;
this.isLoadingThread = isLoadingThread;
}
static final class LogEvent {
final Level level;
final PlatformLogger.Level platformLevel;
final BootstrapLogger bootstrap;
final ResourceBundle bundle;
final String msg;
final Throwable thrown;
final Object[] params;
final Supplier<String> msgSupplier;
final String sourceClass;
final String sourceMethod;
final long timeMillis;
final long nanoAdjustment;
LogEvent next;
@SuppressWarnings("removal")
private LogEvent(BootstrapLogger bootstrap, Level level,
ResourceBundle bundle, String msg,
Throwable thrown, Object[] params) {
this.timeMillis = System.currentTimeMillis();
this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis);
this.level = level;
this.platformLevel = null;
this.bundle = bundle;
this.msg = msg;
this.msgSupplier = null;
this.thrown = thrown;
this.params = params;
this.sourceClass = null;
this.sourceMethod = null;
this.bootstrap = bootstrap;
}
@SuppressWarnings("removal")
private LogEvent(BootstrapLogger bootstrap, Level level,
Supplier<String> msgSupplier,
Throwable thrown, Object[] params) {
this.timeMillis = System.currentTimeMillis();
this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis);
this.level = level;
this.platformLevel = null;
this.bundle = null;
this.msg = null;
this.msgSupplier = msgSupplier;
this.thrown = thrown;
this.params = params;
this.sourceClass = null;
this.sourceMethod = null;
this.bootstrap = bootstrap;
}
@SuppressWarnings("removal")
private LogEvent(BootstrapLogger bootstrap,
PlatformLogger.Level platformLevel,
String sourceClass, String sourceMethod,
ResourceBundle bundle, String msg,
Throwable thrown, Object[] params) {
this.timeMillis = System.currentTimeMillis();
this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis);
this.level = null;
this.platformLevel = platformLevel;
this.bundle = bundle;
this.msg = msg;
this.msgSupplier = null;
this.thrown = thrown;
this.params = params;
this.sourceClass = sourceClass;
this.sourceMethod = sourceMethod;
this.bootstrap = bootstrap;
}
@SuppressWarnings("removal")
private LogEvent(BootstrapLogger bootstrap,
PlatformLogger.Level platformLevel,
String sourceClass, String sourceMethod,
Supplier<String> msgSupplier,
Throwable thrown, Object[] params) {
this.timeMillis = System.currentTimeMillis();
this.nanoAdjustment = VM.getNanoTimeAdjustment(timeMillis);
this.level = null;
this.platformLevel = platformLevel;
this.bundle = null;
this.msg = null;
this.msgSupplier = msgSupplier;
this.thrown = thrown;
this.params = params;
this.sourceClass = sourceClass;
this.sourceMethod = sourceMethod;
this.bootstrap = bootstrap;
}
private void log(Logger logger) {
assert platformLevel == null && level != null;
if (msgSupplier != null) {
if (thrown != null) {
logger.log(level, msgSupplier, thrown);
} else {
logger.log(level, msgSupplier);
}
} else {
if (thrown != null) {
logger.log(level, bundle, msg, thrown);
} else {
logger.log(level, bundle, msg, params);
}
}
}
private void log(PlatformLogger.Bridge logger) {
assert platformLevel != null && level == null;
if (sourceClass == null) {
if (msgSupplier != null) {
if (thrown != null) {
logger.log(platformLevel, thrown, msgSupplier);
} else {
logger.log(platformLevel, msgSupplier);
}
} else {
if (thrown != null) {
logger.logrb(platformLevel, bundle, msg, thrown);
} else {
logger.logrb(platformLevel, bundle, msg, params);
}
}
} else {
if (msgSupplier != null) {
if (thrown != null) {
logger.logp(platformLevel, sourceClass, sourceMethod, thrown, msgSupplier);
} else {
logger.logp(platformLevel, sourceClass, sourceMethod, msgSupplier);
}
} else {
if (thrown != null) {
logger.logrb(platformLevel, sourceClass, sourceMethod, bundle, msg, thrown);
} else {
logger.logrb(platformLevel, sourceClass, sourceMethod, bundle, msg, params);
}
}
}
}
static LogEvent valueOf(BootstrapLogger bootstrap, Level level,
ResourceBundle bundle, String key, Throwable thrown) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level), bundle, key,
thrown, null);
}
static LogEvent valueOf(BootstrapLogger bootstrap, Level level,
ResourceBundle bundle, String format, Object[] params) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level), bundle, format,
null, params);
}
static LogEvent valueOf(BootstrapLogger bootstrap, Level level,
Supplier<String> msgSupplier, Throwable thrown) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level),
Objects.requireNonNull(msgSupplier), thrown, null);
}
static LogEvent valueOf(BootstrapLogger bootstrap, Level level,
Supplier<String> msgSupplier) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level),
Objects.requireNonNull(msgSupplier), null, null);
}
static void log(LogEvent log, Logger logger) {
BootstrapExecutors.submit(() -> log.log(logger));
}
static LogEvent valueOf(BootstrapLogger bootstrap,
PlatformLogger.Level level, String msg) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level), null, null, null,
msg, null, null);
}
static LogEvent valueOf(BootstrapLogger bootstrap, PlatformLogger.Level level,
String msg, Throwable thrown) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level), null, null, null, msg, thrown, null);
}
static LogEvent valueOf(BootstrapLogger bootstrap, PlatformLogger.Level level,
String msg, Object[] params) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level), null, null, null, msg, null, params);
}
static LogEvent valueOf(BootstrapLogger bootstrap, PlatformLogger.Level level,
Supplier<String> msgSupplier) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level), null, null, msgSupplier, null, null);
}
static LogEvent vaueOf(BootstrapLogger bootstrap, PlatformLogger.Level level,
Supplier<String> msgSupplier,
Throwable thrown) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level), null, null,
msgSupplier, thrown, null);
}
static LogEvent valueOf(BootstrapLogger bootstrap, PlatformLogger.Level level,
String sourceClass, String sourceMethod,
ResourceBundle bundle, String msg, Object[] params) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level), sourceClass,
sourceMethod, bundle, msg, null, params);
}
static LogEvent valueOf(BootstrapLogger bootstrap, PlatformLogger.Level level,
String sourceClass, String sourceMethod,
ResourceBundle bundle, String msg, Throwable thrown) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level), sourceClass,
sourceMethod, bundle, msg, thrown, null);
}
static LogEvent valueOf(BootstrapLogger bootstrap, PlatformLogger.Level level,
String sourceClass, String sourceMethod,
Supplier<String> msgSupplier, Throwable thrown) {
return new LogEvent(Objects.requireNonNull(bootstrap),
Objects.requireNonNull(level), sourceClass,
sourceMethod, msgSupplier, thrown, null);
}
static void log(LogEvent log, PlatformLogger.Bridge logger) {
BootstrapExecutors.submit(() -> log.log(logger));
}
static void log(LogEvent event) {
event.bootstrap.flush(event);
}
}
void push(LogEvent log) {
BootstrapExecutors.enqueue(log);
checkBootstrapping();
}
void flush(LogEvent event) {
assert event.bootstrap == this;
if (event.platformLevel != null) {
PlatformLogger.Bridge concrete = holder.getConcretePlatformLogger(this);
LogEvent.log(event, concrete);
} else {
Logger concrete = holder.getConcreteLogger(this);
LogEvent.log(event, concrete);
}
}
@Override
public String getName() {
return holder.name;
}
boolean checkBootstrapping() {
if (isBooted() && !isLoadingThread()) {
BootstrapExecutors.flush();
holder.getConcreteLogger(this);
return false;
}
return true;
}
@Override
public boolean isLoggable(Level level) {
if (checkBootstrapping()) {
return level.getSeverity() >= Level.INFO.getSeverity();
} else {
final Logger spi = holder.wrapped();
return spi.isLoggable(level);
}
}
@Override
public void log(Level level, ResourceBundle bundle, String key, Throwable thrown) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, bundle, key, thrown));
} else {
final Logger spi = holder.wrapped();
spi.log(level, bundle, key, thrown);
}
}
@Override
public void log(Level level, ResourceBundle bundle, String format, Object... params) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, bundle, format, params));
} else {
final Logger spi = holder.wrapped();
spi.log(level, bundle, format, params);
}
}
@Override
public void log(Level level, String msg, Throwable thrown) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, null, msg, thrown));
} else {
final Logger spi = holder.wrapped();
spi.log(level, msg, thrown);
}
}
@Override
public void log(Level level, String format, Object... params) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, null, format, params));
} else {
final Logger spi = holder.wrapped();
spi.log(level, format, params);
}
}
@Override
public void log(Level level, Supplier<String> msgSupplier) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, msgSupplier));
} else {
final Logger spi = holder.wrapped();
spi.log(level, msgSupplier);
}
}
@Override
public void log(Level level, Object obj) {
if (checkBootstrapping()) {
Logger.super.log(level, obj);
} else {
final Logger spi = holder.wrapped();
spi.log(level, obj);
}
}
@Override
public void log(Level level, String msg) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, null, msg, (Object[])null));
} else {
final Logger spi = holder.wrapped();
spi.log(level, msg);
}
}
@Override
public void log(Level level, Supplier<String> msgSupplier, Throwable thrown) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, msgSupplier, thrown));
} else {
final Logger spi = holder.wrapped();
spi.log(level, msgSupplier, thrown);
}
}
@Override
public boolean isLoggable(PlatformLogger.Level level) {
if (checkBootstrapping()) {
return level.intValue() >= PlatformLogger.Level.INFO.intValue();
} else {
final PlatformLogger.Bridge spi = holder.platform();
return spi.isLoggable(level);
}
}
@Override
public boolean isEnabled() {
if (checkBootstrapping()) {
return true;
} else {
final PlatformLogger.Bridge spi = holder.platform();
return spi.isEnabled();
}
}
@Override
public void log(PlatformLogger.Level level, String msg) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, msg));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.log(level, msg);
}
}
@Override
public void log(PlatformLogger.Level level, String msg, Throwable thrown) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, msg, thrown));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.log(level, msg, thrown);
}
}
@Override
public void log(PlatformLogger.Level level, String msg, Object... params) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, msg, params));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.log(level, msg, params);
}
}
@Override
public void log(PlatformLogger.Level level, Supplier<String> msgSupplier) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, msgSupplier));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.log(level, msgSupplier);
}
}
@Override
public void log(PlatformLogger.Level level, Throwable thrown,
Supplier<String> msgSupplier) {
if (checkBootstrapping()) {
push(LogEvent.vaueOf(this, level, msgSupplier, thrown));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.log(level, thrown, msgSupplier);
}
}
@Override
public void logp(PlatformLogger.Level level, String sourceClass,
String sourceMethod, String msg) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, sourceClass, sourceMethod, null,
msg, (Object[])null));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.logp(level, sourceClass, sourceMethod, msg);
}
}
@Override
public void logp(PlatformLogger.Level level, String sourceClass,
String sourceMethod, Supplier<String> msgSupplier) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, sourceClass, sourceMethod, msgSupplier, null));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.logp(level, sourceClass, sourceMethod, msgSupplier);
}
}
@Override
public void logp(PlatformLogger.Level level, String sourceClass,
String sourceMethod, String msg, Object... params) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, sourceClass, sourceMethod, null, msg, params));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.logp(level, sourceClass, sourceMethod, msg, params);
}
}
@Override
public void logp(PlatformLogger.Level level, String sourceClass,
String sourceMethod, String msg, Throwable thrown) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, sourceClass, sourceMethod, null, msg, thrown));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.logp(level, sourceClass, sourceMethod, msg, thrown);
}
}
@Override
public void logp(PlatformLogger.Level level, String sourceClass,
String sourceMethod, Throwable thrown, Supplier<String> msgSupplier) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, sourceClass, sourceMethod, msgSupplier, thrown));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.logp(level, sourceClass, sourceMethod, thrown, msgSupplier);
}
}
@Override
public void logrb(PlatformLogger.Level level, String sourceClass,
String sourceMethod, ResourceBundle bundle, String msg, Object... params) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, sourceClass, sourceMethod, bundle, msg, params));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.logrb(level, sourceClass, sourceMethod, bundle, msg, params);
}
}
@Override
public void logrb(PlatformLogger.Level level, String sourceClass,
String sourceMethod, ResourceBundle bundle, String msg, Throwable thrown) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, sourceClass, sourceMethod, bundle, msg, thrown));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.logrb(level, sourceClass, sourceMethod, bundle, msg, thrown);
}
}
@Override
public void logrb(PlatformLogger.Level level, ResourceBundle bundle,
String msg, Object... params) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, null, null, bundle, msg, params));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.logrb(level, bundle, msg, params);
}
}
@Override
public void logrb(PlatformLogger.Level level, ResourceBundle bundle, String msg, Throwable thrown) {
if (checkBootstrapping()) {
push(LogEvent.valueOf(this, level, null, null, bundle, msg, thrown));
} else {
final PlatformLogger.Bridge spi = holder.platform();
spi.logrb(level, bundle, msg, thrown);
}
}
@Override
public LoggerConfiguration getLoggerConfiguration() {
if (checkBootstrapping()) {
return PlatformLogger.ConfigurableBridge.super.getLoggerConfiguration();
} else {
final PlatformLogger.Bridge spi = holder.platform();
return PlatformLogger.ConfigurableBridge.getLoggerConfiguration(spi);
}
}
private static volatile BooleanSupplier isBooted;
public static boolean isBooted() {
if (isBooted != null) return isBooted.getAsBoolean();
else return VM.isBooted();
}
private static enum LoggingBackend {
NONE(true),
JUL_DEFAULT(false),
JUL_WITH_CONFIG(true),
CUSTOM(true);
final boolean useLoggerFinder;
private LoggingBackend(boolean useLoggerFinder) {
this.useLoggerFinder = useLoggerFinder;
}
};
@SuppressWarnings("removal")
private static final class DetectBackend {
static final LoggingBackend detectedBackend = detectBackend();
static LoggingBackend detectBackend() {
final Iterator<LoggerFinder> iterator =
ServiceLoader.load(LoggerFinder.class, ClassLoader.getSystemClassLoader())
.iterator();
if (iterator.hasNext()) {
return LoggingBackend.CUSTOM;
}
final Iterator<DefaultLoggerFinder> iterator2 =
ServiceLoader.loadInstalled(DefaultLoggerFinder.class)
.iterator();
if (iterator2.hasNext()) {
String cname = System.getProperty("java.util.logging.config.class");
String fname = System.getProperty("java.util.logging.config.file");
return (cname != null || fname != null)
? LoggingBackend.JUL_WITH_CONFIG
: LoggingBackend.JUL_DEFAULT;
} else {
return LoggingBackend.NONE;
}
}
}
private static boolean useSurrogateLoggers() {
if (!isBooted()) return true;
return DetectBackend.detectedBackend == LoggingBackend.JUL_DEFAULT
&& !logManagerConfigured;
}
public static boolean useLazyLoggers() {
if (!BootstrapLogger.isBooted() ||
DetectBackend.detectedBackend == LoggingBackend.CUSTOM) {
return true;
}
synchronized (BootstrapLogger.class) {
return useSurrogateLoggers();
}
}
static Logger getLogger(LazyLoggerAccessor accessor, BooleanSupplier isLoading) {
if (!BootstrapLogger.isBooted() || isLoading != null && isLoading.getAsBoolean()) {
return new BootstrapLogger(accessor, isLoading);
} else {
if (useSurrogateLoggers()) {
synchronized(BootstrapLogger.class) {
if (useSurrogateLoggers()) {
return createSurrogateLogger(accessor);
}
}
}
return accessor.createLogger();
}
}
static void ensureBackendDetected() {
assert VM.isBooted() : "VM is not booted";
var backend = DetectBackend.detectedBackend;
}
static final class RedirectedLoggers implements
Function<LazyLoggerAccessor, SurrogateLogger> {
final Map<LazyLoggerAccessor, SurrogateLogger> redirectedLoggers =
new [MASK] <>();
boolean cleared;
@Override
public SurrogateLogger apply(LazyLoggerAccessor t) {
if (cleared) throw new IllegalStateException("LoggerFinder already initialized");
return SurrogateLogger.makeSurrogateLogger(t.getLoggerName());
}
SurrogateLogger get(LazyLoggerAccessor a) {
if (cleared) throw new IllegalStateException("LoggerFinder already initialized");
return redirectedLoggers.computeIfAbsent(a, this);
}
Map<LazyLoggerAccessor, SurrogateLogger> drainLoggersMap() {
if (redirectedLoggers.isEmpty()) return null;
if (cleared) throw new IllegalStateException("LoggerFinder already initialized");
final Map<LazyLoggerAccessor, SurrogateLogger> accessors = new [MASK] <>(redirectedLoggers);
redirectedLoggers.clear();
cleared = true;
return accessors;
}
static void replaceSurrogateLoggers(Map<LazyLoggerAccessor, SurrogateLogger> accessors) {
final LoggingBackend detectedBackend = DetectBackend.detectedBackend;
final boolean lazy = detectedBackend != LoggingBackend.JUL_DEFAULT
&& detectedBackend != LoggingBackend.JUL_WITH_CONFIG;
for (Map.Entry<LazyLoggerAccessor, SurrogateLogger> a : accessors.entrySet()) {
a.getKey().release(a.getValue(), !lazy);
}
}
static final RedirectedLoggers INSTANCE = new RedirectedLoggers();
}
static synchronized Logger createSurrogateLogger(LazyLoggerAccessor a) {
return RedirectedLoggers.INSTANCE.get(a);
}
private static volatile boolean logManagerConfigured;
private static synchronized Map<LazyLoggerAccessor, SurrogateLogger>
releaseSurrogateLoggers() {
final boolean releaseSurrogateLoggers = useSurrogateLoggers();
logManagerConfigured = true;
if (releaseSurrogateLoggers) {
return RedirectedLoggers.INSTANCE.drainLoggersMap();
} else {
return null;
}
}
public static void redirectTemporaryLoggers() {
final Map<LazyLoggerAccessor, SurrogateLogger> accessors =
releaseSurrogateLoggers();
if (accessors != null) {
RedirectedLoggers.replaceSurrogateLoggers(accessors);
}
BootstrapExecutors.flush();
}
static void awaitPendingTasks() {
BootstrapExecutors.awaitPendingTasks();
}
static boolean isAlive() {
return BootstrapExecutors.isAlive();
}
}
| HashMap | java |
package org.elasticsearch.compute.operator;
import org.elasticsearch.TransportVersion;
import org.elasticsearch.TransportVersions;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.compute.Describable;
import org.elasticsearch.compute.aggregation.AggregatorMode;
import org.elasticsearch.compute.aggregation. [MASK] ;
import org.elasticsearch.compute.aggregation. [MASK] Function;
import org.elasticsearch.compute.aggregation.blockhash.BlockHash;
import org.elasticsearch.compute.data.Block;
import org.elasticsearch.compute.data.IntBlock;
import org.elasticsearch.compute.data.IntVector;
import org.elasticsearch.compute.data.Page;
import org.elasticsearch.core.Releasables;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.analysis.AnalysisRegistry;
import org.elasticsearch.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;
public class HashAggregationOperator implements Operator {
public record HashAggregationOperatorFactory(
List<BlockHash.GroupSpec> groups,
AggregatorMode aggregatorMode,
List< [MASK] .Factory> aggregators,
int maxPageSize,
AnalysisRegistry analysisRegistry
) implements OperatorFactory {
@Override
public Operator get(DriverContext driverContext) {
if (groups.stream().anyMatch(BlockHash.GroupSpec::isCategorize)) {
return new HashAggregationOperator(
aggregators,
() -> BlockHash.buildCategorizeBlockHash(
groups,
aggregatorMode,
driverContext.blockFactory(),
analysisRegistry,
maxPageSize
),
driverContext
);
}
return new HashAggregationOperator(
aggregators,
() -> BlockHash.build(groups, driverContext.blockFactory(), maxPageSize, false),
driverContext
);
}
@Override
public String describe() {
return "HashAggregationOperator[mode = "
+ "<not-needed>"
+ ", aggs = "
+ aggregators.stream().map(Describable::describe).collect(joining(", "))
+ "]";
}
}
private boolean finished;
private Page output;
private final BlockHash blockHash;
private final List< [MASK] > aggregators;
private final DriverContext driverContext;
private long hashNanos;
private long aggregationNanos;
private int pagesProcessed;
private long rowsReceived;
private long rowsEmitted;
@SuppressWarnings("this-escape")
public HashAggregationOperator(
List< [MASK] .Factory> aggregators,
Supplier<BlockHash> blockHash,
DriverContext driverContext
) {
this.aggregators = new ArrayList<>(aggregators.size());
this.driverContext = driverContext;
boolean success = false;
try {
this.blockHash = blockHash.get();
for ( [MASK] .Factory a : aggregators) {
this.aggregators.add(a.apply(driverContext));
}
success = true;
} finally {
if (success == false) {
close();
}
}
}
@Override
public boolean needsInput() {
return finished == false;
}
@Override
public void addInput(Page page) {
try {
[MASK] Function.AddInput[] prepared = new [MASK] Function.AddInput[aggregators.size()];
class AddInput implements [MASK] Function.AddInput {
long hashStart = System.nanoTime();
long aggStart;
@Override
public void add(int positionOffset, IntBlock groupIds) {
IntVector groupIdsVector = groupIds.asVector();
if (groupIdsVector != null) {
add(positionOffset, groupIdsVector);
} else {
startAggEndHash();
for ( [MASK] Function.AddInput p : prepared) {
p.add(positionOffset, groupIds);
}
end();
}
}
@Override
public void add(int positionOffset, IntVector groupIds) {
startAggEndHash();
for ( [MASK] Function.AddInput p : prepared) {
p.add(positionOffset, groupIds);
}
end();
}
private void startAggEndHash() {
aggStart = System.nanoTime();
hashNanos += aggStart - hashStart;
}
private void end() {
hashStart = System.nanoTime();
aggregationNanos += hashStart - aggStart;
}
@Override
public void close() {
Releasables.closeExpectNoException(prepared);
}
}
try (AddInput add = new AddInput()) {
checkState(needsInput(), "Operator is already finishing");
requireNonNull(page, "page is null");
for (int i = 0; i < prepared.length; i++) {
prepared[i] = aggregators.get(i).prepareProcessPage(blockHash, page);
}
blockHash.add(wrapPage(page), add);
hashNanos += System.nanoTime() - add.hashStart;
}
} finally {
page.releaseBlocks();
pagesProcessed++;
rowsReceived += page.getPositionCount();
}
}
@Override
public Page getOutput() {
Page p = output;
if (p != null) {
rowsEmitted += p.getPositionCount();
}
output = null;
return p;
}
@Override
public void finish() {
if (finished) {
return;
}
finished = true;
Block[] blocks = null;
IntVector selected = null;
boolean success = false;
try {
selected = blockHash.nonEmpty();
Block[] keys = blockHash.getKeys();
int[] aggBlockCounts = aggregators.stream().mapToInt( [MASK] ::evaluateBlockCount).toArray();
blocks = new Block[keys.length + Arrays.stream(aggBlockCounts).sum()];
System.arraycopy(keys, 0, blocks, 0, keys.length);
int offset = keys.length;
for (int i = 0; i < aggregators.size(); i++) {
var aggregator = aggregators.get(i);
aggregator.evaluate(blocks, offset, selected, driverContext);
offset += aggBlockCounts[i];
}
output = new Page(blocks);
success = true;
} finally {
if (selected != null) {
selected.close();
}
if (success == false && blocks != null) {
Releasables.closeExpectNoException(blocks);
}
}
}
@Override
public boolean isFinished() {
return finished && output == null;
}
@Override
public void close() {
if (output != null) {
output.releaseBlocks();
}
Releasables.close(blockHash, () -> Releasables.close(aggregators));
}
@Override
public Operator.Status status() {
return new Status(hashNanos, aggregationNanos, pagesProcessed, rowsReceived, rowsEmitted);
}
protected static void checkState(boolean condition, String msg) {
if (condition == false) {
throw new IllegalArgumentException(msg);
}
}
protected Page wrapPage(Page page) {
return page;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.getClass().getSimpleName()).append("[");
sb.append("blockHash=").append(blockHash).append(", ");
sb.append("aggregators=").append(aggregators);
sb.append("]");
return sb.toString();
}
public static class Status implements Operator.Status {
public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(
Operator.Status.class,
"hashagg",
Status::new
);
private final long hashNanos;
private final long aggregationNanos;
private final int pagesProcessed;
private final long rowsReceived;
private final long rowsEmitted;
public Status(long hashNanos, long aggregationNanos, int pagesProcessed, long rowsReceived, long rowsEmitted) {
this.hashNanos = hashNanos;
this.aggregationNanos = aggregationNanos;
this.pagesProcessed = pagesProcessed;
this.rowsReceived = rowsReceived;
this.rowsEmitted = rowsEmitted;
}
protected Status(StreamInput in) throws IOException {
hashNanos = in.readVLong();
aggregationNanos = in.readVLong();
pagesProcessed = in.readVInt();
if (in.getTransportVersion().onOrAfter(TransportVersions.ESQL_PROFILE_ROWS_PROCESSED)) {
rowsReceived = in.readVLong();
rowsEmitted = in.readVLong();
} else {
rowsReceived = 0;
rowsEmitted = 0;
}
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeVLong(hashNanos);
out.writeVLong(aggregationNanos);
out.writeVInt(pagesProcessed);
if (out.getTransportVersion().onOrAfter(TransportVersions.ESQL_PROFILE_ROWS_PROCESSED)) {
out.writeVLong(rowsReceived);
out.writeVLong(rowsEmitted);
}
}
@Override
public String getWriteableName() {
return ENTRY.name;
}
public long hashNanos() {
return hashNanos;
}
public long aggregationNanos() {
return aggregationNanos;
}
public int pagesProcessed() {
return pagesProcessed;
}
public long rowsReceived() {
return rowsReceived;
}
public long rowsEmitted() {
return rowsEmitted;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("hash_nanos", hashNanos);
if (builder.humanReadable()) {
builder.field("hash_time", TimeValue.timeValueNanos(hashNanos));
}
builder.field("aggregation_nanos", aggregationNanos);
if (builder.humanReadable()) {
builder.field("aggregation_time", TimeValue.timeValueNanos(aggregationNanos));
}
builder.field("pages_processed", pagesProcessed);
builder.field("rows_received", rowsReceived);
builder.field("rows_emitted", rowsEmitted);
return builder.endObject();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Status status = (Status) o;
return hashNanos == status.hashNanos
&& aggregationNanos == status.aggregationNanos
&& pagesProcessed == status.pagesProcessed
&& rowsReceived == status.rowsReceived
&& rowsEmitted == status.rowsEmitted;
}
@Override
public int hashCode() {
return Objects.hash(hashNanos, aggregationNanos, pagesProcessed, rowsReceived, rowsEmitted);
}
@Override
public String toString() {
return Strings.toString(this);
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersions.V_8_14_0;
}
}
}
| GroupingAggregator | java |
package emu.grasscutter.net.proto;
public final class DoRoguelikeDungeonCardGachaReqOuterClass {
private DoRoguelikeDungeonCardGachaReqOuterClass() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface DoRoguelikeDungeonCardGachaReqOrBuilder extends
com.google.protobuf.MessageOrBuilder {
int getDungeonId();
int getCellId();
}
public static final class DoRoguelikeDungeonCardGachaReq extends
com.google.protobuf.GeneratedMessageV3 implements
DoRoguelikeDungeonCardGachaReqOrBuilder {
private static final long serialVersionUID = 0L;
private DoRoguelikeDungeonCardGachaReq(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DoRoguelikeDungeonCardGachaReq() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new DoRoguelikeDungeonCardGachaReq();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private DoRoguelikeDungeonCardGachaReq(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 24: {
cellId_ = input.readUInt32();
break;
}
case 112: {
dungeonId_ = input.readUInt32();
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable
.ensureFieldAccessorsInitialized(
emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.class, emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.Builder.class);
}
public static final int DUNGEON_ID_FIELD_NUMBER = 14;
private int dungeonId_;
@java.lang.Override
public int getDungeonId() {
return dungeonId_;
}
public static final int CELL_ID_FIELD_NUMBER = 3;
private int cellId_;
@java.lang.Override
public int getCellId() {
return cellId_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (cellId_ != 0) {
output.writeUInt32(3, cellId_);
}
if (dungeonId_ != 0) {
output.writeUInt32(14, dungeonId_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (cellId_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(3, cellId_);
}
if (dungeonId_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeUInt32Size(14, dungeonId_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq)) {
return super.equals(obj);
}
emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq other = (emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) obj;
if (getDungeonId()
!= other.getDungeonId()) return false;
if (getCellId()
!= other.getCellId()) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + DUNGEON_ID_FIELD_NUMBER;
hash = (53 * hash) + getDungeonId();
hash = (37 * hash) + CELL_ID_FIELD_NUMBER;
hash = (53 * hash) + getCellId();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReqOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable
.ensureFieldAccessorsInitialized(
emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.class, emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.Builder.class);
}
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
dungeonId_ = 0;
cellId_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.internal_static_DoRoguelikeDungeonCardGachaReq_descriptor;
}
@java.lang.Override
public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstanceForType() {
return emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.getDefaultInstance();
}
@java.lang.Override
public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq build() {
emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq buildPartial() {
emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq result = new emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq(this);
result.dungeonId_ = dungeonId_;
result.cellId_ = cellId_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) {
return mergeFrom((emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq other) {
if (other == emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq.getDefaultInstance()) return this;
if (other.getDungeonId() != 0) {
setDungeonId(other.getDungeonId());
}
if (other.getCellId() != 0) {
setCellId(other.getCellId());
}
this. [MASK] (other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int dungeonId_ ;
@java.lang.Override
public int getDungeonId() {
return dungeonId_;
}
public Builder setDungeonId(int value) {
dungeonId_ = value;
onChanged();
return this;
}
public Builder clearDungeonId() {
dungeonId_ = 0;
onChanged();
return this;
}
private int cellId_ ;
@java.lang.Override
public int getCellId() {
return cellId_;
}
public Builder setCellId(int value) {
cellId_ = value;
onChanged();
return this;
}
public Builder clearCellId() {
cellId_ = 0;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder [MASK] (
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super. [MASK] (unknownFields);
}
}
private static final emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq();
}
public static emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq>
PARSER = new com.google.protobuf.AbstractParser<DoRoguelikeDungeonCardGachaReq>() {
@java.lang.Override
public DoRoguelikeDungeonCardGachaReq parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new DoRoguelikeDungeonCardGachaReq(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DoRoguelikeDungeonCardGachaReq> getParserForType() {
return PARSER;
}
@java.lang.Override
public emu.grasscutter.net.proto.DoRoguelikeDungeonCardGachaReqOuterClass.DoRoguelikeDungeonCardGachaReq getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_DoRoguelikeDungeonCardGachaReq_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n$DoRoguelikeDungeonCardGachaReq.proto\"E" +
"\n\036DoRoguelikeDungeonCardGachaReq\022\022\n\ndung" +
"eon_id\030\016 \001(\r\022\017\n\007cell_id\030\003 \001(\rB\033\n\031emu.gra" +
"sscutter.net.protob\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
});
internal_static_DoRoguelikeDungeonCardGachaReq_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_DoRoguelikeDungeonCardGachaReq_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_DoRoguelikeDungeonCardGachaReq_descriptor,
new java.lang.String[] { "DungeonId", "CellId", });
}
}
| mergeUnknownFields | java |
package ai.chat2db.server.test.domain.data.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson2.JSON;
import ai.chat2db.server.domain.api.param.ConsoleConnectParam;
import ai.chat2db.server.domain.api.param.DlExecuteParam;
import ai.chat2db.server.domain.api.param.DropParam;
import ai.chat2db.server.domain.api.param.ShowCreateTableParam;
import ai.chat2db.server.domain.api.param.TablePageQueryParam;
import ai.chat2db.server.domain.api.param.TableQueryParam;
import ai.chat2db.server.domain.api.param.TableSelector;
import ai.chat2db.server.domain.api.param.datasource.DataSourcePreConnectParam;
import ai.chat2db.server.domain.api.service.ConsoleService;
import ai.chat2db.server.domain.api.service.DataSourceService;
import ai.chat2db.server.domain.api.service.DlTemplateService;
import ai.chat2db.server.domain.api.service.TableService;
import ai.chat2db.server.test.common.BaseTest;
import ai.chat2db.server.test.domain.data.service.dialect.DialectProperties;
import ai.chat2db.server.test.domain.data.utils.TestUtils;
import ai.chat2db.server.tools.base.wrapper.result.DataResult;
import ai.chat2db.server.tools.common.util.EasyCollectionUtils;
import ai.chat2db.spi.enums.CollationEnum;
import ai.chat2db.spi.enums.IndexTypeEnum;
import ai.chat2db.spi.model.Sql;
import ai.chat2db.spi.model.Table;
import ai.chat2db.spi.model.TableColumn;
import ai.chat2db.spi.model.TableIndex;
import ai.chat2db.spi.model.TableIndexColumn;
import com.google.common.collect.Lists;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
public class TableOperationsTest extends BaseTest {
public static final String TABLE_NAME = "data_ops_table_test_" + System.currentTimeMillis();
@Resource
private DataSourceService dataSourceService;
@Resource
private ConsoleService consoleService;
@Autowired
private List<DialectProperties> dialectPropertiesList;
@Resource
private DlTemplateService dlTemplateService;
@Resource
private TableService tableService;
@Test
@Order(1)
public void table() {
for (DialectProperties dialectProperties : dialectPropertiesList) {
String dbTypeEnum = dialectProperties.getDbType();
Long dataSourceId = TestUtils.nextLong();
Long consoleId = TestUtils.nextLong();
putConnect(dialectProperties.getUrl(), dialectProperties.getUsername(), dialectProperties.getPassword(),
dialectProperties.getDbType(), dialectProperties.getDatabaseName(), dataSourceId, consoleId);
DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam();
dataSourceCreateParam.setType(dbTypeEnum);
dataSourceCreateParam.setUrl(dialectProperties.getUrl());
dataSourceCreateParam.setUser(dialectProperties.getUsername());
dataSourceCreateParam.setPassword(dialectProperties.getPassword());
dataSourceService.preConnect(dataSourceCreateParam);
ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam();
consoleCreateParam.setDataSourceId(dataSourceId);
consoleCreateParam.setConsoleId(consoleId);
consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName());
consoleService.createConsole(consoleCreateParam);
DlExecuteParam templateQueryParam = new DlExecuteParam();
templateQueryParam.setConsoleId(consoleId);
templateQueryParam.setDataSourceId(dataSourceId);
templateQueryParam.setSql(dialectProperties.getCrateTableSql(TABLE_NAME));
dlTemplateService.execute(templateQueryParam);
ShowCreateTableParam showCreateTableParam = ShowCreateTableParam.builder()
.dataSourceId(dataSourceId)
.databaseName(dialectProperties.getDatabaseName())
.tableName(dialectProperties.toCase(TABLE_NAME))
.build();
if (dialectProperties.getDbType() == "POSTGRESQL") {
showCreateTableParam.setSchemaName("public");
}
DataResult<String> createTable = tableService.showCreateTable(showCreateTableParam);
log.info("Table creation statement: {}", createTable.getData());
if (dialectProperties.getDbType() != "H2") {
Assertions.assertTrue(createTable.getData().contains(dialectProperties.toCase(TABLE_NAME)),
"Query table structure failed");
}
TablePageQueryParam [MASK] = new TablePageQueryParam();
[MASK] .setDataSourceId(dataSourceId);
[MASK] .setDatabaseName(dialectProperties.getDatabaseName());
[MASK] .setTableName(dialectProperties.toCase(TABLE_NAME));
if (dialectProperties.getDbType() == "POSTGRESQL") {
[MASK] .setSchemaName("public");
}
List<Table> tableList = tableService.pageQuery( [MASK] , TableSelector.builder()
.columnList(Boolean.TRUE)
.indexList(Boolean.TRUE)
.build()).getData();
log.info("Analyzing data returns {}", JSON.toJSONString(tableList));
Assertions.assertNotEquals(0L, tableList.size(), "Query table structure failed");
Table table = tableList.get(0);
if (dialectProperties.getDbType() != "POSTGRESQL") {
Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed");
}
TableQueryParam tableQueryParam = new TableQueryParam();
tableQueryParam.setTableName(table.getName());
tableQueryParam.setDataSourceId(dataSourceId);
tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName());
if (dialectProperties.getDbType() == "POSTGRESQL") {
tableQueryParam.setSchemaName("public");
}
List<TableColumn> columnList = tableService.queryColumns(tableQueryParam);
Assertions.assertEquals(4L, columnList.size(), "Query table structure failed");
TableColumn id = columnList.get(0);
Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed");
Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed");
Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed");
TableColumn string = columnList.get(3);
Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed");
Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()),
"Query table structure failed");
if (dialectProperties.getDbType() == "POSTGRESQL") {
[MASK] .setSchemaName("public");
}
List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam);
log.info("Analyzing data returns {}", JSON.toJSONString(tableIndexList));
Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed");
Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList,
TableIndex::getName);
TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_date"));
Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed");
Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed");
Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed");
Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(),
"Query table structure failed");
Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(),
"Query table structure failed");
TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_uk_number"));
Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed");
Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed");
TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(TABLE_NAME + "_idx_number_string"));
Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed");
DropParam dropParam = DropParam.builder()
.dataSourceId(dataSourceId)
.databaseName(dialectProperties.getDatabaseName())
.tableName(dialectProperties.toCase(TABLE_NAME))
.build();
tableService.drop(dropParam);
[MASK] = new TablePageQueryParam();
[MASK] .setDataSourceId(dataSourceId);
[MASK] .setDatabaseName(dialectProperties.getDatabaseName());
[MASK] .setTableName(dialectProperties.toCase(TABLE_NAME));
tableList = tableService.pageQuery( [MASK] , TableSelector.builder()
.columnList(Boolean.TRUE)
.indexList(Boolean.TRUE)
.build()).getData();
log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList));
Assertions.assertEquals(0L, tableList.size(), "Query table structure failed");
testBuildSql(dialectProperties, dataSourceId, consoleId);
removeConnect();
}
}
private void testBuildSql(DialectProperties dialectProperties, Long dataSourceId, Long consoleId) {
if (dialectProperties.getDbType() != "MYSQL") {
log.error("Currently the test case only supports mysql");
return;
}
String tableName = dialectProperties.toCase("data_ops_table_test_" + System.currentTimeMillis());
Table newTable = new Table();
newTable.setName(tableName);
newTable.setComment("Test table");
List<TableColumn> tableColumnList = new ArrayList<>();
newTable.setColumnList(tableColumnList);
TableColumn idTableColumn = new TableColumn();
idTableColumn.setName("id");
idTableColumn.setAutoIncrement(Boolean.TRUE);
idTableColumn.setPrimaryKey(Boolean.TRUE);
idTableColumn.setComment("Primary key auto-increment");
idTableColumn.setColumnType("bigint");
tableColumnList.add(idTableColumn);
TableColumn dateTableColumn = new TableColumn();
dateTableColumn.setName("date");
dateTableColumn.setComment("date");
dateTableColumn.setColumnType("datetime(3)");
tableColumnList.add(dateTableColumn);
TableColumn numberTableColumn = new TableColumn();
numberTableColumn.setName("number");
numberTableColumn.setComment("long integer");
numberTableColumn.setColumnType("bigint");
tableColumnList.add(numberTableColumn);
TableColumn stringTableColumn = new TableColumn();
stringTableColumn.setName("string");
stringTableColumn.setComment("name");
stringTableColumn.setColumnType("varchar(100)");
stringTableColumn.setDefaultValue("DATA");
tableColumnList.add(stringTableColumn);
List<TableIndex> tableIndexList = new ArrayList<>();
newTable.setIndexList(tableIndexList);
tableIndexList.add(TableIndex.builder()
.name(tableName + "_idx_date")
.type(IndexTypeEnum.NORMAL.getCode())
.comment("date index")
.columnList(Lists.newArrayList(TableIndexColumn.builder()
.columnName("date")
.collation(CollationEnum.DESC.getCode())
.build()))
.build());
tableIndexList.add(TableIndex.builder()
.name(tableName + "_uk_number")
.type(IndexTypeEnum.UNIQUE.getCode())
.comment("unique index")
.columnList(Lists.newArrayList(TableIndexColumn.builder()
.columnName("number")
.build()))
.build());
tableIndexList.add(TableIndex.builder()
.name(tableName + "_idx_number_string")
.type(IndexTypeEnum.NORMAL.getCode())
.comment("Union index")
.columnList(Lists.newArrayList(TableIndexColumn.builder()
.columnName("number")
.build(),
TableIndexColumn.builder()
.columnName("date")
.build()))
.build());
List<Sql> buildTableSqlList = tableService.buildSql(null, newTable).getData();
log.info("The structural statement to create a table is:{}", JSON.toJSONString(buildTableSqlList));
for (Sql sql : buildTableSqlList) {
DlExecuteParam templateQueryParam = new DlExecuteParam();
templateQueryParam.setConsoleId(consoleId);
templateQueryParam.setDataSourceId(dataSourceId);
templateQueryParam.setSql(sql.getSql());
dlTemplateService.execute(templateQueryParam);
}
checkTable(tableName, dialectProperties, dataSourceId);
TableQueryParam [MASK] = new TableQueryParam();
[MASK] .setDataSourceId(dataSourceId);
[MASK] .setDatabaseName(dialectProperties.getDatabaseName());
[MASK] .setTableName(dialectProperties.toCase(tableName));
Table table = tableService.query( [MASK] , TableSelector.builder()
.columnList(Boolean.TRUE)
.indexList(Boolean.TRUE)
.build()).getData();
log.info("Analyzing data returns {}", JSON.toJSONString(table));
Assertions.assertNotNull(table, "Query table structure failed");
Table oldTable = table;
Assertions.assertEquals(dialectProperties.toCase(tableName), oldTable.getName(), "Query table structure failed");
Assertions.assertEquals("Test table", oldTable.getComment(), "Query table structure failed");
log.info("oldTable:{}", JSON.toJSONString(oldTable));
log.info("newTable:{}", JSON.toJSONString(newTable));
buildTableSqlList = tableService.buildSql(oldTable, newTable).getData();
log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList));
Assertions.assertTrue(!buildTableSqlList.isEmpty(), "构建sql失败");
[MASK] = new TableQueryParam();
[MASK] .setDataSourceId(dataSourceId);
[MASK] .setDatabaseName(dialectProperties.getDatabaseName());
[MASK] .setTableName(dialectProperties.toCase(tableName));
newTable = tableService.query( [MASK] , TableSelector.builder()
.columnList(Boolean.TRUE)
.indexList(Boolean.TRUE)
.build()).getData();
newTable.getColumnList().add(TableColumn.builder()
.name("add_string")
.columnType("varchar(20)")
.comment("New string")
.build());
newTable.getIndexList().add(TableIndex.builder()
.name(tableName + "_idx_string_new")
.type(IndexTypeEnum.NORMAL.getCode())
.comment("new string index")
.columnList(Lists.newArrayList(TableIndexColumn.builder()
.columnName("add_string")
.collation(CollationEnum.DESC.getCode())
.build()))
.build());
log.info("oldTable:{}", JSON.toJSONString(oldTable));
log.info("newTable:{}", JSON.toJSONString(newTable));
buildTableSqlList = tableService.buildSql(oldTable, newTable).getData();
log.info("Modify the table structure: {}", JSON.toJSONString(buildTableSqlList));
dropTable(tableName, dialectProperties, dataSourceId);
}
private void dropTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) {
DropParam dropParam = DropParam.builder()
.dataSourceId(dataSourceId)
.databaseName(dialectProperties.getDatabaseName())
.tableName(dialectProperties.toCase(tableName))
.build();
tableService.drop(dropParam);
TablePageQueryParam [MASK] = new TablePageQueryParam();
[MASK] .setDataSourceId(dataSourceId);
[MASK] .setDatabaseName(dialectProperties.getDatabaseName());
[MASK] .setTableName(dialectProperties.toCase(tableName));
List<Table> tableList = tableService.pageQuery( [MASK] , TableSelector.builder()
.columnList(Boolean.TRUE)
.indexList(Boolean.TRUE)
.build()).getData();
log.info("After deleting the table, the data returns {}", JSON.toJSONString(tableList));
Assertions.assertEquals(0L, tableList.size(), "Query table structure failed");
}
private void checkTable(String tableName, DialectProperties dialectProperties, Long dataSourceId) {
TablePageQueryParam [MASK] = new TablePageQueryParam();
[MASK] .setDataSourceId(dataSourceId);
[MASK] .setDatabaseName(dialectProperties.getDatabaseName());
[MASK] .setTableName(dialectProperties.toCase(tableName));
List<Table> tableList = tableService.pageQuery( [MASK] , TableSelector.builder()
.columnList(Boolean.TRUE)
.indexList(Boolean.TRUE)
.build()).getData();
log.info("Analyzing data returns {}", JSON.toJSONString(tableList));
Assertions.assertEquals(1L, tableList.size(), "Query table structure failed");
Table table = tableList.get(0);
Assertions.assertEquals(dialectProperties.toCase(tableName), table.getName(), "Query table structure failed");
Assertions.assertEquals("Test table", table.getComment(), "Query table structure failed");
TableQueryParam tableQueryParam = new TableQueryParam();
tableQueryParam.setTableName(table.getName());
tableQueryParam.setDataSourceId(dataSourceId);
tableQueryParam.setDatabaseName(dialectProperties.getDatabaseName());
List<TableColumn> columnList = tableService.queryColumns(tableQueryParam);
Assertions.assertEquals(4L, columnList.size(), "Query table structure failed");
TableColumn id = columnList.get(0);
Assertions.assertEquals(dialectProperties.toCase("id"), id.getName(), "Query table structure failed");
Assertions.assertEquals("Primary key auto-increment", id.getComment(), "Query table structure failed");
Assertions.assertTrue(id.getAutoIncrement(), "Query table structure failed");
Assertions.assertTrue(id.getPrimaryKey(), "Query table structure failed");
TableColumn string = columnList.get(3);
Assertions.assertEquals(dialectProperties.toCase("string"), string.getName(), "Query table structure failed");
Assertions.assertEquals("DATA", TestUtils.unWrapperDefaultValue(string.getDefaultValue()),
"Query table structure failed");
List<TableIndex> tableIndexList = tableService.queryIndexes(tableQueryParam);
Assertions.assertEquals(4L, tableIndexList.size(), "Query table structure failed");
Map<String, TableIndex> tableIndexMap = EasyCollectionUtils.toIdentityMap(tableIndexList,
TableIndex::getName);
TableIndex idxDate = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_date"));
Assertions.assertEquals("date index", idxDate.getComment(), "Query table structure failed");
Assertions.assertEquals(IndexTypeEnum.NORMAL.getCode(), idxDate.getType(), "Query table structure failed");
Assertions.assertEquals(1L, idxDate.getColumnList().size(), "Query table structure failed");
Assertions.assertEquals(dialectProperties.toCase("date"), idxDate.getColumnList().get(0).getColumnName(),
"Query table structure failed");
Assertions.assertEquals(CollationEnum.DESC.getCode(), idxDate.getColumnList().get(0).getCollation(),
"Query table structure failed");
TableIndex ukNumber = tableIndexMap.get(dialectProperties.toCase(tableName + "_uk_number"));
Assertions.assertEquals("unique index", ukNumber.getComment(), "Query table structure failed");
Assertions.assertEquals(IndexTypeEnum.UNIQUE.getCode(), ukNumber.getType(), "Query table structure failed");
TableIndex idxNumberString = tableIndexMap.get(dialectProperties.toCase(tableName + "_idx_number_string"));
Assertions.assertEquals(2, idxNumberString.getColumnList().size(), "Query table structure failed");
}
@Test
@Order(Integer.MAX_VALUE)
public void dropTable() {
for (DialectProperties dialectProperties : dialectPropertiesList) {
try {
String dbTypeEnum = dialectProperties.getDbType();
Long dataSourceId = TestUtils.nextLong();
Long consoleId = TestUtils.nextLong();
DataSourcePreConnectParam dataSourceCreateParam = new DataSourcePreConnectParam();
dataSourceCreateParam.setType(dbTypeEnum);
dataSourceCreateParam.setUrl(dialectProperties.getUrl());
dataSourceCreateParam.setUser(dialectProperties.getUsername());
dataSourceCreateParam.setPassword(dialectProperties.getPassword());
dataSourceService.preConnect(dataSourceCreateParam);
ConsoleConnectParam consoleCreateParam = new ConsoleConnectParam();
consoleCreateParam.setDataSourceId(dataSourceId);
consoleCreateParam.setConsoleId(consoleId);
consoleCreateParam.setDatabaseName(dialectProperties.getDatabaseName());
consoleService.createConsole(consoleCreateParam);
DlExecuteParam templateQueryParam = new DlExecuteParam();
templateQueryParam.setConsoleId(consoleId);
templateQueryParam.setDataSourceId(dataSourceId);
templateQueryParam.setSql(dialectProperties.getDropTableSql(TABLE_NAME));
dlTemplateService.execute(templateQueryParam);
} catch (Exception e) {
log.warn("Failed to delete table structure.", e);
}
}
}
}
| tablePageQueryParam | java |
package javax.swing.plaf.metal;
import javax.swing.plaf.basic.BasicSliderUI;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Color;
import java.beans.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class MetalSliderUI extends BasicSliderUI {
protected final int TICK_BUFFER = 4;
protected boolean filledSlider = false;
protected static Color thumbColor;
protected static Color highlightColor;
protected static Color darkShadowColor;
protected static int trackWidth;
protected static int tickLength;
private int safeLength;
protected static Icon horizThumbIcon;
protected static Icon vertThumbIcon;
protected final String SLIDER_FILL = "JSlider.isFilled";
public static ComponentUI createUI(JComponent c) {
return new MetalSliderUI();
}
public MetalSliderUI() {
super( null );
}
private static Icon getHorizThumbIcon() {
return horizThumbIcon;
}
private static Icon getVertThumbIcon() {
return vertThumbIcon;
}
public void installUI( JComponent c ) {
trackWidth = ((Integer)UIManager.get( "Slider.trackWidth" )).intValue();
tickLength = safeLength = ((Integer)UIManager.get( "Slider.majorTickLength" )).intValue();
horizThumbIcon = UIManager.getIcon( "Slider.horizontalThumbIcon" );
vertThumbIcon = UIManager.getIcon( "Slider.verticalThumbIcon" );
super.installUI( c );
thumbColor = UIManager.getColor("Slider.thumb");
highlightColor = UIManager.getColor("Slider.highlight");
darkShadowColor = UIManager.getColor("Slider.darkShadow");
scrollListener.setScrollByBlock( false );
prepareFilledSliderField();
}
protected PropertyChangeListener createPropertyChangeListener( JSlider slider ) {
return new MetalPropertyListener();
}
protected class MetalPropertyListener extends BasicSliderUI.PropertyChangeHandler {
protected MetalPropertyListener() {}
public void propertyChange( PropertyChangeEvent e ) {
super.propertyChange( e );
if (e.getPropertyName().equals(SLIDER_FILL)) {
prepareFilledSliderField();
}
}
}
private void prepareFilledSliderField() {
filledSlider = MetalLookAndFeel.usingOcean();
Object sliderFillProp = slider.getClientProperty(SLIDER_FILL);
if (sliderFillProp != null) {
filledSlider = ((Boolean) sliderFillProp).booleanValue();
}
}
public void paintThumb(Graphics g) {
Rectangle knobBounds = thumbRect;
g.translate( knobBounds.x, knobBounds.y );
if ( slider.getOrientation() == JSlider.HORIZONTAL ) {
getHorizThumbIcon().paintIcon( slider, g, 0, 0 );
}
else {
getVertThumbIcon().paintIcon( slider, g, 0, 0 );
}
g.translate( -knobBounds.x, -knobBounds.y );
}
private Rectangle getPaintTrackRect() {
int trackLeft = 0, trackRight, trackTop = 0, trackBottom;
if (slider.getOrientation() == JSlider.HORIZONTAL) {
trackBottom = (trackRect.height - 1) - getThumbOverhang();
trackTop = trackBottom - (getTrackWidth() - 1);
trackRight = trackRect.width - 1;
}
else {
if (MetalUtils.isLeftToRight(slider)) {
trackLeft = (trackRect.width - getThumbOverhang()) -
getTrackWidth();
trackRight = (trackRect.width - getThumbOverhang()) - 1;
}
else {
trackLeft = getThumbOverhang();
trackRight = getThumbOverhang() + getTrackWidth() - 1;
}
trackBottom = trackRect.height - 1;
}
return new Rectangle(trackRect.x + trackLeft, trackRect.y + trackTop,
trackRight - trackLeft, trackBottom - trackTop);
}
public void paintTrack(Graphics g) {
if (MetalLookAndFeel.usingOcean()) {
oceanPaintTrack(g);
return;
}
Color trackColor = !slider.isEnabled() ? MetalLookAndFeel.getControlShadow() :
slider.getForeground();
boolean leftToRight = MetalUtils.isLeftToRight(slider);
g.translate( trackRect.x, trackRect.y );
int trackLeft = 0;
int trackTop = 0;
int trackRight;
int trackBottom;
if ( slider.getOrientation() == JSlider.HORIZONTAL ) {
trackBottom = (trackRect.height - 1) - getThumbOverhang();
trackTop = trackBottom - (getTrackWidth() - 1);
trackRight = trackRect.width - 1;
}
else {
if (leftToRight) {
trackLeft = (trackRect.width - getThumbOverhang()) -
getTrackWidth();
trackRight = (trackRect.width - getThumbOverhang()) - 1;
}
else {
trackLeft = getThumbOverhang();
trackRight = getThumbOverhang() + getTrackWidth() - 1;
}
trackBottom = trackRect.height - 1;
}
if ( slider.isEnabled() ) {
g.setColor( MetalLookAndFeel.getControlDarkShadow() );
g.drawRect( trackLeft, trackTop,
(trackRight - trackLeft) - 1, (trackBottom - trackTop) - 1 );
g.setColor( MetalLookAndFeel.getControlHighlight() );
g.drawLine( trackLeft + 1, trackBottom, trackRight, trackBottom );
g.drawLine( trackRight, trackTop + 1, trackRight, trackBottom );
g.setColor( MetalLookAndFeel.getControlShadow() );
g.drawLine( trackLeft + 1, trackTop + 1, trackRight - 2, trackTop + 1 );
g.drawLine( trackLeft + 1, trackTop + 1, trackLeft + 1, trackBottom - 2 );
}
else {
g.setColor( MetalLookAndFeel.getControlShadow() );
g.drawRect( trackLeft, trackTop,
(trackRight - trackLeft) - 1, (trackBottom - trackTop) - 1 );
}
if ( filledSlider ) {
int middleOfThumb;
int fillTop;
int fillLeft;
int fillBottom;
int fillRight;
if ( slider.getOrientation() == JSlider.HORIZONTAL ) {
middleOfThumb = thumbRect.x + (thumbRect.width / 2);
middleOfThumb -= trackRect.x;
fillTop = !slider.isEnabled() ? trackTop : trackTop + 1;
fillBottom = !slider.isEnabled() ? trackBottom - 1 : trackBottom - 2;
if ( !drawInverted() ) {
fillLeft = !slider.isEnabled() ? trackLeft : trackLeft + 1;
fillRight = middleOfThumb;
}
else {
fillLeft = middleOfThumb;
fillRight = !slider.isEnabled() ? trackRight - 1 : trackRight - 2;
}
}
else {
middleOfThumb = thumbRect.y + (thumbRect.height / 2);
middleOfThumb -= trackRect.y;
fillLeft = !slider.isEnabled() ? trackLeft : trackLeft + 1;
fillRight = !slider.isEnabled() ? trackRight - 1 : trackRight - 2;
if ( !drawInverted() ) {
fillTop = middleOfThumb;
fillBottom = !slider.isEnabled() ? trackBottom - 1 : trackBottom - 2;
}
else {
fillTop = !slider.isEnabled() ? trackTop : trackTop + 1;
fillBottom = middleOfThumb;
}
}
if ( slider.isEnabled() ) {
g.setColor( slider.getBackground() );
g.drawLine( fillLeft, fillTop, fillRight, fillTop );
g.drawLine( fillLeft, fillTop, fillLeft, fillBottom );
g.setColor( MetalLookAndFeel.getControlShadow() );
g.fillRect( fillLeft + 1, fillTop + 1,
fillRight - fillLeft, fillBottom - fillTop );
}
else {
g.setColor( MetalLookAndFeel.getControlShadow() );
g.fillRect(fillLeft, fillTop, fillRight - fillLeft, fillBottom - fillTop);
}
}
g.translate( -trackRect.x, -trackRect.y );
}
private void oceanPaintTrack(Graphics g) {
boolean leftToRight = MetalUtils.isLeftToRight(slider);
boolean drawInverted = drawInverted();
Color sliderAltTrackColor = (Color)UIManager.get(
"Slider.altTrackColor");
Rectangle paintRect = getPaintTrackRect();
g.translate(paintRect.x, paintRect.y);
int w = paintRect.width;
int h = paintRect.height;
if (slider.getOrientation() == JSlider.HORIZONTAL) {
int middleOfThumb = thumbRect.x + thumbRect.width / 2 - paintRect.x;
if (slider.isEnabled()) {
int fillMinX;
int fillMaxX;
if (middleOfThumb > 0) {
g.setColor(drawInverted ? MetalLookAndFeel.getControlDarkShadow() :
MetalLookAndFeel.getPrimaryControlDarkShadow());
g.drawRect(0, 0, middleOfThumb - 1, h - 1);
}
if (middleOfThumb < w) {
g.setColor(drawInverted ? MetalLookAndFeel.getPrimaryControlDarkShadow() :
MetalLookAndFeel.getControlDarkShadow());
g.drawRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1);
}
if (filledSlider) {
g.setColor(MetalLookAndFeel.getPrimaryControlShadow());
if (drawInverted) {
fillMinX = middleOfThumb;
fillMaxX = w - 2;
g.drawLine(1, 1, middleOfThumb, 1);
} else {
fillMinX = 1;
fillMaxX = middleOfThumb;
g.drawLine(middleOfThumb, 1, w - 1, 1);
}
if (h == 6) {
g.setColor(MetalLookAndFeel.getWhite());
g.drawLine(fillMinX, 1, fillMaxX, 1);
g.setColor(sliderAltTrackColor);
g.drawLine(fillMinX, 2, fillMaxX, 2);
g.setColor(MetalLookAndFeel.getControlShadow());
g.drawLine(fillMinX, 3, fillMaxX, 3);
g.setColor(MetalLookAndFeel.getPrimaryControlShadow());
g.drawLine(fillMinX, 4, fillMaxX, 4);
}
}
} else {
g.setColor(MetalLookAndFeel.getControlShadow());
if (middleOfThumb > 0) {
if (!drawInverted && filledSlider) {
g.fillRect(0, 0, middleOfThumb - 1, h - 1);
} else {
g.drawRect(0, 0, middleOfThumb - 1, h - 1);
}
}
if (middleOfThumb < w) {
if (drawInverted && filledSlider) {
g.fillRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1);
} else {
g.drawRect(middleOfThumb, 0, w - middleOfThumb - 1, h - 1);
}
}
}
} else {
int middleOfThumb = thumbRect.y + (thumbRect.height / 2) - paintRect.y;
if (slider.isEnabled()) {
int fillMinY;
int fillMaxY;
if (middleOfThumb > 0) {
g.setColor(drawInverted ? MetalLookAndFeel.getPrimaryControlDarkShadow() :
MetalLookAndFeel.getControlDarkShadow());
g.drawRect(0, 0, w - 1, middleOfThumb - 1);
}
if (middleOfThumb < h) {
g.setColor(drawInverted ? MetalLookAndFeel.getControlDarkShadow() :
MetalLookAndFeel.getPrimaryControlDarkShadow());
g.drawRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1);
}
if (filledSlider) {
g.setColor(MetalLookAndFeel.getPrimaryControlShadow());
if (drawInverted()) {
fillMinY = 1;
fillMaxY = middleOfThumb;
if (leftToRight) {
g.drawLine(1, middleOfThumb, 1, h - 1);
} else {
g.drawLine(w - 2, middleOfThumb, w - 2, h - 1);
}
} else {
fillMinY = middleOfThumb;
fillMaxY = h - 2;
if (leftToRight) {
g.drawLine(1, 1, 1, middleOfThumb);
} else {
g.drawLine(w - 2, 1, w - 2, middleOfThumb);
}
}
if (w == 6) {
g.setColor(leftToRight ? MetalLookAndFeel.getWhite() : MetalLookAndFeel.getPrimaryControlShadow());
g.drawLine(1, fillMinY, 1, fillMaxY);
g.setColor(leftToRight ? sliderAltTrackColor : MetalLookAndFeel.getControlShadow());
g.drawLine(2, fillMinY, 2, fillMaxY);
g.setColor(leftToRight ? MetalLookAndFeel.getControlShadow() : sliderAltTrackColor);
g.drawLine(3, fillMinY, 3, fillMaxY);
g.setColor(leftToRight ? MetalLookAndFeel.getPrimaryControlShadow() : MetalLookAndFeel.getWhite());
g.drawLine(4, fillMinY, 4, fillMaxY);
}
}
} else {
g.setColor(MetalLookAndFeel.getControlShadow());
if (middleOfThumb > 0) {
if (drawInverted && filledSlider) {
g.fillRect(0, 0, w - 1, middleOfThumb - 1);
} else {
g.drawRect(0, 0, w - 1, middleOfThumb - 1);
}
}
if (middleOfThumb < h) {
if (!drawInverted && filledSlider) {
g.fillRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1);
} else {
g.drawRect(0, middleOfThumb, w - 1, h - middleOfThumb - 1);
}
}
}
}
g.translate(-paintRect.x, -paintRect.y);
}
public void paintFocus(Graphics g) {
}
protected Dimension getThumbSize() {
Dimension size = new Dimension();
if ( slider.getOrientation() == JSlider.VERTICAL ) {
size.width = getVertThumbIcon().getIconWidth();
size.height = getVertThumbIcon().getIconHeight();
}
else {
size.width = getHorizThumbIcon().getIconWidth();
size.height = getHorizThumbIcon().getIconHeight();
}
return size;
}
public int getTickLength() {
return slider.getOrientation() == JSlider.HORIZONTAL ? safeLength + TICK_BUFFER + 1 :
safeLength + TICK_BUFFER + 3;
}
protected int getTrackWidth() {
final double kIdealTrackWidth = 7.0;
final double kIdealThumbHeight = 16.0;
final double kWidthScalar = kIdealTrackWidth / kIdealThumbHeight;
if ( slider.getOrientation() == JSlider.HORIZONTAL ) {
return (int)(kWidthScalar * thumbRect.height);
}
else {
return (int)(kWidthScalar * thumbRect.width);
}
}
protected int getTrackLength() {
if ( slider.getOrientation() == JSlider.HORIZONTAL ) {
return trackRect.width;
}
return trackRect.height;
}
protected int getThumbOverhang() {
return (int)(getThumbSize().getHeight()-getTrackWidth())/2;
}
protected void scrollDueToClickInTrack( int dir ) {
scrollByUnit( dir );
}
protected void paintMinorTickForHorizSlider( Graphics g, Rectangle [MASK] , int x ) {
g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() );
g.drawLine( x, TICK_BUFFER, x, TICK_BUFFER + (safeLength / 2) );
}
protected void paintMajorTickForHorizSlider( Graphics g, Rectangle [MASK] , int x ) {
g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() );
g.drawLine( x, TICK_BUFFER , x, TICK_BUFFER + (safeLength - 1) );
}
protected void paintMinorTickForVertSlider( Graphics g, Rectangle [MASK] , int y ) {
g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() );
if (MetalUtils.isLeftToRight(slider)) {
g.drawLine( TICK_BUFFER, y, TICK_BUFFER + (safeLength / 2), y );
}
else {
g.drawLine( 0, y, safeLength/2, y );
}
}
protected void paintMajorTickForVertSlider( Graphics g, Rectangle [MASK] , int y ) {
g.setColor( slider.isEnabled() ? slider.getForeground() : MetalLookAndFeel.getControlShadow() );
if (MetalUtils.isLeftToRight(slider)) {
g.drawLine( TICK_BUFFER, y, TICK_BUFFER + safeLength, y );
}
else {
g.drawLine( 0, y, safeLength, y );
}
}
}
| tickBounds | java |
package org.keycloak.protocol.oidc;
import org.keycloak.OAuth2Constants;
import org.keycloak.authentication.ClientAuthenticator;
import org.keycloak.authentication.ClientAuthenticatorFactory;
import org.keycloak.authentication.authenticators.util.LoAUtil;
import org.keycloak.common.Profile;
import org.keycloak.crypto.CekManagementProvider;
import org.keycloak.crypto.ClientSignatureVerifierProvider;
import org.keycloak.crypto.ContentEncryptionProvider;
import org.keycloak.crypto.SignatureProvider;
import org.keycloak.jose.jws.Algorithm;
import org.keycloak.models.CibaConfig;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint;
import org.keycloak.protocol.oidc.endpoints.TokenEndpoint;
import org.keycloak.protocol.oidc.grants.PreAuthorizedCodeGrantType;
import org.keycloak.protocol.oidc.grants.PreAuthorizedCodeGrantTypeFactory;
import org.keycloak.protocol.oidc.grants.ciba.CibaGrantType;
import org.keycloak.protocol.oidc.grants.device.endpoints.DeviceEndpoint;
import org.keycloak.protocol.oidc.par.endpoints.ParEndpoint;
import org.keycloak.protocol.oidc.representations.MTLSEndpointAliases;
import org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation;
import org.keycloak.protocol.oidc.utils.AcrUtils;
import org.keycloak.protocol.oidc.utils.OIDCResponseType;
import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.representations.IDToken;
import org.keycloak.services.Urls;
import org.keycloak.services.clientregistration.ClientRegistrationService;
import org.keycloak.services.clientregistration.oidc.OIDCClientRegistrationProviderFactory;
import org.keycloak.services.resources.RealmsResource;
import org.keycloak.services.util.DPoPUtil;
import org.keycloak.urls.UrlType;
import org.keycloak.util.JsonSerialization;
import org.keycloak.wellknown.WellKnownProvider;
import jakarta.ws.rs.core.UriBuilder;
import jakarta.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class OIDCWellKnownProvider implements WellKnownProvider {
public final List<String> DEFAULT_GRANT_TYPES_SUPPORTED;
public static final List<String> DEFAULT_RESPONSE_TYPES_SUPPORTED = list(OAuth2Constants.CODE, OIDCResponseType.NONE, OIDCResponseType.ID_TOKEN, OIDCResponseType.TOKEN, "id_token token", "code id_token", "code token", "code id_token token");
public static final List<String> DEFAULT_SUBJECT_TYPES_SUPPORTED = list("public", "pairwise");
public static final List<String> DEFAULT_RESPONSE_MODES_SUPPORTED = list("query", "fragment", "form_post", "query.jwt", "fragment.jwt", "form_post.jwt", "jwt");
public static final List<String> DEFAULT_CLIENT_AUTH_SIGNING_ALG_VALUES_SUPPORTED = list(Algorithm.RS256.toString());
public static final List<String> DEFAULT_CLAIMS_SUPPORTED = list("aud", "sub", "iss", IDToken.AUTH_TIME, IDToken.NAME, IDToken.GIVEN_NAME, IDToken.FAMILY_NAME, IDToken.PREFERRED_USERNAME, IDToken.EMAIL, IDToken.ACR);
public static final List<String> DEFAULT_CLAIM_TYPES_SUPPORTED = list("normal");
public static final List<String> DEFAULT_CODE_CHALLENGE_METHODS_SUPPORTED = list(OAuth2Constants.PKCE_METHOD_PLAIN, OAuth2Constants.PKCE_METHOD_S256);
public static final List<String> DEFAULT_PROMPT_VALUES_SUPPORTED = list(OIDCLoginProtocol.PROMPT_VALUE_NONE , OIDCLoginProtocol.PROMPT_VALUE_LOGIN, OIDCLoginProtocol.PROMPT_VALUE_CONSENT);
private final KeycloakSession session;
private final Map<String, Object> openidConfigOverride;
private final boolean includeClientScopes;
public OIDCWellKnownProvider(KeycloakSession session) {
this(session, null, true);
}
public OIDCWellKnownProvider(KeycloakSession session, Map<String, Object> openidConfigOverride, boolean includeClientScopes) {
DEFAULT_GRANT_TYPES_SUPPORTED = Stream.of(OAuth2Constants.AUTHORIZATION_CODE,
OAuth2Constants.IMPLICIT, OAuth2Constants.REFRESH_TOKEN, OAuth2Constants.PASSWORD, OAuth2Constants.CLIENT_CREDENTIALS,
OAuth2Constants.CIBA_GRANT_TYPE).collect(Collectors.toList());
if (Profile.isFeatureEnabled(Profile.Feature.TOKEN_EXCHANGE)) {
DEFAULT_GRANT_TYPES_SUPPORTED.add(OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE);
}
if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) {
DEFAULT_GRANT_TYPES_SUPPORTED.add(OAuth2Constants.DEVICE_CODE_GRANT_TYPE);
}
if (Profile.isFeatureEnabled(Profile.Feature.OID4VC_VCI)) {
DEFAULT_GRANT_TYPES_SUPPORTED.add(PreAuthorizedCodeGrantTypeFactory.GRANT_TYPE);
}
this.session = session;
this.openidConfigOverride = openidConfigOverride;
this.includeClientScopes = includeClientScopes;
}
@Override
public Object getConfig() {
UriInfo frontendUriInfo = session.getContext().getUri(UrlType.FRONTEND);
UriInfo backendUriInfo = session.getContext().getUri(UrlType.BACKEND);
RealmModel realm = session.getContext().getRealm();
UriBuilder frontendUriBuilder = RealmsResource.protocolUrl(frontendUriInfo);
UriBuilder backendUriBuilder = RealmsResource.protocolUrl(backendUriInfo);
OIDCConfigurationRepresentation config = new OIDCConfigurationRepresentation();
config.setIssuer(Urls.realmIssuer(frontendUriInfo.getBaseUri(), realm.getName()));
config.setAuthorizationEndpoint(frontendUriBuilder.clone().path(OIDCLoginProtocolService.class, "auth").build(realm.getName(), OIDCLoginProtocol.LOGIN_PROTOCOL).toString());
config.setTokenEndpoint(backendUriBuilder.clone().path(OIDCLoginProtocolService.class, "token").build(realm.getName(), OIDCLoginProtocol.LOGIN_PROTOCOL).toString());
config.setIntrospectionEndpoint(backendUriBuilder.clone().path(OIDCLoginProtocolService.class, "token").path(TokenEndpoint.class, "introspect").build(realm.getName(), OIDCLoginProtocol.LOGIN_PROTOCOL).toString());
config.setUserinfoEndpoint(backendUriBuilder.clone().path(OIDCLoginProtocolService.class, "issueUserInfo").build(realm.getName(), OIDCLoginProtocol.LOGIN_PROTOCOL).toString());
config.setLogoutEndpoint(frontendUriBuilder.clone().path(OIDCLoginProtocolService.class, "logout").build(realm.getName(), OIDCLoginProtocol.LOGIN_PROTOCOL).toString());
if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) {
config.setDeviceAuthorizationEndpoint(frontendUriBuilder.clone().path(OIDCLoginProtocolService.class, "auth")
.path(AuthorizationEndpoint.class, "authorizeDevice").path(DeviceEndpoint.class, "handleDeviceRequest")
.build(realm.getName(), OIDCLoginProtocol.LOGIN_PROTOCOL).toString());
}
URI jwksUri = backendUriBuilder.clone().path(OIDCLoginProtocolService.class, "certs").build(realm.getName(),
OIDCLoginProtocol.LOGIN_PROTOCOL);
config.setJwksUri(jwksUri.toString());
config.setCheckSessionIframe(frontendUriBuilder.clone().path(OIDCLoginProtocolService.class, "getLoginStatusIframe").build(realm.getName(), OIDCLoginProtocol.LOGIN_PROTOCOL).toString());
config.setRegistrationEndpoint(RealmsResource.clientRegistrationUrl(backendUriInfo).path(ClientRegistrationService.class, "provider").build(realm.getName(), OIDCClientRegistrationProviderFactory.ID).toString());
config.setIdTokenSigningAlgValuesSupported(getSupportedSigningAlgorithms(false));
config.setIdTokenEncryptionAlgValuesSupported(getSupportedEncryptionAlg(false));
config.setIdTokenEncryptionEncValuesSupported(getSupportedEncryptionEnc(false));
config.setUserInfoSigningAlgValuesSupported(getSupportedSigningAlgorithms(true));
config.setUserInfoEncryptionAlgValuesSupported(getSupportedEncryptionAlgorithms());
config.setUserInfoEncryptionEncValuesSupported(getSupportedContentEncryptionAlgorithms());
config.setRequestObjectSigningAlgValuesSupported(getSupportedClientSigningAlgorithms(true));
config.setRequestObjectEncryptionAlgValuesSupported(getSupportedEncryptionAlgorithms());
config.setRequestObjectEncryptionEncValuesSupported(getSupportedContentEncryptionAlgorithms());
config.setResponseTypesSupported(DEFAULT_RESPONSE_TYPES_SUPPORTED);
config.setSubjectTypesSupported(DEFAULT_SUBJECT_TYPES_SUPPORTED);
config.setResponseModesSupported(DEFAULT_RESPONSE_MODES_SUPPORTED);
config.setGrantTypesSupported(DEFAULT_GRANT_TYPES_SUPPORTED);
config.setAcrValuesSupported(getAcrValuesSupported(realm));
config.setPromptValuesSupported(getPromptValuesSupported(realm));
config.setTokenEndpointAuthMethodsSupported(getClientAuthMethodsSupported());
config.setTokenEndpointAuthSigningAlgValuesSupported(getSupportedClientSigningAlgorithms(false));
config.setIntrospectionEndpointAuthMethodsSupported(getClientAuthMethodsSupported());
config.setIntrospectionEndpointAuthSigningAlgValuesSupported(getSupportedClientSigningAlgorithms(false));
config.setAuthorizationSigningAlgValuesSupported(getSupportedSigningAlgorithms(false));
config.setAuthorizationEncryptionAlgValuesSupported(getSupportedEncryptionAlg(false));
config.setAuthorizationEncryptionEncValuesSupported(getSupportedEncryptionEnc(false));
config.setClaimsSupported(DEFAULT_CLAIMS_SUPPORTED);
config.setClaimTypesSupported(DEFAULT_CLAIM_TYPES_SUPPORTED);
config.setClaimsParameterSupported(true);
if (includeClientScopes) {
List<String> scopeNames = realm.getClientScopesStream()
.filter(clientScope -> Objects.equals(OIDCLoginProtocol.LOGIN_PROTOCOL, clientScope.getProtocol()))
.map(ClientScopeModel::getName)
.collect(Collectors.toList());
if (!scopeNames.contains(OAuth2Constants.SCOPE_OPENID)) {
scopeNames.add(0, OAuth2Constants.SCOPE_OPENID);
}
config.setScopesSupported(scopeNames);
}
config.setRequestParameterSupported(true);
config.setRequestUriParameterSupported(true);
config.setRequireRequestUriRegistration(true);
config.setCodeChallengeMethodsSupported(DEFAULT_CODE_CHALLENGE_METHODS_SUPPORTED);
config.setTlsClientCertificateBoundAccessTokens(true);
if (Profile.isFeatureEnabled(Profile.Feature.DPOP)) {
config.setDpopSigningAlgValuesSupported(new ArrayList<>(DPoPUtil.DPOP_SUPPORTED_ALGS));
}
URI revocationEndpoint = frontendUriBuilder.clone().path(OIDCLoginProtocolService.class, "revoke")
.build(realm.getName(), OIDCLoginProtocol.LOGIN_PROTOCOL);
config.setRevocationEndpoint(revocationEndpoint.toString());
config.setRevocationEndpointAuthMethodsSupported(getClientAuthMethodsSupported());
config.setRevocationEndpointAuthSigningAlgValuesSupported(getSupportedClientSigningAlgorithms(false));
config.setBackchannelLogoutSupported(true);
config.setBackchannelLogoutSessionSupported(true);
config.setBackchannelTokenDeliveryModesSupported(CibaConfig.CIBA_SUPPORTED_MODES);
config.setBackchannelAuthenticationEndpoint(CibaGrantType.authorizationUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString());
config.setBackchannelAuthenticationRequestSigningAlgValuesSupported(getSupportedBackchannelAuthenticationRequestSigningAlgorithms());
config.setPushedAuthorizationRequestEndpoint(ParEndpoint.parUrl(backendUriInfo.getBaseUriBuilder()).build(realm.getName()).toString());
config.setRequirePushedAuthorizationRequests(Boolean.FALSE);
MTLSEndpointAliases mtlsEndpointAliases = getMtlsEndpointAliases(config);
config.setMtlsEndpointAliases(mtlsEndpointAliases);
config.setAuthorizationResponseIssParameterSupported(true);
config = checkConfigOverride(config);
return config;
}
protected List<String> getPromptValuesSupported(RealmModel realm) {
List<String> prompts = new ArrayList<>(DEFAULT_PROMPT_VALUES_SUPPORTED);
if (realm.isRegistrationAllowed()) {
prompts.add(OIDCLoginProtocol.PROMPT_VALUE_CREATE);
}
return prompts;
}
@Override
public void close() {
}
private static List<String> list(String... values) {
return Arrays.asList(values);
}
private List<String> getClientAuthMethodsSupported() {
return session.getKeycloakSessionFactory().getProviderFactoriesStream(ClientAuthenticator.class)
.map(ClientAuthenticatorFactory.class::cast)
.map(caf -> caf.getProtocolAuthenticatorMethods(OIDCLoginProtocol.LOGIN_PROTOCOL))
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
private List<String> getSupportedAlgorithms(Class<? extends Provider> clazz, boolean includeNone) {
Stream<String> supportedAlgorithms = session.getKeycloakSessionFactory().getProviderFactoriesStream(clazz)
.map(ProviderFactory::getId);
if (includeNone) {
supportedAlgorithms = Stream.concat(supportedAlgorithms, Stream.of("none"));
}
return supportedAlgorithms.collect(Collectors.toList());
}
private List<String> getSupportedAsymmetricAlgorithms() {
return getSupportedAlgorithms(SignatureProvider.class, false).stream()
.map(algorithm -> new AbstractMap.SimpleEntry<>(algorithm, session.getProvider(SignatureProvider.class, algorithm)))
.filter(entry -> entry.getValue() != null)
.filter(entry -> entry.getValue().isAsymmetricAlgorithm())
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
private List<String> getSupportedSigningAlgorithms(boolean includeNone) {
return getSupportedAlgorithms(SignatureProvider.class, includeNone);
}
private List<String> getSupportedClientSigningAlgorithms(boolean includeNone) {
return getSupportedAlgorithms(ClientSignatureVerifierProvider.class, includeNone);
}
private List<String> getSupportedContentEncryptionAlgorithms() {
return getSupportedAlgorithms(ContentEncryptionProvider.class, false);
}
private List<String> getAcrValuesSupported(RealmModel realm) {
Map<String, Integer> realmAcrLoaMap = AcrUtils.getAcrLoaMap(realm);
List<String> result = new ArrayList<>(realmAcrLoaMap.keySet());
result.addAll(LoAUtil.getLoAConfiguredInRealmBrowserFlow(realm)
.map(String::valueOf)
.collect(Collectors.toList()));
return result;
}
private List<String> getSupportedEncryptionAlgorithms() {
return getSupportedAlgorithms(CekManagementProvider.class, false);
}
private List<String> getSupportedBackchannelAuthenticationRequestSigningAlgorithms() {
return getSupportedAsymmetricAlgorithms();
}
private List<String> getSupportedEncryptionAlg(boolean includeNone) {
return getSupportedAlgorithms(CekManagementProvider.class, includeNone);
}
private List<String> getSupportedEncryptionEnc(boolean includeNone) {
return getSupportedAlgorithms(ContentEncryptionProvider.class, includeNone);
}
protected MTLSEndpointAliases getMtlsEndpointAliases(OIDCConfigurationRepresentation config) {
MTLSEndpointAliases [MASK] = new MTLSEndpointAliases();
[MASK] .setTokenEndpoint(config.getTokenEndpoint());
[MASK] .setRevocationEndpoint(config.getRevocationEndpoint());
[MASK] .setIntrospectionEndpoint(config.getIntrospectionEndpoint());
if (Profile.isFeatureEnabled(Profile.Feature.DEVICE_FLOW)) {
[MASK] .setDeviceAuthorizationEndpoint(config.getDeviceAuthorizationEndpoint());
}
[MASK] .setRegistrationEndpoint(config.getRegistrationEndpoint());
[MASK] .setUserInfoEndpoint(config.getUserinfoEndpoint());
[MASK] .setBackchannelAuthenticationEndpoint(config.getBackchannelAuthenticationEndpoint());
[MASK] .setPushedAuthorizationRequestEndpoint(config.getPushedAuthorizationRequestEndpoint());
return [MASK] ;
}
private OIDCConfigurationRepresentation checkConfigOverride(OIDCConfigurationRepresentation config) {
if (openidConfigOverride != null) {
Map<String, Object> asMap = JsonSerialization.mapper.convertValue(config, Map.class);
asMap.putAll(openidConfigOverride);
return JsonSerialization.mapper.convertValue(asMap, OIDCConfigurationRepresentation.class);
} else {
return config;
}
}
}
| mtls_endpoints | java |
package cn.binarywang.wx.miniapp.api;
import cn.binarywang.wx.miniapp.bean.WxMaApiResponse;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.executor.ApiSignaturePostRequestExecutor;
import com.google.gson.JsonObject;
import java.util.Map;
import java.util.function.Function;
import me.chanjar.weixin.common.error. [MASK] ;
import me.chanjar.weixin.common.service.WxImgProcService;
import me.chanjar.weixin.common.service.WxOcrService;
import me.chanjar.weixin.common.service.WxService;
import me.chanjar.weixin.common.util.http.MediaUploadRequestExecutor;
import me.chanjar.weixin.common.util.http.RequestExecutor;
import me.chanjar.weixin.common.util.http.RequestHttp;
public interface WxMaService extends WxService {
String GET_ACCESS_TOKEN_URL =
"https:
String GET_STABLE_ACCESS_TOKEN = "https:
String JSCODE_TO_SESSION_URL = "https:
String GET_PAID_UNION_ID_URL = "https:
String SET_DYNAMIC_DATA_URL = "https:
WxMaJscode2SessionResult jsCode2SessionInfo(String jsCode) throws [MASK] ;
void setDynamicData(int lifespan, String type, int scene, String data) throws [MASK] ;
boolean checkSignature(String timestamp, String nonce, String signature);
String getAccessToken() throws [MASK] ;
String getAccessToken(boolean forceRefresh) throws [MASK] ;
String getPaidUnionId(String openid, String transactionId, String mchId, String outTradeNo)
throws [MASK] ;
<T, E> T execute(RequestExecutor<T, E> executor, String uri, E data) throws [MASK] ;
WxMaApiResponse execute(
ApiSignaturePostRequestExecutor executor,
String uri,
Map<String, String> headers,
String data)
throws [MASK] ;
void setRetrySleepMillis(int retrySleepMillis);
void setMaxRetryTimes(int maxRetryTimes);
WxMaConfig getWxMaConfig();
void setWxMaConfig(WxMaConfig maConfig);
void addConfig(String miniappId, WxMaConfig configStorage);
void removeConfig(String miniappId);
void setMultiConfigs(Map<String, WxMaConfig> configs);
void setMultiConfigs(Map<String, WxMaConfig> configs, String defaultMiniappId);
boolean switchover(String mpId);
WxMaService switchoverTo(String miniAppId);
WxMaService switchoverTo(String miniAppId, Function<String, WxMaConfig> func);
WxMaMsgService getMsgService();
WxMaMediaService getMediaService();
WxMaUserService getUserService();
WxMaQrcodeService getQrcodeService();
WxMaSchemeService getWxMaSchemeService();
WxMaSubscribeService getSubscribeService();
WxMaAnalysisService getAnalysisService();
WxMaCodeService getCodeService();
WxMaJsapiService getJsapiService();
WxMaSettingService getSettingService();
WxMaShareService getShareService();
WxMaRunService getRunService();
WxMaSecurityService getSecurityService();
WxMaPluginService getPluginService();
void initHttp();
RequestHttp getRequestHttp();
WxMaExpressService getExpressService();
WxMaCloudService getCloudService();
WxMaInternetService getInternetService();
WxMaLiveService getLiveService();
WxMaLiveGoodsService getLiveGoodsService();
WxMaLiveMemberService getLiveMemberService();
WxOcrService getOcrService();
WxImgProcService getImgProcService();
WxMaShopAfterSaleService getShopAfterSaleService();
WxMaShopDeliveryService getShopDeliveryService();
WxMaShopOrderService getShopOrderService();
WxMaShopSpuService getShopSpuService();
WxMaShopRegisterService getShopRegisterService();
WxMaShopAccountService getShopAccountService();
WxMaShopCatService getShopCatService();
WxMaShopImgService getShopImgService();
WxMaShopAuditService getShopAuditService();
WxMaLinkService getLinkService();
WxMaReimburseInvoiceService getReimburseInvoiceService();
WxMaDeviceSubscribeService getDeviceSubscribeService();
WxMaMarketingService getMarketingService();
WxMaImmediateDeliveryService getWxMaImmediateDeliveryService();
WxMaShopSharerService getShopSharerService();
WxMaProductService getProductService();
WxMaProductOrderService getProductOrderService();
WxMaShopCouponService getWxMaShopCouponService();
WxMaShopPayService getWxMaShopPayService();
WxMaOrderShippingService getWxMaOrderShippingService();
WxMaOrderManagementService getWxMaOrderManagementService();
WxMaOpenApiService getWxMaOpenApiService();
WxMaVodService getWxMaVodService();
WxMaXPayService getWxMaXPayService();
WxMaExpressDeliveryReturnService getWxMaExpressDeliveryReturnService();
WxMaPromotionService getWxMaPromotionService();
String postWithSignature(String url, Object obj) throws [MASK] ;
String postWithSignature(String url, JsonObject jsonObject) throws [MASK] ;
WxMaIntracityService getIntracityService();
}
| WxErrorException | java |
End of preview.
No dataset card yet
- Downloads last month
- 26