src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
FailedMessageStatusHistoryResource implements FailedMessageStatusHistoryClient { @Override public List<StatusHistoryResponse> getStatusHistory(FailedMessageId failedMessageId) { final List<StatusHistoryResponse> statusHistoryResponses = new ArrayList<>(); final List<StatusHistoryEvent> statusHistory = failedMessageDao.getStatusHistory(failedMessageId); for (int i=0; i<statusHistory.size(); i++) { final FailedMessageStatus failedMessageStatus = toFailedMessageStatus(statusHistory.get(i).getStatus()); if (i+1<statusHistory.size() && failedMessageStatus.equals(toFailedMessageStatus(statusHistory.get(i+1).getStatus()))) { i++; } statusHistoryResponses.add(new StatusHistoryResponse(failedMessageStatus, statusHistory.get(i).getEffectiveDateTime())); } return statusHistoryResponses; } FailedMessageStatusHistoryResource(FailedMessageDao failedMessageDao); @Override List<StatusHistoryResponse> getStatusHistory(FailedMessageId failedMessageId); } | @Test public void failedMessageWithStatusHistoryEntries() { when(failedMessageDao.getStatusHistory(FAILED_MESSAGE_ID)).thenReturn(Arrays.asList( new StatusHistoryEvent(StatusHistoryEvent.Status.FAILED, NOW), new StatusHistoryEvent(StatusHistoryEvent.Status.SENT, NOW.plusSeconds(1)) )); assertThat(underTest.getStatusHistory(FAILED_MESSAGE_ID), contains( statusHistoryResponse().withStatus(FAILED).withEffectiveDateTime(NOW), statusHistoryResponse().withStatus(SENT).withEffectiveDateTime(NOW.plusSeconds(1)) )); }
@Test public void responseOnlyContainsASingleEntryWhenFailedAndClassifiedStatusAreConcurrent() { when(failedMessageDao.getStatusHistory(FAILED_MESSAGE_ID)).thenReturn(Arrays.asList( new StatusHistoryEvent(StatusHistoryEvent.Status.FAILED, NOW), new StatusHistoryEvent(StatusHistoryEvent.Status.CLASSIFIED, NOW.plusSeconds(1)) )); assertThat(underTest.getStatusHistory(FAILED_MESSAGE_ID), contains( statusHistoryResponse().withStatus(FAILED).withEffectiveDateTime(NOW.plusSeconds(1)) )); }
@Test public void singleStatusHistoryEntry() { when(failedMessageDao.getStatusHistory(FAILED_MESSAGE_ID)).thenReturn(Collections.singletonList( new StatusHistoryEvent(StatusHistoryEvent.Status.CLASSIFIED, NOW) )); assertThat(underTest.getStatusHistory(FAILED_MESSAGE_ID), contains( statusHistoryResponse().withStatus(FAILED).withEffectiveDateTime(NOW) )); } |
CreateFailedMessageResource implements CreateFailedMessageClient { public void create(CreateFailedMessageRequest failedMessageRequest) { failedMessageDao.insert(failedMessageFactory.create(failedMessageRequest)); } CreateFailedMessageResource(FailedMessageFactory failedMessageFactory, FailedMessageDao failedMessageDao); void create(CreateFailedMessageRequest failedMessageRequest); } | @Test public void createFailedMessage() throws Exception { when(failedMessageFactory.create(request)).thenReturn(failedMessage); underTest.create(request); verify(failedMessageDao).insert(failedMessage); } |
FailedMessageFactory { public FailedMessage create(CreateFailedMessageRequest request) { return FailedMessageBuilder.newFailedMessage() .withFailedMessageId(request.getFailedMessageId()) .withContent(request.getContent()) .withDestination(new Destination(request.getBrokerName(), ofNullable(request.getDestinationName()))) .withFailedDateTime(request.getFailedAt()) .withProperties(request.getProperties()) .withSentDateTime(request.getSentAt()) .withLabels(request.getLabels()) .build(); } FailedMessage create(CreateFailedMessageRequest request); } | @Test public void createFailedMessageFromRequest() throws Exception { FailedMessage failedMessage = underTest.create(newCreateFailedMessageRequest() .withContent("Hello World") .withBrokerName("broker") .withDestinationName("queue") .withFailedDateTime(NOW) .withFailedMessageId(FAILED_MESSAGE_ID) .withProperties(Collections.singletonMap("foo", "bar")) .withSentDateTime(NOW) .build()); assertThat(failedMessage, aFailedMessage() .withContent(equalTo("Hello World")) .withDestination(DestinationMatcher.aDestination().withBrokerName("broker").withName("queue")) .withFailedAt(equalTo(NOW)) .withFailedMessageId(equalTo(FAILED_MESSAGE_ID)) .withProperties(Matchers.hasEntry("foo", "bar")) .withSentAt(equalTo(NOW)) ); } |
FailedMessageSearchResource implements SearchFailedMessageClient { @Override public FailedMessageResponse getFailedMessage(FailedMessageId failedMessageId) { return failedMessageDao.findById(failedMessageId) .filter(failedMessage -> !DELETED.equals(failedMessage.getStatus())) .map(failedMessageResponseFactory::create) .orElseThrow(() -> new NotFoundException(format("Failed Message: %s not found", failedMessageId))); } FailedMessageSearchResource(FailedMessageDao failedMessageDao,
FailedMessageResponseFactory failedMessageResponseFactory,
FailedMessageSearchService failedMessageSearchService,
SearchFailedMessageResponseAdapter searchFailedMessageResponseAdapter); @Override FailedMessageResponse getFailedMessage(FailedMessageId failedMessageId); @Override Collection<SearchFailedMessageResponse> search(SearchFailedMessageRequest request); } | @Test public void findMessageById() { when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.of(failedMessage)); when(failedMessage.getStatus()).thenReturn(FAILED); when(failedMessageResponseFactory.create(failedMessage)).thenReturn(failedMessageResponse); assertThat(underTest.getFailedMessage(FAILED_MESSAGE_ID), is(failedMessageResponse)); }
@Test public void findMessageByIdThrowsNotFoundExceptionWhenMessageDoesNotExist() { expectedException.expect(NotFoundException.class); expectedException.expectMessage("Failed Message: " + FAILED_MESSAGE_ID + " not found"); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.empty()); underTest.getFailedMessage(FAILED_MESSAGE_ID); verifyZeroInteractions(failedMessageResponseFactory); }
@Test public void findMessageByIdThrowsNotFoundExceptionWhenMessageIsDeleted() { expectedException.expect(NotFoundException.class); expectedException.expectMessage("Failed Message: " + FAILED_MESSAGE_ID + " not found"); when(failedMessageDao.findById(FAILED_MESSAGE_ID)).thenReturn(Optional.of(failedMessage)); when(failedMessage.getStatus()).thenReturn(DELETED); underTest.getFailedMessage(FAILED_MESSAGE_ID); verifyZeroInteractions(failedMessageResponseFactory); } |
RemoveRecordsQueryFactory { public Document create() { return new Document() .append(STATUS_HISTORY + ".0." + STATUS, DELETED.name()) .append(STATUS_HISTORY + ".0." + EFFECTIVE_DATE_TIME, new Document(QueryOperators.LT, now().minus(7, DAYS))); } Document create(); } | @Test public void removeRecordsQueryCreatedSuccessfully() { assertThat(underTest.create(), allOf( hasField(STATUS_HISTORY + ".0." + STATUS, equalTo(StatusHistoryEvent.Status.DELETED.name())), hasField(STATUS_HISTORY + ".0." + EFFECTIVE_DATE_TIME, hasField(QueryOperators.LT, notNullValue(Instant.class))) )); } |
FailedMessageSearchResource implements SearchFailedMessageClient { @Override public Collection<SearchFailedMessageResponse> search(SearchFailedMessageRequest request) { return failedMessageSearchService.search(request) .stream() .map(searchFailedMessageResponseAdapter::toResponse) .collect(Collectors.toList()); } FailedMessageSearchResource(FailedMessageDao failedMessageDao,
FailedMessageResponseFactory failedMessageResponseFactory,
FailedMessageSearchService failedMessageSearchService,
SearchFailedMessageResponseAdapter searchFailedMessageResponseAdapter); @Override FailedMessageResponse getFailedMessage(FailedMessageId failedMessageId); @Override Collection<SearchFailedMessageResponse> search(SearchFailedMessageRequest request); } | @Test public void validSearch() { FailedMessage failedMessage = mock(FailedMessage.class); SearchFailedMessageResponse searchFailedMessageResponse = mock(SearchFailedMessageResponse.class); SearchFailedMessageRequest searchFailedMessageRequest = mock(SearchFailedMessageRequest.class); when(searchFailedMessageRequest.getBroker()).thenReturn(Optional.of("broker")); when(failedMessageSearchService.search(searchFailedMessageRequest)).thenReturn(singletonList(failedMessage)); when(searchFailedMessageResponseAdapter.toResponse(failedMessage)).thenReturn(searchFailedMessageResponse); final Collection<SearchFailedMessageResponse> results = underTest.search(searchFailedMessageRequest); assertThat(results, contains(searchFailedMessageResponse)); verify(failedMessageSearchService).search(Mockito.refEq(searchFailedMessageRequest)); } |
UpdateFailedMessageResource implements UpdateFailedMessageClient { @Override public void update(FailedMessageId failedMessageId, FailedMessageUpdateRequest failedMessageUpdateRequest) { failedMessageService.update(failedMessageId, failedMessageUpdateRequest.getUpdateRequests()); } UpdateFailedMessageResource(FailedMessageService failedMessageService); @Override void update(FailedMessageId failedMessageId, FailedMessageUpdateRequest failedMessageUpdateRequest); } | @Test public void resourceDelegatesToTheFailedMessageService() { underTest.update(FAILED_MESSAGE_ID, FailedMessageUpdateRequest.aNewFailedMessageUpdateRequest().withUpdateRequest(updateRequest).build()); verify(failedMessageService).update(FAILED_MESSAGE_ID, Collections.singletonList(updateRequest)); } |
MessageTextExtractor { public String extractText(Message message) { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; try { return textMessage.getText(); } catch (JMSException e) { String errorMsg = String.format("Failed to extract the text from TextMessage: %s", textMessage.toString()); LOGGER.error(errorMsg, e); throw new RuntimeException(errorMsg, e); } } else { String errorMsg = String.format("Expected TextMessage received: %s", message.getClass().getName()); LOGGER.error(errorMsg); throw new RuntimeException(errorMsg); } } String extractText(Message message); } | @Test public void extractTextFromMessage() throws Exception { TextMessage textMessage = mock(TextMessage.class); when(textMessage.getText()).thenReturn("Text"); assertThat(underTest.extractText(textMessage), is("Text")); }
@Test public void throwsExceptionIfNotTextMessage() throws Exception { expectedException.expect(RuntimeException.class); expectedException.expectMessage(allOf(startsWith("Expected TextMessage received:"), containsString("javax.jms.BytesMessage"))); underTest.extractText(mock(BytesMessage.class)); } |
FailedMessageTransformer implements JmsMessageTransformer<TextMessage, FailedMessage> { @Override public void transform(TextMessage textMessage, FailedMessage data) throws JMSException { textMessage.setText(data.getContent()); Map<String, Object> properties = data.getProperties(); properties.keySet().forEach(key -> { try { textMessage.setObjectProperty(key, properties.get(key)); } catch (JMSException ignore) { LOGGER.warn("Could not add property: '{}' when sending FailedMessage: {}", key, data.getFailedMessageId()); } }); textMessage.setStringProperty(FailedMessageId.FAILED_MESSAGE_ID, data.getFailedMessageId().toString()); } @Override void transform(TextMessage textMessage, FailedMessage data); } | @Test public void processingContinuesObjectPropertyCannotBeWritten() throws JMSException { when(failedMessage.getContent()).thenReturn("content"); when(failedMessage.getProperties()).thenReturn(ImmutableMap.of("foo", "bar", "ham", "eggs")); when(failedMessage.getFailedMessageId()).thenReturn(FAILED_MESSAGE_ID); doThrow(new JMSException("Arrrghhhhh")).when(textMessage).setObjectProperty("foo", "bar"); underTest.transform(textMessage, failedMessage); verify(textMessage).setText("content"); verify(textMessage).setObjectProperty("foo", "bar"); verify(textMessage).setObjectProperty("ham", "eggs"); verify(textMessage).setStringProperty(FailedMessageId.FAILED_MESSAGE_ID, FAILED_MESSAGE_ID.toString()); } |
FailedMessageListener implements MessageListener { @Override public void onMessage(Message message) { try { LOGGER.debug("Received message: {} with CorrelationId: {}", message.getJMSMessageID(), message.getJMSCorrelationID()); failedMessageProcessor.process(failedMessageFactory.createFailedMessage(message)); } catch (JMSException e) { LOGGER.error("Could not read jmsMessageId or correlationId", e); } } FailedMessageListener(FailedMessageFactory failedMessageFactory,
FailedMessageProcessor failedMessageProcessor); @Override void onMessage(Message message); } | @Test public void processMessageSuccessfully() throws Exception { when(failedMessageFactory.createFailedMessage(message)).thenReturn(failedMessage); underTest.onMessage(message); verify(failedMessageProcessor).process(failedMessage); }
@Test public void exceptionIsThrownRetrievingTheJMSMessageId() throws JMSException { when(message.getJMSMessageID()).thenThrow(JMSException.class); underTest.onMessage(message); verifyZeroInteractions(failedMessageProcessor); } |
FailedMessageConverter implements DocumentWithIdConverter<FailedMessage, FailedMessageId> { @Override public Document createId(FailedMessageId failedMessageId) { return new Document("_id", failedMessageId.getId().toString()); } FailedMessageConverter(DocumentConverter<Destination> destinationDocumentConverter,
DocumentConverter<StatusHistoryEvent> statusHistoryEventDocumentConverter,
ObjectConverter<Map<String, Object>, String> propertiesMongoMapper); @Override FailedMessage convertToObject(Document document); StatusHistoryEvent getStatusHistoryEvent(Document document); FailedMessageId getFailedMessageId(Document document); Destination getDestination(Document document); String getContent(Document document); Instant getFailedDateTime(Document document); Instant getSentDateTime(Document document); @Override Document convertFromObject(FailedMessage item); Document convertForUpdate(FailedMessage item); @Override Document createId(FailedMessageId failedMessageId); static final String DESTINATION; static final String SENT_DATE_TIME; static final String FAILED_DATE_TIME; static final String CONTENT; static final String PROPERTIES; static final String STATUS_HISTORY; static final String LABELS; static final String JMS_MESSAGE_ID; } | @Test public void createId() { assertThat(underTest.createId(FAILED_MESSAGE_ID), equalTo(new Document("_id", FAILED_MESSAGE_ID_AS_STRING))); } |
CircularBuffer { public int size() { return currentSize; } CircularBuffer(int size); void enqueue(T item); int size(); @SuppressWarnings("unchecked") T getItem(int index); } | @Test public void size() { CircularBuffer<Integer> queue = new CircularBuffer<>(2); assertEquals(0, queue.size()); queue.enqueue(0); queue.enqueue(1); assertEquals(2, queue.size()); queue.enqueue(3); assertEquals(2, queue.size()); } |
CircularBuffer { @SuppressWarnings("unchecked") public T getItem(int index) { int target = head - index; if (target < 0) target = queue.length + target; return (T) queue[target]; } CircularBuffer(int size); void enqueue(T item); int size(); @SuppressWarnings("unchecked") T getItem(int index); } | @Test public void getItem() { CircularBuffer<Integer> queue = new CircularBuffer<>(3); queue.enqueue(0); assertEquals((Integer) 0, queue.getItem(0)); queue.enqueue(1); assertEquals((Integer) 1, queue.getItem(0)); assertEquals((Integer) 0, queue.getItem(1)); queue.enqueue(2); assertEquals((Integer) 2, queue.getItem(0)); assertEquals((Integer) 1, queue.getItem(1)); assertEquals((Integer) 0, queue.getItem(2)); queue.enqueue(3); assertEquals((Integer) 3, queue.getItem(0)); assertEquals((Integer) 2, queue.getItem(1)); assertEquals((Integer) 1, queue.getItem(2)); } |
KubeCloudInstanceImpl implements KubeCloudInstance { @NotNull @Override public Date getStartedTime() { final PodStatus podStatus = myPod.getStatus(); if(podStatus == null) return myCreationTime; try { final List<PodCondition> podConditions = podStatus.getConditions(); if (podConditions != null && !podConditions.isEmpty()) { for (PodCondition podCondition : podConditions) { if (PodConditionType.valueOf(podCondition.getType()) == PodConditionType.Ready) return myPodTransitionTimeFormat.parse(podCondition.getLastTransitionTime()); } } String startTime = podStatus.getStartTime(); return !StringUtil.isEmpty(startTime) ? myPodStartTimeFormat.parse(startTime) : myCreationTime; } catch (ParseException e) { throw new KubeCloudException("Failed to get instance start date", e); } } KubeCloudInstanceImpl(@NotNull KubeCloudImage kubeCloudImage, @NotNull Pod pod); @NotNull @Override String getInstanceId(); @NotNull @Override String getName(); @NotNull @Override String getImageId(); @NotNull @Override KubeCloudImage getImage(); @Override void setStatus(final InstanceStatus status); @NotNull @Override Date getStartedTime(); @Nullable @Override String getNetworkIdentity(); @NotNull @Override InstanceStatus getStatus(); @Nullable @Override CloudErrorInfo getErrorInfo(); @Override boolean containsAgent(@NotNull AgentDescription agentDescription); void updateState(@NotNull Pod actualPod); @Override void setError(@Nullable final CloudErrorInfo errorInfo); @Override @Nullable String getPVCName(); } | @Test public void testGetStartedTime() throws Exception { KubeCloudImage image = m.mock(KubeCloudImage.class); ObjectMeta metadata = new ObjectMeta(); metadata.setName("foo"); Pod pod = new Pod("1.0", "kind", metadata, new PodSpec(), new PodStatusBuilder().withStartTime("2017-06-12T22:59Z").build()); m.checking(new Expectations(){{ allowing(myApi).getPodStatus(with("foo")); will(returnValue(pod.getStatus())); }}); KubeCloudInstanceImpl instance = new KubeCloudInstanceImpl(image, pod); Date startedTime = instance.getStartedTime(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); assertEquals("2017-06-12T22:59Z", dateFormat.format(startedTime)); } |
KubeCloudClient implements CloudClientEx { @Override public boolean isInitialized() { return true; } KubeCloudClient(@NotNull KubeApiConnector apiConnector,
@Nullable String serverUuid,
@NotNull String cloudProfileId,
@NotNull List<KubeCloudImage> images,
@NotNull KubeCloudClientParametersImpl kubeClientParams,
@NotNull KubeBackgroundUpdater updater,
@NotNull BuildAgentPodTemplateProviders podTemplateProviders,
@Nullable ExecutorService executorService,
@NotNull KubePodNameGenerator nameGenerator); @Override boolean isInitialized(); @Override void dispose(); @NotNull @Override CloudInstance startNewInstance(@NotNull CloudImage cloudImage, @NotNull CloudInstanceUserData cloudInstanceUserData); @Override void restartInstance(@NotNull CloudInstance cloudInstance); @Override void terminateInstance(@NotNull CloudInstance cloudInstance); @Nullable @Override CloudImage findImageById(@NotNull String imageId); @Nullable @Override CloudInstance findInstanceByAgent(@NotNull AgentDescription agentDescription); @NotNull @Override Collection<? extends CloudImage> getImages(); @Nullable @Override CloudErrorInfo getErrorInfo(); @Override boolean canStartNewInstance(@NotNull CloudImage cloudImage); @Nullable @Override String generateAgentName(@NotNull AgentDescription agentDescription); String getProfileId(); } | @Test public void testIsInitialized() throws Exception { assertTrue(createClient(Collections.emptyList()).isInitialized()); } |
KubeCloudClient implements CloudClientEx { @Override public boolean canStartNewInstance(@NotNull CloudImage cloudImage) { KubeCloudImage kubeCloudImage = (KubeCloudImage) cloudImage; String kubeCloudImageId = kubeCloudImage.getId(); if(!myImageIdToImageMap.containsKey(kubeCloudImageId)){ LOG.debug("Can't start instance of unknown cloud image with id " + kubeCloudImageId); return false; } int profileInstanceLimit = myKubeClientParams.getInstanceLimit(); if(profileInstanceLimit >= 0 && myImageIdToImageMap.values().stream().mapToInt(KubeCloudImage::getRunningInstanceCount).sum() >= profileInstanceLimit) return false; int imageLimit = kubeCloudImage.getInstanceLimit(); return imageLimit < 0 || kubeCloudImage.getRunningInstanceCount() < imageLimit; } KubeCloudClient(@NotNull KubeApiConnector apiConnector,
@Nullable String serverUuid,
@NotNull String cloudProfileId,
@NotNull List<KubeCloudImage> images,
@NotNull KubeCloudClientParametersImpl kubeClientParams,
@NotNull KubeBackgroundUpdater updater,
@NotNull BuildAgentPodTemplateProviders podTemplateProviders,
@Nullable ExecutorService executorService,
@NotNull KubePodNameGenerator nameGenerator); @Override boolean isInitialized(); @Override void dispose(); @NotNull @Override CloudInstance startNewInstance(@NotNull CloudImage cloudImage, @NotNull CloudInstanceUserData cloudInstanceUserData); @Override void restartInstance(@NotNull CloudInstance cloudInstance); @Override void terminateInstance(@NotNull CloudInstance cloudInstance); @Nullable @Override CloudImage findImageById(@NotNull String imageId); @Nullable @Override CloudInstance findInstanceByAgent(@NotNull AgentDescription agentDescription); @NotNull @Override Collection<? extends CloudImage> getImages(); @Nullable @Override CloudErrorInfo getErrorInfo(); @Override boolean canStartNewInstance(@NotNull CloudImage cloudImage); @Nullable @Override String generateAgentName(@NotNull AgentDescription agentDescription); String getProfileId(); } | @Test public void testCanStartNewInstance_UnknownImage() throws Exception { KubeCloudClient cloudClient = createClient(Collections.emptyList()); CloudImage image = m.mock(KubeCloudImage.class); m.checking(new Expectations(){{ allowing(image).getId(); will(returnValue("image-1-id")); }}); assertFalse(cloudClient.canStartNewInstance(image)); }
@Test public void testCanStartNewInstance() throws Exception { KubeCloudImage image = m.mock(KubeCloudImage.class); m.checking(new Expectations(){{ allowing(image).getName(); will(returnValue("image-1-name")); allowing(image).getId(); will(returnValue("image-1-id")); allowing(image).getRunningInstanceCount(); will(returnValue(0)); allowing(image).getInstanceLimit(); will(returnValue(0)); }}); List<KubeCloudImage> images = Collections.singletonList(image); KubeCloudClient cloudClient = createClient(images); assertFalse(cloudClient.canStartNewInstance(image)); }
@Test public void testCanStartNewInstance2() throws Exception { KubeCloudImage image = m.mock(KubeCloudImage.class); m.checking(new Expectations(){{ allowing(image).getName(); will(returnValue("image-1-name")); allowing(image).getId(); will(returnValue("image-1-id")); allowing(image).getRunningInstanceCount(); will(returnValue(1)); allowing(image).getInstanceLimit(); will(returnValue(5)); }}); List<KubeCloudImage> images = Collections.singletonList(image); KubeCloudClient cloudClient = createClient(images); assertTrue(cloudClient.canStartNewInstance(image)); }
@Test public void testCanStartNewInstance_ProfileLimit() throws Exception { KubeCloudImage image = m.mock(KubeCloudImage.class); m.checking(new Expectations(){{ allowing(image).getId(); will(returnValue("image-1-id")); allowing(image).getRunningInstanceCount(); will(returnValue(1)); allowing(image).getInstanceLimit(); will(returnValue(2)); }}); List<KubeCloudImage> images = Collections.singletonList(image); CloudClientParameters cloudClientParameters = new MockCloudClientParameters(Collections.singletonMap(PROFILE_INSTANCE_LIMIT, "1")); KubeCloudClient cloudClient = createClient(images, cloudClientParameters); assertFalse(cloudClient.canStartNewInstance(image)); }
@Test public void testCanStartNewInstance_ProfileLimit2() throws Exception { KubeCloudImage image = m.mock(KubeCloudImage.class); m.checking(new Expectations(){{ allowing(image).getId(); will(returnValue("image-1-id")); allowing(image).getRunningInstanceCount(); will(returnValue(3)); allowing(image).getInstanceLimit(); will(returnValue(5)); }}); List<KubeCloudImage> images = Collections.singletonList(image); CloudClientParameters cloudClientParameters = new MockCloudClientParameters(Collections.singletonMap(PROFILE_INSTANCE_LIMIT, "5")); KubeCloudClient cloudClient = createClient(images, cloudClientParameters); assertTrue(cloudClient.canStartNewInstance(image)); }
@Test public void testCanStartNewInstance_ImageLimit() throws Exception { KubeCloudImage image = m.mock(KubeCloudImage.class); m.checking(new Expectations(){{ allowing(image).getName(); will(returnValue("image-1-name")); allowing(image).getId(); will(returnValue("image-1-id")); allowing(image).getRunningInstanceCount(); will(returnValue(1)); allowing(image).getInstanceLimit(); will(returnValue(1)); }}); List<KubeCloudImage> images = Collections.singletonList(image); KubeCloudClient cloudClient = createClient(images); assertFalse(cloudClient.canStartNewInstance(image)); } |
BoltOptions implements AutoCloseable { @Override public void close() { BoltNative.BoltDBOptions_Free(objectId); } BoltOptions(); BoltOptions(long timeout); BoltOptions(long timeout, boolean noGrowSync, boolean readOnly, int mmapFlags, int initialMmapSize); @Override void close(); } | @Test public void create_and_free() { BoltOptions boltOptions = new BoltOptions(); boltOptions.close(); } |
BoltBucket implements AutoCloseable { public void delete(byte[] key) { Error.ByValue error = BoltNative.BoltDBBucket_Delete(objectId, key, key.length); error.checkError(); } BoltBucket(long objectId); @Override void close(); byte[] get(byte[] key); void put(byte[] key, byte[] value); void delete(byte[] key); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); long nextSequenceId(); BoltBucketStats getStats(); } | @Test public void delete() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try(BoltBucket bucket = boltTransaction.createBucket("test".getBytes())) { byte[] key = "foo".getBytes(); byte[] value = "bar".getBytes(); bucket.put(key, value); bucket.delete(key); byte[] getValue = bucket.get(key); Assert.assertNull(getValue); } }); } } |
BoltBucket implements AutoCloseable { public BoltBucket createBucket(byte[] name) { Result.ByValue result = BoltNative.BoltDBBucket_CreateBucket(objectId, name, name.length); result.checkError(); return new BoltBucket(result.objectId); } BoltBucket(long objectId); @Override void close(); byte[] get(byte[] key); void put(byte[] key, byte[] value); void delete(byte[] key); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); long nextSequenceId(); BoltBucketStats getStats(); } | @Test @SuppressWarnings("EmptyTryBlock") public void create_bucket() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try(BoltBucket parentBucket = boltTransaction.createBucket("parent".getBytes())) { try(BoltBucket ignored = parentBucket.createBucket("test".getBytes())) {} } }); } }
@Test(expected = BoltException.class) public void create_bucket_with_empty_name() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket parentBucket = boltTransaction.createBucket("parent".getBytes())) { parentBucket.createBucket("".getBytes()); } }); } }
@Test(expected = BoltException.class) @SuppressWarnings("EmptyTryBlock") public void create_bucket_twice() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket parentBucket = boltTransaction.createBucket("parent".getBytes())) { try (BoltBucket ignored = parentBucket.createBucket(bucketName)) {} parentBucket.createBucket(bucketName); } }); } } |
BoltTransaction { public void commit() { Error.ByValue error = BoltNative.BoltDBTransaction_Commit(objectId); error.checkError(); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); } | @Test public void commit_transaction() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { BoltTransaction boltTransaction = bolt.begin(true); boltTransaction.commit(); } } |
BoltTransaction { public void rollback() { Error.ByValue error = BoltNative.BoltDBTransaction_Rollback(objectId); error.checkError(); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); } | @Test public void rollback_transaction() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { BoltTransaction boltTransaction = bolt.begin(true); boltTransaction.rollback(); } } |
BoltTransaction { public int getId() { return BoltNative.BoltDBTransaction_GetId(objectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); } | @Test public void get_transaction_id() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> Assert.assertTrue(boltTransaction.getId() > 0)); } } |
BoltTransaction { public long getDatabaseSize() { return BoltNative.BoltDBTransaction_Size(objectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); } | @Test public void get_database_size() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> Assert.assertTrue(boltTransaction.getDatabaseSize() > 0)); } } |
BoltTransaction { public BoltBucket createBucket(byte[] name) { Result.ByValue result = BoltNative.BoltDBTransaction_CreateBucket(objectId, name, name.length); result.checkError(); return new BoltBucket(result.objectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); } | @Test @SuppressWarnings("EmptyTryBlock") public void create_bucket() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucket("test".getBytes())) {} }); } }
@Test(expected = BoltException.class) public void create_bucket_with_empty_name() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> boltTransaction.createBucket("".getBytes())); } }
@Test(expected = BoltException.class) @SuppressWarnings("EmptyTryBlock") public void create_bucket_twice() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucket(bucketName)) {} boltTransaction.createBucket(bucketName); }); } } |
BoltCursor implements AutoCloseable { public BoltKeyValue first() { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_First(objectId)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); } | @Test public void move_first() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucket(bucketName)) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue first = cursor.first(); Assert.assertNotNull(first); Assert.assertArrayEquals(bucketName, first.getKey()); Assert.assertNull(first.getValue()); } } }); } }
@Test public void move_first_when_not_exists() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue first = cursor.first(); Assert.assertNull(first); } }); } } |
BoltTransaction { public BoltBucket createBucketIfNotExists(byte[] name) { Result.ByValue result = BoltNative.BoltDBTransaction_CreateBucketIfNotExists(objectId, name, name.length); result.checkError(); return new BoltBucket(result.objectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); } | @Test @SuppressWarnings("EmptyTryBlock") public void create_bucket_if_not_exists() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucketIfNotExists(bucketName)) {} }); } }
@Test(expected = BoltException.class) public void create_bucket_if_not_exists_with_empty_name() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> boltTransaction.createBucketIfNotExists("".getBytes())); } }
@Test @SuppressWarnings("EmptyTryBlock") public void create_bucket_if_not_exists_twice() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucketIfNotExists(bucketName)) {} try (BoltBucket ignored = boltTransaction.createBucketIfNotExists(bucketName)) {} }); } } |
BoltTransaction { public void deleteBucket(byte[] name) { Error.ByValue error = BoltNative.BoltDBTransaction_DeleteBucket(objectId, name, name.length); error.checkError(); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); } | @Test(expected = BoltException.class) public void delete_bucket_with_empty_name() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> boltTransaction.deleteBucket("".getBytes())); } } |
BoltTransaction { public BoltBucket getBucket(byte[] name) { Result.ByValue result = BoltNative.BoltDBTransaction_Bucket(objectId, name, name.length); result.checkError(); return new BoltBucket(result.objectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); } | @Test(expected = BoltException.class) public void get_bucket_with_empty_name() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> boltTransaction.getBucket("".getBytes())); } } |
BoltTransaction { public BoltCursor createCursor() { long cursorObjectId = BoltNative.BoltDBTransaction_Cursor(objectId); return new BoltCursor(cursorObjectId); } BoltTransaction(long objectId); void commit(); void rollback(); int getId(); long getDatabaseSize(); BoltBucket createBucket(byte[] name); BoltBucket createBucketIfNotExists(byte[] name); void deleteBucket(byte[] name); BoltBucket getBucket(byte[] name); BoltCursor createCursor(); BoltTransactionStats getStats(); } | @Test @SuppressWarnings("EmptyTryBlock") public void create_cursor() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltCursor ignored = boltTransaction.createCursor()) {} }); } } |
Bolt implements AutoCloseable { public void close() { BoltNative.BoltDB_Close(objectId); } Bolt(String databaseFileName); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode, BoltOptions options); void close(); BoltTransaction begin(boolean writeable); void update(Consumer<BoltTransaction> callback); void view(Consumer<BoltTransaction> callback); BoltStats getStats(); static void init(); } | @Test public void open_and_close() throws IOException { Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath()); bolt.close(); }
@Test public void open_from_other_thread() { Thread thread = new Thread(() -> { try { Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath()); bolt.close(); } catch (Throwable e) { Assert.fail("Bolt adapter can't be created in other thread."); } }); thread.run(); }
@Test @Ignore public void open_and_close_with_file_mode() throws IOException { Path databaseFileName = Paths.get(testFolder.getRoot().getAbsolutePath(), "bd.bolt"); EnumSet<BoltFileMode> fileMode = EnumSet.of(BoltFileMode.USER_READ, BoltFileMode.USER_WRITE, BoltFileMode.GROUP_READ, BoltFileMode.GROUP_WRITE); Bolt bolt = new Bolt(databaseFileName.toString(), fileMode); bolt.close(); Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(databaseFileName); Assert.assertEquals(4, permissions.size()); Assert.assertTrue(permissions.containsAll(Arrays.asList(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE))); }
@Test public void open_and_close_with_options() throws IOException { try(BoltOptions boltOptions = new BoltOptions()) { Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath(), BoltFileMode.DEFAULT, boltOptions); bolt.close(); } } |
Bolt implements AutoCloseable { public void update(Consumer<BoltTransaction> callback) { BoltTransaction transaction = begin(true); try { callback.accept(transaction); transaction.commit(); } catch (Throwable ex) { transaction.rollback(); throw ex; } } Bolt(String databaseFileName); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode, BoltOptions options); void close(); BoltTransaction begin(boolean writeable); void update(Consumer<BoltTransaction> callback); void view(Consumer<BoltTransaction> callback); BoltStats getStats(); static void init(); } | @Test public void open_update_transaction() throws IOException { String databaseFileName = testFolder.newFile().getAbsolutePath(); try(Bolt bolt = new Bolt(databaseFileName)) { final boolean[] wasInTransaction = {false}; bolt.update(boltTransaction -> { Assert.assertNotNull(boltTransaction); wasInTransaction[0] = true; }); Assert.assertTrue(wasInTransaction[0]); } } |
Bolt implements AutoCloseable { public void view(Consumer<BoltTransaction> callback) { BoltTransaction transaction = begin(false); try { callback.accept(transaction); } finally { transaction.rollback(); } } Bolt(String databaseFileName); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode); Bolt(String databaseFileName, EnumSet<BoltFileMode> fileMode, BoltOptions options); void close(); BoltTransaction begin(boolean writeable); void update(Consumer<BoltTransaction> callback); void view(Consumer<BoltTransaction> callback); BoltStats getStats(); static void init(); } | @Test public void open_view_transaction() throws IOException { String databaseFileName = testFolder.newFile().getAbsolutePath(); try(Bolt bolt = new Bolt(databaseFileName)) { final boolean[] wasInTransaction = {false}; bolt.view(boltTransaction -> { Assert.assertNotNull(boltTransaction); wasInTransaction[0] = true; }); Assert.assertTrue(wasInTransaction[0]); } } |
BoltCursor implements AutoCloseable { public BoltKeyValue last() { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_Last(objectId)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); } | @Test public void move_last() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored = boltTransaction.createBucket(bucketName)) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue last = cursor.last(); Assert.assertNotNull(last); Assert.assertArrayEquals(bucketName, last.getKey()); Assert.assertNull(last.getValue()); } } }); } }
@Test public void move_last_when_not_exists() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue last = cursor.last(); Assert.assertNull(last); } }); } } |
BoltCursor implements AutoCloseable { public BoltKeyValue next() { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_Next(objectId)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); } | @Test public void move_next() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored1 = boltTransaction.createBucket("test1".getBytes())) { try (BoltBucket ignored2 = boltTransaction.createBucket("test2".getBytes())) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue next = cursor.next(); Assert.assertNull(next); } } } }); } } |
BoltCursor implements AutoCloseable { public BoltKeyValue prev() { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_Prev(objectId)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); } | @Test public void move_prev() throws IOException { try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try (BoltBucket ignored1 = boltTransaction.createBucket("test1".getBytes())) { try (BoltBucket ignored2 = boltTransaction.createBucket("test2".getBytes())) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue prev = cursor.prev(); Assert.assertNull(prev); } } } }); } } |
BoltCursor implements AutoCloseable { public BoltKeyValue seek(byte[] seek) { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_Seek(objectId, seek, seek.length)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); } | @Test public void seek() throws IOException { byte[] bucketName1 = "test1".getBytes(); byte[] bucketName2 = "test2".getBytes(); byte[] bucketName3 = "test3".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try(BoltBucket ignored1 = boltTransaction.createBucket(bucketName1)) { try(BoltBucket ignored2 = boltTransaction.createBucket(bucketName2)) { try(BoltBucket ignored3 = boltTransaction.createBucket(bucketName3)) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue seek = cursor.seek(bucketName2); Assert.assertNotNull(seek); Assert.assertArrayEquals(bucketName2, seek.getKey()); } } } } }); } }
@Test public void seek_to_unknown_position() throws IOException { byte[] bucketName1 = "test1".getBytes(); byte[] bucketName2 = "test2".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try(BoltBucket ignored = boltTransaction.createBucket(bucketName1)) { try (BoltCursor cursor = boltTransaction.createCursor()) { BoltKeyValue seek = cursor.seek(bucketName2); Assert.assertNull(seek); } } }); } } |
BoltCursor implements AutoCloseable { public void delete() { Error.ByValue error = BoltNative.BoltDBCursor_Delete(objectId); error.checkError(); } BoltCursor(long objectId); @Override void close(); BoltKeyValue first(); BoltKeyValue last(); BoltKeyValue next(); BoltKeyValue prev(); BoltKeyValue seek(byte[] seek); void delete(); } | @Test public void delete() throws IOException { byte[] bucketName = "test".getBytes(); try(Bolt bolt = new Bolt(testFolder.newFile().getAbsolutePath())) { bolt.update(boltTransaction -> { try(BoltBucket bucket = boltTransaction.createBucket(bucketName)) { byte[] key = "key".getBytes(); byte[] value = "value".getBytes(); bucket.put(key, value); try (BoltCursor cursor = bucket.createCursor()) { cursor.first(); cursor.delete(); } } }); } } |
FlowsApi { public Flow create(CreateFlowRequest body) throws ApiException { ApiResponse<Flow> resp = createWithHttpInfo(body); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); } | @Test public void createTest() throws ApiException { CreateFlowRequest body = null; Flow response = api.create(body); } |
FunctionsApi { public KFFunction create(CreateFunctionRequest body) throws ApiException { ApiResponse<KFFunction> resp = createWithHttpInfo(body); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); } | @Test public void createTest() throws ApiException { CreateFunctionRequest body = null; KFFunction response = api.create(body); } |
FunctionsApi { public void delete(String id) throws ApiException { deleteWithHttpInfo(id); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); } | @Test public void deleteTest() throws ApiException { String id = null; api.delete(id); } |
FunctionsApi { public KFFunction get(String id) throws ApiException { ApiResponse<KFFunction> resp = getWithHttpInfo(id); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); } | @Test public void getTest() throws ApiException { String id = null; KFFunction response = api.get(id); } |
FunctionsApi { public Service getService(String id) throws ApiException { ApiResponse<Service> resp = getServiceWithHttpInfo(id); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); } | @Test public void getServiceTest() throws ApiException { String id = null; Service response = api.getService(id); } |
FunctionsApi { public Version getVersion(String id, String versionId) throws ApiException { ApiResponse<Version> resp = getVersionWithHttpInfo(id, versionId); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); } | @Test public void getVersionTest() throws ApiException { String id = null; String versionId = null; Version response = api.getVersion(id, versionId); } |
FunctionsApi { public List<Version> getVersions(String id) throws ApiException { ApiResponse<List<Version>> resp = getVersionsWithHttpInfo(id); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); } | @Test public void getVersionsTest() throws ApiException { String id = null; List<Version> response = api.getVersions(id); } |
FunctionsApi { public List<KFFunction> list() throws ApiException { ApiResponse<List<KFFunction>> resp = listWithHttpInfo(); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); } | @Test public void listTest() throws ApiException { List<KFFunction> response = api.list(); } |
FunctionsApi { public ProxyResponse proxy(String id, String body) throws ApiException { ApiResponse<ProxyResponse> resp = proxyWithHttpInfo(id, body); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); } | @Test public void proxyTest() throws ApiException { String id = null; String body = null; ProxyResponse response = api.proxy(id, body); } |
FunctionsApi { public Map<String, String> setVersion(String id, String versionId) throws ApiException { ApiResponse<Map<String, String>> resp = setVersionWithHttpInfo(id, versionId); return resp.getData(); } FunctionsApi(); FunctionsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); KFFunction create(CreateFunctionRequest body); ApiResponse<KFFunction> createWithHttpInfo(CreateFunctionRequest body); com.squareup.okhttp.Call createAsync(CreateFunctionRequest body, final ApiCallback<KFFunction> callback); void delete(String id); ApiResponse<Void> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<Void> callback); KFFunction get(String id); ApiResponse<KFFunction> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<KFFunction> callback); Service getService(String id); ApiResponse<Service> getServiceWithHttpInfo(String id); com.squareup.okhttp.Call getServiceAsync(String id, final ApiCallback<Service> callback); Version getVersion(String id, String versionId); ApiResponse<Version> getVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call getVersionAsync(String id, String versionId, final ApiCallback<Version> callback); List<Version> getVersions(String id); ApiResponse<List<Version>> getVersionsWithHttpInfo(String id); com.squareup.okhttp.Call getVersionsAsync(String id, final ApiCallback<List<Version>> callback); List<KFFunction> list(); ApiResponse<List<KFFunction>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<KFFunction>> callback); ProxyResponse proxy(String id, String body); ApiResponse<ProxyResponse> proxyWithHttpInfo(String id, String body); com.squareup.okhttp.Call proxyAsync(String id, String body, final ApiCallback<ProxyResponse> callback); Map<String, String> setVersion(String id, String versionId); ApiResponse<Map<String, String>> setVersionWithHttpInfo(String id, String versionId); com.squareup.okhttp.Call setVersionAsync(String id, String versionId, final ApiCallback<Map<String, String>> callback); } | @Test public void setVersionTest() throws ApiException { String id = null; String versionId = null; Map<String, String> response = api.setVersion(id, versionId); } |
FlowsApi { public String delete(String id) throws ApiException { ApiResponse<String> resp = deleteWithHttpInfo(id); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); } | @Test public void deleteTest() throws ApiException { String id = null; String response = api.delete(id); } |
FlowsApi { public Flow deploy(String id) throws ApiException { ApiResponse<Flow> resp = deployWithHttpInfo(id); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); } | @Test public void deployTest() throws ApiException { String id = null; Flow response = api.deploy(id); } |
FlowsApi { public Flow get(String id) throws ApiException { ApiResponse<Flow> resp = getWithHttpInfo(id); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); } | @Test public void getTest() throws ApiException { String id = null; Flow response = api.get(id); } |
FlowsApi { public DAGStepRef getModel(String id) throws ApiException { ApiResponse<DAGStepRef> resp = getModelWithHttpInfo(id); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); } | @Test public void getModelTest() throws ApiException { String id = null; DAGStepRef response = api.getModel(id); } |
FlowsApi { public List<Flow> list() throws ApiException { ApiResponse<List<Flow>> resp = listWithHttpInfo(); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); } | @Test public void listTest() throws ApiException { List<Flow> response = api.list(); } |
FlowsApi { public String saveModel(String id, Object body) throws ApiException { ApiResponse<String> resp = saveModelWithHttpInfo(id, body); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); } | @Test public void saveModelTest() throws ApiException { String id = null; Object body = null; String response = api.saveModel(id, body); } |
FlowsApi { public String validate(Object body) throws ApiException { ApiResponse<String> resp = validateWithHttpInfo(body); return resp.getData(); } FlowsApi(); FlowsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Flow create(CreateFlowRequest body); ApiResponse<Flow> createWithHttpInfo(CreateFlowRequest body); com.squareup.okhttp.Call createAsync(CreateFlowRequest body, final ApiCallback<Flow> callback); String delete(String id); ApiResponse<String> deleteWithHttpInfo(String id); com.squareup.okhttp.Call deleteAsync(String id, final ApiCallback<String> callback); Flow deploy(String id); ApiResponse<Flow> deployWithHttpInfo(String id); com.squareup.okhttp.Call deployAsync(String id, final ApiCallback<Flow> callback); Flow get(String id); ApiResponse<Flow> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Flow> callback); DAGStepRef getModel(String id); ApiResponse<DAGStepRef> getModelWithHttpInfo(String id); com.squareup.okhttp.Call getModelAsync(String id, final ApiCallback<DAGStepRef> callback); List<Flow> list(); ApiResponse<List<Flow>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Flow>> callback); String saveModel(String id, Object body); ApiResponse<String> saveModelWithHttpInfo(String id, Object body); com.squareup.okhttp.Call saveModelAsync(String id, Object body, final ApiCallback<String> callback); String validate(Object body); ApiResponse<String> validateWithHttpInfo(Object body); com.squareup.okhttp.Call validateAsync(Object body, final ApiCallback<String> callback); } | @Test public void validateTest() throws ApiException { Object body = null; String response = api.validate(body); } |
ConnectorsApi { public Connector get(String id) throws ApiException { ApiResponse<Connector> resp = getWithHttpInfo(id); return resp.getData(); } ConnectorsApi(); ConnectorsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Connector get(String id); ApiResponse<Connector> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Connector> callback); List<Connector> list(); ApiResponse<List<Connector>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Connector>> callback); } | @Test public void getTest() throws ApiException { String id = null; Connector response = api.get(id); } |
ConnectorsApi { public List<Connector> list() throws ApiException { ApiResponse<List<Connector>> resp = listWithHttpInfo(); return resp.getData(); } ConnectorsApi(); ConnectorsApi(ApiClient apiClient); ApiClient getApiClient(); void setApiClient(ApiClient apiClient); Connector get(String id); ApiResponse<Connector> getWithHttpInfo(String id); com.squareup.okhttp.Call getAsync(String id, final ApiCallback<Connector> callback); List<Connector> list(); ApiResponse<List<Connector>> listWithHttpInfo(); com.squareup.okhttp.Call listAsync(final ApiCallback<List<Connector>> callback); } | @Test public void listTest() throws ApiException { List<Connector> response = api.list(); } |
TableStats { public double estimateScanCost() { return table.numPages() * ioCostPerPage; } TableStats(int tableid, int ioCostPerPage); static TableStats getTableStats(String tablename); static void setTableStats(String tablename, TableStats stats); static void setStatsMap(HashMap<String, TableStats> s); static Map<String, TableStats> getStatsMap(); static void computeStatistics(); double estimateScanCost(); int estimateTableCardinality(double selectivityFactor); double avgSelectivity(int field, simpledb.Predicate.Op op); double estimateSelectivity(int field, Predicate.Op op, Field constant); int totalTuples(); } | @Test public void estimateScanCostTest() throws IOException, DbException, TransactionAbortedException { Object[] ret; int[] ioCosts = new int[20]; int[] pageNums = new int[ioCosts.length]; for(int i = 0; i < ioCosts.length; ++i) { ioCosts[i] = 1; pageNums[i] = 3*(i+1); } double stats[] = getRandomTableScanCosts(pageNums, ioCosts); ret = SystemTestUtil.checkConstant(stats); Assert.assertEquals(ret[0], Boolean.FALSE); ret = SystemTestUtil.checkLinear(stats); Assert.assertEquals(ret[0], Boolean.TRUE); for(int i = 0; i < ioCosts.length; ++i) { ioCosts[i] = 10*(i + 1); pageNums[i] = 3; } stats = getRandomTableScanCosts(pageNums, ioCosts); ret = SystemTestUtil.checkConstant(stats); Assert.assertEquals(ret[0], Boolean.FALSE); ret = SystemTestUtil.checkLinear(stats); Assert.assertEquals(ret[0], Boolean.TRUE); for(int i = 0; i < ioCosts.length; ++i) { ioCosts[i] = 3*(i + 1); pageNums[i] = (i+1); } stats = getRandomTableScanCosts(pageNums, ioCosts); ret = SystemTestUtil.checkConstant(stats); Assert.assertEquals(ret[0], Boolean.FALSE); ret = SystemTestUtil.checkLinear(stats); Assert.assertEquals(ret[0], Boolean.FALSE); ret = SystemTestUtil.checkQuadratic(stats); Assert.assertEquals(ret[0], Boolean.TRUE); } |
Join extends Operator { public void rewind() throws DbException, TransactionAbortedException { child1.rewind(); child2.rewind(); joinResults.rewind(); } Join(JoinPredicate p, DbIterator child1, DbIterator child2); @Override String getName(); JoinPredicate getJoinPredicate(); String getJoinField1Name(); String getJoinField2Name(); TupleDesc getTupleDesc(); void open(); void close(); void rewind(); @Override DbIterator[] getChildren(); @Override void setChildren(DbIterator[] children); static final int blockMemory; } | @Test public void rewind() throws Exception { JoinPredicate pred = new JoinPredicate(0, Predicate.Op.EQUALS, 0); Join op = new Join(pred, scan1, scan2); op.open(); while (op.hasNext()) { assertNotNull(op.next()); } assertTrue(TestUtil.checkExhausted(op)); op.rewind(); eqJoin.open(); Tuple expected = eqJoin.next(); Tuple actual = op.next(); assertTrue(TestUtil.compareTuples(expected, actual)); } |
Join extends Operator { public void open() throws DbException, NoSuchElementException, TransactionAbortedException { child1.open(); child2.open(); super.open(); joinResults = blockNestedLoopJoin(); joinResults.open(); } Join(JoinPredicate p, DbIterator child1, DbIterator child2); @Override String getName(); JoinPredicate getJoinPredicate(); String getJoinField1Name(); String getJoinField2Name(); TupleDesc getTupleDesc(); void open(); void close(); void rewind(); @Override DbIterator[] getChildren(); @Override void setChildren(DbIterator[] children); static final int blockMemory; } | @Test public void gtJoin() throws Exception { JoinPredicate pred = new JoinPredicate(0, Predicate.Op.GREATER_THAN, 0); Join op = new Join(pred, scan1, scan2); op.open(); gtJoin.open(); TestUtil.matchAllTuples(gtJoin, op); }
@Test public void eqJoin() throws Exception { JoinPredicate pred = new JoinPredicate(0, Predicate.Op.EQUALS, 0); Join op = new Join(pred, scan1, scan2); op.open(); eqJoin.open(); TestUtil.matchAllTuples(eqJoin, op); } |
TableStats { public int estimateTableCardinality(double selectivityFactor) { return (int) Math.ceil(totalTuples() * selectivityFactor); } TableStats(int tableid, int ioCostPerPage); static TableStats getTableStats(String tablename); static void setTableStats(String tablename, TableStats stats); static void setStatsMap(HashMap<String, TableStats> s); static Map<String, TableStats> getStatsMap(); static void computeStatistics(); double estimateScanCost(); int estimateTableCardinality(double selectivityFactor); double avgSelectivity(int field, simpledb.Predicate.Op op); double estimateSelectivity(int field, Predicate.Op op, Field constant); int totalTuples(); } | @Test public void estimateTableCardinalityTest() { TableStats s = new TableStats(this.tableId, IO_COST); Assert.assertEquals(306, s.estimateTableCardinality(0.3)); Assert.assertEquals(1020, s.estimateTableCardinality(1.0)); Assert.assertEquals(0, s.estimateTableCardinality(0.0)); } |
TableStats { public double estimateSelectivity(int field, Predicate.Op op, Field constant) { String fieldName = td.getFieldName(field); if (constant.getType() == Type.INT_TYPE) { int value = ((IntField)constant).getValue(); IntHistogram histogram = (IntHistogram) name2hist.get(fieldName); return histogram.estimateSelectivity(op, value); } else { String value = ((StringField)constant).getValue(); StringHistogram histogram = (StringHistogram)name2hist.get(fieldName); return histogram.estimateSelectivity(op, value); } } TableStats(int tableid, int ioCostPerPage); static TableStats getTableStats(String tablename); static void setTableStats(String tablename, TableStats stats); static void setStatsMap(HashMap<String, TableStats> s); static Map<String, TableStats> getStatsMap(); static void computeStatistics(); double estimateScanCost(); int estimateTableCardinality(double selectivityFactor); double avgSelectivity(int field, simpledb.Predicate.Op op); double estimateSelectivity(int field, Predicate.Op op, Field constant); int totalTuples(); } | @Test public void estimateSelectivityTest() { final int maxCellVal = 32; final Field aboveMax = new IntField(maxCellVal + 10); final Field atMax = new IntField(maxCellVal); final Field halfMaxMin = new IntField(maxCellVal/2); final Field atMin = new IntField(0); final Field belowMin = new IntField(-10); TableStats s = new TableStats(this.tableId, IO_COST); for (int col = 0; col < 10; col++) { Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.EQUALS, aboveMax), 0.001); Assert.assertEquals(1.0/32.0, s.estimateSelectivity(col, Predicate.Op.EQUALS, halfMaxMin), 0.015); Assert.assertEquals(0, s.estimateSelectivity(col, Predicate.Op.EQUALS, belowMin), 0.001); Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.NOT_EQUALS, aboveMax), 0.001); Assert.assertEquals(31.0/32.0, s.estimateSelectivity(col, Predicate.Op.NOT_EQUALS, halfMaxMin), 0.015); Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.NOT_EQUALS, belowMin), 0.015); Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN, aboveMax), 0.001); Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN, atMax), 0.001); Assert.assertEquals(0.5, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN, halfMaxMin), 0.1); Assert.assertEquals(31.0/32.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN, atMin), 0.05); Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN, belowMin), 0.001); Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN, aboveMax), 0.001); Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN, atMax), 0.015); Assert.assertEquals(0.5, s.estimateSelectivity(col, Predicate.Op.LESS_THAN, halfMaxMin), 0.1); Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN, atMin), 0.001); Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN, belowMin), 0.001); Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN_OR_EQ, aboveMax), 0.001); Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN_OR_EQ, atMax), 0.015); Assert.assertEquals(0.5, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN_OR_EQ, halfMaxMin), 0.1); Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN_OR_EQ, atMin), 0.015); Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.GREATER_THAN_OR_EQ, belowMin), 0.001); Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN_OR_EQ, aboveMax), 0.001); Assert.assertEquals(1.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN_OR_EQ, atMax), 0.015); Assert.assertEquals(0.5, s.estimateSelectivity(col, Predicate.Op.LESS_THAN_OR_EQ, halfMaxMin), 0.1); Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN_OR_EQ, atMin), 0.05); Assert.assertEquals(0.0, s.estimateSelectivity(col, Predicate.Op.LESS_THAN_OR_EQ, belowMin), 0.001); } } |
JoinOptimizer { public double estimateJoinCost(LogicalJoinNode j, int card1, int card2, double cost1, double cost2) { if (j instanceof LogicalSubplanJoinNode) { return card1 + cost1 + cost2; } else { TupleDesc desc = p.getTupleDesc(j.t1Alias); int blockSize = Join.blockMemory / desc.getSize(); int fullNum = card1 / blockSize; int left = (card1 - blockSize * fullNum) == 0 ? 0 : 1; int blockCard = fullNum + left; double cost = cost1 + blockCard * cost2 + (double) card1 * (double) card2; return cost; } } JoinOptimizer(LogicalPlan p, Vector<LogicalJoinNode> joins); static DbIterator instantiateJoin(LogicalJoinNode lj,
DbIterator plan1, DbIterator plan2); double estimateJoinCost(LogicalJoinNode j, int card1, int card2,
double cost1, double cost2); int estimateJoinCardinality(LogicalJoinNode j, int card1, int card2,
boolean t1pkey, boolean t2pkey, Map<String, TableStats> stats); static int estimateTableJoinCardinality(Predicate.Op joinOp,
String table1Alias, String table2Alias, String field1PureName,
String field2PureName, int card1, int card2, boolean t1pkey,
boolean t2pkey, Map<String, TableStats> stats,
Map<String, Integer> tableAliasToId); @SuppressWarnings("unchecked") Set<Set<T>> enumerateSubsets(Vector<T> v, int size); Vector<LogicalJoinNode> orderJoins(
HashMap<String, TableStats> stats,
HashMap<String, Double> filterSelectivities, boolean explain); } | @Test public void estimateJoinCostTest() throws ParsingException { TransactionId tid = new TransactionId(); JoinOptimizer jo; Parser p = new Parser(); String t1Alia = "t1"; String t2Alia = "t2"; jo = new JoinOptimizer(p.generateLogicalPlan(tid, "SELECT * FROM " + tableName1 + " t1, " + tableName2 + " t2 WHERE t1.c1 = t2.c2;"), new Vector<LogicalJoinNode>()); LogicalJoinNode equalsJoinNode = new LogicalJoinNode(t1Alia, t2Alia, Integer.toString(1), Integer.toString(2), Predicate.Op.EQUALS); checkJoinEstimateCosts(jo, equalsJoinNode); jo = new JoinOptimizer(p.generateLogicalPlan(tid, "SELECT * FROM " + tableName1 + " t1, " + tableName2 + " t2 WHERE t1.c1 = t2.c2;"), new Vector<LogicalJoinNode>()); equalsJoinNode = new LogicalJoinNode(t2Alia, t1Alia, Integer.toString(2), Integer.toString(1), Predicate.Op.EQUALS); checkJoinEstimateCosts(jo, equalsJoinNode); jo = new JoinOptimizer(p.generateLogicalPlan(tid, "SELECT * FROM " + tableName1 + " t1, " + tableName1 + " t2 WHERE t1.c3 = t2.c4;"), new Vector<LogicalJoinNode>()); equalsJoinNode = new LogicalJoinNode(t1Alia, t1Alia, Integer.toString(3), Integer.toString(4), Predicate.Op.EQUALS); checkJoinEstimateCosts(jo, equalsJoinNode); jo = new JoinOptimizer(p.generateLogicalPlan(tid, "SELECT * FROM " + tableName2 + " t1, " + tableName2 + " t2 WHERE t1.c8 = t2.c7;"), new Vector<LogicalJoinNode>()); equalsJoinNode = new LogicalJoinNode(t2Alia, t2Alia, Integer.toString(8), Integer.toString(7), Predicate.Op.EQUALS); checkJoinEstimateCosts(jo, equalsJoinNode); } |
JoinOptimizer { public int estimateJoinCardinality(LogicalJoinNode j, int card1, int card2, boolean t1pkey, boolean t2pkey, Map<String, TableStats> stats) { if (j instanceof LogicalSubplanJoinNode) { return card1; } else { return estimateTableJoinCardinality(j.p, j.t1Alias, j.t2Alias, j.f1PureName, j.f2PureName, card1, card2, t1pkey, t2pkey, stats, p.getTableAliasToIdMapping()); } } JoinOptimizer(LogicalPlan p, Vector<LogicalJoinNode> joins); static DbIterator instantiateJoin(LogicalJoinNode lj,
DbIterator plan1, DbIterator plan2); double estimateJoinCost(LogicalJoinNode j, int card1, int card2,
double cost1, double cost2); int estimateJoinCardinality(LogicalJoinNode j, int card1, int card2,
boolean t1pkey, boolean t2pkey, Map<String, TableStats> stats); static int estimateTableJoinCardinality(Predicate.Op joinOp,
String table1Alias, String table2Alias, String field1PureName,
String field2PureName, int card1, int card2, boolean t1pkey,
boolean t2pkey, Map<String, TableStats> stats,
Map<String, Integer> tableAliasToId); @SuppressWarnings("unchecked") Set<Set<T>> enumerateSubsets(Vector<T> v, int size); Vector<LogicalJoinNode> orderJoins(
HashMap<String, TableStats> stats,
HashMap<String, Double> filterSelectivities, boolean explain); } | @Test public void estimateJoinCardinality() throws ParsingException { TransactionId tid = new TransactionId(); Parser p = new Parser(); JoinOptimizer j = new JoinOptimizer(p.generateLogicalPlan(tid, "SELECT * FROM " + tableName2 + " t1, " + tableName2 + " t2 WHERE t1.c8 = t2.c7;"), new Vector<LogicalJoinNode>()); double cardinality; cardinality = j.estimateJoinCardinality(new LogicalJoinNode("t1", "t2", "c"+Integer.toString(3), "c"+Integer.toString(4), Predicate.Op.EQUALS), stats1.estimateTableCardinality(0.8), stats2.estimateTableCardinality(0.2), true, false, TableStats.getStatsMap()); Assert.assertTrue(cardinality == 800 || cardinality == 2000); cardinality = j.estimateJoinCardinality(new LogicalJoinNode("t1", "t2", "c"+Integer.toString(3), "c"+Integer.toString(4), Predicate.Op.EQUALS), stats1.estimateTableCardinality(0.8), stats2.estimateTableCardinality(0.2), false, true,TableStats.getStatsMap()); Assert.assertTrue(cardinality == 800 || cardinality == 2000); } |
JoinOptimizer { public Vector<LogicalJoinNode> orderJoins( HashMap<String, TableStats> stats, HashMap<String, Double> filterSelectivities, boolean explain) throws ParsingException { int numJoinNodes = joins.size(); PlanCache pc = new PlanCache(); Set<LogicalJoinNode> wholeSet = null; for (int i = 1; i <= numJoinNodes; i++) { Set<Set<LogicalJoinNode>> setOfSubset = this.enumerateSubsets(this.joins, i); for (Set<LogicalJoinNode> s : setOfSubset) { if (s.size() == numJoinNodes) { wholeSet = s; } Double bestCostSofar = Double.MAX_VALUE; CostCard bestPlan = new CostCard(); for (LogicalJoinNode toRemove : s) { CostCard plan = computeCostAndCardOfSubplan(stats, filterSelectivities, toRemove, s, bestCostSofar, pc); if (plan != null) { bestCostSofar = plan.cost; bestPlan = plan; } } if (bestPlan.plan != null) { pc.addPlan(s, bestPlan.cost, bestPlan.card, bestPlan.plan); } } } return pc.getOrder(wholeSet); } JoinOptimizer(LogicalPlan p, Vector<LogicalJoinNode> joins); static DbIterator instantiateJoin(LogicalJoinNode lj,
DbIterator plan1, DbIterator plan2); double estimateJoinCost(LogicalJoinNode j, int card1, int card2,
double cost1, double cost2); int estimateJoinCardinality(LogicalJoinNode j, int card1, int card2,
boolean t1pkey, boolean t2pkey, Map<String, TableStats> stats); static int estimateTableJoinCardinality(Predicate.Op joinOp,
String table1Alias, String table2Alias, String field1PureName,
String field2PureName, int card1, int card2, boolean t1pkey,
boolean t2pkey, Map<String, TableStats> stats,
Map<String, Integer> tableAliasToId); @SuppressWarnings("unchecked") Set<Set<T>> enumerateSubsets(Vector<T> v, int size); Vector<LogicalJoinNode> orderJoins(
HashMap<String, TableStats> stats,
HashMap<String, Double> filterSelectivities, boolean explain); } | @Test public void orderJoinsTest() throws ParsingException, IOException, DbException, TransactionAbortedException { final int IO_COST = 101; TransactionId tid = new TransactionId(); JoinOptimizer j; Vector<LogicalJoinNode> result; Vector<LogicalJoinNode> nodes = new Vector<LogicalJoinNode>(); HashMap<String, TableStats> stats = new HashMap<String, TableStats>(); HashMap<String, Double> filterSelectivities = new HashMap<String, Double>(); ArrayList<ArrayList<Integer>> empTuples = new ArrayList<ArrayList<Integer>>(); HeapFile emp = SystemTestUtil.createRandomHeapFile(6, 100000, null, empTuples, "c"); Database.getCatalog().addTable(emp, "emp"); ArrayList<ArrayList<Integer>> deptTuples = new ArrayList<ArrayList<Integer>>(); HeapFile dept = SystemTestUtil.createRandomHeapFile(3, 1000, null, deptTuples, "c"); Database.getCatalog().addTable(dept, "dept"); ArrayList<ArrayList<Integer>> hobbyTuples = new ArrayList<ArrayList<Integer>>(); HeapFile hobby = SystemTestUtil.createRandomHeapFile(6, 1000, null, hobbyTuples, "c"); Database.getCatalog().addTable(hobby, "hobby"); ArrayList<ArrayList<Integer>> hobbiesTuples = new ArrayList<ArrayList<Integer>>(); HeapFile hobbies = SystemTestUtil.createRandomHeapFile(2, 200000, null, hobbiesTuples, "c"); Database.getCatalog().addTable(hobbies, "hobbies"); stats.put("emp", new TableStats(Database.getCatalog().getTableId("emp"), IO_COST)); stats.put("dept", new TableStats(Database.getCatalog().getTableId("dept"), IO_COST)); stats.put("hobby", new TableStats(Database.getCatalog().getTableId("hobby"), IO_COST)); stats.put("hobbies", new TableStats(Database.getCatalog().getTableId("hobbies"), IO_COST)); filterSelectivities.put("emp", 0.1); filterSelectivities.put("dept", 1.0); filterSelectivities.put("hobby", 1.0); filterSelectivities.put("hobbies", 1.0); nodes.add(new LogicalJoinNode("hobbies", "hobby", "c1", "c0", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("emp", "dept", "c1", "c0", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("emp", "hobbies", "c2", "c0", Predicate.Op.EQUALS)); Parser p = new Parser(); j = new JoinOptimizer( p.generateLogicalPlan(tid, "SELECT * FROM emp,dept,hobbies,hobby WHERE emp.c1 = dept.c0 AND hobbies.c0 = emp.c2 AND hobbies.c1 = hobby.c0 AND e.c3 < 1000;"), nodes); result = j.orderJoins(stats, filterSelectivities, false); Assert.assertEquals(result.size(), nodes.size()); Assert.assertFalse(result.get(0).t1Alias == "hobbies"); Assert.assertFalse(result.get(2).t2Alias == "hobbies" && (result.get(0).t1Alias == "hobbies" || result.get(0).t2Alias == "hobbies")); }
@Test(timeout=60000) public void bigOrderJoinsTest() throws IOException, DbException, TransactionAbortedException, ParsingException { final int IO_COST = 103; JoinOptimizer j; HashMap<String, TableStats> stats = new HashMap<String,TableStats>(); Vector<LogicalJoinNode> result; Vector<LogicalJoinNode> nodes = new Vector<LogicalJoinNode>(); HashMap<String, Double> filterSelectivities = new HashMap<String, Double>(); TransactionId tid = new TransactionId(); ArrayList<ArrayList<Integer>> smallHeapFileTuples = new ArrayList<ArrayList<Integer>>(); HeapFile smallHeapFileA = SystemTestUtil.createRandomHeapFile(2, 100, Integer.MAX_VALUE, null, smallHeapFileTuples, "c"); HeapFile smallHeapFileB = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileC = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileD = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileE = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileF = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileG = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileH = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileI = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileJ = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileK = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileL = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileM = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileN = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); ArrayList<ArrayList<Integer>> bigHeapFileTuples = new ArrayList<ArrayList<Integer>>(); for (int i = 0; i < 100000; i++) { bigHeapFileTuples.add( smallHeapFileTuples.get( i%100 ) ); } HeapFile bigHeapFile = createDuplicateHeapFile(bigHeapFileTuples, 2, "c"); Database.getCatalog().addTable(bigHeapFile, "bigTable"); Database.getCatalog().addTable(smallHeapFileA, "a"); Database.getCatalog().addTable(smallHeapFileB, "b"); Database.getCatalog().addTable(smallHeapFileC, "c"); Database.getCatalog().addTable(smallHeapFileD, "d"); Database.getCatalog().addTable(smallHeapFileE, "e"); Database.getCatalog().addTable(smallHeapFileF, "f"); Database.getCatalog().addTable(smallHeapFileG, "g"); Database.getCatalog().addTable(smallHeapFileH, "h"); Database.getCatalog().addTable(smallHeapFileI, "i"); Database.getCatalog().addTable(smallHeapFileJ, "j"); Database.getCatalog().addTable(smallHeapFileK, "k"); Database.getCatalog().addTable(smallHeapFileL, "l"); Database.getCatalog().addTable(smallHeapFileM, "m"); Database.getCatalog().addTable(smallHeapFileN, "n"); stats.put("bigTable", new TableStats(bigHeapFile.getId(), IO_COST)); stats.put("a", new TableStats(smallHeapFileA.getId(), IO_COST)); stats.put("b", new TableStats(smallHeapFileB.getId(), IO_COST)); stats.put("c", new TableStats(smallHeapFileC.getId(), IO_COST)); stats.put("d", new TableStats(smallHeapFileD.getId(), IO_COST)); stats.put("e", new TableStats(smallHeapFileE.getId(), IO_COST)); stats.put("f", new TableStats(smallHeapFileF.getId(), IO_COST)); stats.put("g", new TableStats(smallHeapFileG.getId(), IO_COST)); stats.put("h", new TableStats(smallHeapFileG.getId(), IO_COST)); stats.put("i", new TableStats(smallHeapFileG.getId(), IO_COST)); stats.put("j", new TableStats(smallHeapFileG.getId(), IO_COST)); stats.put("k", new TableStats(smallHeapFileG.getId(), IO_COST)); stats.put("l", new TableStats(smallHeapFileG.getId(), IO_COST)); stats.put("m", new TableStats(smallHeapFileG.getId(), IO_COST)); stats.put("n", new TableStats(smallHeapFileG.getId(), IO_COST)); filterSelectivities.put("bigTable", 1.0); filterSelectivities.put("a", 1.0); filterSelectivities.put("b", 1.0); filterSelectivities.put("c", 1.0); filterSelectivities.put("d", 1.0); filterSelectivities.put("e", 1.0); filterSelectivities.put("f", 1.0); filterSelectivities.put("g", 1.0); filterSelectivities.put("h", 1.0); filterSelectivities.put("i", 1.0); filterSelectivities.put("j", 1.0); filterSelectivities.put("k", 1.0); filterSelectivities.put("l", 1.0); filterSelectivities.put("m", 1.0); filterSelectivities.put("n", 1.0); nodes.add(new LogicalJoinNode("a", "b", "c1", "c1", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("b", "c", "c0", "c0", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("c", "d", "c1", "c1", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("d", "e", "c0", "c0", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("e", "f", "c1", "c1", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("f", "g", "c0", "c0", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("g", "h", "c1", "c1", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("h", "i", "c0", "c0", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("i", "j", "c1", "c1", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("j", "k", "c0", "c0", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("k", "l", "c1", "c1", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("l", "m", "c0", "c0", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("m", "n", "c1", "c1", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("n", "bigTable", "c0", "c0", Predicate.Op.EQUALS)); Collections.shuffle(nodes); Parser p = new Parser(); j = new JoinOptimizer( p.generateLogicalPlan(tid, "SELECT COUNT(a.c0) FROM bigTable, a, b, c, d, e, f, g, h, i, j, k, l, m, n WHERE bigTable.c0 = n.c0 AND a.c1 = b.c1 AND b.c0 = c.c0 AND c.c1 = d.c1 AND d.c0 = e.c0 AND e.c1 = f.c1 AND f.c0 = g.c0 AND g.c1 = h.c1 AND h.c0 = i.c0 AND i.c1 = j.c1 AND j.c0 = k.c0 AND k.c1 = l.c1 AND l.c0 = m.c0 AND m.c1 = n.c1;"), nodes); result = j.orderJoins(stats, filterSelectivities, false); Assert.assertEquals(result.size(), nodes.size()); Assert.assertEquals(result.get(result.size()-1).t2Alias, "bigTable"); }
@Test public void nonequalityOrderJoinsTest() throws IOException, DbException, TransactionAbortedException, ParsingException { final int IO_COST = 103; JoinOptimizer j; HashMap<String, TableStats> stats = new HashMap<String,TableStats>(); Vector<LogicalJoinNode> result; Vector<LogicalJoinNode> nodes = new Vector<LogicalJoinNode>(); HashMap<String, Double> filterSelectivities = new HashMap<String, Double>(); TransactionId tid = new TransactionId(); ArrayList<ArrayList<Integer>> smallHeapFileTuples = new ArrayList<ArrayList<Integer>>(); HeapFile smallHeapFileA = SystemTestUtil.createRandomHeapFile(2, 100, Integer.MAX_VALUE, null, smallHeapFileTuples, "c"); HeapFile smallHeapFileB = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileC = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); HeapFile smallHeapFileD = createDuplicateHeapFile(smallHeapFileTuples, 2, "c"); Database.getCatalog().addTable(smallHeapFileA, "a"); Database.getCatalog().addTable(smallHeapFileB, "b"); Database.getCatalog().addTable(smallHeapFileC, "c"); Database.getCatalog().addTable(smallHeapFileD, "d"); stats.put("a", new TableStats(smallHeapFileA.getId(), IO_COST)); stats.put("b", new TableStats(smallHeapFileB.getId(), IO_COST)); stats.put("c", new TableStats(smallHeapFileC.getId(), IO_COST)); stats.put("d", new TableStats(smallHeapFileD.getId(), IO_COST)); filterSelectivities.put("a", 1.0); filterSelectivities.put("b", 1.0); filterSelectivities.put("c", 1.0); filterSelectivities.put("d", 1.0); nodes.add(new LogicalJoinNode("a", "b", "c1", "c1", Predicate.Op.LESS_THAN)); nodes.add(new LogicalJoinNode("b", "c", "c0", "c0", Predicate.Op.EQUALS)); nodes.add(new LogicalJoinNode("c", "d", "c1", "c1", Predicate.Op.EQUALS)); Parser p = new Parser(); j = new JoinOptimizer( p.generateLogicalPlan(tid, "SELECT COUNT(a.c0) FROM a, b, c, d WHERE a.c1 < b.c1 AND b.c0 = c.c0 AND c.c1 = d.c1;"), nodes); result = j.orderJoins(stats, filterSelectivities, false); Assert.assertEquals(result.size(), nodes.size()); Assert.assertTrue(result.get(result.size() - 1).t2Alias.equals("a") || result.get(result.size() - 1).t1Alias.equals("a")); } |
Transaction { public void transactionComplete(boolean abort) throws IOException { if (started) { if (abort) { Database.getLogFile().logAbort(tid); } else { Database.getBufferPool().flushPages(tid); Database.getLogFile().logCommit(tid); } try { Database.getBufferPool().transactionComplete(tid, !abort); } catch (IOException e) { e.printStackTrace(); } started = false; } } Transaction(); void start(); TransactionId getId(); void commit(); void abort(); void transactionComplete(boolean abort); } | @Test public void attemptTransactionTwice() throws Exception { bp.getPage(tid1, p0, Permissions.READ_ONLY); bp.getPage(tid1, p1, Permissions.READ_WRITE); bp.transactionComplete(tid1, true); bp.getPage(tid2, p0, Permissions.READ_WRITE); bp.getPage(tid2, p0, Permissions.READ_WRITE); } |
Join extends Operator { public TupleDesc getTupleDesc() { return td; } Join(JoinPredicate p, DbIterator child1, DbIterator child2); @Override String getName(); JoinPredicate getJoinPredicate(); String getJoinField1Name(); String getJoinField2Name(); TupleDesc getTupleDesc(); void open(); void close(); void rewind(); @Override DbIterator[] getChildren(); @Override void setChildren(DbIterator[] children); static final int blockMemory; } | @Test public void getTupleDesc() { JoinPredicate pred = new JoinPredicate(0, Predicate.Op.EQUALS, 0); Join op = new Join(pred, scan1, scan2); TupleDesc expected = Utility.getTupleDesc(width1 + width2); TupleDesc actual = op.getTupleDesc(); assertEquals(expected, actual); } |
WebsiteRestController { @RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_PROFILES_USER_COMMENTS) public HttpEntity<PagedResources<PublicCommentResource>> getUserApprovedCommentPosts( @PathVariable("userId") String userId, @PageableDefault(size = UtilConstants.DEFAULT_RETURN_RECORD_COUNT, page = 0) Pageable pageable, PagedResourcesAssembler<CommentPost> assembler) throws ResourceNotFoundException { Page<CommentPost> commentPosts = this.commentPostRepository.findByAuthorIdAndStatusOrderByCreatedTimeDesc( userId, CommentStatusType.APPROVED, pageable); return new ResponseEntity<>(assembler.toResource(commentPosts, publicCommentResourceAssembler), HttpStatus.OK); } @Inject WebsiteRestController(
UserAccountService userAccountService,
UserAccountRepository userAccountRepository,
BlogPostRepository blogPostRepository,
CommentPostRepository commentPostRepository,
MessageSender messageSender,
WebsiteResourceAssembler websiteResourceAssembler,
PublicBlogResourceAssembler publicBlogResourceAssembler,
PublicCommentResourceAssembler publicCommentResourceAssembler,
UserProfileResourceAssembler userProfileResourceAssembler); @RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE) HttpEntity<WebsiteResource> getPublicWebsiteResource(); @RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_CURRENT_USER) HttpEntity<Resource<UserAccount>> getCurrentUserAccount(); @RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_PROFILES_USER) HttpEntity<UserProfileResource> getUserProfile(@PathVariable("userId") String userId); @RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_PROFILES_USER_COMMENTS) HttpEntity<PagedResources<PublicCommentResource>> getUserApprovedCommentPosts(
@PathVariable("userId") String userId,
@PageableDefault(size = UtilConstants.DEFAULT_RETURN_RECORD_COUNT, page = 0) Pageable pageable,
PagedResourcesAssembler<CommentPost> assembler); @RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_LATEST_BLOG) HttpEntity<PublicBlogResource> getLatestBlogPost(); @RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_RECENT_BLOGS) HttpEntity<Resources<PublicBlogResource>> getRecentPublicBlogPosts(); @RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_RECENT_COMMENTS) HttpEntity<Resources<Resource<CommentPost>>> getRecentPublicCommentPosts(); @RequestMapping(method = RequestMethod.GET, value = ApiUrls.URL_SITE_TAG_CLOUDS) HttpEntity<TagCloud[]> getTagCloud(); @RequestMapping(method = RequestMethod.POST, value = ApiUrls.URL_SITE_CONTACT) @ResponseBody String submitContactMessage(@RequestBody ContactForm contactForm); static final int MOST_RECENT_NUMBER; } | @Test public void getUserApprovedCommentPosts() throws Exception { Page<CommentPost> page = new PageImpl<CommentPost>(getTestApprovedCommentPostList(), new PageRequest(0, 10), 2); when(commentPostRepositoryMock.findByAuthorIdAndStatusOrderByCreatedTimeDesc( eq(USER_ID), eq(CommentStatusType.APPROVED), any(Pageable.class))) .thenReturn(page); mockMvc.perform(get(ApiUrls.API_ROOT + ApiUrls.URL_SITE_PROFILES_USER_COMMENTS, USER_ID)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaTypes.HAL_JSON)) .andExpect(jsonPath("$._embedded.commentPostList", hasSize(2))) .andExpect(jsonPath("$._embedded.commentPostList[0].id", is(COMMENTS_1_ID))) .andExpect(jsonPath("$._embedded.commentPostList[0].blogPostId", is(BLOG_ID))) .andExpect(jsonPath("$._embedded.commentPostList[0].authorId", is(COMMENTS_1_AUTHOR_ID))) .andExpect(jsonPath("$._embedded.commentPostList[0].content", is (COMMENTS_1_CONTENT))) .andExpect(jsonPath("$._embedded.commentPostList[1].id", is(COMMENTS_2_ID))) .andExpect(jsonPath("$._embedded.commentPostList[1].blogPostId", is(BLOG_ID))) .andExpect(jsonPath("$._embedded.commentPostList[1].authorId", is(COMMENTS_2_AUTHOR_ID))) .andExpect(jsonPath("$._embedded.commentPostList[1].content", is(COMMENTS_2_CONTENT))) .andExpect(jsonPath("$._links.self.templated", is(true))) .andExpect(jsonPath("$._links.self.href", endsWith("/comments{?page,size,sort}"))) .andExpect(jsonPath("$.page.size", is(10))) .andExpect(jsonPath("$.page.totalElements", is(2))) .andExpect(jsonPath("$.page.totalPages", is(1))) .andExpect(jsonPath("$.page.number", is(0))) ; verify(commentPostRepositoryMock, times(1)).findByAuthorIdAndStatusOrderByCreatedTimeDesc( eq(USER_ID), eq(CommentStatusType.APPROVED), any(Pageable.class)); verifyNoMoreInteractions(commentPostRepositoryMock); } |
UserAccount extends BaseAuditableEntity implements SocialUserDetails { public boolean isAuthor(){ for (UserRoleType role : getRoles()) { if (role == UserRoleType.ROLE_AUTHOR){ return true; } } return false; } UserAccount(); UserAccount(String userId, UserRoleType[] roles); String getUserId(); void setUserId(String userId); UserRoleType[] getRoles(); void setRoles(UserRoleType[] roles); String getEmail(); void setEmail(String email); String getDisplayName(); void setDisplayName(String displayName); String getImageUrl(); void setImageUrl(String imageUrl); String getWebSite(); void setWebSite(String webSite); boolean isAccountLocked(); void setAccountLocked(boolean accountLocked); boolean isTrustedAccount(); void setTrustedAccount(boolean trustedAccount); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override String getPassword(); @Override String getUsername(); boolean isAuthor(); boolean isAdmin(); void updateProfile(String displayName, String email, String webSite); @Override String toString(); } | @Test public void testIsAuthor() { UserAccount normalUser = new UserAccount(); assertFalse(normalUser.isAuthor()); UserRoleType[] roles = new UserRoleType[]{UserRoleType.ROLE_USER, UserRoleType.ROLE_AUTHOR}; UserAccount author = new UserAccount("1234", roles); assertTrue(author.isAuthor()); } |
UserAccount extends BaseAuditableEntity implements SocialUserDetails { public boolean isAdmin(){ for (UserRoleType role : getRoles()) { if (role == UserRoleType.ROLE_ADMIN){ return true; } } return false; } UserAccount(); UserAccount(String userId, UserRoleType[] roles); String getUserId(); void setUserId(String userId); UserRoleType[] getRoles(); void setRoles(UserRoleType[] roles); String getEmail(); void setEmail(String email); String getDisplayName(); void setDisplayName(String displayName); String getImageUrl(); void setImageUrl(String imageUrl); String getWebSite(); void setWebSite(String webSite); boolean isAccountLocked(); void setAccountLocked(boolean accountLocked); boolean isTrustedAccount(); void setTrustedAccount(boolean trustedAccount); @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override String getPassword(); @Override String getUsername(); boolean isAuthor(); boolean isAdmin(); void updateProfile(String displayName, String email, String webSite); @Override String toString(); } | @Test public void testIsAdmin() { UserAccount normalUser = new UserAccount(); assertFalse(normalUser.isAdmin()); UserRoleType[] roles = new UserRoleType[]{UserRoleType.ROLE_USER, UserRoleType.ROLE_ADMIN}; UserAccount author = new UserAccount("1234", roles); assertTrue(author.isAdmin()); } |
SingleEntryScope extends AbstractScope implements Scope { public <T> T call(Callable<T> toCall, Object... scopeContents) throws Exception { enter(scopeContents); try { return toCall.call(); } finally { exit(); } } void run(Runnable toRun, Object... scopeContents); T call(Callable<T> toCall, Object... scopeContents); @Override boolean inScope(); } | @Test public void testCall() throws Exception { class I implements ThrowingFunction<String, String> { @Override public String apply(String argument) throws Exception { X x = deps.getInstance(X.class); assertNotNull(x); assertEquals("test", x.toString()); return argument + "." + x.toString(); } } String s = SCOPE.run(new I(), "hello", x); assertNotNull(s); assertEquals("hello." + x.toString(), s); } |
ReentrantScope extends AbstractScope { public boolean inScope() { List<?> l = this.lists.get(); return l != null && !l.isEmpty(); } ReentrantScope(); ReentrantScope(Provider<String> injectionInfoProvider); QuietAutoCloseable enter(Object... o); @Override void exit(); boolean inScope(); } | @Test public void testInScope() throws Exception { final int limit = 10; StringBuilder constant = new StringBuilder("hello"); final boolean[] ran = new boolean[1]; class One implements ThrowingFunction<Integer, Void> { @Override public Void apply(Integer argument) throws Exception { ran[0] = true; assertNotNull(dependencies.getInstance(Integer.class)); assertEquals(argument, dependencies.getInstance(Integer.class)); assertNotNull(dependencies.getInstance(String.class)); assertEquals(argument.toString(), dependencies.getInstance(String.class)); assertNotNull(dependencies.getInstance(StringBuilder.class)); assertEquals("hello", dependencies.getInstance(StringBuilder.class).toString()); int next = argument + 1; if (next < limit) { dependencies.getInstance(AbstractScope.class) .run(this, next, Integer.valueOf(next), Integer.toString(next)); } return null; } } assertTrue(dependencies.getInstance(AbstractScope.class) instanceof ReentrantScope); dependencies.getInstance(AbstractScope.class).run(new One(), 1, constant, Integer.valueOf(1), Integer.toString(1)); assertTrue("Invokable was not run", ran[0]); } |
ExecutorServiceProvider implements Provider<ExecutorService> { @Override public ExecutorService get() { ExecutorService result = null; if (registered.compareAndSet(false, true)) { synchronized (this) { if (exe == null) { result = exe = svc.get(); reg.get().add(exe); } else { result = exe; } } } if (result == null) { synchronized (this) { result = exe; } assert result != null; } return result; } ExecutorServiceProvider(Supplier<ExecutorService> svc, Provider<ShutdownHookRegistry> reg); @Override ExecutorService get(); static Provider<ExecutorService> provider(Supplier<ExecutorService> supplier, Binder binder); static Provider<ExecutorService> provider(int threads, Binder binder); static Provider<ExecutorService> provider(Binder binder); } | @Test public void testSomeMethod() throws IOException, InterruptedException, ExecutionException { Dependencies deps = new Dependencies(new M()); Thing thing = deps.getInstance(Thing.class); ExecutorService exe = deps.getInstance(ExecutorService.class); assertNotNull(exe); assertSame(thing.p.get(), exe); exe.submit(() -> { new StringBuilder("Hello.").append(1); }).get(); assertFalse(exe.isShutdown()); assertFalse(exe.isTerminated()); assertSame(exe, thing.p.get()); deps.shutdown(); assertTrue(exe.isShutdown()); } |
Dependencies { public <T> T getInstance(Class<T> type) { return getInjector().getInstance(type); } Dependencies(Module... modules); Dependencies(Settings configuration, Module... modules); Dependencies(boolean mergeNamespaces, Map<String, Settings> settings, Set<SettingsBindings> settingsBindings, Module... modules); @Override String toString(); static Dependencies create(Module... modules); static DependenciesBuilder builder(); Injector getInjector(); T getInstance(Class<T> type); T getInstance(Key<T> key); void shutdown(); static Module createBindings(Settings config); boolean isProductionMode(); static boolean isProductionMode(Settings settings); Settings getSettings(); Settings getSettings(String namespace); Stage getStage(); static boolean isIDEMode(); void autoShutdownRefresh(SettingsBuilder sb); void injectMembers(Object arg); final Dependencies alsoShutdown(Dependencies other); static Set<String> loadNamespaceListsFromClasspath(); static final String SYSTEM_PROP_PRODUCTION_MODE; static final String IDE_MODE_SYSTEM_PROPERTY; } | @Test public void testNamedSettings() throws Throwable { MutableSettings settings = SettingsBuilder.createDefault().buildMutableSettings(); settings.setString("stuff", "This is stuff"); assertEquals("This is stuff", settings.getString("stuff")); assertTrue(settings.allKeys().contains("stuff")); assertTrue(settings.toProperties().containsKey("stuff")); Dependencies deps = new Dependencies(settings); Thing thing = deps.getInstance(Thing.class); assertNotNull(thing); assertNotNull(thing.value); assertEquals("This is stuff", thing.value); assertNull(thing.moreStuff); } |
Reschedulables { public Reschedulable withSimpleDelay(Duration delay, Runnable runnable) { return withSimpleDelay(delay, new CallableForRunnable(runnable)); } @Inject Reschedulables(Settings settings, ShutdownHookRegistry reg, UncaughtExceptionHandler onError); private Reschedulables(int count, ShutdownHookRegistry reg, UncaughtExceptionHandler onError); Reschedulables(ExecutorService threadPool, int threads, UncaughtExceptionHandler onError); Reschedulable withSimpleDelay(Duration delay, Runnable runnable); Reschedulable withSimpleDelay(Duration delay, Callable<?> callable); Reschedulable withResettingDelay(Duration delay, Runnable runnable); Reschedulable withResettingDelay(Duration delay, Callable<?> callable); Reschedulable withSimpleDelayAndMaximum(Duration delay, Runnable runnable, Duration maxElapsed); Reschedulable withSimpleDelayAndMaximum(Duration delay, Callable<?> callable, Duration maxElapsed); Reschedulable withResettingDelayAndMaximumSinceFirstTouch(Duration delay, Runnable runnable, Duration maxElapsed); Reschedulable withResettingDelayAndMaximumSinceFirstTouch(Duration delay, Callable<?> callable, Duration maxElapsed); Reschedulable withResettingDelayAndMaximumSinceLastRun(Duration delay, Runnable runnable, Duration maxElapsed); Reschedulable withResettingDelayAndMaximumSinceLastRun(Duration delay, Callable<?> callable, Duration maxElapsed); static final String SETTINGS_KEY_RESCHEDULABLES_THREADS; } | @Test public void testSimpleDelay() throws Throwable { Runner run = new Runner(); Reschedulable r = rs.withSimpleDelay(Duration.ofMillis(100), run); run.assertWasNotRun(); Thread.sleep(150); run.assertWasNotRun(); long now = System.currentTimeMillis(); r.touch(); Thread.sleep(150); run.assertWasRun(); run.assertRunCount(1); uncaught.assertNotThrown(); run.assertTimestamp(now, 100, 20); }
@Test public void testTemporaryDelay() throws Throwable { Runner run = new Runner(); Reschedulable r = rs.withSimpleDelay(Duration.ofMillis(100), run); run.assertWasNotRun(); Thread.sleep(150); run.assertWasNotRun(); long now = System.currentTimeMillis(); r.touch(Duration.ofMillis(200)); Thread.sleep(150); run.assertWasNotRun(); Thread.sleep(60); run.assertWasRun(); run.assertRunCount(1); uncaught.assertNotThrown(); run.assertTimestamp(now, 200, 20); }
@Test public void testSettingDelay() throws Throwable { Runner run = new Runner(); Reschedulable r = rs.withSimpleDelay(Duration.ofMillis(100), run); run.assertWasNotRun(); long now = System.currentTimeMillis(); r.touch(Duration.ofMillis(200)); Thread.sleep(120); run.assertWasNotRun(); Thread.sleep(100); run.assertWasRun(); run.assertRunCount(1); uncaught.assertNotThrown(); run.assertTimestamp(now, 200, 20); } |
Reschedulables { public Reschedulable withResettingDelay(Duration delay, Runnable runnable) { return withResettingDelay(delay, new CallableForRunnable(runnable)); } @Inject Reschedulables(Settings settings, ShutdownHookRegistry reg, UncaughtExceptionHandler onError); private Reschedulables(int count, ShutdownHookRegistry reg, UncaughtExceptionHandler onError); Reschedulables(ExecutorService threadPool, int threads, UncaughtExceptionHandler onError); Reschedulable withSimpleDelay(Duration delay, Runnable runnable); Reschedulable withSimpleDelay(Duration delay, Callable<?> callable); Reschedulable withResettingDelay(Duration delay, Runnable runnable); Reschedulable withResettingDelay(Duration delay, Callable<?> callable); Reschedulable withSimpleDelayAndMaximum(Duration delay, Runnable runnable, Duration maxElapsed); Reschedulable withSimpleDelayAndMaximum(Duration delay, Callable<?> callable, Duration maxElapsed); Reschedulable withResettingDelayAndMaximumSinceFirstTouch(Duration delay, Runnable runnable, Duration maxElapsed); Reschedulable withResettingDelayAndMaximumSinceFirstTouch(Duration delay, Callable<?> callable, Duration maxElapsed); Reschedulable withResettingDelayAndMaximumSinceLastRun(Duration delay, Runnable runnable, Duration maxElapsed); Reschedulable withResettingDelayAndMaximumSinceLastRun(Duration delay, Callable<?> callable, Duration maxElapsed); static final String SETTINGS_KEY_RESCHEDULABLES_THREADS; } | @Test public void testResettingDelay() throws Throwable { Runner run = new Runner(); Reschedulable r = rs.withResettingDelay(Duration.ofMillis(100), run); run.assertWasNotRun(); r.touch(); Thread.sleep(40); long now = System.currentTimeMillis(); r.touch(); Thread.sleep(150); run.assertWasRun(); run.assertRunCount(1); uncaught.assertNotThrown(); run.assertTimestamp(now, 100, 20); } |
Migration { private void rollback(MongoDatabase db, Document agg) { CountDownLatch latch = new CountDownLatch(backupQueryForCollection.size() - 1); Document rollbacks = new Document(); agg.append("rollback", rollbacks); for (String s : backupQueryForCollection.keySet()) { MongoCollection<Document> from = db.getCollection(backupCollectionName(s)); MongoCollection<Document> to = db.getCollection(s); Document thisCollection = new Document(); rollbacks.append(s, thisCollection); AtomicInteger batchCount = new AtomicInteger(); from.find().batchCursor((cursor, thrown) -> { if (thrown != null) { latch.countDown(); return; } cursor.setBatchSize(50); cursor.next((List<Document> l, Throwable t2) -> { List<ReplaceOneModel<Document>> replacements = new ArrayList<>(); if (l == null) { latch.countDown(); } else { int ct = batchCount.incrementAndGet(); thisCollection.append("batch-" + ct, l.size()); for (Document d : l) { replacements.add(new ReplaceOneModel<>(new Document("_id", d.getObjectId("_id")), d)); } to.bulkWrite(replacements, (bwr, th2) -> { if (th2 != null) { thisCollection.append("batch-" + ct + "-failed", true); thisCollection.append("batch-" + ct + "-succeeded", appendThrowable(th2)); } else { thisCollection.append("batch-" + ct + "-succeeded", l.size()); } }); } }); }); } try { latch.await(); } catch (InterruptedException ex) { Exceptions.chuck(ex); } } Migration(String name, int newVersion, Map<String, OneOf<MigrationWorker, Class<? extends MigrationWorker>>> migrations, Map<String, Document> backupQueryForCollection); boolean isEmpty(); static CompletableFuture<T> future(String name); CompletableFuture<Document> migrate(CompletableFuture<Document> f, MongoClient client, MongoDatabase db, Function<Class<? extends MigrationWorker>, MigrationWorker> converter); } | @Test public void testRollback(@Named("stuff") Provider<MongoCollection<Document>> stuff, @Named("migrations") Provider<MongoCollection<Document>> migrations, Provider<MongoDatabase> db, Provider<MongoClient> client, Provider<Dependencies> deps) throws InterruptedException, Throwable { Function<Class<? extends MigrationWorker>, MigrationWorker> convert = deps.get()::getInstance; Migration[] m = new Migration[1]; new MigrationBuilder("stuff-new", 12, (mig) -> { m[0] = (Migration) mig; return null; }).backup("stuff", new Document("index", new Document("$lte", 150))) .migrateCollection("stuff", Failer.class).build(); assertNotNull(m[0]); CompletableFuture<Document> cf = new CompletableFuture<>(); CompletableFuture<Document> res = m[0].migrate(cf, client.get(), db.get(), convert); Document[] ds = new Document[1]; Throwable[] thr = new Throwable[1]; CountDownLatch latch = new CountDownLatch(1); res.whenCompleteAsync((doc, thrown) -> { thr[0] = thrown; ds[0] = doc; latch.countDown(); }); cf.complete(new Document()); latch.await(20, TimeUnit.SECONDS); assertNotNull(thr[0]); assertTrue(thr[0] instanceof CompletionException); if (!(thr[0].getCause() instanceof FooException)) { throw thr[0]; } assertEquals("Failed", thr[0].getCause().getMessage()); assertNull(ds[0]); Thread.sleep(750); TestSupport.await(ts -> { stuff.get().find().forEach(d -> { assertFalse(d.toString(), d.containsKey("author")); assertTrue(d.toString(), d.containsKey("created")); assertFalse(d.toString(), d.containsKey("ix")); assertTrue(d.toString(), d.containsKey("index")); }, ts.doneCallback()); }); } |
PublisherConfirms { static void publishMessagesIndividually() throws Exception { try (Connection connection = createConnection()) { Channel ch = connection.createChannel(); String queue = UUID.randomUUID().toString(); ch.queueDeclare(queue, false, false, true, null); ch.confirmSelect(); long start = System.nanoTime(); for (int i = 0; i < MESSAGE_COUNT; i++) { String body = String.valueOf(i); ch.basicPublish("", queue, null, body.getBytes()); ch.waitForConfirmsOrDie(5_000); } long end = System.nanoTime(); System.out.format("Published %,d messages individually in %,d ms%n", MESSAGE_COUNT, Duration.ofNanos(end - start).toMillis()); } } static void main(String[] args); } | @Test @DisplayName("publish messages individually") void publishMessagesIndividually() throws Exception { Channel ch = connection.createChannel(); ch.confirmSelect(); for (int i = 0; i < messageCount; i++) { String body = String.valueOf(i); ch.basicPublish("", queue, null, body.getBytes()); ch.waitForConfirmsOrDie(5_000); meter.mark(); } ch.close(); CountDownLatch latch = new CountDownLatch(messageCount); ch = connection.createChannel(); ch.basicConsume(queue, true, ((consumerTag, message) -> latch.countDown()), consumerTag -> { }); assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue(); } |
PublisherConfirms { static void publishMessagesInBatch() throws Exception { try (Connection connection = createConnection()) { Channel ch = connection.createChannel(); String queue = UUID.randomUUID().toString(); ch.queueDeclare(queue, false, false, true, null); ch.confirmSelect(); int batchSize = 100; int outstandingMessageCount = 0; long start = System.nanoTime(); for (int i = 0; i < MESSAGE_COUNT; i++) { String body = String.valueOf(i); ch.basicPublish("", queue, null, body.getBytes()); outstandingMessageCount++; if (outstandingMessageCount == batchSize) { ch.waitForConfirmsOrDie(5_000); outstandingMessageCount = 0; } } if (outstandingMessageCount > 0) { ch.waitForConfirmsOrDie(5_000); } long end = System.nanoTime(); System.out.format("Published %,d messages in batch in %,d ms%n", MESSAGE_COUNT, Duration.ofNanos(end - start).toMillis()); } } static void main(String[] args); } | @Test @DisplayName("publish messages in batch") void publishMessagesInBatch() throws Exception { Channel ch = connection.createChannel(); ch.confirmSelect(); int batchSize = 100; int outstandingMessageCount = 0; for (int i = 0; i < messageCount; i++) { String body = String.valueOf(i); ch.basicPublish("", queue, null, body.getBytes()); outstandingMessageCount++; if (outstandingMessageCount == batchSize) { ch.waitForConfirmsOrDie(5_000); outstandingMessageCount = 0; } meter.mark(); } if (outstandingMessageCount > 0) { ch.waitForConfirmsOrDie(5_000); } ch.close(); CountDownLatch latch = new CountDownLatch(messageCount); ch = connection.createChannel(); ch.basicConsume(queue, true, ((consumerTag, message) -> latch.countDown()), consumerTag -> { }); assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue(); } |
PublisherConfirms { static boolean waitUntil(Duration timeout, BooleanSupplier condition) throws InterruptedException { int waited = 0; while (!condition.getAsBoolean() && waited < timeout.toMillis()) { Thread.sleep(100L); waited = +100; } return condition.getAsBoolean(); } static void main(String[] args); } | @Test @DisplayName("allow max of outstanding confirms") void allowMaxOfOutstandingConfirms() throws Exception { int maxOutstandingConfirms = 100; Semaphore semaphore = new Semaphore(maxOutstandingConfirms); Channel ch = connection.createChannel(); ch.confirmSelect(); ConcurrentSkipListSet<Long> outstandingConfirms = new ConcurrentSkipListSet<>(); ConfirmCallback handleConfirm = (deliveryTag, multiple) -> { if (multiple) { NavigableSet<Long> confirmed = outstandingConfirms.headSet(deliveryTag, true); int confirmedSize = confirmed.size(); confirmed.clear(); semaphore.release(confirmedSize); } else { outstandingConfirms.remove(deliveryTag); semaphore.release(); } }; ch.addConfirmListener(handleConfirm, handleConfirm); for (int i = 0; i < messageCount; i++) { String body = String.valueOf(i); boolean acquired = semaphore.tryAcquire(10, TimeUnit.SECONDS); if (!acquired) { throw new IllegalStateException("Could not publish because of too many outstanding publisher confirms"); } outstandingConfirms.add(ch.getNextPublishSeqNo()); ch.basicPublish("", queue, null, body.getBytes()); meter.mark(); } assertThat(waitUntil(Duration.ofSeconds(5), () -> outstandingConfirms.isEmpty())).isTrue(); ch.close(); CountDownLatch latch = new CountDownLatch(messageCount); ch = connection.createChannel(); ch.basicConsume(queue, true, ((consumerTag, message) -> latch.countDown()), consumerTag -> { }); assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue(); }
@Test @DisplayName("resend unconfirmed messages") void resendUnconfirmedMessagesIntegration() throws Exception { Channel ch = connection.createChannel(); ch.confirmSelect(); Map<Long, String> outstandingConfirms = resendUnconfirmedMessages(ch); assertThat(waitUntil(Duration.ofSeconds(5), () -> outstandingConfirms.isEmpty())).isTrue(); ch.close(); Set<String> receivedMessages = ConcurrentHashMap.newKeySet(messageCount); CountDownLatch latch = new CountDownLatch(messageCount); ch = connection.createChannel(); ch.basicConsume(queue, true, ((consumerTag, message) -> { receivedMessages.add(new String(message.getBody())); latch.countDown(); }), consumerTag -> { }); assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue(); assertThat(receivedMessages).hasSize(messageCount); }
@Test @DisplayName("resend unconfirmed messages with lower bound and map confirm handling") void resendUnconfirmedMessagesUseLowerBoundAndConcurrentMapIntegration() throws Exception { Channel ch = connection.createChannel(); ch.confirmSelect(); Map<Long, String> outstandingConfirms = resendUnconfirmedMessagesUseLowerBoundAndConcurrentMap(ch); assertThat(waitUntil(Duration.ofSeconds(5), () -> outstandingConfirms.isEmpty())).isTrue(); ch.close(); Set<String> receivedMessages = ConcurrentHashMap.newKeySet(messageCount); CountDownLatch latch = new CountDownLatch(messageCount); ch = connection.createChannel(); ch.basicConsume(queue, true, ((consumerTag, message) -> { receivedMessages.add(new String(message.getBody())); latch.countDown(); }), consumerTag -> { }); assertThat(latch.await(60, TimeUnit.SECONDS)).isTrue(); assertThat(receivedMessages).hasSize(messageCount); } |
HessianProtocol extends AbstractProxyProtocol { public HessianProtocol() { super(HessianException.class); } HessianProtocol(); void setHttpBinder(HttpBinder httpBinder); @Override int getDefaultPort(); @Override void destroy(); } | @Test public void testHessianProtocol() { HessianServiceImpl server = new HessianServiceImpl(); Assertions.assertFalse(server.isCalled()); ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf("hessian: Exporter<HessianService> exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); Invoker<HessianService> invoker = protocol.refer(HessianService.class, url); HessianService client = proxyFactory.getProxy(invoker); String result = client.sayHello("haha"); Assertions.assertTrue(server.isCalled()); Assertions.assertEquals("Hello, haha", result); invoker.destroy(); exporter.unexport(); } |
EagerThreadPoolExecutor extends ThreadPoolExecutor { @Override public void execute(Runnable command) { if (command == null) { throw new NullPointerException(); } submittedTaskCount.incrementAndGet(); try { super.execute(command); } catch (RejectedExecutionException rx) { final TaskQueue queue = (TaskQueue) super.getQueue(); try { if (!queue.retryOffer(command, 0, TimeUnit.MILLISECONDS)) { submittedTaskCount.decrementAndGet(); throw new RejectedExecutionException("Queue capacity is full.", rx); } } catch (InterruptedException x) { submittedTaskCount.decrementAndGet(); throw new RejectedExecutionException(x); } } catch (Throwable t) { submittedTaskCount.decrementAndGet(); throw t; } } EagerThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit, TaskQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler); int getSubmittedTaskCount(); @Override void execute(Runnable command); } | @Test public void testEagerThreadPool() throws Exception { String name = "eager-tf"; int queues = 5; int cores = 5; int threads = 10; long alive = 1000; TaskQueue<Runnable> taskQueue = new TaskQueue<Runnable>(queues); final EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(cores, threads, alive, TimeUnit.MILLISECONDS, taskQueue, new NamedThreadFactory(name, true), new AbortPolicyWithReport(name, URL)); taskQueue.setExecutor(executor); for (int i = 0; i < 15; i++) { Thread.sleep(50); executor.execute(new Runnable() { @Override public void run() { System.out.println("thread number in current pool:" + executor.getPoolSize() + ", task number in task queue:" + executor.getQueue() .size() + " executor size: " + executor.getPoolSize()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); } Thread.sleep(5000); Assertions.assertTrue(executor.getPoolSize() == cores, "more than cores threads alive!"); } |
EagerThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS); int threads = url.getParameter(Constants.THREADS_KEY, Integer.MAX_VALUE); int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES); int alive = url.getParameter(Constants.ALIVE_KEY, Constants.DEFAULT_ALIVE); TaskQueue<Runnable> taskQueue = new TaskQueue<Runnable>(queues <= 0 ? 1 : queues); EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(cores, threads, alive, TimeUnit.MILLISECONDS, taskQueue, new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); taskQueue.setExecutor(executor); return executor; } @Override Executor getExecutor(URL url); } | @Test public void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo: Constants.THREAD_NAME_KEY + "=demo&" + Constants.CORE_THREADS_KEY + "=1&" + Constants.THREADS_KEY + "=2&" + Constants.ALIVE_KEY + "=1000&" + Constants.QUEUES_KEY + "=0"); ThreadPool threadPool = new EagerThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor, instanceOf(EagerThreadPoolExecutor.class)); assertThat(executor.getCorePoolSize(), is(1)); assertThat(executor.getMaximumPoolSize(), is(2)); assertThat(executor.getKeepAliveTime(TimeUnit.MILLISECONDS), is(1000L)); assertThat(executor.getQueue().remainingCapacity(), is(1)); assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(TaskQueue.class)); assertThat(executor.getRejectedExecutionHandler(), Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class)); final CountDownLatch latch = new CountDownLatch(1); executor.execute(new Runnable() { @Override public void run() { Thread thread = Thread.currentThread(); assertThat(thread, instanceOf(InternalThread.class)); assertThat(thread.getName(), startsWith("demo")); latch.countDown(); } }); latch.await(); assertThat(latch.getCount(), is(0L)); }
@Test public void getExecutor2() throws Exception { URL url = URL.valueOf("dubbo: ThreadPool threadPool = new EagerThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getQueue().remainingCapacity(), is(2)); } |
FixedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES); return new ThreadPoolExecutor(threads, threads, 0, TimeUnit.MILLISECONDS, queues == 0 ? new SynchronousQueue<Runnable>() : (queues < 0 ? new LinkedBlockingQueue<Runnable>() : new LinkedBlockingQueue<Runnable>(queues)), new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); } @Override Executor getExecutor(URL url); } | @Test public void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo: Constants.THREAD_NAME_KEY + "=demo&" + Constants.CORE_THREADS_KEY + "=1&" + Constants.THREADS_KEY + "=2&" + Constants.QUEUES_KEY + "=0"); ThreadPool threadPool = new FixedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getCorePoolSize(), is(2)); assertThat(executor.getMaximumPoolSize(), is(2)); assertThat(executor.getKeepAliveTime(TimeUnit.MILLISECONDS), is(0L)); assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(SynchronousQueue.class)); assertThat(executor.getRejectedExecutionHandler(), Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class)); final CountDownLatch latch = new CountDownLatch(1); executor.execute(new Runnable() { @Override public void run() { Thread thread = Thread.currentThread(); assertThat(thread, instanceOf(InternalThread.class)); assertThat(thread.getName(), startsWith("demo")); latch.countDown(); } }); latch.await(); assertThat(latch.getCount(), is(0L)); }
@Test public void getExecutor2() throws Exception { URL url = URL.valueOf("dubbo: ThreadPool threadPool = new FixedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(LinkedBlockingQueue.class)); } |
CachedThreadPool implements ThreadPool { @Override public Executor getExecutor(URL url) { String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME); int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS); int threads = url.getParameter(Constants.THREADS_KEY, Integer.MAX_VALUE); int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES); int alive = url.getParameter(Constants.ALIVE_KEY, Constants.DEFAULT_ALIVE); return new ThreadPoolExecutor(cores, threads, alive, TimeUnit.MILLISECONDS, queues == 0 ? new SynchronousQueue<Runnable>() : (queues < 0 ? new LinkedBlockingQueue<Runnable>() : new LinkedBlockingQueue<Runnable>(queues)), new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url)); } @Override Executor getExecutor(URL url); } | @Test public void getExecutor1() throws Exception { URL url = URL.valueOf("dubbo: Constants.THREAD_NAME_KEY + "=demo&" + Constants.CORE_THREADS_KEY + "=1&" + Constants.THREADS_KEY + "=2&" + Constants.ALIVE_KEY + "=1000&" + Constants.QUEUES_KEY + "=0"); ThreadPool threadPool = new CachedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getCorePoolSize(), is(1)); assertThat(executor.getMaximumPoolSize(), is(2)); assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(SynchronousQueue.class)); assertThat(executor.getRejectedExecutionHandler(), Matchers.<RejectedExecutionHandler>instanceOf(AbortPolicyWithReport.class)); final CountDownLatch latch = new CountDownLatch(1); executor.execute(new Runnable() { @Override public void run() { Thread thread = Thread.currentThread(); assertThat(thread, instanceOf(InternalThread.class)); assertThat(thread.getName(), startsWith("demo")); latch.countDown(); } }); latch.await(); assertThat(latch.getCount(), is(0L)); }
@Test public void getExecutor2() throws Exception { URL url = URL.valueOf("dubbo: ThreadPool threadPool = new CachedThreadPool(); ThreadPoolExecutor executor = (ThreadPoolExecutor) threadPool.getExecutor(url); assertThat(executor.getQueue(), Matchers.<BlockingQueue<Runnable>>instanceOf(LinkedBlockingQueue.class)); } |
JEtcdClient extends AbstractEtcdClient<JEtcdClient.EtcdWatcher> { @Override public void delete(String path) { clientWrapper.delete(path); } JEtcdClient(URL url); @Override void doCreatePersistent(String path); @Override long doCreateEphemeral(String path); @Override boolean checkExists(String path); @Override EtcdWatcher createChildWatcherListener(String path, ChildListener listener); @Override List<String> addChildWatcherListener(String path, EtcdWatcher etcdWatcher); @Override void removeChildWatcherListener(String path, EtcdWatcher etcdWatcher); @Override List<String> getChildren(String path); @Override boolean isConnected(); @Override long createLease(long second); @Override long createLease(long ttl, long timeout, TimeUnit unit); @Override void delete(String path); @Override void revokeLease(long lease); @Override void doClose(); @Override String getKVValue(String key); @Override boolean put(String key, String value); ManagedChannel getChannel(); } | @Test public void test_watch_when_create_path() throws InterruptedException { String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers"; String child = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers/demoService1"; final CountDownLatch notNotified = new CountDownLatch(1); ChildListener childListener = (parent, children) -> { Assertions.assertEquals(1, children.size()); Assertions.assertEquals(child.substring(child.lastIndexOf("/") + 1), children.get(0)); notNotified.countDown(); }; client.addChildListener(path, childListener); client.createEphemeral(child); Assertions.assertTrue(notNotified.await(10, TimeUnit.SECONDS)); client.removeChildListener(path, childListener); client.delete(child); }
@Test public void test_watch_when_create_wrong_path() throws InterruptedException { String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers"; String child = "/dubbo/com.alibaba.dubbo.demo.DemoService/routers/demoService1"; final CountDownLatch notNotified = new CountDownLatch(1); ChildListener childListener = (parent, children) -> { Assertions.assertEquals(1, children.size()); Assertions.assertEquals(child, children.get(0)); notNotified.countDown(); }; client.addChildListener(path, childListener); client.createEphemeral(child); Assertions.assertFalse(notNotified.await(1, TimeUnit.SECONDS)); client.removeChildListener(path, childListener); client.delete(child); }
@Test public void test_watch_when_delete_path() throws InterruptedException { String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers"; String child = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers/demoService1"; final CountDownLatch notNotified = new CountDownLatch(1); ChildListener childListener = (parent, children) -> { Assertions.assertEquals(0, children.size()); notNotified.countDown(); }; client.createEphemeral(child); client.addChildListener(path, childListener); client.delete(child); Assertions.assertTrue(notNotified.await(10, TimeUnit.SECONDS)); client.removeChildListener(path, childListener); }
@Test public void test_watch_then_unwatch() throws InterruptedException { String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers"; String child = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers/demoService2"; final CountDownLatch notNotified = new CountDownLatch(1); final CountDownLatch notTwiceNotified = new CountDownLatch(2); final Holder notified = new Holder(); ChildListener childListener = (parent, children) -> { Assertions.assertEquals(1, children.size()); Assertions.assertEquals(child.substring(child.lastIndexOf("/") + 1), children.get(0)); notNotified.countDown(); notTwiceNotified.countDown(); notified.getAndIncrease(); }; client.addChildListener(path, childListener); client.createEphemeral(child); Assertions.assertTrue(notNotified.await(15, TimeUnit.SECONDS)); client.removeChildListener(path, childListener); client.delete(child); Assertions.assertFalse(notTwiceNotified.await(5, TimeUnit.SECONDS)); Assertions.assertEquals(1, notified.value); client.delete(child); }
@Test public void test_watch_on_recoverable_connection() throws InterruptedException { String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/connection"; String child = "/dubbo/com.alibaba.dubbo.demo.DemoService/connection/demoService1"; final CountDownLatch notNotified = new CountDownLatch(1); final CountDownLatch notTwiceNotified = new CountDownLatch(2); final Holder notified = new Holder(); ChildListener childListener = (parent, children) -> { notTwiceNotified.countDown(); switch (notified.increaseAndGet()) { case 1: { notNotified.countDown(); Assertions.assertTrue(children.size() == 1); Assertions.assertEquals(child.substring(child.lastIndexOf("/") + 1), children.get(0)); break; } case 2: { Assertions.assertTrue(children.size() == 0); Assertions.assertEquals(path, parent); break; } default: Assertions.fail("two many callback invoked."); } }; client.addChildListener(path, childListener); client.createEphemeral(child); Assertions.assertTrue(notNotified.await(15, TimeUnit.SECONDS)); JEtcdClient.EtcdWatcher watcher = client.getChildListener(path, childListener); watcher.onError(Status.UNAVAILABLE.withDescription("temporary connection issue").asRuntimeException()); client.delete(child); Assertions.assertTrue(notTwiceNotified.await(15, TimeUnit.SECONDS)); client.removeChildListener(path, childListener); } |
JsonRpcProtocol extends AbstractProxyProtocol { public JsonRpcProtocol() { super(HttpException.class, JsonRpcClientException.class); } JsonRpcProtocol(); void setHttpBinder(HttpBinder httpBinder); @Override int getDefaultPort(); @Override void destroy(); static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER; static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER; static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER; } | @Test public void testJsonrpcProtocol() { JsonRpcServiceImpl server = new JsonRpcServiceImpl(); assertFalse(server.isCalled()); ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf("jsonrpc: Exporter<JsonRpcService> exporter = protocol.export(proxyFactory.getInvoker(server, JsonRpcService.class, url)); Invoker<JsonRpcService> invoker = protocol.refer(JsonRpcService.class, url); JsonRpcService client = proxyFactory.getProxy(invoker); String result = client.sayHello("haha"); assertTrue(server.isCalled()); assertEquals("Hello, haha", result); invoker.destroy(); exporter.unexport(); } |
JEtcdClient extends AbstractEtcdClient<JEtcdClient.EtcdWatcher> { @Override public boolean put(String key, String value) { return clientWrapper.put(key, value); } JEtcdClient(URL url); @Override void doCreatePersistent(String path); @Override long doCreateEphemeral(String path); @Override boolean checkExists(String path); @Override EtcdWatcher createChildWatcherListener(String path, ChildListener listener); @Override List<String> addChildWatcherListener(String path, EtcdWatcher etcdWatcher); @Override void removeChildWatcherListener(String path, EtcdWatcher etcdWatcher); @Override List<String> getChildren(String path); @Override boolean isConnected(); @Override long createLease(long second); @Override long createLease(long ttl, long timeout, TimeUnit unit); @Override void delete(String path); @Override void revokeLease(long lease); @Override void doClose(); @Override String getKVValue(String key); @Override boolean put(String key, String value); ManagedChannel getChannel(); } | @Test public void test_watch_when_modify() { String path = "/dubbo/config/jetcd-client-unit-test/configurators"; String endpoint = "http: CountDownLatch latch = new CountDownLatch(1); ByteSequence key = ByteSequence.from(path, UTF_8); Watch.Listener listener = Watch.listener(response -> { for (WatchEvent event : response.getEvents()) { Assertions.assertEquals("PUT", event.getEventType().toString()); Assertions.assertEquals(path, event.getKeyValue().getKey().toString(UTF_8)); Assertions.assertEquals("Hello", event.getKeyValue().getValue().toString(UTF_8)); latch.countDown(); } }); try (Client client = Client.builder().endpoints(endpoint).build(); Watch watch = client.getWatchClient(); Watch.Watcher watcher = watch.watch(key, listener)) { client.getKVClient().put(ByteSequence.from(path, UTF_8), ByteSequence.from("Hello", UTF_8)); latch.await(); } catch (Exception e) { Assertions.fail(e.getMessage()); } } |
MulticastExchangeNetworker implements ExchangeNetworker { @Override public ExchangeGroup lookup(URL url) throws RemotingException { return new MulticastExchangeGroup(url); } @Override ExchangeGroup lookup(URL url); } | @Test public void testJoin() throws RemotingException, InterruptedException { final String groupURL = "multicast: MulticastExchangeNetworker multicastExchangeNetworker = new MulticastExchangeNetworker(); final CountDownLatch countDownLatch = new CountDownLatch(1); Peer peer1 = multicastExchangeNetworker.lookup(URL.valueOf(groupURL)) .join(URL.valueOf("dubbo: @Override public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) throws RemotingException { countDownLatch.countDown(); return super.reply(channel, msg); } }); Peer peer2 = multicastExchangeNetworker.lookup(URL.valueOf(groupURL)) .join(URL.valueOf("dubbo: while (true) { for (Channel channel : peer1.getChannels()) { channel.send("hello multicast exchange network!"); } TimeUnit.MILLISECONDS.sleep(50); long count = countDownLatch.getCount(); if (count > 0) { break; } } Group lookup = Networkers.lookup(groupURL); assertThat(lookup, not(nullValue())); assertThat(peer1, instanceOf(ExchangeServerPeer.class)); peer1.close(); peer2.close(); } |
FileNetworker implements Networker { @Override public Group lookup(URL url) throws RemotingException { return new FileGroup(url); } @Override Group lookup(URL url); } | @Test public void testJoin(@TempDir Path folder) throws RemotingException, InterruptedException { final String groupURL = "file: FileNetworker networker = new FileNetworker(); Group group = networker.lookup(URL.valueOf(groupURL)); final CountDownLatch countDownLatch = new CountDownLatch(1); Peer peer1 = group.join(URL.valueOf("dubbo: @Override public void received(Channel channel, Object message) { countDownLatch.countDown(); } }); Peer peer2 = group.join(URL.valueOf("dubbo: mock(ChannelHandlerAdapter.class)); while (true) { long count = countDownLatch.getCount(); if (count > 0) { break; } for (Channel channel : peer1.getChannels()) { channel.send(0, false); channel.send("hello world!"); } TimeUnit.MILLISECONDS.sleep(50); } peer2.close(); peer1.close(); } |
MulticastNetworker implements Networker { @Override public Group lookup(URL url) throws RemotingException { return new MulticastGroup(url); } @Override Group lookup(URL url); } | @Test public void testJoin() throws RemotingException, InterruptedException { final String groupURL = "multicast: final String peerURL = "dubbo: final CountDownLatch countDownLatch = new CountDownLatch(1); Peer peer1 = Networkers.join(groupURL, peerURL, new ChannelHandlerAdapter() { @Override public void received(Channel channel, Object message) { countDownLatch.countDown(); } }); Peer peer2 = Networkers.join(groupURL, "dubbo: mock(ChannelHandlerAdapter.class)); while (true) { long count = countDownLatch.getCount(); if (count > 0) { break; } for (Channel channel : peer1.getChannels()) { channel.send("hello world!"); } TimeUnit.MILLISECONDS.sleep(50); } Group lookup = Networkers.lookup(groupURL); assertThat(lookup, not(nullValue())); peer2.close(); peer1.close(); } |
ConsumerConfig extends AbstractReferenceConfig { @Override public void setTimeout(Integer timeout) { super.setTimeout(timeout); String rmiTimeout = System.getProperty("sun.rmi.transport.tcp.responseTimeout"); if (timeout != null && timeout > 0 && (StringUtils.isEmpty(rmiTimeout))) { System.setProperty("sun.rmi.transport.tcp.responseTimeout", String.valueOf(timeout)); } } @Override void setTimeout(Integer timeout); Boolean isDefault(); String getClient(); void setClient(String client); String getThreadpool(); void setThreadpool(String threadpool); Boolean getDefault(); void setDefault(Boolean isDefault); Integer getCorethreads(); void setCorethreads(Integer corethreads); Integer getThreads(); void setThreads(Integer threads); Integer getQueues(); void setQueues(Integer queues); Integer getShareconnections(); void setShareconnections(Integer shareconnections); } | @Test public void testTimeout() throws Exception { try { System.clearProperty("sun.rmi.transport.tcp.responseTimeout"); ConsumerConfig consumer = new ConsumerConfig(); consumer.setTimeout(10); assertThat(consumer.getTimeout(), is(10)); assertThat(System.getProperty("sun.rmi.transport.tcp.responseTimeout"), equalTo("10")); } finally { System.clearProperty("sun.rmi.transport.tcp.responseTimeout"); } } |
ApplicationConfig extends AbstractConfig { public void setEnvironment(String environment) { checkName(Constants.ENVIRONMENT, environment); if (environment != null) { if (!(Constants.DEVELOPMENT_ENVIRONMENT.equals(environment) || Constants.TEST_ENVIRONMENT.equals(environment) || Constants.PRODUCTION_ENVIRONMENT.equals(environment))) { throw new IllegalStateException(String.format("Unsupported environment: %s, only support %s/%s/%s, default is %s.", environment, Constants.DEVELOPMENT_ENVIRONMENT, Constants.TEST_ENVIRONMENT, Constants.PRODUCTION_ENVIRONMENT, Constants.PRODUCTION_ENVIRONMENT)); } } this.environment = environment; } ApplicationConfig(); ApplicationConfig(String name); @Parameter(key = Constants.APPLICATION_KEY, required = true, useKeyAsProperty = false) String getName(); void setName(String name); @Parameter(key = "application.version") String getVersion(); void setVersion(String version); String getOwner(); void setOwner(String owner); String getOrganization(); void setOrganization(String organization); String getArchitecture(); void setArchitecture(String architecture); String getEnvironment(); void setEnvironment(String environment); RegistryConfig getRegistry(); void setRegistry(RegistryConfig registry); List<RegistryConfig> getRegistries(); @SuppressWarnings({"unchecked"}) void setRegistries(List<? extends RegistryConfig> registries); @Parameter(excluded = true) String getRegistryIds(); void setRegistryIds(String registryIds); MonitorConfig getMonitor(); void setMonitor(String monitor); void setMonitor(MonitorConfig monitor); String getCompiler(); void setCompiler(String compiler); String getLogger(); void setLogger(String logger); Boolean isDefault(); void setDefault(Boolean isDefault); @Parameter(key = Constants.DUMP_DIRECTORY) String getDumpDirectory(); void setDumpDirectory(String dumpDirectory); @Parameter(key = Constants.QOS_ENABLE) Boolean getQosEnable(); void setQosEnable(Boolean qosEnable); @Parameter(key = Constants.QOS_PORT) Integer getQosPort(); void setQosPort(Integer qosPort); @Parameter(key = Constants.ACCEPT_FOREIGN_IP) Boolean getQosAcceptForeignIp(); void setQosAcceptForeignIp(Boolean qosAcceptForeignIp); Map<String, String> getParameters(); void setParameters(Map<String, String> parameters); String getShutwait(); void setShutwait(String shutwait); @Override @Parameter(excluded = true) boolean isValid(); } | @Test public void testEnvironment2() throws Exception { Assertions.assertThrows(IllegalStateException.class, () -> { ApplicationConfig application = new ApplicationConfig("app"); application.setEnvironment("illegal-env"); }); } |
JsonRpcProtocol extends AbstractProxyProtocol { @Override public void destroy() { super.destroy(); for (String key : new ArrayList<>(serverMap.keySet())) { HttpServer server = serverMap.remove(key); if (server != null) { try { if (logger.isInfoEnabled()) { logger.info("Close jsonrpc server " + server.getUrl()); } server.close(); } catch (Throwable t) { logger.warn(t.getMessage(), t); } } } } JsonRpcProtocol(); void setHttpBinder(HttpBinder httpBinder); @Override int getDefaultPort(); @Override void destroy(); static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER; static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER; static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER; } | @Test public void testJsonrpcProtocolForServerJetty9() { JsonRpcServiceImpl server = new JsonRpcServiceImpl(); assertFalse(server.isCalled()); ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); URL url = URL.valueOf("jsonrpc: Exporter<JsonRpcService> exporter = protocol.export(proxyFactory.getInvoker(server, JsonRpcService.class, url)); Invoker<JsonRpcService> invoker = protocol.refer(JsonRpcService.class, url); JsonRpcService client = proxyFactory.getProxy(invoker); String result = client.sayHello("haha"); assertTrue(server.isCalled()); assertEquals("Hello, haha", result); invoker.destroy(); exporter.unexport(); } |
ApplicationConfig extends AbstractConfig { public void setQosAcceptForeignIp(Boolean qosAcceptForeignIp) { this.qosAcceptForeignIp = qosAcceptForeignIp; } ApplicationConfig(); ApplicationConfig(String name); @Parameter(key = Constants.APPLICATION_KEY, required = true, useKeyAsProperty = false) String getName(); void setName(String name); @Parameter(key = "application.version") String getVersion(); void setVersion(String version); String getOwner(); void setOwner(String owner); String getOrganization(); void setOrganization(String organization); String getArchitecture(); void setArchitecture(String architecture); String getEnvironment(); void setEnvironment(String environment); RegistryConfig getRegistry(); void setRegistry(RegistryConfig registry); List<RegistryConfig> getRegistries(); @SuppressWarnings({"unchecked"}) void setRegistries(List<? extends RegistryConfig> registries); @Parameter(excluded = true) String getRegistryIds(); void setRegistryIds(String registryIds); MonitorConfig getMonitor(); void setMonitor(String monitor); void setMonitor(MonitorConfig monitor); String getCompiler(); void setCompiler(String compiler); String getLogger(); void setLogger(String logger); Boolean isDefault(); void setDefault(Boolean isDefault); @Parameter(key = Constants.DUMP_DIRECTORY) String getDumpDirectory(); void setDumpDirectory(String dumpDirectory); @Parameter(key = Constants.QOS_ENABLE) Boolean getQosEnable(); void setQosEnable(Boolean qosEnable); @Parameter(key = Constants.QOS_PORT) Integer getQosPort(); void setQosPort(Integer qosPort); @Parameter(key = Constants.ACCEPT_FOREIGN_IP) Boolean getQosAcceptForeignIp(); void setQosAcceptForeignIp(Boolean qosAcceptForeignIp); Map<String, String> getParameters(); void setParameters(Map<String, String> parameters); String getShutwait(); void setShutwait(String shutwait); @Override @Parameter(excluded = true) boolean isValid(); } | @Test public void testParameters() throws Exception { ApplicationConfig application = new ApplicationConfig("app"); application.setQosAcceptForeignIp(true); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("k1", "v1"); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry("k1", "v1")); assertThat(parameters, hasEntry(Constants.ACCEPT_FOREIGN_IP, "true")); } |
AbstractInterfaceConfig extends AbstractMethodConfig { protected void checkRegistry() { loadRegistriesFromBackwardConfig(); convertRegistryIdsToRegistries(); for (RegistryConfig registryConfig : registries) { if (!registryConfig.isValid()) { throw new IllegalStateException("No registry config found or it's not a valid config! " + "The registry config is: " + registryConfig); } } useRegistryForConfigIfNecessary(); } @Deprecated String getLocal(); @Deprecated void setLocal(Boolean local); @Deprecated void setLocal(String local); String getStub(); void setStub(Boolean stub); void setStub(String stub); String getCluster(); void setCluster(String cluster); String getProxy(); void setProxy(String proxy); Integer getConnections(); void setConnections(Integer connections); @Parameter(key = Constants.REFERENCE_FILTER_KEY, append = true) String getFilter(); void setFilter(String filter); @Parameter(key = Constants.INVOKER_LISTENER_KEY, append = true) String getListener(); void setListener(String listener); String getLayer(); void setLayer(String layer); ApplicationConfig getApplication(); void setApplication(ApplicationConfig application); ModuleConfig getModule(); void setModule(ModuleConfig module); RegistryConfig getRegistry(); void setRegistry(RegistryConfig registry); List<RegistryConfig> getRegistries(); @SuppressWarnings({"unchecked"}) void setRegistries(List<? extends RegistryConfig> registries); @Parameter(excluded = true) String getRegistryIds(); void setRegistryIds(String registryIds); MonitorConfig getMonitor(); void setMonitor(String monitor); void setMonitor(MonitorConfig monitor); String getOwner(); void setOwner(String owner); ConfigCenterConfig getConfigCenter(); void setConfigCenter(ConfigCenterConfig configCenter); Integer getCallbacks(); void setCallbacks(Integer callbacks); String getOnconnect(); void setOnconnect(String onconnect); String getOndisconnect(); void setOndisconnect(String ondisconnect); String getScope(); void setScope(String scope); MetadataReportConfig getMetadataReportConfig(); void setMetadataReportConfig(MetadataReportConfig metadataReportConfig); MetricsConfig getMetrics(); void setMetrics(MetricsConfig metrics); @Parameter(key = Constants.TAG_KEY, useKeyAsProperty = false) String getTag(); void setTag(String tag); } | @Test public void testCheckRegistry2() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.checkRegistry(); }); } |
AbstractInterfaceConfig extends AbstractMethodConfig { @SuppressWarnings("deprecation") protected void checkApplication() { createApplicationIfAbsent(); if (!application.isValid()) { throw new IllegalStateException("No application config found or it's not a valid config! " + "Please add <dubbo:application name=\"...\" /> to your spring config."); } ApplicationModel.setApplication(application.getName()); String wait = ConfigUtils.getProperty(Constants.SHUTDOWN_WAIT_KEY); if (wait != null && wait.trim().length() > 0) { System.setProperty(Constants.SHUTDOWN_WAIT_KEY, wait.trim()); } else { wait = ConfigUtils.getProperty(Constants.SHUTDOWN_WAIT_SECONDS_KEY); if (wait != null && wait.trim().length() > 0) { System.setProperty(Constants.SHUTDOWN_WAIT_SECONDS_KEY, wait.trim()); } } } @Deprecated String getLocal(); @Deprecated void setLocal(Boolean local); @Deprecated void setLocal(String local); String getStub(); void setStub(Boolean stub); void setStub(String stub); String getCluster(); void setCluster(String cluster); String getProxy(); void setProxy(String proxy); Integer getConnections(); void setConnections(Integer connections); @Parameter(key = Constants.REFERENCE_FILTER_KEY, append = true) String getFilter(); void setFilter(String filter); @Parameter(key = Constants.INVOKER_LISTENER_KEY, append = true) String getListener(); void setListener(String listener); String getLayer(); void setLayer(String layer); ApplicationConfig getApplication(); void setApplication(ApplicationConfig application); ModuleConfig getModule(); void setModule(ModuleConfig module); RegistryConfig getRegistry(); void setRegistry(RegistryConfig registry); List<RegistryConfig> getRegistries(); @SuppressWarnings({"unchecked"}) void setRegistries(List<? extends RegistryConfig> registries); @Parameter(excluded = true) String getRegistryIds(); void setRegistryIds(String registryIds); MonitorConfig getMonitor(); void setMonitor(String monitor); void setMonitor(MonitorConfig monitor); String getOwner(); void setOwner(String owner); ConfigCenterConfig getConfigCenter(); void setConfigCenter(ConfigCenterConfig configCenter); Integer getCallbacks(); void setCallbacks(Integer callbacks); String getOnconnect(); void setOnconnect(String onconnect); String getOndisconnect(); void setOndisconnect(String ondisconnect); String getScope(); void setScope(String scope); MetadataReportConfig getMetadataReportConfig(); void setMetadataReportConfig(MetadataReportConfig metadataReportConfig); MetricsConfig getMetrics(); void setMetrics(MetricsConfig metrics); @Parameter(key = Constants.TAG_KEY, useKeyAsProperty = false) String getTag(); void setTag(String tag); } | @Test public void checkApplication2() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.checkApplication(); }); } |
AbstractInterfaceConfig extends AbstractMethodConfig { protected List<URL> loadRegistries(boolean provider) { List<URL> registryList = new ArrayList<URL>(); if (CollectionUtils.isNotEmpty(registries)) { for (RegistryConfig config : registries) { String address = config.getAddress(); if (StringUtils.isEmpty(address)) { address = Constants.ANYHOST_VALUE; } if (!RegistryConfig.NO_AVAILABLE.equalsIgnoreCase(address)) { Map<String, String> map = new HashMap<String, String>(); appendParameters(map, application); appendParameters(map, config); map.put(Constants.PATH_KEY, RegistryService.class.getName()); appendRuntimeParameters(map); if (!map.containsKey(Constants.PROTOCOL_KEY)) { map.put(Constants.PROTOCOL_KEY, Constants.DUBBO_PROTOCOL); } List<URL> urls = UrlUtils.parseURLs(address, map); for (URL url : urls) { url = URLBuilder.from(url) .addParameter(Constants.REGISTRY_KEY, url.getProtocol()) .setProtocol(Constants.REGISTRY_PROTOCOL) .build(); if ((provider && url.getParameter(Constants.REGISTER_KEY, true)) || (!provider && url.getParameter(Constants.SUBSCRIBE_KEY, true))) { registryList.add(url); } } } } } return registryList; } @Deprecated String getLocal(); @Deprecated void setLocal(Boolean local); @Deprecated void setLocal(String local); String getStub(); void setStub(Boolean stub); void setStub(String stub); String getCluster(); void setCluster(String cluster); String getProxy(); void setProxy(String proxy); Integer getConnections(); void setConnections(Integer connections); @Parameter(key = Constants.REFERENCE_FILTER_KEY, append = true) String getFilter(); void setFilter(String filter); @Parameter(key = Constants.INVOKER_LISTENER_KEY, append = true) String getListener(); void setListener(String listener); String getLayer(); void setLayer(String layer); ApplicationConfig getApplication(); void setApplication(ApplicationConfig application); ModuleConfig getModule(); void setModule(ModuleConfig module); RegistryConfig getRegistry(); void setRegistry(RegistryConfig registry); List<RegistryConfig> getRegistries(); @SuppressWarnings({"unchecked"}) void setRegistries(List<? extends RegistryConfig> registries); @Parameter(excluded = true) String getRegistryIds(); void setRegistryIds(String registryIds); MonitorConfig getMonitor(); void setMonitor(String monitor); void setMonitor(MonitorConfig monitor); String getOwner(); void setOwner(String owner); ConfigCenterConfig getConfigCenter(); void setConfigCenter(ConfigCenterConfig configCenter); Integer getCallbacks(); void setCallbacks(Integer callbacks); String getOnconnect(); void setOnconnect(String onconnect); String getOndisconnect(); void setOndisconnect(String ondisconnect); String getScope(); void setScope(String scope); MetadataReportConfig getMetadataReportConfig(); void setMetadataReportConfig(MetadataReportConfig metadataReportConfig); MetricsConfig getMetrics(); void setMetrics(MetricsConfig metrics); @Parameter(key = Constants.TAG_KEY, useKeyAsProperty = false) String getTag(); void setTag(String tag); } | @Test public void testLoadRegistries() { System.setProperty("dubbo.registry.address", "addr1"); InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.checkRegistry(); List<URL> urls = interfaceConfig.loadRegistries(true); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("registry", url.getProtocol()); Assertions.assertEquals("addr1:9090", url.getAddress()); Assertions.assertEquals(RegistryService.class.getName(), url.getPath()); Assertions.assertTrue(url.getParameters().containsKey("timestamp")); Assertions.assertTrue(url.getParameters().containsKey("pid")); Assertions.assertTrue(url.getParameters().containsKey("registry")); Assertions.assertTrue(url.getParameters().containsKey("dubbo")); } |
AbstractInterfaceConfig extends AbstractMethodConfig { protected URL loadMonitor(URL registryURL) { checkMonitor(); Map<String, String> map = new HashMap<String, String>(); map.put(Constants.INTERFACE_KEY, MonitorService.class.getName()); appendRuntimeParameters(map); String hostToRegistry = ConfigUtils.getSystemProperty(Constants.DUBBO_IP_TO_REGISTRY); if (StringUtils.isEmpty(hostToRegistry)) { hostToRegistry = NetUtils.getLocalHost(); } else if (NetUtils.isInvalidLocalHost(hostToRegistry)) { throw new IllegalArgumentException("Specified invalid registry ip from property:" + Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry); } map.put(Constants.REGISTER_IP_KEY, hostToRegistry); appendParameters(map, monitor); appendParameters(map, application); String address = monitor.getAddress(); String sysaddress = System.getProperty("dubbo.monitor.address"); if (sysaddress != null && sysaddress.length() > 0) { address = sysaddress; } if (ConfigUtils.isNotEmpty(address)) { if (!map.containsKey(Constants.PROTOCOL_KEY)) { if (getExtensionLoader(MonitorFactory.class).hasExtension(Constants.LOGSTAT_PROTOCOL)) { map.put(Constants.PROTOCOL_KEY, Constants.LOGSTAT_PROTOCOL); } else { map.put(Constants.PROTOCOL_KEY, Constants.DUBBO_PROTOCOL); } } return UrlUtils.parseURL(address, map); } else if (Constants.REGISTRY_PROTOCOL.equals(monitor.getProtocol()) && registryURL != null) { return URLBuilder.from(registryURL) .setProtocol(Constants.DUBBO_PROTOCOL) .addParameter(Constants.PROTOCOL_KEY, Constants.REGISTRY_PROTOCOL) .addParameterAndEncoded(Constants.REFER_KEY, StringUtils.toQueryString(map)) .build(); } return null; } @Deprecated String getLocal(); @Deprecated void setLocal(Boolean local); @Deprecated void setLocal(String local); String getStub(); void setStub(Boolean stub); void setStub(String stub); String getCluster(); void setCluster(String cluster); String getProxy(); void setProxy(String proxy); Integer getConnections(); void setConnections(Integer connections); @Parameter(key = Constants.REFERENCE_FILTER_KEY, append = true) String getFilter(); void setFilter(String filter); @Parameter(key = Constants.INVOKER_LISTENER_KEY, append = true) String getListener(); void setListener(String listener); String getLayer(); void setLayer(String layer); ApplicationConfig getApplication(); void setApplication(ApplicationConfig application); ModuleConfig getModule(); void setModule(ModuleConfig module); RegistryConfig getRegistry(); void setRegistry(RegistryConfig registry); List<RegistryConfig> getRegistries(); @SuppressWarnings({"unchecked"}) void setRegistries(List<? extends RegistryConfig> registries); @Parameter(excluded = true) String getRegistryIds(); void setRegistryIds(String registryIds); MonitorConfig getMonitor(); void setMonitor(String monitor); void setMonitor(MonitorConfig monitor); String getOwner(); void setOwner(String owner); ConfigCenterConfig getConfigCenter(); void setConfigCenter(ConfigCenterConfig configCenter); Integer getCallbacks(); void setCallbacks(Integer callbacks); String getOnconnect(); void setOnconnect(String onconnect); String getOndisconnect(); void setOndisconnect(String ondisconnect); String getScope(); void setScope(String scope); MetadataReportConfig getMetadataReportConfig(); void setMetadataReportConfig(MetadataReportConfig metadataReportConfig); MetricsConfig getMetrics(); void setMetrics(MetricsConfig metrics); @Parameter(key = Constants.TAG_KEY, useKeyAsProperty = false) String getTag(); void setTag(String tag); } | @Test public void testLoadMonitor() { System.setProperty("dubbo.monitor.address", "monitor-addr:12080"); System.setProperty("dubbo.monitor.protocol", "monitor"); InterfaceConfig interfaceConfig = new InterfaceConfig(); URL url = interfaceConfig.loadMonitor(new URL("dubbo", "addr1", 9090)); Assertions.assertEquals("monitor-addr:12080", url.getAddress()); Assertions.assertEquals(MonitorService.class.getName(), url.getParameter("interface")); Assertions.assertNotNull(url.getParameter("dubbo")); Assertions.assertNotNull(url.getParameter("pid")); Assertions.assertNotNull(url.getParameter("timestamp")); } |
AbstractInterfaceConfig extends AbstractMethodConfig { protected void checkInterfaceAndMethods(Class<?> interfaceClass, List<MethodConfig> methods) { Assert.notNull(interfaceClass, new IllegalStateException("interface not allow null!")); if (!interfaceClass.isInterface()) { throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!"); } if (CollectionUtils.isNotEmpty(methods)) { for (MethodConfig methodBean : methods) { methodBean.setService(interfaceClass.getName()); methodBean.setServiceId(this.getId()); methodBean.refresh(); String methodName = methodBean.getName(); if (StringUtils.isEmpty(methodName)) { throw new IllegalStateException("<dubbo:method> name attribute is required! Please check: " + "<dubbo:service interface=\"" + interfaceClass.getName() + "\" ... >" + "<dubbo:method name=\"\" ... /></<dubbo:reference>"); } boolean hasMethod = Arrays.stream(interfaceClass.getMethods()).anyMatch(method -> method.getName().equals(methodName)); if (!hasMethod) { throw new IllegalStateException("The interface " + interfaceClass.getName() + " not found method " + methodName); } } } } @Deprecated String getLocal(); @Deprecated void setLocal(Boolean local); @Deprecated void setLocal(String local); String getStub(); void setStub(Boolean stub); void setStub(String stub); String getCluster(); void setCluster(String cluster); String getProxy(); void setProxy(String proxy); Integer getConnections(); void setConnections(Integer connections); @Parameter(key = Constants.REFERENCE_FILTER_KEY, append = true) String getFilter(); void setFilter(String filter); @Parameter(key = Constants.INVOKER_LISTENER_KEY, append = true) String getListener(); void setListener(String listener); String getLayer(); void setLayer(String layer); ApplicationConfig getApplication(); void setApplication(ApplicationConfig application); ModuleConfig getModule(); void setModule(ModuleConfig module); RegistryConfig getRegistry(); void setRegistry(RegistryConfig registry); List<RegistryConfig> getRegistries(); @SuppressWarnings({"unchecked"}) void setRegistries(List<? extends RegistryConfig> registries); @Parameter(excluded = true) String getRegistryIds(); void setRegistryIds(String registryIds); MonitorConfig getMonitor(); void setMonitor(String monitor); void setMonitor(MonitorConfig monitor); String getOwner(); void setOwner(String owner); ConfigCenterConfig getConfigCenter(); void setConfigCenter(ConfigCenterConfig configCenter); Integer getCallbacks(); void setCallbacks(Integer callbacks); String getOnconnect(); void setOnconnect(String onconnect); String getOndisconnect(); void setOndisconnect(String ondisconnect); String getScope(); void setScope(String scope); MetadataReportConfig getMetadataReportConfig(); void setMetadataReportConfig(MetadataReportConfig metadataReportConfig); MetricsConfig getMetrics(); void setMetrics(MetricsConfig metrics); @Parameter(key = Constants.TAG_KEY, useKeyAsProperty = false) String getTag(); void setTag(String tag); } | @Test public void checkInterfaceAndMethods1() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.checkInterfaceAndMethods(null, null); }); }
@Test public void checkInterfaceAndMethods2() { Assertions.assertThrows(IllegalStateException.class, () -> { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.checkInterfaceAndMethods(AbstractInterfaceConfigTest.class, null); }); }
@Test public void checkInterfaceAndMethod3() { Assertions.assertThrows(IllegalStateException.class, () -> { MethodConfig methodConfig = new MethodConfig(); InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.checkInterfaceAndMethods(Greeting.class, Collections.singletonList(methodConfig)); }); }
@Test public void checkInterfaceAndMethod4() { Assertions.assertThrows(IllegalStateException.class, () -> { MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("nihao"); InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.checkInterfaceAndMethods(Greeting.class, Collections.singletonList(methodConfig)); }); }
@Test public void checkInterfaceAndMethod5() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("hello"); InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.checkInterfaceAndMethods(Greeting.class, Collections.singletonList(methodConfig)); } |
InvokerInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); if (method.getDeclaringClass() == Object.class) { return method.invoke(invoker, args); } if ("toString".equals(methodName) && parameterTypes.length == 0) { return invoker.toString(); } if ("hashCode".equals(methodName) && parameterTypes.length == 0) { return invoker.hashCode(); } if ("equals".equals(methodName) && parameterTypes.length == 1) { return invoker.equals(args[0]); } return invoker.invoke(createInvocation(method, args)).recreate(); } InvokerInvocationHandler(Invoker<?> handler); @Override Object invoke(Object proxy, Method method, Object[] args); } | @Test public void testInvokeToString() throws Throwable { String methodName = "toString"; when(invoker.toString()).thenReturn(methodName); Method method = invoker.getClass().getMethod(methodName); Object result = invokerInvocationHandler.invoke(null, method, new Object[]{}); Assertions.assertEquals(methodName, result); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.